@maincode-ai/matilda-code 0.20.8 → 0.20.9
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/chunks/{agent-3E4OSF2E.js → agent-MR6HBCNC.js} +1 -1
- package/chunks/{agent-headless-22O7UBQY.js → agent-headless-Y5AQHZHB.js} +1 -1
- package/chunks/anthropicContentGenerator-I3ANKUSE.js +39 -0
- package/chunks/{chunk-2FYDKSRH.js → chunk-2D5W3WW7.js} +498 -494
- package/chunks/{chunk-LYNJBU6H.js → chunk-2JIJ6PFL.js} +1 -1
- package/chunks/chunk-7VBRP4XQ.js +18 -0
- package/chunks/chunk-7VE3KGS4.js +8 -0
- package/chunks/{chunk-WLZF5HVE.js → chunk-FIUFMVRX.js} +1 -1
- package/chunks/{chunk-IRT3RU6X.js → chunk-JFICDNCB.js} +1 -1
- package/chunks/{chunk-FXQULW2K.js → chunk-NPLAJOCA.js} +2 -2
- package/chunks/chunk-OVZKSZIR.js +101 -0
- package/chunks/{computer-use-KS6XCSQU.js → computer-use-5NE6OER4.js} +1 -1
- package/chunks/{contextCommand-TNTORBHV.js → contextCommand-TQW3E3L6.js} +1 -1
- package/chunks/edit-PMMM4Z57.js +39 -0
- package/chunks/{enter-worktree-NF7MA5QG.js → enter-worktree-KOLSAE3N.js} +1 -1
- package/chunks/{enterPlanMode-KPWSPCF2.js → enterPlanMode-WIEHROJ4.js} +1 -1
- package/chunks/{exit-worktree-XWVGI4HA.js → exit-worktree-5GFNCQCU.js} +1 -1
- package/chunks/{exitPlanMode-OS2BGGZK.js → exitPlanMode-4SD3GHP7.js} +1 -1
- package/chunks/{geminiContentGenerator-WF3CO3CH.js → geminiContentGenerator-GSNXCP36.js} +1 -1
- package/chunks/{glob-Y3XNORZ3.js → glob-6NLJB2GI.js} +1 -1
- package/chunks/{grep-NA3SFYUM.js → grep-7TT7XXG2.js} +1 -1
- package/chunks/matildaAgentContentGenerator-BZXWJKJ6.js +32 -0
- package/chunks/{matildaContentGenerator-4BGLGEWH.js → matildaContentGenerator-BBG5MEI5.js} +1 -1
- package/chunks/{monitor-R3FCMPC6.js → monitor-7Z2SKQOD.js} +1 -1
- package/chunks/{notebook-edit-4U5TTZFZ.js → notebook-edit-ZWC6PWD3.js} +1 -1
- package/chunks/{openaiContentGenerator-DMT4SZML.js → openaiContentGenerator-JACPHIUG.js} +1 -1
- package/chunks/{ripGrep-43PC37KD.js → ripGrep-3EJOL3QF.js} +1 -1
- package/chunks/{scheduler-SRRKOB5L.js → scheduler-6GFBYAJV.js} +1 -1
- package/chunks/{serve-YOJETSOR.js → serve-HI33OSTP.js} +1 -1
- package/chunks/{shell-N7HJYZVF.js → shell-6VEGUV5J.js} +1 -1
- package/chunks/{skill-YXHHDMLR.js → skill-HOXYLSX3.js} +1 -1
- package/chunks/src-3M4GZHJB.js +3 -0
- package/chunks/{team-create-EOV7F7EH.js → team-create-PWPR4OKM.js} +1 -1
- package/chunks/{workflow-Y5CYLQU7.js → workflow-UMB2MXXJ.js} +2 -2
- package/chunks/{write-file-ECUYLTFL.js → write-file-REUJ4LGI.js} +1 -1
- package/cli.js +399 -399
- package/package.json +2 -2
- package/chunks/anthropicContentGenerator-ATLOKYPR.js +0 -39
- package/chunks/chunk-2XZIKUB6.js +0 -18
- package/chunks/chunk-6V6R7SFP.js +0 -101
- package/chunks/chunk-ISW2QC5B.js +0 -8
- package/chunks/edit-5OWDNHI4.js +0 -38
- package/chunks/matildaAgentContentGenerator-4B4MMKWH.js +0 -32
- package/chunks/src-55PQXZJ3.js +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.20.
|
|
3
|
+
"version": "0.20.9",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.20.
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.20.9"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as Sr,b as kr}from"./chunk-QN6Y6NPA.js";import{a as R,b as rt,c as we,d as An}from"./chunk-4Q2SNBUH.js";import{a as Tn}from"./chunk-QCIDUZV6.js";import{c as xn,f as _e}from"./chunk-S4K76QPI.js";import{a as tt,b as _n,e as nt,j as wn,o as Sn,q as kn}from"./chunk-XYA3SFGC.js";import{b as Z,e as et}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as Cn}from"./chunk-XJDC3ZQZ.js";import{Y as bn}from"./chunk-QWBNNEV2.js";import{a as wr}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";import{a as Ze,d as be,f as qt}from"./chunk-OWGSC52X.js";var Bn=be((eo,On)=>{"use strict";c();var vr=Ze("util"),Ir=wr();On.exports=function(r){if(typeof r=="number")return r;var e=Ir(r);if(e===void 0){var t=new Error(vr.format("humanize-ms(%j) result undefined",r));console.warn(t.stack)}return e}});var ct=be((no,Ln)=>{"use strict";c();Ln.exports={CURRENT_ID:Symbol("agentkeepalive#currentId"),CREATE_ID:Symbol("agentkeepalive#createId"),INIT_SOCKET:Symbol("agentkeepalive#initSocket"),CREATE_HTTPS_CONNECTION:Symbol("agentkeepalive#createHttpsConnection"),SOCKET_CREATED_TIME:Symbol("agentkeepalive#socketCreatedTime"),SOCKET_NAME:Symbol("agentkeepalive#socketName"),SOCKET_REQUEST_COUNT:Symbol("agentkeepalive#socketRequestCount"),SOCKET_REQUEST_FINISHED_COUNT:Symbol("agentkeepalive#socketRequestFinishedCount")}});var Jt=be((so,Dn)=>{"use strict";c();var Fr=Ze("http").Agent,$t=Bn(),E=Ze("util").debuglog("agentkeepalive"),{INIT_SOCKET:qn,CURRENT_ID:ut,CREATE_ID:jn,SOCKET_CREATED_TIME:Nn,SOCKET_NAME:P,SOCKET_REQUEST_COUNT:v,SOCKET_REQUEST_FINISHED_COUNT:q}=ct(),Ht=1,Gt=parseInt(process.version.split(".",1)[0].substring(1));Gt>=11&&Gt<=12?Ht=2:Gt>=13&&(Ht=3);function Se(r){console.log("[agentkeepalive:deprecated] %s",r)}var Kt=class extends Fr{constructor(e){e=e||{},e.keepAlive=e.keepAlive!==!1,e.freeSocketTimeout===void 0&&(e.freeSocketTimeout=4e3),e.keepAliveTimeout&&(Se("options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.keepAliveTimeout,delete e.keepAliveTimeout),e.freeSocketKeepAliveTimeout&&(Se("options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.freeSocketKeepAliveTimeout,delete e.freeSocketKeepAliveTimeout),e.timeout===void 0&&(e.timeout=Math.max(e.freeSocketTimeout*2,8e3)),e.timeout=$t(e.timeout),e.freeSocketTimeout=$t(e.freeSocketTimeout),e.socketActiveTTL=e.socketActiveTTL?$t(e.socketActiveTTL):0,super(e),this[ut]=0,this.createSocketCount=0,this.createSocketCountLastCheck=0,this.createSocketErrorCount=0,this.createSocketErrorCountLastCheck=0,this.closeSocketCount=0,this.closeSocketCountLastCheck=0,this.errorSocketCount=0,this.errorSocketCountLastCheck=0,this.requestCount=0,this.requestCountLastCheck=0,this.timeoutSocketCount=0,this.timeoutSocketCountLastCheck=0,this.on("free",t=>{let n=this.calcSocketTimeout(t);n>0&&t.timeout!==n&&t.setTimeout(n)})}get freeSocketKeepAliveTimeout(){return Se("agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead"),this.options.freeSocketTimeout}get timeout(){return Se("agent.timeout is deprecated, please use agent.options.timeout instead"),this.options.timeout}get socketActiveTTL(){return Se("agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead"),this.options.socketActiveTTL}calcSocketTimeout(e){let t=this.options.freeSocketTimeout,n=this.options.socketActiveTTL;if(n){let s=Date.now()-e[Nn],o=n-s;if(o<=0)return o;t&&o<t&&(t=o)}if(t)return e.freeSocketTimeout||e.freeSocketKeepAliveTimeout||t}keepSocketAlive(e){let t=super.keepSocketAlive(e);if(!t)return t;let n=this.calcSocketTimeout(e);return typeof n>"u"?!0:n<=0?(E("%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s",e[P],e[v],e[q],n),!1):(e.timeout!==n&&e.setTimeout(n),!0)}reuseSocket(...e){super.reuseSocket(...e);let t=e[0],n=e[1];n.reusedSocket=!0;let s=this.options.timeout;ke(t)!==s&&(t.setTimeout(s),E("%s reset timeout to %sms",t[P],s)),t[v]++,E("%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms",t[P],t[v],t[q],ke(t))}[jn](){let e=this[ut]++;return this[ut]===Number.MAX_SAFE_INTEGER&&(this[ut]=0),e}[qn](e,t){t.timeout&&(ke(e)||e.setTimeout(t.timeout)),this.options.keepAlive&&e.setNoDelay(!0),this.createSocketCount++,this.options.socketActiveTTL&&(e[Nn]=Date.now()),e[P]=`sock[${this[jn]()}#${t._agentKey}]`.split("-----BEGIN",1)[0],e[v]=1,e[q]=0,Or(this,e,t)}createConnection(e,t){let n=!1,s=(i,a)=>{if(!n){if(n=!0,i)return this.createSocketErrorCount++,t(i);this[qn](a,e),t(i,a)}},o=super.createConnection(e,s);return o&&s(null,o),o}get statusChanged(){let e=this.createSocketCount!==this.createSocketCountLastCheck||this.createSocketErrorCount!==this.createSocketErrorCountLastCheck||this.closeSocketCount!==this.closeSocketCountLastCheck||this.errorSocketCount!==this.errorSocketCountLastCheck||this.timeoutSocketCount!==this.timeoutSocketCountLastCheck||this.requestCount!==this.requestCountLastCheck;return e&&(this.createSocketCountLastCheck=this.createSocketCount,this.createSocketErrorCountLastCheck=this.createSocketErrorCount,this.closeSocketCountLastCheck=this.closeSocketCount,this.errorSocketCountLastCheck=this.errorSocketCount,this.timeoutSocketCountLastCheck=this.timeoutSocketCount,this.requestCountLastCheck=this.requestCount),e}getCurrentStatus(){return{createSocketCount:this.createSocketCount,createSocketErrorCount:this.createSocketErrorCount,closeSocketCount:this.closeSocketCount,errorSocketCount:this.errorSocketCount,timeoutSocketCount:this.timeoutSocketCount,requestCount:this.requestCount,freeSockets:Wt(this.freeSockets),sockets:Wt(this.sockets),requests:Wt(this.requests)}}};function ke(r){return r.timeout||r._idleTimeout}function Or(r,e,t){E("%s create, timeout %sms",e[P],ke(e));function n(){if(!e._httpMessage&&e[v]===1)return;e[q]++,r.requestCount++,E("%s(requests: %s, finished: %s) free",e[P],e[v],e[q]);let u=r.getName(t);e.writable&&r.requests[u]&&r.requests[u].length&&(e[v]++,E("%s(requests: %s, finished: %s) will be reuse on agent free event",e[P],e[v],e[q]))}e.on("free",n);function s(u){E("%s(requests: %s, finished: %s) close, isError: %s",e[P],e[v],e[q],u),r.closeSocketCount++}e.on("close",s);function o(){let u=e.listeners("timeout").length,l=ke(e),m=e._httpMessage,f=m&&m.listeners("timeout").length||0;E("%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s",e[P],e[v],e[q],l,u,Ht,!!m,f),E.enabled&&E("timeout listeners: %s",e.listeners("timeout").map(g=>g.name).join(", ")),r.timeoutSocketCount++;let _=r.getName(t);if(r.freeSockets[_]&&r.freeSockets[_].indexOf(e)!==-1)e.destroy(),r.removeSocket(e,t),E("%s is free, destroy quietly",e[P]);else if(f===0){let g=new Error("Socket timeout");g.code="ERR_SOCKET_TIMEOUT",g.timeout=l,e.destroy(g),r.removeSocket(e,t),E("%s destroy with timeout error",e[P])}}e.on("timeout",o);function i(u){let l=e.listeners("error").length;E("%s(requests: %s, finished: %s) error: %s, listenerCount: %s",e[P],e[v],e[q],u,l),r.errorSocketCount++,l===1&&(E("%s emit uncaught error event",e[P]),e.removeListener("error",i),e.emit("error",u))}e.on("error",i);function a(){E("%s(requests: %s, finished: %s) agentRemove",e[P],e[v],e[q]),e.removeListener("close",s),e.removeListener("error",i),e.removeListener("free",n),e.removeListener("timeout",o),e.removeListener("agentRemove",a)}e.on("agentRemove",a)}Dn.exports=Kt;function Wt(r){let e={};for(let t in r)e[t]=r[t].length;return e}});var Gn=be((io,$n)=>{"use strict";c();var Xt=Ze("https").Agent,Br=Jt(),{INIT_SOCKET:Lr,CREATE_HTTPS_CONNECTION:Un}=ct(),Ce=class extends Br{constructor(e){super(e),this.defaultPort=443,this.protocol="https:",this.maxCachedSessions=this.options.maxCachedSessions,this.maxCachedSessions===void 0&&(this.maxCachedSessions=100),this._sessionCache={map:{},list:[]}}createConnection(e,t){let n=this[Un](e,t);return this[Lr](n,e),n}};Ce.prototype[Un]=Xt.prototype.createConnection;["getName","_getSession","_cacheSession","_evictSession"].forEach(function(r){typeof Xt.prototype[r]=="function"&&(Ce.prototype[r]=Xt.prototype[r])});$n.exports=Ce});var Hn=be((co,xe)=>{"use strict";c();var Wn=Jt();xe.exports=Wn;xe.exports.HttpAgent=Wn;xe.exports.HttpsAgent=Gn();xe.exports.constants=ct()});c();c();c();c();c();var ee="0.36.3";c();c();c();var En=!1,te,jt,Cr,xr,Tr,Pn,Ar,st,Nt,Rn,Dt,ot,Mn;function vn(r,e={auto:!1}){if(En)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(te)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${te}'\``);En=e.auto,te=r.kind,jt=r.fetch,Cr=r.Request,xr=r.Response,Tr=r.Headers,Pn=r.FormData,Ar=r.Blob,st=r.File,Nt=r.ReadableStream,Rn=r.getMultipartRequestOptions,Dt=r.getDefaultAgent,ot=r.fileFromPath,Mn=r.isFsReadStream}c();var J=qt(Sr(),1);c();c();import{inspect as Rr}from"util";c();var In=r=>r instanceof rt;c();import{deprecate as Pr}from"util";var Fn=Pr(()=>{},'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');var B=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},it,L,Ut,at=class{constructor(e){it.add(this),L.set(this,new Map),e&&(Fn(),e.forEach(({name:t,value:n,fileName:s})=>this.append(t,n,s)))}static[(L=new WeakMap,it=new WeakSet,Symbol.hasInstance)](e){return!!(e&&R(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&R(e.append)&&R(e.set)&&R(e.get)&&R(e.getAll)&&R(e.has)&&R(e.delete)&&R(e.entries)&&R(e.values)&&R(e.keys)&&R(e[Symbol.iterator])&&R(e.forEach))}append(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!0,rawValue:t,argsLength:arguments.length})}set(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!1,rawValue:t,argsLength:arguments.length})}get(e){let t=B(this,L,"f").get(String(e));return t?t[0]:null}getAll(e){let t=B(this,L,"f").get(String(e));return t?t.slice():[]}has(e){return B(this,L,"f").has(String(e))}delete(e){B(this,L,"f").delete(String(e))}*keys(){for(let e of B(this,L,"f").keys())yield e}*entries(){for(let e of this.keys()){let t=this.getAll(e);for(let n of t)yield[e,n]}}*values(){for(let[,e]of this)yield e}[(Ut=function({name:t,rawValue:n,append:s,fileName:o,argsLength:i}){let a=s?"append":"set";if(i<2)throw new TypeError(`Failed to execute '${a}' on 'FormData': 2 arguments required, but only ${i} present.`);t=String(t);let u;if(An(n))u=o===void 0?n:new we([n],o,{type:n.type,lastModified:n.lastModified});else if(In(n))u=new we([n],o===void 0?"blob":o,{type:n.type});else{if(o)throw new TypeError(`Failed to execute '${a}' on 'FormData': parameter 2 is not of type 'Blob'.`);u=String(n)}let l=B(this,L,"f").get(t);if(!l)return void B(this,L,"f").set(t,[u]);if(!s)return void B(this,L,"f").set(t,[u]);l.push(u)},Symbol.iterator)](){return this.entries()}forEach(e,t){for(let[n,s]of this)e.call(t,s,n,this)}get[Symbol.toStringTag](){return"FormData"}[Rr.custom](){return this[Symbol.toStringTag]}};var Zt=qt(Hn(),1),Vn=qt(kr(),1);import{ReadStream as Wr}from"node:fs";c();c();c();var Kn="abcdefghijklmnopqrstuvwxyz0123456789";function qr(){let r=16,e="";for(;r--;)e+=Kn[Math.random()*Kn.length<<0];return e}var Jn=qr;c();var jr=r=>Object.prototype.toString.call(r).slice(8,-1).toLowerCase();function Nr(r){if(jr(r)!=="object")return!1;let e=Object.getPrototypeOf(r);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}var zt=Nr;c();var Dr=r=>String(r).replace(/\r|\n/g,(e,t,n)=>e==="\r"&&n[t+1]!==`
|
|
4
|
-
`||e===`
|
|
5
|
-
`&&n[t-1]!=="\r"?`\r
|
|
6
|
-
`:e),Vt=Dr;c();var Ur=r=>String(r).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Qt=Ur;c();c();var $r=r=>typeof r=="function",U=$r;var ne=r=>!!(r&&typeof r=="object"&&U(r.constructor)&&r[Symbol.toStringTag]==="File"&&U(r.stream)&&r.name!=null&&r.size!=null&&r.lastModified!=null);c();var Xn=r=>!!(r&&U(r.constructor)&&r[Symbol.toStringTag]==="FormData"&&U(r.append)&&U(r.getAll)&&U(r.entries)&&U(r[Symbol.iterator]));var Te=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},w=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},lt,K,Ae,ft,Ee,re,Pe,Re,ht,Yt,Gr={enableAdditionalHeaders:!1},dt=class{constructor(e,t,n){if(lt.add(this),K.set(this,`\r
|
|
7
|
-
`),Ae.set(this,void 0),ft.set(this,void 0),Ee.set(this,"-".repeat(2)),re.set(this,new TextEncoder),Pe.set(this,void 0),Re.set(this,void 0),ht.set(this,void 0),!Xn(e))throw new TypeError("Expected first argument to be a FormData instance.");let s;if(zt(t)?n=t:s=t,s||(s=Jn()),typeof s!="string")throw new TypeError("Expected boundary argument to be a string.");if(n&&!zt(n))throw new TypeError("Expected options argument to be an object.");Te(this,Re,e,"f"),Te(this,ht,{...Gr,...n},"f"),Te(this,Ae,w(this,re,"f").encode(w(this,K,"f")),"f"),Te(this,ft,w(this,Ae,"f").byteLength,"f"),this.boundary=`form-data-boundary-${s}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,Te(this,Pe,w(this,re,"f").encode(`${w(this,Ee,"f")}${this.boundary}${w(this,Ee,"f")}${w(this,K,"f").repeat(2)}`),"f"),this.contentLength=String(this.getContentLength()),this.headers=Object.freeze({"Content-Type":this.contentType,"Content-Length":this.contentLength}),Object.defineProperties(this,{boundary:{writable:!1,configurable:!1},contentType:{writable:!1,configurable:!1},contentLength:{writable:!1,configurable:!1},headers:{writable:!1,configurable:!1}})}getContentLength(){let e=0;for(let[t,n]of w(this,Re,"f")){let s=ne(n)?n:w(this,re,"f").encode(Vt(n));e+=w(this,lt,"m",Yt).call(this,t,s).byteLength,e+=ne(s)?s.size:s.byteLength,e+=w(this,ft,"f")}return e+w(this,Pe,"f").byteLength}*values(){for(let[e,t]of w(this,Re,"f").entries()){let n=ne(t)?t:w(this,re,"f").encode(Vt(t));yield w(this,lt,"m",Yt).call(this,e,n),yield n,yield w(this,Ae,"f")}yield w(this,Pe,"f")}async*encode(){for(let e of this.values())ne(e)?yield*e.stream():yield e}[(K=new WeakMap,Ae=new WeakMap,ft=new WeakMap,Ee=new WeakMap,re=new WeakMap,Pe=new WeakMap,Re=new WeakMap,ht=new WeakMap,lt=new WeakSet,Yt=function(t,n){let s="";return s+=`${w(this,Ee,"f")}${this.boundary}${w(this,K,"f")}`,s+=`Content-Disposition: form-data; name="${Qt(t)}"`,ne(n)&&(s+=`; filename="${Qt(n.name)}"${w(this,K,"f")}`,s+=`Content-Type: ${n.type||"application/octet-stream"}`),w(this,ht,"f").enableAdditionalHeaders===!0&&(s+=`${w(this,K,"f")}Content-Length: ${ne(n)?n.size:n.byteLength}`),w(this,re,"f").encode(`${s}${w(this,K,"f").repeat(2)}`)},Symbol.iterator)](){return this.values()}[Symbol.asyncIterator](){return this.encode()}};c();c();import{Readable as Hr}from"node:stream";c();var pt=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};import{ReadableStream as Kr}from"node:stream/web";var zn=!1;async function Jr(r,...e){let{fileFromPath:t}=await import("./fileFromPath-7UCWPD4W.js");return zn||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(r)}) instead`),zn=!0),await t(r,...e)}var Xr=new Zt.default({keepAlive:!0,timeout:5*60*1e3}),zr=new Zt.default.HttpsAgent({keepAlive:!0,timeout:5*60*1e3});async function Vr(r,e){let t=new dt(r),n=Hr.from(t),s=new pt(n),o={...e.headers,...t.headers,"Content-Length":t.contentLength};return{...e,body:s,headers:o}}function Qn(){return typeof AbortController>"u"&&(globalThis.AbortController=Vn.AbortController),{kind:"node",fetch:J.default,Request:J.Request,Response:J.Response,Headers:J.Headers,FormData:at,Blob:rt,File:we,ReadableStream:Kr,getMultipartRequestOptions:Vr,getDefaultAgent:r=>r.startsWith("https")?zr:Xr,fileFromPath:Jr,isFsReadStream:r=>r instanceof Wr}}te||vn(Qn(),{auto:!0});c();var h=class extends Error{},k=class r extends h{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["request-id"],this.error=t}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new X({message:n,cause:mt(t)});let o=t;return e===400?new Me(e,o,n,s):e===401?new ve(e,o,n,s):e===403?new Ie(e,o,n,s):e===404?new Fe(e,o,n,s):e===409?new Oe(e,o,n,s):e===422?new Be(e,o,n,s):e===429?new Le(e,o,n,s):e>=500?new qe(e,o,n,s):new r(e,o,n,s)}},x=class extends k{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},X=class extends k{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ue=class extends X{constructor({message:e}={}){super({message:e??"Request timed out."})}},Me=class extends k{},ve=class extends k{},Ie=class extends k{},Fe=class extends k{},Oe=class extends k{},Be=class extends k{},Le=class extends k{},qe=class extends k{};c();var $=class r{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];let n=r.NEWLINE_CHARS.has(t[t.length-1]||""),s=t.split(r.NEWLINE_REGEXP);return n&&s.pop(),s.length===1&&!n?(this.buffer.push(s[0]),[]):(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),n||(this.buffer=[s.pop()||""]),s)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new h(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new h(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new h("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};$.NEWLINE_CHARS=new Set([`
|
|
8
|
-
`,"\r"]);$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;c();function je(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var j=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let i of Yr(e,t)){if(i.event==="completion")try{yield JSON.parse(i.data)}catch(a){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),a}if(i.event==="message_start"||i.event==="message_delta"||i.event==="message_stop"||i.event==="content_block_start"||i.event==="content_block_delta"||i.event==="content_block_stop")try{yield JSON.parse(i.data)}catch(a){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),a}if(i.event!=="ping"&&i.event==="error")throw k.generate(void 0,`SSE Error: ${i.data}`,i.data,tn(e.headers))}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new r(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){let i=new $,a=je(e);for await(let u of a)for(let l of i.decode(u))yield l;for(let u of i.flush())yield u}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of s())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||t.abort()}}return new r(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new r(()=>s(e),this.controller),new r(()=>s(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new Nt({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:o,done:i}=await t.next();if(i)return s.close();let a=n.encode(JSON.stringify(o)+`
|
|
9
|
-
`);s.enqueue(a)}catch(o){s.error(o)}},async cancel(){await t.return?.()}})}};async function*Yr(r,e){if(!r.body)throw e.abort(),new h("Attempted to iterate over a response with no body");let t=new en,n=new $,s=je(r.body);for await(let o of Zr(s))for(let i of n.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of n.flush()){let i=t.decode(o);i&&(yield i)}}async function*Zr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=es(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}function es(r){for(let n=0;n<r.length-2;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var en=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
10
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=ts(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function ts(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}c();var ns=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",rs=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Ne(r),Ne=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function Yn(r,e,t){if(r=await r,rs(r))return r;if(ns(r)){let s=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Ne(s)?[await s.arrayBuffer()]:[s];return new st(o,e,t)}let n=await ss(r);if(e||(e=is(r)??"unknown_file"),!t?.type){let s=n[0]?.type;typeof s=="string"&&(t={...t,type:s})}return new st(n,e,t)}async function ss(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Ne(r))e.push(await r.arrayBuffer());else if(as(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${os(r)}`);return e}function os(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function is(r){return nn(r.name)||nn(r.filename)||nn(r.path)?.split(/[\\/]/).pop()}var nn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},as=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",rn=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var us=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},ls=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},gt;async function sr(r){let{response:e}=r;if(r.options.stream)return le("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):j.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return le("response",e.status,e.url,e.headers,o),or(o,e)}let s=await e.text();return le("response",e.status,e.url,e.headers,s),s}function or(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var yt=class r extends Promise{constructor(e,t=sr){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>or(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},bt=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=sn("maxRetries",t),this.timeout=sn("timeout",n),this.httpAgent=s,this.fetch=o??jt}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ps(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${_s()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{let o=s&&Ne(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let{method:n,path:s,query:o,headers:i={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:rn(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,u=this.calculateContentLength(a),l=this.buildURL(s,o);"timeout"in e&&sn("timeout",e.timeout);let m=e.timeout??this.timeout,f=e.httpAgent??this.httpAgent??Dt(l),_=m+1e3;typeof f?.options?.timeout=="number"&&_>(f.options.timeout??0)&&(f.options.timeout=_),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let g=this.buildHeaders({options:e,headers:i,contentLength:u,retryCount:t});return{req:{method:n,...a&&{body:a},headers:g,...f&&{agent:f},signal:e.signal??null},url:l,timeout:m}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){let o={};n&&(o["content-length"]=n);let i=this.defaultHeaders(e);return nr(o,i),nr(o,t),rn(e.body)&&te!=="node"&&delete o["content-type"],rr(i,"x-stainless-retry-count")===void 0&&rr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return k.generate(e,t,n,s)}request(e,t=null){return new yt(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);let{req:o,url:i,timeout:a}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:i,options:n}),le("request",i,n,o.headers),n.signal?.aborted)throw new x;let u=new AbortController,l=await this.fetchWithTimeout(i,o,a,u).catch(mt);if(l instanceof Error){if(n.signal?.aborted)throw new x;if(t)return this.retryRequest(n,t);throw l.name==="AbortError"?new ue:new X({cause:l})}let m=tn(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){let M=`retrying, ${t} attempts remaining`;return le(`response (error; ${M})`,l.status,i,m),this.retryRequest(n,t,m)}let f=await l.text().catch(M=>mt(M).message),_=ms(f),g=_?void 0:f;throw le(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,i,m,g),this.makeStatusError(l.status,_,g,m)}return{response:l,options:n,controller:u}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new on(this,n,e)}buildURL(e,t){let n=ys(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return De(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new h(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){let{signal:o,...i}=t||{};o&&o.addEventListener("abort",()=>s.abort());let a=setTimeout(()=>s.abort(),n),u={signal:s.signal,...i};return u.method&&(u.method=u.method.toUpperCase()),this.fetch.call(void 0,e,u).finally(()=>{clearTimeout(a)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s,o=n?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(s=a)}let i=n?.["retry-after"];if(i&&!s){let a=parseFloat(i);Number.isNaN(a)?s=Date.parse(i)-Date.now():s=a*1e3}if(!(s&&0<=s&&s<60*1e3)){let a=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,a)}return await bs(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${ee}`}},_t=class{constructor(e,t,n,s){gt.set(this,void 0),us(this,gt,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[s,o]of n)e.url.searchParams.set(s,o);t.query=void 0,t.path=e.url.toString()}return await ls(this,gt,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},on=class extends yt{constructor(e,t,n){super(t,async s=>new n(e,s.response,await sr(s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tn=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),fs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},I=r=>typeof r=="object"&&r!==null&&!De(r)&&Object.keys(r).every(e=>ir(fs,e)),hs=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ee,"X-Stainless-OS":er(Deno.build.os),"X-Stainless-Arch":Zn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ee,"X-Stainless-OS":er(process.platform),"X-Stainless-Arch":Zn(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ds();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ds(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var Zn=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",er=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),tr,ps=()=>tr??(tr=hs()),ms=r=>{try{return JSON.parse(r)}catch{return}},gs=/^[a-z][a-z0-9+.-]*:/i,ys=r=>gs.test(r),bs=r=>new Promise(e=>setTimeout(e,r)),sn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new h(`${r} must be an integer`);if(e<0)throw new h(`${r} must be a positive integer`);return e},mt=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var wt=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function De(r){if(!r)return!0;for(let e in r)return!1;return!0}function ir(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function nr(r,e){for(let t in e){if(!ir(e,t))continue;let n=t.toLowerCase();if(!n)continue;let s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}function le(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var _s=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),ar=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ws=r=>typeof r?.get=="function";var rr=(r,e)=>{let t=e.toLowerCase();if(ws(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(s,o,i)=>o+i.toUpperCase());for(let s of[e,t,e.toUpperCase(),n]){let o=r.get(s);if(o)return o}}for(let[n,s]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(s)?(s.length<=1||console.warn(`Received ${s.length} entries for the ${e} header, using the first entry.`),s[0]):s};c();var N=class extends _t{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};c();c();c();var C=class{constructor(e){this._client=e}};c();var se=class extends C{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",fe,{query:e,...t})}},fe=class extends N{};se.BetaModelInfosPage=fe;c();c();c();var he=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new $;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new h("Attempted to iterate over a response with no body");return new r(je(e.body),t)}};var oe=class extends C{create(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(I(t))return this.retrieve(e,{},t);let{betas:s}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(I(e))return this.list({},e);let{betas:n,...s}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",de,{query:s,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(I(t))return this.delete(e,{},t);let{betas:s}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(I(t))return this.cancel(e,{},t);let{betas:s}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(I(t))return this.results(e,{},t);let s=await this.retrieve(e);if(!s.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:o}=t;return this._client.get(s.results_url,{...n,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((i,a)=>he.fromResponse(a.response,a.controller))}},de=class extends N{};oe.BetaMessageBatchesPage=de;c();c();var xs=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",u=!1;for(n=r[++e];n!=='"';){if(e===r.length){u=!0;break}if(n==="\\"){if(e++,e===r.length){u=!0;break}a+=n+r[e],n=r[++e]}else a+=n,n=r[++e]}n=r[++e],u||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=r[++e]);n&&o.test(n)||n===".";)a+=n,n=r[++e];t.push({type:"number",value:a});continue}let i=/[a-z]/i;if(n&&i.test(n)){let a="";for(;n&&i.test(n)&&e!==r.length;)a+=n,n=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},pe=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),pe(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),pe(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),pe(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),pe(r);break;case"delimiter":return r=r.slice(0,r.length-1),pe(r);break}return r},Ts=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},As=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},St=r=>JSON.parse(As(Ts(pe(xs(r)))));var T=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},d=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},F,z,Ue,kt,$e,Ge,Ct,We,G,He,xt,Tt,me,At,Et,an,cr,cn,un,ln,fn,ur,lr="__json_buf",Pt=class r{constructor(){F.add(this),this.messages=[],this.receivedMessages=[],z.set(this,void 0),this.controller=new AbortController,Ue.set(this,void 0),kt.set(this,()=>{}),$e.set(this,()=>{}),Ge.set(this,void 0),Ct.set(this,()=>{}),We.set(this,()=>{}),G.set(this,{}),He.set(this,!1),xt.set(this,!1),Tt.set(this,!1),me.set(this,!1),At.set(this,void 0),Et.set(this,void 0),cn.set(this,e=>{if(T(this,xt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new x),e instanceof x)return T(this,Tt,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))}),T(this,Ue,new Promise((e,t)=>{T(this,kt,e,"f"),T(this,$e,t,"f")}),"f"),T(this,Ge,new Promise((e,t)=>{T(this,Ct,e,"f"),T(this,We,t,"f")}),"f"),d(this,Ue,"f").catch(()=>{}),d(this,Ge,"f").catch(()=>{})}get response(){return d(this,At,"f")}get request_id(){return d(this,Et,"f")}async withResponse(){let e=await d(this,Ue,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let o of t.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},d(this,cn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),d(this,F,"m",un).call(this);let{response:o,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of i)d(this,F,"m",ln).call(this,a);if(i.controller.signal?.aborted)throw new x;d(this,F,"m",fn).call(this)}_connected(e){this.ended||(T(this,At,e,"f"),T(this,Et,e?.headers.get("request-id"),"f"),d(this,kt,"f").call(this,e),this._emit("connect"))}get ended(){return d(this,He,"f")}get errored(){return d(this,xt,"f")}get aborted(){return d(this,Tt,"f")}abort(){this.controller.abort()}on(e,t){return(d(this,G,"f")[e]||(d(this,G,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=d(this,G,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(d(this,G,"f")[e]||(d(this,G,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{T(this,me,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){T(this,me,!0,"f"),await d(this,Ge,"f")}get currentMessage(){return d(this,z,"f")}async finalMessage(){return await this.done(),d(this,F,"m",an).call(this)}async finalText(){return await this.done(),d(this,F,"m",cr).call(this)}_emit(e,...t){if(d(this,He,"f"))return;e==="end"&&(T(this,He,!0,"f"),d(this,Ct,"f").call(this));let n=d(this,G,"f")[e];if(n&&(d(this,G,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!d(this,me,"f")&&!n?.length&&Promise.reject(s),d(this,$e,"f").call(this,s),d(this,We,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!d(this,me,"f")&&!n?.length&&Promise.reject(s),d(this,$e,"f").call(this,s),d(this,We,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",d(this,F,"m",an).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),d(this,F,"m",un).call(this),this._connected(null);let s=j.fromReadableStream(e,this.controller);for await(let o of s)d(this,F,"m",ln).call(this,o);if(s.controller.signal?.aborted)throw new x;d(this,F,"m",fn).call(this)}[(z=new WeakMap,Ue=new WeakMap,kt=new WeakMap,$e=new WeakMap,Ge=new WeakMap,Ct=new WeakMap,We=new WeakMap,G=new WeakMap,He=new WeakMap,xt=new WeakMap,Tt=new WeakMap,me=new WeakMap,At=new WeakMap,Et=new WeakMap,cn=new WeakMap,F=new WeakSet,an=function(){if(this.receivedMessages.length===0)throw new h("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},cr=function(){if(this.receivedMessages.length===0)throw new h("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new h("stream ended without producing a content block with type=text");return t.join(" ")},un=function(){this.ended||T(this,z,void 0,"f")},ln=function(t){if(this.ended)return;let n=d(this,F,"m",ur).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{T(this,z,n,"f");break}case"content_block_start":case"message_delta":break}},fn=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=d(this,z,"f");if(!t)throw new h("request ended without sending any chunks");return T(this,z,void 0,"f"),t},ur=function(t){let n=d(this,z,"f");if(t.type==="message_start"){if(n)throw new h(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new h(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let o=s[lr]||"";o+=t.delta.partial_json,Object.defineProperty(s,lr,{value:o,enumerable:!1,writable:!0}),o&&(s.input=St(o))}break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var fr={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},V=class extends C{constructor(){super(...arguments),this.batches=new oe(this._client)}create(e,t){let{betas:n,...s}=e;return s.model in fr&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${fr[s.model]}
|
|
11
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:s,timeout:this._client._options.timeout??6e5,...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return Pt.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};V.Batches=oe;V.BetaMessageBatchesPage=de;var D=class extends C{constructor(){super(...arguments),this.models=new se(this._client),this.messages=new V(this._client)}};D.Models=se;D.BetaModelInfosPage=fe;D.Messages=V;c();var ie=class extends C{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};c();c();var ae=class extends C{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",ge,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new h(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((s,o)=>he.fromResponse(o.response,o.controller))}},ge=class extends N{};ae.MessageBatchesPage=ge;c();var A=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},p=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},O,Q,Ke,Rt,Je,Xe,Mt,ze,W,Ve,vt,It,ye,Ft,Ot,hn,hr,dn,pn,mn,gn,dr,pr="__json_buf",Bt=class r{constructor(){O.add(this),this.messages=[],this.receivedMessages=[],Q.set(this,void 0),this.controller=new AbortController,Ke.set(this,void 0),Rt.set(this,()=>{}),Je.set(this,()=>{}),Xe.set(this,void 0),Mt.set(this,()=>{}),ze.set(this,()=>{}),W.set(this,{}),Ve.set(this,!1),vt.set(this,!1),It.set(this,!1),ye.set(this,!1),Ft.set(this,void 0),Ot.set(this,void 0),dn.set(this,e=>{if(A(this,vt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new x),e instanceof x)return A(this,It,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))}),A(this,Ke,new Promise((e,t)=>{A(this,Rt,e,"f"),A(this,Je,t,"f")}),"f"),A(this,Xe,new Promise((e,t)=>{A(this,Mt,e,"f"),A(this,ze,t,"f")}),"f"),p(this,Ke,"f").catch(()=>{}),p(this,Xe,"f").catch(()=>{})}get response(){return p(this,Ft,"f")}get request_id(){return p(this,Ot,"f")}async withResponse(){let e=await p(this,Ke,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let s=new r;for(let o of t.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},p(this,dn,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),p(this,O,"m",pn).call(this);let{response:o,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of i)p(this,O,"m",mn).call(this,a);if(i.controller.signal?.aborted)throw new x;p(this,O,"m",gn).call(this)}_connected(e){this.ended||(A(this,Ft,e,"f"),A(this,Ot,e?.headers.get("request-id"),"f"),p(this,Rt,"f").call(this,e),this._emit("connect"))}get ended(){return p(this,Ve,"f")}get errored(){return p(this,vt,"f")}get aborted(){return p(this,It,"f")}abort(){this.controller.abort()}on(e,t){return(p(this,W,"f")[e]||(p(this,W,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,W,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(p(this,W,"f")[e]||(p(this,W,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{A(this,ye,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){A(this,ye,!0,"f"),await p(this,Xe,"f")}get currentMessage(){return p(this,Q,"f")}async finalMessage(){return await this.done(),p(this,O,"m",hn).call(this)}async finalText(){return await this.done(),p(this,O,"m",hr).call(this)}_emit(e,...t){if(p(this,Ve,"f"))return;e==="end"&&(A(this,Ve,!0,"f"),p(this,Mt,"f").call(this));let n=p(this,W,"f")[e];if(n&&(p(this,W,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!p(this,ye,"f")&&!n?.length&&Promise.reject(s),p(this,Je,"f").call(this,s),p(this,ze,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!p(this,ye,"f")&&!n?.length&&Promise.reject(s),p(this,Je,"f").call(this,s),p(this,ze,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",p(this,O,"m",hn).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),p(this,O,"m",pn).call(this),this._connected(null);let s=j.fromReadableStream(e,this.controller);for await(let o of s)p(this,O,"m",mn).call(this,o);if(s.controller.signal?.aborted)throw new x;p(this,O,"m",gn).call(this)}[(Q=new WeakMap,Ke=new WeakMap,Rt=new WeakMap,Je=new WeakMap,Xe=new WeakMap,Mt=new WeakMap,ze=new WeakMap,W=new WeakMap,Ve=new WeakMap,vt=new WeakMap,It=new WeakMap,ye=new WeakMap,Ft=new WeakMap,Ot=new WeakMap,dn=new WeakMap,O=new WeakSet,hn=function(){if(this.receivedMessages.length===0)throw new h("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},hr=function(){if(this.receivedMessages.length===0)throw new h("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new h("stream ended without producing a content block with type=text");return t.join(" ")},pn=function(){this.ended||A(this,Q,void 0,"f")},mn=function(t){if(this.ended)return;let n=p(this,O,"m",dr).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let s=n.content.at(-1);switch(t.delta.type){case"text_delta":{s.type==="text"&&this._emit("text",t.delta.text,s.text||"");break}case"citations_delta":{s.type==="text"&&this._emit("citation",t.delta.citation,s.citations??[]);break}case"input_json_delta":{s.type==="tool_use"&&s.input&&this._emit("inputJson",t.delta.partial_json,s.input);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{A(this,Q,n,"f");break}case"content_block_start":case"message_delta":break}},gn=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=p(this,Q,"f");if(!t)throw new h("request ended without sending any chunks");return A(this,Q,void 0,"f"),t},dr=function(t){let n=p(this,Q,"f");if(t.type==="message_start"){if(n)throw new h(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new h(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let s=n.content.at(t.index);switch(t.delta.type){case"text_delta":{s?.type==="text"&&(s.text+=t.delta.text);break}case"citations_delta":{s?.type==="text"&&(s.citations??(s.citations=[]),s.citations.push(t.delta.citation));break}case"input_json_delta":{if(s?.type==="tool_use"){let o=s[pr]||"";o+=t.delta.partial_json,Object.defineProperty(s,pr,{value:o,enumerable:!1,writable:!0}),o&&(s.input=St(o))}break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new j(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var H=class extends C{constructor(){super(...arguments),this.batches=new ae(this._client)}create(e,t){return e.model in mr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${mr[e.model]}
|
|
12
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}stream(e,t){return Bt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},mr={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};H.Batches=ae;H.MessageBatchesPage=ge;c();var Y=class extends C{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return I(e)?this.list({},e):this._client.getAPIList("/v1/models",ce,{query:e,...t})}},ce=class extends N{};Y.ModelInfosPage=ce;var gr,b=class extends bt{constructor({baseURL:e=wt("ANTHROPIC_BASE_URL"),apiKey:t=wt("ANTHROPIC_API_KEY")??null,authToken:n=wt("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){let o={apiKey:t,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&ar())throw new h(`It looks like you're running in a browser-like environment.
|
|
13
|
-
|
|
14
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
15
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
16
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
17
|
-
|
|
18
|
-
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
19
|
-
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new ie(this),this.messages=new H(this),this.models=new Y(this),this.beta=new D(this),this._options=o,this.apiKey=t,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(e){let t=this.apiKeyAuth(e),n=this.bearerAuth(e);return t!=null&&!De(t)?t:n!=null&&!De(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};gr=b;b.Anthropic=gr;b.HUMAN_PROMPT=`
|
|
20
|
-
|
|
21
|
-
Human:`;b.AI_PROMPT=`
|
|
22
|
-
|
|
23
|
-
Assistant:`;b.DEFAULT_TIMEOUT=6e5;b.AnthropicError=h;b.APIError=k;b.APIConnectionError=X;b.APIConnectionTimeoutError=ue;b.APIUserAbortError=x;b.NotFoundError=Fe;b.ConflictError=Oe;b.RateLimitError=Le;b.BadRequestError=Me;b.AuthenticationError=ve;b.InternalServerError=qe;b.PermissionDeniedError=Ie;b.UnprocessableEntityError=Be;b.toFile=Yn;b.fileFromPath=ot;b.Completions=ie;b.Messages=H;b.Models=Y;b.ModelInfosPage=ce;b.Beta=D;var{HUMAN_PROMPT:Ga,AI_PROMPT:Wa}=b,yr=b;c();c();function Qe(r){let{inputTokens:e,cacheReadTokens:t,cacheCreationTokens:n,outputTokens:s}=r,i=n===0&&t>0&&e>=t?e:e+t+n;return{promptTokenCount:i,candidatesTokenCount:s,totalTokenCount:i+s,cachedContentTokenCount:t}}var Lt=class{model;schemaCompliance;enableCacheControl;constructor(e,t="auto",n=!0){this.model=e,this.schemaCompliance=t,this.enableCacheControl=n}convertGeminiRequestToAnthropic(e,t={}){let n=[],s=this.extractTextFromContentUnion(e.config?.systemInstruction);this.processContents(e.contents,n),t.stripAssistantThinking&&this.stripThinkingFromAssistantMessages(n),t.normalizeAssistantThinkingSignature&&this.fillMissingThinkingSignatures(n),t.injectThinkingOnToolUseTurns&&this.injectEmptyThinkingOnToolUseTurns(n);let o=t.enableCacheControl??this.enableCacheControl,i=t.useGlobalCacheScope??!1,a=o?this.buildSystemWithCacheControl(s,i):s;return o&&this.addCacheControlToMessages(n),{system:a,messages:n}}async convertGeminiToolsToAnthropic(e,t={}){let n=[];for(let i of e){let a;if("tool"in i?a=await i.tool():a=i,!!a.functionDeclarations)for(let u of a.functionDeclarations){if(!u.name||!u.description)continue;let l;u.parametersJsonSchema?l={...u.parametersJsonSchema}:u.parameters&&(l=u.parameters),l||(l={type:"object",properties:{}}),l=_n(l,this.schemaCompliance),typeof l.type!="string"&&(l.type="object"),n.push({name:u.name,description:u.description,input_schema:l})}}let s=t.enableCacheControl??this.enableCacheControl,o=t.useGlobalCacheScope??!1;if(s&&n.length>0){let i=n.length-1;n[i]={...n[i],cache_control:o?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}}return n}convertAnthropicResponseToGemini(e){let t=new et,n=[];for(let i of e.content||[]){let a=String(i.type||"");if(a==="text"){let u=typeof i.text=="string"?i.text:"";u&&n.push({text:u})}else if(a==="tool_use"){let u=i;n.push({functionCall:{id:typeof u.id=="string"?u.id:void 0,name:typeof u.name=="string"?u.name:void 0,args:this.safeInputToArgs(u.input)}})}else if(a==="thinking"){let u=typeof i.thinking=="string"?i.thinking:"",l=typeof i.signature=="string"?i.signature:"";if(u||l){let m={text:u,thought:!0,thoughtSignature:l};n.push(m)}}else a==="redacted_thinking"&&n.push({text:"",thought:!0})}let s={content:{parts:n,role:"model"},index:0,safetyRatings:[]},o=this.mapAnthropicFinishReasonToGemini(e.stop_reason);return o&&(s.finishReason=o),t.candidates=[s],t.responseId=e.id,t.createTime=Date.now().toString(),t.modelVersion=e.model||this.model,t.promptFeedback={safetyRatings:[]},e.usage&&(t.usageMetadata=Qe({inputTokens:e.usage.input_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreationTokens:e.usage.cache_creation_input_tokens||0,outputTokens:e.usage.output_tokens||0})),t}processContents(e,t){if(Array.isArray(e))for(let n of e)this.processContent(n,t);else e&&this.processContent(e,t)}processContent(e,t){if(typeof e=="string"){t.push({role:"user",content:[{type:"text",text:e}]});return}if(!this.isContentObject(e))return;let n=e.parts||[],s=e.role==="model"?"assistant":"user",o=[],i=0;for(let a of n){if(typeof a=="string"){o.push({type:"text",text:a});continue}if("text"in a&&"thought"in a&&a.thought&&s==="assistant"){let l={type:"thinking",thinking:a.text||""};"thoughtSignature"in a&&typeof a.thoughtSignature=="string"&&(l.signature=a.thoughtSignature),o.push(l)}"text"in a&&a.text&&!("thought"in a&&a.thought)&&o.push({type:"text",text:a.text});let u=this.createMediaBlockFromPart(a);if(u&&o.push(u),"functionCall"in a&&a.functionCall&&s==="assistant"&&(o.push({type:"tool_use",id:a.functionCall.id||`tool_${i}`,name:a.functionCall.name||"",input:a.functionCall.args||{}}),i+=1),a.functionResponse){let l=this.createToolResultBlock(a.functionResponse);l&&s==="user"&&o.push(l)}}o.length>0&&t.push({role:s,content:o})}createToolResultBlock(e){let t=this.extractFunctionResponseContent(e.response),n=[];for(let o of e.parts||[]){let i=this.createMediaBlockFromPart(o);i&&n.push(i)}let s;if(n.length>0){let o=[];t&&o.push({type:"text",text:t}),o.push(...n),s=o}else s=t;return{type:"tool_result",tool_use_id:e.id||"",content:s}}createMediaBlockFromPart(e){if(e.inlineData?.mimeType&&e.inlineData?.data){if(this.isSupportedAnthropicImageMimeType(e.inlineData.mimeType))return{type:"image",source:{type:"base64",media_type:e.inlineData.mimeType,data:e.inlineData.data}};if(e.inlineData.mimeType==="application/pdf")return{type:"document",source:{type:"base64",media_type:"application/pdf",data:e.inlineData.data}};let t=e.inlineData.displayName?` (${e.inlineData.displayName})`:"";return{type:"text",text:`Unsupported inline media type: ${e.inlineData.mimeType}${t}.`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let t=e.fileData.displayName?` (${e.fileData.displayName})`:"",n=e.fileData.fileUri;return this.isSupportedAnthropicImageMimeType(e.fileData.mimeType)?{type:"image",source:{type:"url",url:n}}:e.fileData.mimeType==="application/pdf"?{type:"document",source:{type:"url",url:n}}:{type:"text",text:`Unsupported file media type: ${e.fileData.mimeType}${t}.`}}return null}isSupportedAnthropicImageMimeType(e){return e==="image/jpeg"||e==="image/png"||e==="image/gif"||e==="image/webp"}extractTextFromContentUnion(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.extractTextFromContentUnion(t)).filter(Boolean).join(`
|
|
24
|
-
`):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
25
|
-
`)||""}extractFunctionResponseContent(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let s=t.error;if(typeof s=="string")return s}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}safeInputToArgs(e){return e&&typeof e=="object"?e:typeof e=="string"?tt(e,{}):{}}mapAnthropicFinishReasonToGemini(e){return e?{end_turn:Z.STOP,stop_sequence:Z.STOP,tool_use:Z.STOP,max_tokens:Z.MAX_TOKENS,content_filter:Z.SAFETY}[e]||Z.FINISH_REASON_UNSPECIFIED:void 0}isContentObject(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}buildSystemWithCacheControl(e,t){return e&&[{type:"text",text:e,cache_control:t?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}]}stripThinkingFromAssistantMessages(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content.filter(s=>{let o=s.type;return o!=="thinking"&&o!=="redacted_thinking"});n.length!==0&&n.length!==t.content.length&&(t.content=n)}}fillMissingThinkingSignatures(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=!1,s=t.content.map(o=>{let i=o;return i.type==="thinking"&&typeof i.signature!="string"?(n=!0,{...o,signature:""}):o});n&&(t.content=s)}}injectEmptyThinkingOnToolUseTurns(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content;if(!n.some(a=>a.type==="tool_use")||n.some(a=>{let u=a.type;return u==="thinking"||u==="redacted_thinking"}))continue;let i={type:"thinking",thinking:"",signature:""};t.content=[i,...n]}}addCacheControlToMessages(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"){let s=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];if(s.length>0){let o=s[s.length-1];if(typeof o=="object"&&"type"in o){let i=o.type,a=i==="text"&&(!("text"in o)||!o.text);(i==="text"||i==="tool_result")&&!a&&(o.cache_control={type:"ephemeral"})}n.content=s}break}}}};var yn=bn("ANTHROPIC");function _r(r){let e=r.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function vs(r){return _r(r)?!0:(r.model??"").toLowerCase().includes("deepseek")}function Is(r){let e=r.baseUrl?.trim();if(e)return e;let t=process.env.ANTHROPIC_BASE_URL?.trim();return t||"https://api.anthropic.com"}function br(r){try{let e=new URL(Is(r)).hostname.toLowerCase();return e==="api.anthropic.com"||e.endsWith(".anthropic.com")}catch{return!1}}var Ye=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t;let n=!br(e),s=this.buildHeaders(n),o=e.baseUrl,i=xn("anthropic",this.cliConfig.getProxy());this.client=new yr({...n?{authToken:e.apiKey,apiKey:null}:{apiKey:e.apiKey,authToken:null},baseURL:o,timeout:e.timeout||6e5,maxRetries:e.maxRetries,defaultHeaders:s,...i}),this.converter=new Lt(e.model,e.schemaCompliance,e.enableCacheControl)}client;converter;effortClampWarned=!1;async generateContent(e){let t;try{let n=await this.buildRequest(e);nt.recordAnthropicWireRequest(n);let s=this.buildPerRequestHeaders(n);t=await this.client.messages.create(n,{signal:e.config?.abortSignal,...s?{headers:s}:{}})}catch(n){throw _e(n)}return this.converter.convertAnthropicResponseToGemini(t)}async generateContentStream(e){let t=await this.buildRequest(e),n=this.buildPerRequestHeaders(t),s={...t,stream:!0};nt.recordAnthropicWireRequest(s);let o;try{o=await this.client.messages.create(s,{signal:e.config?.abortSignal,...n?{headers:n}:{}})}catch(i){throw _e(i)}return this.processStreamWithEmptyFallback(this.redactStreamErrors(o),t,e.config?.abortSignal,n)}async countTokens(e){try{return{totalTokens:(await new Tn().calculateTokens(e)).totalTokens}}catch(t){yn.warn("Failed to calculate tokens with tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){throw new Error("Anthropic does not support embeddings.")}useSummarizedThinking(){return!1}buildHeaders(e){let t=this.cliConfig.getCliVersion()||"unknown",n=e?`claude-cli/${t} (external, cli)`:`MatildaCode/${t} (${process.platform}; ${process.arch})`,{customHeaders:s}=this.contentGeneratorConfig,o={"User-Agent":n};if(e&&(o["x-app"]="cli"),s)for(let[i,a]of Object.entries(s))i.toLowerCase()==="anthropic-beta"||Cn(i)||(o[i]=a);return o}buildPerRequestHeaders(e){let t=[];for(let s of this.collectCustomBetaFlags())t.push(s);return e.thinking&&t.push("interleaved-thinking-2025-05-14"),e.output_config&&t.push("effort-2025-11-24"),this.hasGlobalCacheScopeOnWire(e)&&t.push("prompt-caching-scope-2026-01-05"),t.length===0?void 0:{"anthropic-beta":Array.from(new Set(t)).join(",")}}useGlobalCacheScope(){return this.contentGeneratorConfig.enableCacheControl!==!1&&br(this.contentGeneratorConfig)}hasGlobalCacheScopeOnWire(e){let t=n=>{if(!n||typeof n!="object")return!1;let s=n.cache_control;return!s||typeof s!="object"?!1:s.scope==="global"};if(Array.isArray(e.system)){for(let n of e.system)if(t(n))return!0}if(Array.isArray(e.tools)){for(let n of e.tools)if(t(n))return!0}return!1}collectCustomBetaFlags(){let e=this.contentGeneratorConfig.customHeaders;if(!e)return[];let t=[];for(let[n,s]of Object.entries(e))if(n.toLowerCase()==="anthropic-beta"&&!(typeof s!="string"||!s))for(let o of s.split(",")){let i=o.trim();i&&t.push(i)}return t}async buildRequest(e){let t=this.buildSamplingParameters(e),n=this.resolveEffectiveEffort(e),s=this.buildThinkingConfig(e,n),o=this.buildOutputConfig(e,n),i=vs(this.contentGeneratorConfig),a=i&&!!s,u=i&&!s,l=this.contentGeneratorConfig.enableCacheControl!==!1,m=this.useGlobalCacheScope(),f=e.config?.tools?await this.converter.convertGeminiToolsToAnthropic(e.config.tools,{enableCacheControl:l,useGlobalCacheScope:m}):void 0,_=m&&!!f&&f.length>0,g=m&&!_,{system:S,messages:y}=this.converter.convertGeminiRequestToAnthropic(e,{normalizeAssistantThinkingSignature:a,injectThinkingOnToolUseTurns:a,stripAssistantThinking:u,enableCacheControl:l,useGlobalCacheScope:g});return{model:this.contentGeneratorConfig.model,system:S,messages:y,tools:f,...t,...s?{thinking:s}:{},...o?{output_config:o}:{}}}buildSamplingParameters(e){let t=this.contentGeneratorConfig.samplingParams,n=e.config||{},s=(m,f)=>{let _=t?.[m],g=f?n[f]:void 0;return _!==void 0?_:g},o=s("max_tokens","maxOutputTokens"),i=this.contentGeneratorConfig.model,a=kn(i,"output"),u=Sn(i),l;if(o!=null)l=u?Math.min(o,a):o;else{let m=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,f=m?parseInt(m,10):NaN;!isNaN(f)&&f>0?l=u?Math.min(f,a):f:l=Math.min(a,8e3)}return{max_tokens:l,temperature:s("temperature","temperature")??1,top_p:s("top_p","topP"),top_k:s("top_k","topK")}}resolveEffectiveEffort(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let t=this.contentGeneratorConfig.reasoning;if(t===!1||t===void 0)return;let n=t.effort;if(n!==void 0)return n==="max"&&!_r(this.contentGeneratorConfig)?(this.effortClampWarned||(yn.warn("reasoning.effort='max' is a DeepSeek extension; clamping to 'high' for non-DeepSeek anthropic provider to avoid HTTP 400."),this.effortClampWarned=!0),"high"):n}modelSupportsAdaptiveThinking(){let t=(this.contentGeneratorConfig.model||"").toLowerCase().match(/claude-(?:opus|sonnet|haiku)-(\d+)-(\d+)/);if(!t)return!1;let n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);return n>4||n===4&&s>=6}buildThinkingConfig(e,t){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let n=this.contentGeneratorConfig.reasoning;return n===!1?void 0:n?.budget_tokens!==void 0?{type:"enabled",budget_tokens:n.budget_tokens}:this.modelSupportsAdaptiveThinking()?{type:"adaptive"}:{type:"enabled",budget_tokens:t==="low"?16e3:t==="max"?128e3:t==="high"?64e3:32e3}}buildOutputConfig(e,t){if(t!==void 0)return{effort:t}}async*redactStreamErrors(e){try{for await(let t of e)yield t}catch(t){throw _e(t)}}async*processStream(e){let t,n=this.contentGeneratorConfig.model,s=0,o=0,i=0,a=0,u,l=new Map,m=[];for await(let f of e)switch(f.type){case"message_start":{t=f.message.id??t,n=f.message.model??n,s=f.message.usage?.cache_read_input_tokens??s,o=f.message.usage?.cache_creation_input_tokens??o,i=f.message.usage?.input_tokens??i;break}case"content_block_start":{let _=f.index??0,g=String(f.content_block.type||"text"),S=g==="tool_use"&&"input"in f.content_block?JSON.stringify(f.content_block.input):"";l.set(_,{type:g,id:"id"in f.content_block?f.content_block.id:void 0,name:"name"in f.content_block?f.content_block.name:void 0,inputJson:S!=="{}"?S:"",signature:g==="thinking"&&"signature"in f.content_block&&typeof f.content_block.signature=="string"?f.content_block.signature:""});break}case"content_block_delta":{let _=f.index??0,g=f.delta.type||"",S=l.get(_);if(g==="text_delta"){let y="text"in f.delta?f.delta.text:"";if(y){let M=this.buildGeminiChunk({text:y},t,n);m.push(M),yield M}}else if(g==="thinking_delta"){let y=f.delta.thinking||"";if(y){let M=this.buildGeminiChunk({text:y,thought:!0},t,n);m.push(M),yield M}}else if(g==="signature_delta"&&S){let y=f.delta.signature||"";if(y){S.signature+=y;let M=this.buildGeminiChunk({thought:!0,thoughtSignature:y},t,n);m.push(M),yield M}}else if(g==="input_json_delta"&&S){let y=f.delta.partial_json||"";y&&(S.inputJson+=y)}break}case"content_block_stop":{let _=f.index??0,g=l.get(_);if(g?.type==="tool_use"){let S=tt(g.inputJson||"{}",{}),y=this.buildGeminiChunk({functionCall:{id:g.id,name:g.name,args:S}},t,n);m.push(y),yield y}l.delete(_);break}case"message_delta":{let _=f.delta.stop_reason;_&&(u=_);let g=f.usage,S=g&&typeof g=="object"?g:void 0;if(f.usage?.output_tokens!==void 0&&(a=f.usage.output_tokens),S?.input_tokens!==void 0){let y=S.input_tokens;typeof y=="number"&&(i=y)}if(S?.cache_read_input_tokens!==void 0){let y=S.cache_read_input_tokens;typeof y=="number"&&(s=y)}if(S?.cache_creation_input_tokens!==void 0){let y=S.cache_creation_input_tokens;typeof y=="number"&&(o=y)}if(u||f.usage){let y=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(y),yield y}break}case"message_stop":{if(i||a){let _=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(_),yield _}break}default:break}}async*processStreamWithEmptyFallback(e,t,n,s){let o=!1,i=!1;for await(let u of this.processStream(e)){let l=u.candidates??[];i||=l.some(m=>m.finishReason!==void 0),o||=l.some(m=>m.content?.parts?.some(f=>f.text||f.thought||f.thoughtSignature||f.functionCall)),yield u}if(o||i)return;yn.warn("Anthropic stream ended without assistant payload or finish reason; probing once with a non-streaming request to surface provider errors.");let a;try{nt.recordAnthropicWireRequest(t),a=await this.client.messages.create(t,{signal:n,...s?{headers:s}:{}}),yield this.converter.convertAnthropicResponseToGemini(a)}catch(u){throw _e(u)}}buildGeminiChunk(e,t,n,s,o){let i=new et;i.responseId=t,i.createTime=Date.now().toString(),i.modelVersion=n||this.contentGeneratorConfig.model,i.promptFeedback={safetyRatings:[]};let a=e?[e]:[],u=s!==void 0?this.converter.mapAnthropicFinishReasonToGemini(s):void 0;return i.candidates=[{content:{parts:a,role:"model"},index:0,safetyRatings:[],...u?{finishReason:u}:{}}],o&&(i.usageMetadata=o),i}};function gc(r,e){return new Ye(r,e)}export{Ye as AnthropicContentGenerator,gc as createAnthropicContentGenerator};
|
|
26
|
-
/**
|
|
27
|
-
* @license
|
|
28
|
-
* Copyright 2025 Matilda
|
|
29
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
30
|
-
*/
|
|
31
|
-
/*! Bundled license information:
|
|
32
|
-
|
|
33
|
-
humanize-ms/index.js:
|
|
34
|
-
(*!
|
|
35
|
-
* humanize-ms - index.js
|
|
36
|
-
* Copyright(c) 2014 dead_horse <dead_horse@qq.com>
|
|
37
|
-
* MIT Licensed
|
|
38
|
-
*)
|
|
39
|
-
*/
|
package/chunks/chunk-2XZIKUB6.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Bb as C,Pa as Te,Ra as ge,a as c,ab as L,na as M}from"./chunk-CFBZKYFB.js";import{P as U,R as h,j as O}from"./chunk-QWBNNEV2.js";import{b,c as u,f as I,g as A,h as f,i as v,k as w,l as m,n as y}from"./chunk-FWDMPRKU.js";import{b as l}from"./chunk-GZPNIYVZ.js";import{f as Ee}from"./chunk-OWGSC52X.js";l();l();y();ge();l();y();var B=Ee(Te(),1);import{createHash as fe}from"node:crypto";var S="matilda.telemetry.traceparent",D="matilda.telemetry.tracestate",Se="matilda-code.daemon.request",H="matilda-code.daemon.bridge",Ae="matilda-code.daemon.error";function ye(e){return e instanceof Error?e.message:String(e)}function Ce(e){return e instanceof Error?e.name||"Error":typeof e}var Re="0".repeat(32),_e="0".repeat(16);function ve(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t=e;if(!(S in t)&&!(D in t))return{...t};let r={...t};return delete r[S],delete r[D],r}function De(e){return fe("sha256").update(e).digest("hex").slice(0,16)}async function k(e,t,r,n={}){if(!C())return await r(void 0);let o=n.autoOkOnSuccess??!0;return await m.getTracer(c).startActiveSpan(e,{kind:I.INTERNAL,attributes:t},async s=>{try{let a=await r(s);return o&&s.setStatus({code:A.OK}),a}catch(a){throw F(s,a),a}finally{s.end()}})}async function xe(e,t){return await k(Se,{"http.request.method":e.method,"http.route":e.route,"matilda-code.daemon.operation":"http_request",...e.workspaceHash?{"matilda-code.workspace.hash":e.workspaceHash}:{},...e.sessionId?{"session.id":e.sessionId}:{},...e.clientId?{"matilda-code.client_id":e.clientId}:{},...e.permissionRequestId?{"matilda-code.daemon.permission.request_id":e.permissionRequestId}:{}},t,{autoOkOnSuccess:!1})}async function q(e,t,r){return await k(H,{"matilda-code.daemon.operation":e,...t},async()=>await r())}function Oe(e,t){try{e?.setAttribute("http.response.status_code",t)}catch{}}function be(e,t){try{m.getSpan(f.active())?.setAttribute(e,t)}catch{}}function F(e,t,r={}){let n=e??m.getSpan(f.active());if(n)try{let o=L(ye(t));n.recordException(t instanceof Error?t:new Error(o)),n.setAttributes({"error.type":Ce(t),"error.message":o,...r}),n.setStatus({code:A.ERROR,message:o})}catch{}}function Ie(e,t={},r){if(C())try{B.logs.getLogger(c).emit({body:e,timestamp:new Date,attributes:{"event.name":r?.eventName??Ae,...t},...r?.severityNumber!=null?{severityNumber:r.severityNumber}:{}})}catch{}}function $(){return{context:f.active()}}async function W(e,t){let r=e&&typeof e=="object"&&"context"in e&&e.context?e.context:void 0;return r?await f.with(r,t):await t()}function j(e){let t=e._meta,r=ve(t);try{let n=U();n&&(r[S]=h(n))}catch{}return!t&&!r[S]?e:{...e,_meta:r}}function he(e){let t=e?._meta;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t,n=r[S];if(typeof n!="string"||n.length===0)return;let o={traceparent:n},i=r[D];typeof i=="string"&&i.length>0&&(o.tracestate=i);let s=w.extract(b,o);if(m.getSpanContext(s))return s;let a=n.split("-"),d=a[1],p=a[2],_=a[3];if(!(a[0]!=="00"||!d?.match(/^[0-9a-f]{32}$/)||!p?.match(/^[0-9a-f]{16}$/)||!_?.match(/^[0-9a-f]{2}$/)||d===Re||p===_e))return m.setSpan(b,m.wrapSpanContext({traceId:d,spanId:p,traceFlags:Number.parseInt(_,16),isRemote:!0}))}function Me(){return{captureContext:$,runWithContext:W,withSpan:q,event(e,t){if(C())try{let r=m.getSpan(f.active());if(r){r.addEvent(e,t);return}let n=m.getTracer(c).startSpan(H,{kind:I.INTERNAL,attributes:{"event.name":e,"matilda-code.daemon.operation":`event.${e}`,...t}});n.addEvent(e,t),n.setStatus({code:A.OK}),n.end()}catch{}},injectPromptContext:j}}l();y();var Le=`${c}.daemon.http.request.count`,ke=`${c}.daemon.http.request.duration`,Pe=`${c}.daemon.session.active`,Ne=`${c}.daemon.session.lifecycle`,we=`${c}.daemon.channel.lifecycle`,Ue=`${c}.daemon.prompt.queue_wait`,Be=`${c}.daemon.prompt.duration`,He=`${c}.daemon.bridge.error.count`,qe=`${c}.daemon.cancel.count`,Fe=`${c}.daemon.sse.active`,$e=`${c}.daemon.process.heap_used`,We=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),E=!1,Y,G,K,z,Q,X,J,Z;function je(e){let t=e instanceof Error?e.name:typeof e;return We.has(t)?t:"unknown"}function Ve(){if(E)return;let e=M();e&&(Y=e.createCounter(Le,{description:"Daemon HTTP request count by route and status class.",valueType:u.INT}),G=e.createHistogram(ke,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:u.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),K=e.createCounter(Ne,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:u.INT}),z=e.createCounter(we,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:u.INT}),Q=e.createHistogram(Ue,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:u.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),X=e.createHistogram(Be,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:u.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),J=e.createCounter(He,{description:"Daemon bridge error count by normalized error type.",valueType:u.INT}),Z=e.createCounter(qe,{description:"Daemon cancel request count.",valueType:u.INT}),E=!0)}var V=!1;function Ye(e){if(V)return;let t=M();t&&(t.createObservableGauge(Pe,{description:"Current number of active daemon sessions.",valueType:u.INT}).addCallback(r=>{try{r.observe(e.sessionCount())}catch{}}),t.createObservableGauge(Fe,{description:"Current number of active SSE connections.",valueType:u.INT}).addCallback(r=>{try{r.observe(e.sseCount())}catch{}}),t.createObservableGauge($e,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:u.INT}).addCallback(r=>{try{r.observe(e.heapUsed())}catch{}}),V=!0)}function Ge(e,t,r){if(!E)return;let n=`${Math.floor(r/100)}xx`;Y?.add(1,{route:t,status_class:n}),G?.record(e,{route:t})}function Ke(e){E&&K?.add(1,{action:e})}function ze(e,t){E&&z?.add(1,{action:e,...t!=null?{expected:t}:{}})}function Qe(e){E&&Q?.record(e)}function Xe(e){E&&X?.record(e)}function Je(e){E&&J?.add(1,{error_type:je(e)})}function Ze(){E&&Z?.add(1)}l();y();var et=3e3,tt=64,rt=64,nt=100,ot=1e3;function it(e){return`${new URL(e).origin}/api/client-events`}function st(e){let t={eventType:e.eventType,platform:"cli",clientTimestamp:e.clientTimestamp??new Date().toISOString()};return e.traceId&&(t.traceId=e.traceId.slice(0,tt)),e.supportRef&&(t.supportRef=e.supportRef.slice(0,rt)),typeof e.status=="number"&&(t.status=e.status),e.errorClass&&(t.errorClass=e.errorClass.slice(0,nt)),e.rawError&&(t.rawError=e.rawError.slice(0,ot)),e.appVersion&&(t.appVersion=e.appVersion),e.sessionId&&(t.sessionId=e.sessionId),t}async function at(e,t){let{baseUrl:r,token:n}=t;if(!r||!n)return;let o=t.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),t.timeoutMs??et);try{let a=await o(it(r),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${n}`},body:JSON.stringify(st(e)),signal:i.signal});a.ok||v.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`)}catch{}finally{clearTimeout(s)}}var te=(r=>(r.GCP="gcp",r.LOCAL="local",r))(te||{}),Vn="local",Yn="http://localhost:4317";l();y();var ut=new Set(["service.version","service.instance.id","session.id"]);function T(e,t){v.warn(e),t?.push(e)}function re(e,t){if(!e)return{};let r={};for(let n of e.split(",")){let o=n.trim();if(!o)continue;let i=o.indexOf("=");if(i<0){T(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${o}" (hint: percent-encode literal commas as %2C)`,t);continue}let s=o.slice(0,i).trim();if(!s)continue;let a=o.slice(i+1).trim(),d;try{d=decodeURIComponent(s)}catch{T(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),d=s}let p;try{p=decodeURIComponent(a)}catch{T(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${d}", using raw value`,t),p=a}r[d]=p}return r}function P(e,t,r){for(let n of ut)n in e&&(T(`${t} cannot override reserved key "${n}"; ignoring`,r),delete e[n]);return e}function ne(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))return T("settings.telemetry.resourceAttributes must be an object; ignoring",t),{};let r={};for(let[n,o]of Object.entries(e)){let i=n.trim();if(!i){T("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",t);continue}typeof o=="string"?r[i]=o:T(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof o}); ignoring`,t)}return r}function R(e){if(e!==void 0)return e==="true"||e==="1"}function ee(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function ct(e){let t=e.argv??{},r=e.env??{},n=e.settings??{},o=t.telemetry??R(r.MATILDA_TELEMETRY_ENABLED)??n.enabled,i=t.telemetryTarget??r.MATILDA_TELEMETRY_TARGET??n.target,s=ee(i);if(i!==void 0&&s===void 0)throw new O(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=t.telemetryOtlpEndpoint??r.MATILDA_TELEMETRY_OTLP_ENDPOINT??r.OTEL_EXPORTER_OTLP_ENDPOINT??n.otlpEndpoint,d=t.telemetryOtlpProtocol??r.MATILDA_TELEMETRY_OTLP_PROTOCOL??n.otlpProtocol,p=["grpc","http"].find(me=>me===d);if(d!==void 0&&p===void 0)throw new O(`Invalid telemetry OTLP protocol: ${String(d)}. Valid values are: grpc, http`);let _=t.telemetryLogPrompts??R(r.MATILDA_TELEMETRY_LOG_PROMPTS)??n.logPrompts,oe=R(r.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??n.includeSensitiveSpanAttributes??!1,ie=t.telemetryOutfile??r.MATILDA_TELEMETRY_OUTFILE??n.outfile,se=r.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??r.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??n.otlpTracesEndpoint,ae=r.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??r.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??n.otlpLogsEndpoint,ce=r.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??r.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??n.otlpMetricsEndpoint,g=[],ue=P(re(r.OTEL_RESOURCE_ATTRIBUTES,g),"OTEL_RESOURCE_ATTRIBUTES",g),de=P(ne(n.resourceAttributes,g),"settings.telemetry.resourceAttributes",g),x={...ue,...de},N=r.OTEL_SERVICE_NAME?.trim();N&&(x["service.name"]=N);let le=Object.keys(x).length?x:void 0,pe=R(r.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??n.metrics?.includeSessionId??!1;return{enabled:o,target:s,otlpEndpoint:a,otlpProtocol:p,otlpTracesEndpoint:se,otlpLogsEndpoint:ae,otlpMetricsEndpoint:ce,logPrompts:_,includeSensitiveSpanAttributes:oe,outfile:ie,resourceAttributes:le,metrics:{includeSessionId:pe},resourceAttributeWarnings:g.length?g:void 0}}export{R as a,ee as b,ct as c,S as d,D as e,De as f,k as g,xe as h,q as i,Oe as j,be as k,F as l,Ie as m,$ as n,W as o,j as p,he as q,Me as r,Ve as s,Ye as t,Ge as u,Ke as v,ze as w,Qe as x,Xe as y,Je as z,Ze as A,at as B,te as C,Vn as D,Yn as E};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
|
9
|
-
/**
|
|
10
|
-
* @license
|
|
11
|
-
* Copyright 2026 Matilda
|
|
12
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
13
|
-
*/
|
|
14
|
-
/**
|
|
15
|
-
* @license
|
|
16
|
-
* Copyright 2025 Google LLC
|
|
17
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
18
|
-
*/
|
package/chunks/chunk-6V6R7SFP.js
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as L,d as ct}from"./chunk-4F4DA5UI.js";import{a as pt,b as Ee,c as gt,d as ft}from"./chunk-DC7LAFZZ.js";import{a as st,b as lt,e as Pe,n as ut,q as B,r as ht}from"./chunk-XYA3SFGC.js";import{b as A,e as K}from"./chunk-4J6DC24J.js";import{a as dt}from"./chunk-XJDC3ZQZ.js";import{Jc as it,Kc as rt,Mb as tt,Mc as at,Pb as nt,Rb as ot,Sa as F,Wa as ke,Xa as xe,Ya as we,eb as Re,f as P,fb as $,tb as te,ub as ne}from"./chunk-CFBZKYFB.js";import{b as mt}from"./chunk-3YLXGE6T.js";import{L as et,Y as b,c as Qe,d as H,e as V}from"./chunk-QWBNNEV2.js";import{h as x,l as be,n as Qt}from"./chunk-FWDMPRKU.js";import{b as h}from"./chunk-GZPNIYVZ.js";h();h();var oe=b("TAGGED_THINKING_PARSER"),Ct=["<think>","<thinking>"],yt=["</think>","</thinking>"],en=Math.max(...Ct.map(t=>t.length),...yt.map(t=>t.length));function Oe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function tn(t,e,n){let o=t.length-e;return o<=0||o>en?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function nn(t,e,n){return n.find(o=>t.startsWith(o,e))}var Le=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){let s=this.mode==="text"?Ct:yt,l=nn(o,a,s);if(l){oe.debug(`taggedThinking: detected tag "${l}" at offset ${a}`),Oe(i,r,this.mode),r="",this.mode=this.mode==="text"?"thought":"text",a+=l.length;continue}if(!n&&tn(o,a,s))break;r+=this.buffer[a],a+=1}return a<this.buffer.length?(Oe(i,r,this.mode),this.buffer=this.buffer.slice(a),oe.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),i):(this.buffer="",this.mode==="thought"&&r&&oe.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),Oe(i,r,this.mode),oe.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),i)}};function Tt(t){return new Le().parse(t,!0)}var w=b("CONVERTER"),bt="(attached media from previous tool call)";function kt(t){let e=t.prompt_tokens||0,n=t.completion_tokens||0,o=t.total_tokens||0,i=t.prompt_tokens_details,r=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details?.reasoning_tokens||0,s=t.usage_is_incomplete===!0||n>0&&e===0||o>0&&e===0&&n===0,l=e,d=n,c=o;return c===0&&(l>0||d>0)&&(c=l+d),{promptTokenCount:l,candidatesTokenCount:d,totalTokenCount:c,cachedContentTokenCount:r,thoughtsTokenCount:a,...s?{usageIsIncomplete:!0}:{}}}var on=64,At=1024;function Mt(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,i=n>=At&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=on?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<At&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function xt(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function rn(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=xt(r.parameters)),a&&(a=lt(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function an(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ln(t,o),dn(t.contents,o,e),o=It(o),n.cleanOrphanToolCalls&&(o=Cn(o),o=It(o)),o}function sn(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let g of o)typeof g=="string"?r.push(g):"text"in g&&g.text?"thought"in g&&g.thought?i.push(g.text):r.push(g.text):"functionCall"in g&&g.functionCall&&(a.push({id:g.functionCall.id||`call_${s}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},d=i.join("");d&&(l.reasoning_content=d),a.length>0&&(l.tool_calls=a);let c=mn(n?.finishReason),p=t.usageMetadata,u={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),f=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:f,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:u}}function ln(t,e){if(!t.config?.systemInstruction)return;let n=Rt(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function dn(t,e,n){if(Array.isArray(t))for(let o of t)St(o,e,n);else t&&St(t,e,n)}function St(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!gn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,d=new Set,c=new Set,p=[];for(let u of o){if(typeof u=="string"){r.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&i==="assistant"&&u.text&&a.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&r.push({type:"text",text:u.text});let m=wt(u,n);if(m&&i==="user"&&r.push(m),"functionCall"in u&&u.functionCall&&i==="assistant"){let f=u.functionCall.id;if(f){if(d.has(f)){w.debug(`Dropping duplicate functionCall id=${f} while converting content`);continue}d.add(f)}s.push({id:f||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&i==="user"){let f=u.functionResponse.id;if(f){if(c.has(f))continue;c.add(f)}let g=un(u.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],y=[];for(let T of g.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
|
|
4
|
-
`);g.content=T||"[media attached in following user message]",p.push(...C)}}e.push(g)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:bt},...p]}),i==="assistant"){if(r.length===0&&s.length===0&&a.length===0)return;let m={role:"assistant",content:r.filter(g=>g.type==="text").map(g=>g.text).join("")||(a.length>0?"":null)};s.length>0&&(m.tool_calls=s);let f=a.join("");f&&(m.reasoning_content=f),e.push(m);return}r.length>0&&e.push({role:"user",content:r})}function cn(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function un(t,e){let n=cn(t.response),o=[];n&&o.push({type:"text",text:n});for(let i of t.parts||[]){if("text"in i&&typeof i.text=="string"){i.text.length>0&&o.push({type:"text",text:i.text});continue}let r=wt(i,e);r&&o.push(r)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function wt(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,i=vt(o),r=t.inlineData.displayName||o;if(i==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("image",r,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:U("pdf",r,e);if(i==="audio"){if(!n.audio)return U("audio",r,e);let a=pn(o);if(a)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:a}}}return i==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("video",r,e):{type:"text",text:`Unsupported inline media type: ${o} (${r}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",i=t.fileData.fileUri,r=t.fileData.mimeType,a=vt(r);if(a==="image")return n.image?{type:"image_url",image_url:{url:i}}:U("image",o,e);if(r==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:i}}:U("pdf",o,e);if(a==="video")return n.video?{type:"video_url",video_url:{url:i}}:U("video",o,e);let s=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${r}${s}.`}}return null}function U(t,e,n){w.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
|
|
5
|
-
/extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function vt(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function pn(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function gn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Rt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Rt(e)).filter(Boolean).join(`
|
|
6
|
-
`):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
7
|
-
`)||""}function De(t,e,n=!0){return e.responseParsingOptions?.taggedThinkingTags?e.taggedThinkingParser?e.taggedThinkingParser.parse(t,n):Tt(t):t?[{text:t}]:[]}function fn(t,e){let n=t.choices?.[0],o=new K;if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let r=n.message.reasoning_content??n.message.reasoning;r&&i.push({text:r,thought:!0})}if(n.message.content&&i.push(...De(n.message.content,e)),n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a={};r.function.arguments&&(a=st(r.function.arguments,{})),i.push({functionCall:{id:r.id,name:r.function.name,args:a}})}}o.candidates=[{content:{parts:i,role:"model"},finishReason:Pt(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=kt(t.usage)),o}function hn(t,e){let n=t.choices?.[0],o=new K,i=e.toolCallParser;if(!i)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let d=n.delta?.reasoning_content??n.delta?.reasoning;if(d){let c=Mt(d,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&r.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let d=Mt(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(d||n.finish_reason)&&r.push(...De(d,e,!!n.finish_reason))}else n.finish_reason&&r.push(...De("",e,!0));if(n.delta?.tool_calls)for(let d of n.delta.tool_calls){let c=d.index??0;d.function?.arguments?i.addChunk(c,d.function.arguments,d.id,d.function.name):i.addChunk(c,"",d.id,d.function?.name)}let a=!1;if(n.finish_reason){a=i.hasIncompleteToolCalls();let d=i.getCompletedToolCalls();for(let c of d)c.name&&r.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let s=a&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:r,role:"model"},index:0,safetyRatings:[]};s&&(l.finishReason=Pt(s)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=kt(t.usage)),o}function Pt(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function mn(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Ue(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function _t(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===bt}function Cn(t){let e=[],n=new Map,o=new Map,i=new Map,r=new Set,a=new Set;for(let s=0;s<t.length;s+=1){let l=t[s];if(Ue(l)){let d=[],c=new Set;for(let C of l.tool_calls){let y=C.id;!y||a.has(y)||c.has(y)||(c.add(y),d.push(C))}let p=new Set,u=[],m=[],f=!1;for(let C=s+1;C<t.length;C+=1){let y=t[C];if(y.role==="tool"&&"tool_call_id"in y){if(!y.tool_call_id){f=!1;continue}c.has(y.tool_call_id)&&!p.has(y.tool_call_id)?(p.add(y.tool_call_id),u.push(C),f=!0):f=!1;continue}if(_t(y)){f&&m.push(C);continue}if(!(y.role==="assistant"&&!Ue(y)))break}let g=d.filter(C=>p.has(C.id));for(let C of g)a.add(C.id);n.set(s,g),o.set(s,u),i.set(s,m)}}for(let s=0;s<t.length;s+=1){if(r.has(s))continue;let l=t[s];if(Ue(l)){let d=l.reasoning_content,c=n.get(s)??[];if(c.length>0){let p={...l};p.tool_calls=c,e.push(p);for(let u of o.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}for(let u of i.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}}else if(typeof l.content=="string"&&l.content.trim()||d){let p={...l};delete p.tool_calls,e.push(p)}else w.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?w.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):_t(l)?w.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function It(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let i="tool_calls"in o?o.tool_calls||[]:[],r="tool_calls"in n?n.tool_calls||[]:[],a=o.content,s=n.content,l=Array.isArray(a)||Array.isArray(s),d;if(l){let p=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[],u=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[];d=[...p,...u]}else d=[typeof a=="string"?a:"",typeof s=="string"?s:""].filter(Boolean).join("")||null;let c=[...i,...r];o.content=d||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var ie={convertGeminiToolParametersToOpenAI:xt,convertGeminiToolsToOpenAI:rn,convertGeminiRequestToOpenAI:an,convertGeminiResponseToOpenAI:sn,convertOpenAIResponseToGemini:fn,convertOpenAIChunkToGemini:hn};h();import*as _ from"node:path";import{promises as se}from"node:fs";h();h();import yn from"crypto";var ae=new Uint8Array(256),re=ae.length;function Ge(){return re>ae.length-16&&(yn.randomFillSync(ae),re=0),ae.slice(re,re+=16)}h();var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function Et(t,e=0){return M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]}h();h();import Tn from"crypto";var Ne={randomUUID:Tn.randomUUID};function An(t,e,n){if(Ne.randomUUID&&!e&&!t)return Ne.randomUUID();t=t||{};let o=t.random||(t.rng||Ge)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return Et(o)}var Ke=An;import*as E from"os";var le=b("OPENAI_LOGGER"),Mn="########",Sn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function vn(t,e){let n=e||process.cwd();if(!t)return _.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=_.join(E.homedir(),t.slice(1)):_.isAbsolute(t)||(o=_.resolve(n,t)),_.normalize(o)}function Ot(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function _n(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function In(t){if(t)return F(t)?Ot(t):Ot(_n(t))}function bn(t){if(!t)return;let e=t.indexOf(Mn);if(e>0)return t.slice(0,e);if(Sn.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function kn(t){let e=t?.trim(),n=bn(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var W=class{logDir;initialized=!1;constructor(e,n){this.logDir=vn(e,n)}async initialize(){if(!this.initialized)try{await se.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw le.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,i){this.initialized||await this.initialize();let r=new Date().toISOString().replace(/:/g,"-"),a=Ke().slice(0,8),s=In(i),l=s?`openai-${r}-${a}-${s}.json`:`openai-${r}-${a}.json`,d=_.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:kn(i),system:{hostname:E.hostname(),platform:E.platform(),release:E.release(),nodeVersion:process.version}};try{return await se.writeFile(d,JSON.stringify(c,null,2),"utf-8"),d}catch(p){throw le.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await se.readdir(this.logDir)).filter(i=>i.startsWith("openai-")&&i.endsWith(".json")).map(i=>_.join(this.logDir,i)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(le.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await se.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw le.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Wo=new W;h();var de="$runtime|";function qo(t){let e=t;for(;e.startsWith(de);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}h();var ce=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Lt=["model","apiKey","apiKeyEnvKey","baseUrl"],ue=[...Lt,...ce],ei={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},ti={openai:ct,"matilda-oauth":L},pe=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],ni=pe.map(t=>t.id);h();h();h();h();Qt();h();import{AsyncLocalStorage as xn}from"node:async_hooks";var Ut=new xn;h();function Dt(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(wn)}function wn(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function Gt(){let t=dt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var D=b("LOGGING_CONTENT_GENERATOR"),Rn=4096,Nt="...[truncated]",Pn=Rn-Nt.length,Y=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new W(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let i=JSON.stringify(e);tt(this.config,new it(n,o,i,P.getStore()))}_logApiResponse(e,n,o,i,r,a){ot(this.config,new at(e,o,n,i,this.generatorAuthType,r,a,P.getStore()))}_logApiError(e,n,o,i,r){let a=Qe(o),s=V(o),l=o?.requestID||o?.request_id||e,d=H(o);nt(this.config,new rt({responseId:l,model:i,durationMs:n,promptId:r,authType:this.generatorAuthType,errorMessage:a,errorType:s,statusCode:d,subagentName:P.getStore()}))}safelyLogApiError(e,n,o,i,r){try{this._logApiError(e,n,o,i,r)}catch(a){D.warn("Failed to log API error:",a)}}safelyLogApiResponse(e,n,o,i,r,a){try{this._logApiResponse(e,n,o,i,r,a)}catch(s){D.warn("Failed to log API response:",s)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=Gt(),i=Re(e.model,n);try{i.setAttribute("llm_request.stream",!1)}catch{}let r=be.setSpan(x.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession();try{Pe.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),s||(ke(this.config,i,e.config?.systemInstruction),xe(this.config,i,e.config?.tools));let d=await x.with(r,async()=>{s||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),p=Date.now()-a,u=s?void 0:this.extractResponseText(c);s||we(this.config,i,u),this.safelyLogApiResponse(c.responseId??"",p,this.getClientVisibleModelId(e.model,c.modelVersion),n,c.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(m){D.warn("Failed to log OpenAI interaction:",m)}return c});return $(i,{success:!0,inputTokens:d.usageMetadata?.promptTokenCount,outputTokens:d.usageMetadata?.candidatesTokenCount,cachedInputTokens:d.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-a,responseId:d.responseId||void 0,finishReason:d.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:d.usageMetadata?.thoughtsTokenCount,subagentName:P.getStore()||void 0,...o}),d}catch(d){let c=Date.now()-a,p=e.config?.abortSignal?.aborted??!1;throw $(i,{success:!1,durationMs:c,error:p?ne:te,errorType:V(d),errorStatusCode:H(d),subagentName:P.getStore()||void 0,...o}),await x.with(r,async()=>{this.safelyLogApiError("",c,d,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,d,n)}catch(u){D.warn("Failed to log OpenAI interaction:",u)}}),d}}async generateContentStream(e,n){let o=Gt(),i=Re(e.model,n);try{i.setAttribute("llm_request.stream",!0)}catch{}let r=be.setSpan(x.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession(),d;try{Pe.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),s||(ke(this.config,i,e.config?.systemInstruction),xe(this.config,i,e.config?.tools)),d=await x.with(r,async()=>(s||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(p){let u=Date.now()-a;x.with(r,()=>this.safelyLogApiError("",u,p,e.model,n));let m=e.config?.abortSignal?.aborted??!1;$(i,{success:!1,durationMs:u,error:m?ne:te,errorType:V(p),errorStatusCode:H(p),subagentName:P.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,p,n)}catch(f){D.warn("Failed to log OpenAI interaction:",f)}throw p}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(p){D.warn("Failed to resolve OpenAI request:",p)}return x.with(r,()=>this.loggingStreamWrapper(d,a,n,e.model,c,i,r,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():Ut.run(i=>{e=i},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,i,r,a,s,l,d){let c=F(o),p=!c||!!this.openaiLogger,u=[],m="",f="",g,C=!1,y,T,S=P.getStore(),R,j=!1,Q=v=>s?x.with(s,v):v(),Zt=5*6e4,k,qe=a?()=>{j||(k!==void 0&&clearTimeout(k),k=setTimeout(()=>{try{a.setAttribute("stream.timed_out",!0)}catch{}$(a,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:S||void 0,...d}),j=!0},Zt),k.unref())}:void 0;qe?.();try{for await(let I of e){!m&&I.responseId&&(m=I.responseId),!f&&I.modelVersion&&(f=I.modelVersion),p&&u.push(I),I.usageMetadata&&(g=I.usageMetadata);let Ze=I.candidates?.[0];Ze?.finishReason&&(y=Ze.finishReason),R===void 0&&Dt(I)&&(R=Date.now()-n),qe?.(),yield I}k!==void 0&&(clearTimeout(k),k=void 0);let v=Date.now()-n,ee=p?this.consolidateGeminiResponsesForLogging(u):void 0,Xe=c?void 0:this.extractResponseText(ee);j||(Q(()=>this.safelyLogApiResponse(m,v,this.getClientVisibleModelId(i,f),o,g,Xe)),!c&&a&&we(this.config,a,Xe),await Q(()=>this.safelyLogOpenAIInteraction(r,ee,void 0,o)))}catch(v){if(C=!0,T=v,!j){let ee=Date.now()-n;Q(()=>this.safelyLogApiError(m,ee,v,this.getClientVisibleModelId(i,f),o)),await Q(()=>this.safelyLogOpenAIInteraction(r,void 0,v,o))}throw v}finally{if(k!==void 0&&clearTimeout(k),a&&!j){let v=l?.aborted??!1;$(a,{success:!C,inputTokens:g?.promptTokenCount,outputTokens:g?.candidatesTokenCount,cachedInputTokens:g?.cachedContentTokenCount,ttftMs:R,durationMs:Date.now()-n,error:C?v?ne:te:void 0,responseId:m||void 0,finishReason:y,thoughtsTokenCount:g?.thoughtsTokenCount,subagentName:S||void 0,errorType:T?V(T):void 0,errorStatusCode:T?H(T):void 0,...d})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ie.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),i={model:e.model,messages:o};return e.config?.tools&&(i.tools=await ie.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(i.temperature=e.config.temperature),e.config?.topP!==void 0&&(i.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(i.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(i.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(i.frequency_penalty=e.config.frequencyPenalty),i}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,i){if(!this.openaiLogger||!e)return;let r=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,r,o instanceof Error?o:o?new Error(String(o)):void 0,i)}async safelyLogOpenAIInteraction(e,n,o,i){try{await this.logOpenAIInteraction(e,n,o,i)}catch(r){D.warn("Failed to log OpenAI interaction:",r)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new K;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),ie.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new K,o=[],i=new Map,r,a;for(let d of e){d.usageMetadata&&(a=d.usageMetadata);let c=d.candidates?.[0];c?.finishReason&&(r=c.finishReason);let p=c?.content?.parts??[];for(let u of p){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let m=u.functionCall.id||u.functionCall.name||"tool_call",f=i.get(m),g={functionCall:u.functionCall};f!==void 0?o[f]=g:(i.set(m,o.length),o.push(g));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let s=e[e.length-1],l=s.candidates?.[0];return n.responseId=s.responseId,n.createTime=s.createTime,n.modelVersion=s.modelVersion,n.promptFeedback=s.promptFeedback,n.usageMetadata=a,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...r?{finishReason:r}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",i=!1,r=!1,a=s=>{if(i=!0,r)return;let l=Pn-o.length;if(s.length<=l){o+=s;return}o+=s.slice(0,Math.max(0,l)),r=!0};for(let s of n){if(typeof s=="string"){a(s);continue}"text"in s&&typeof s.text=="string"&&!("thought"in s&&s.thought)&&a(s.text)}if(i)return r?`${o}${Nt}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let r=o.text,a=r?String(r):"",s=a?`${a}
|
|
8
|
-
${n}`:n;return{...o,text:s}}return e}};h();function Kt(t){switch(t){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Ft(t){switch(t){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var O=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends O{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let i=e||"(unknown)",r=n||"(unknown)";super(`Missing credentials for modelProviders model '${r}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${i}[].envKey.`:`Configure modelProviders.${i}[].envKey and set that environment variable.`))}},fe=class extends O{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},he=class extends O{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},me=class extends O{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},Ce=class extends O{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},ye=class extends O{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};h();import On from"node:process";h();var $t={image:!0,pdf:!0,audio:!0,video:!0},En=[[/^gemini-3/,$t],[/^gemini-/,$t],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function J(t){let e=ut(t);for(let[n,o]of En)if(n.test(e))return{...o};return{}}h();var zt=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new Te(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||L}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),o=new Set,i=[];for(let l of n)o.has(l)||(o.add(l),i.push(l));let r=[];i.includes("matilda-oauth")&&r.push("matilda-oauth");for(let l of i)l!=="matilda-oauth"&&r.push(l);let a=this.getRuntimeModelOption(),s=[];for(let l of r)a&&a.authType===l&&s.push(a),s.push(...this.modelRegistry.getModelsForAuthType(l));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===Ee&&e?.envKey===pt&&e?.baseUrl===ft&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?Ee:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?gt:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===L){this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(i){throw this.rollbackToStateSnapshot(o),i}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=J(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=B(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let i=this.extractRuntimeModelSnapshotId(n);if(i){await this.switchToRuntimeModel(i);return}let r=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let a=e!==this.currentAuthType;this.currentAuthType=e;let s=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!s)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=r.generationConfig.model||"",d=!a&&l?this.modelRegistry.getModel(e,l,r.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,c=e!=="matilda-oauth"&&!a&&!!r.generationConfig.apiKey&&!!s.envKey&&d?.envKey===s.envKey&&d.baseUrl===s.baseUrl,p=c?r.generationConfig.apiKey:void 0,u=c?r.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,u&&(this.generationConfigSources.apiKey=t.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0;let m=a?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,m)}catch(a){throw this.rollbackToStateSnapshot(r),a}}buildRuntimeModelSnapshotId(e,n){return`${de}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(de))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of ce)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:i}=this._generationConfig;if(!(!n||!e||!o||!i)&&!this.modelRegistry.hasModel(e,n,i))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let r=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);r.apiKey=o,r.baseUrl=i,r.modelId=n;let a=this.buildRuntimeModelSnapshotId(r.authType,r.modelId);a!==r.id&&(this.runtimeModelSnapshots.delete(r.id),r.id=a,this.runtimeModelSnapshots.set(a,r),this.activeRuntimeModelSnapshotId=a),r.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of ue)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),e.envKey!==void 0){let o=On.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of ce)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=B(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=J(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),i=this.modelRegistry.getModel(n,e);return!i||!o||i.envKey!==o.envKey||i.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,r=n?this.modelRegistry.getModel(e,n,i)??this.modelRegistry.getModel(e,n):void 0;if(r){let m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==r.envKey||this._generationConfig.baseUrl!==r.baseUrl),f=o===e&&this._generationConfig.model===n&&!m,g=f?this._generationConfig.apiKey:void 0,C=f&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,y=this.generationConfigSources.baseUrl,T=f&&!!this._generationConfig.baseUrl&&(y?.kind==="cli"||y?.kind==="env"||y?.kind==="settings"),S=T?this._generationConfig.baseUrl:void 0,R=T&&y?{...y}:void 0;this.applyResolvedModelDefaults(r),f&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,s=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&s?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(e);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,...r}=this._generationConfig,a=this.currentAuthType;if(!e||!a)return;if(this.modelRegistry.hasModel(a,e,o)){this.clearRuntimeModelSnapshotForAuthType(a);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(a,e),d={id:l,authType:a,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,generationConfig:r,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,d),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let i=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let r=i;this.onModelChange&&await this.onModelChange(n.authType,r)}catch(i){throw this.rollbackToStateSnapshot(o),i}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};h();import{readFileSync as qn}from"node:fs";import{join as Xn}from"node:path";h();h();import{randomBytes as Ln,createHash as Un}from"node:crypto";function jt(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Fe(){let t=Ln(32).toString("base64url"),e=Un("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function q(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function $e(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!jt(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let i=await o.json();if(!i.issuer||!i.authorization_endpoint||!i.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:i.issuer,authorization_endpoint:i.authorization_endpoint,token_endpoint:i.token_endpoint,device_authorization_endpoint:i.device_authorization_endpoint}}h();import{promises as Ae,openSync as Dn,closeSync as Gn,unlinkSync as Ht,statSync as Nn}from"node:fs";import{dirname as Kn}from"node:path";var Fn=1e4,$n=3e4,zn=50;function ze(t){let e=async()=>{try{let i=await Ae.readFile(t,"utf8"),r=JSON.parse(i);return r&&typeof r=="object"?r:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},n=async i=>{await Ae.mkdir(Kn(t),{recursive:!0}),await Ae.writeFile(t,JSON.stringify(i,null,2),{mode:384}),await Ae.chmod(t,384).catch(()=>{})};return{store:{async get(i){return(await e())[i]??null},async set(i,r){let a=await e();a[i]=r,await n(a)},async remove(i){let r=await e();i in r&&(delete r[i],await n(r))}},lock:jn(`${t}.lock`)}}function jn(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Hn(t);try{return await n()}finally{Vn(t)}});return e=o.then(()=>{},()=>{}),o}}async function Hn(t){let e=Date.now()+Fn;for(;;)try{Gn(Dn(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Nn(t).mtimeMs>$n){Ht(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Bn(zn)}}function Vn(t){try{Ht(t)}catch{}}function Bn(t){return new Promise(e=>setTimeout(e,t))}h();var z=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function je(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,i=null,r=async()=>{let l=await t.store.get(e);if(!l)return null;try{let d=JSON.parse(l);return d.accessToken?d:null}catch{return null}},a=l=>l.expiresAt-Date.now()>o,s=l=>t.lock(async()=>{let d=await r()??l;if(d.accessToken!==l.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new z("No refresh token available \u2014 sign in again.");let c=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:d.refreshToken})});if(!c.ok){let m=await c.text().catch(()=>"");throw c.status>=400&&c.status<500&&Wn(m)==="invalid_grant"?(await t.store.remove(e),new z):new Error(`Token refresh failed (${c.status})`)}let p=await c.json(),u=q(p,d);return await t.store.set(e,JSON.stringify(u)),u.accessToken});return{async getAccessToken(l){let d=await r();if(!d)throw new z("Not signed in.");return!l?.forceRefresh&&a(d)?d.accessToken:(i||(i=s(d).finally(()=>{i=null})),i)}}}function Wn(t){try{return JSON.parse(t).error}catch{return}}h();import{createServer as Yn}from"node:http";import{randomBytes as Jn}from"node:crypto";async function He(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=f=>t.onEvent?.(f),{codeVerifier:n,codeChallenge:o}=Fe(),i=Jn(16).toString("hex"),r=t.timeoutMs??5*60*1e3,a=t.transport.successRedirect;e({type:"state",status:"idle"});let s,l,d=new Promise((f,g)=>{s=f,l=g});d.catch(()=>{});let c=Yn((f,g)=>{let C=new URL(f.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let y=C.searchParams.get("error"),T=C.searchParams.get("state"),S=C.searchParams.get("code");if(y){Vt(g,a,()=>l(new Error(`OAuth error: ${y}`)));return}if(T!==i){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){g.writeHead(400).end("Missing authorization code");return}Vt(g,a,()=>s(S))}),p=await new Promise((f,g)=>{c.once("error",g),c.listen(t.transport.port??0,"127.0.0.1",()=>{f(c.address().port)})}),u=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),r),m=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",m,{once:!0});try{let f=`http://127.0.0.1:${p}/callback`,g=new URL(t.metadata.authorization_endpoint);g.searchParams.set("client_id",t.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",f),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",i),g.searchParams.set("scope",t.scope??"openid offline_access");let C=g.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let y=await d;e({type:"state",status:"exchanging"});let T=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:y,code_verifier:n,redirect_uri:f})});if(!T.ok){let R=await T.text().catch(()=>"");throw new Error(`Token exchange failed (${T.status}): ${R}`)}let S=q(await T.json());return e({type:"state",status:"authenticated"}),S}catch(f){throw e({type:"state",status:"error"}),f}finally{clearTimeout(u),t.signal?.removeEventListener("abort",m),c.close()}}function Vt(t,e,n){t.writeHead(302,{location:e}).end(n)}var Me="matilda-code",Zn="matilda-desktop",Se="MATILDA_API_KEY",Qn="openid profile email offline_access matilda:code",eo="matilda";function X(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Bt(){return Xn(et.getGlobalMatildaDir(),"matilda-auth.json")}function Be(){return ze(Bt())}function to(t){return t==="desktop"}function ve(t){return t?.clientId?t.clientId:to(t?.channel)?Zn:Me}function Z(t){return`matilda:${t}`}function _e(t){return t===Me?[Z(t),eo]:[Z(t)]}function Ve(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function no(t,e){return X(t)===X(e)}function oo(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function io(t,e){let n=oo(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Wt(t){try{return await $e(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function N(t){try{let e=qn(Bt(),"utf8"),n=JSON.parse(e),o=ve(t);for(let i of _e(o)){let r=Ve(n[i]);if(r)return r}return null}catch{return null}}async function ro(t,e){let n=ve(e),o=Be().store;await o.set(Z(n),JSON.stringify(t));for(let i of _e(n))i!==Z(n)&&await o.remove(i);process.env[Se]=t.accessToken}async function ao(t){let e=ve(t),n=Be().store;for(let o of _e(e))await n.remove(o);delete process.env[Se]}function _r(t){let e=N(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Ir(t){let e={channel:t?.channel,clientId:t?.clientId},n=N(e);if(n?.accessToken){let o=X(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await ao(e)}async function We(t){let e=ve(t),n=Z(e),o=N({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!no(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[Se]??"";let i=X(o.baseUrl),r=await Wt(i),{store:a,lock:s}=Be(),d=await so(a,s,r.token_endpoint,o.baseUrl,e,n,t?.signal).getAccessToken({forceRefresh:t?.forceRefresh});return process.env[Se]=d,d}async function br(t){await We(t);let e=N(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function so(t,e,n,o,i,r,a){let s=_e(i);return je({tokenEndpoint:n,clientId:i,store:{get:async c=>{let p=c===r?s:[c],u=null;for(let f of p)if(u=Ve(await t.get(f)),u)break;if(!u?.accessToken)return null;let m={accessToken:u.accessToken,refreshToken:u.refreshToken,expiresAt:u.accessTokenExpiresAt};return JSON.stringify(m)},set:async(c,p)=>{let u=JSON.parse(p),m=c===r?s:[c],f={};for(let C of m){let y=Ve(await t.get(C));if(y){f=y;break}}let g={...f,accessToken:u.accessToken,accessTokenExpiresAt:u.expiresAt,refreshToken:u.refreshToken??f.refreshToken??"",baseUrl:f.baseUrl??o};await t.set(r,JSON.stringify(g));for(let C of s)C!==r&&await t.remove(C)},remove:async c=>{let p=c===r?s:[c];for(let u of p)await t.remove(u)}},storageKey:r,lock:e,fetchImpl:(c,p)=>fetch(c,{...p,signal:a}),expirySkewMs:3e5})}function lo(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&mt()}async function kr(t){let e=X(t.baseUrl),n=await Wt(e),o="",i=s=>He({metadata:n,clientId:Me,scope:s,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Me)}`},signal:t.signal,onEvent:l=>{l.type==="authorize_url"&&(o=l.url,t.onAuthorizeUrl?.(l.url))},openBrowser:async l=>{if(!(t.openBrowser===!1||!lo()))try{let{default:d}=await import("./open-QQ7FWG4A.js");(await d(l)).once("error",()=>{})}catch{}}}),r;try{r=await i(Qn)}catch(s){if(s instanceof Error&&s.message.includes("invalid_scope"))r=await i("openid offline_access");else throw s}let a=io(r,t.baseUrl);return await ro(a),{...a,authorizeUrl:o}}var G=(r=>(r.USE_OPENAI="openai",r.MATILDA_OAUTH="matilda-oauth",r.USE_GEMINI="gemini",r.USE_VERTEX_AI="vertex-ai",r.USE_ANTHROPIC="anthropic",r))(G||{}),co="MATILDA_AGENT_SDK",Ie="MATILDA_API_KEY";function uo(t,e){if(t.apiKey||t.apiKeyEnvKey!==Ie)return;let n=N({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[Ie]=n.accessToken)}async function po(t,e){if(t.apiKeyEnvKey!==Ie)return;let n=N({channel:e});if(!n?.accessToken)return;let o=await We({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[Ie]=o)}function go(t){return t.matildaAgentSdk===!0||process.env[co]==="1"}function Ye(t,e,n){t[e]=n}function fo(t,e){return t?.[e]}function ho(t,e,n,o,i){let r={...o||{}},a=i?.strictModelProvider===!0,s={...n||{},authType:e,proxy:t?.getProxy()};Ye(r,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Ye(r,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>fo(o,c)??{kind:"unknown"};for(let c of ue)n&&c in n&&!r[c]&&Ye(r,c,l(c));uo(s,t.getChannel());let d=Jt(s,a);if(!d.valid)throw new Error(d.errors.map(c=>c.message).join(`
|
|
9
|
-
`));return{config:s,sources:r}}function Jt(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new ge(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Kt(t.authType);n.push(new he({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new fe(t.authType));else{let o=Ft(t.authType);n.push(new me({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new Ce({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new ye)),{valid:n.length===0,errors:n}}function Lr(t,e,n){return ho(t,e,n).config}function Yt(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function Ur(t,e,n){await po(t,e.getChannel());let o=Jt(t,!1);if(!o.valid)throw new Error(o.errors.map(a=>a.message).join(`
|
|
10
|
-
`));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(go(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-4B4MMKWH.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-DMT4SZML.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-4BGLGEWH.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Yt(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-ATLOKYPR.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-WF3CO3CH.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Yt(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
|
|
11
|
-
Please exit and restart Matilda to use the '${i}' provider.`,{cause:s}):a}return new Y(r,e,t)}var Je=b("MODEL_REGISTRY");function qt(t){if(Object.values(G).includes(t))return t}function mo(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function Xt(t,e){return e?`${t}\0${e}`:t}var Te=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return ht;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",pe),e)for(let[n,o]of Object.entries(e)){let i=qt(n);if(!i){Je.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let i of n){let r=Xt(i.id,i.baseUrl);if(o.has(r)){Je.warn(`Duplicate model id "${i.id}"${i.baseUrl?` with baseUrl "${i.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let a=this.resolveModelConfig(i,e);o.set(r,a)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??B(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let i=this.modelsByAuthType.get(e);if(!i)return;if(o)return i.get(Xt(n,o));let r=i.get(n);if(r)return r;for(let a of i.values())if(a.id===n)return a}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,L);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||mo(e.id))&&(o.modalities=J(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let i=qt(n);if(!i){Je.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}};export{Le as a,ie as b,Ut as c,vn as d,W as e,Wo as f,J as g,de as h,qo as i,ce as j,ei as k,ti as l,pe as m,ni as n,Xt as o,Te as p,zt as q,Bt as r,N as s,ro as t,ao as u,_r as v,Ir as w,We as x,br as y,lo as z,kr as A,G as B,ho as C,Jt as D,Lr as E,Ur as F};
|
|
12
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2025 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2025 Google LLC
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* @license
|
|
24
|
-
* Copyright 2025 Matilda Team
|
|
25
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
26
|
-
*/
|
|
27
|
-
/**
|
|
28
|
-
* @license
|
|
29
|
-
* Copyright 2026 Matilda Team
|
|
30
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
31
|
-
*/
|
|
32
|
-
/**
|
|
33
|
-
* @license
|
|
34
|
-
* Copyright 2026 Maincode
|
|
35
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
36
|
-
*
|
|
37
|
-
* Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
|
|
38
|
-
* (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
|
|
39
|
-
* grant, and refresh. Vendored (as source) from matilda-core's
|
|
40
|
-
* `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
|
|
41
|
-
* (display identity) that the higher-level flows need. Node built-ins only —
|
|
42
|
-
* no third-party runtime dependencies.
|
|
43
|
-
*/
|
|
44
|
-
/**
|
|
45
|
-
* @license
|
|
46
|
-
* Copyright 2026 Maincode
|
|
47
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
48
|
-
*
|
|
49
|
-
* File-backed token store + cross-process lock. The store persists a JSON map
|
|
50
|
-
* (`{ [key]: value }`) at 0600 so callers can key several credentials in one
|
|
51
|
-
* file; the lock is an O_EXCL lockfile that serialises refreshes across
|
|
52
|
-
* processes (the guarantee a plaintext read/modify/write can't give).
|
|
53
|
-
*/
|
|
54
|
-
/**
|
|
55
|
-
* @license
|
|
56
|
-
* Copyright 2026 Maincode
|
|
57
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
58
|
-
*
|
|
59
|
-
* Hardened access-token manager: returns a valid access token, refreshing via
|
|
60
|
-
* core-auth's token endpoint when expired or forced. Single-flight within the
|
|
61
|
-
* process, serialised across processes by the store's lock, carries a prior
|
|
62
|
-
* refresh token forward when the response omits one, and evicts on a terminal
|
|
63
|
-
* `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
|
|
64
|
-
*/
|
|
65
|
-
/**
|
|
66
|
-
* @license
|
|
67
|
-
* Copyright 2026 Maincode
|
|
68
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
69
|
-
*
|
|
70
|
-
* Browser login orchestration: PKCE + a loopback capture server, driven off
|
|
71
|
-
* discovery metadata. Unlike a bare loopback helper, this emits lifecycle
|
|
72
|
-
* events for a UI, honours an AbortSignal, and — instead of serving its own
|
|
73
|
-
* HTML — 302-redirects the browser to an app-owned branded landing
|
|
74
|
-
* (`successRedirect`). Returns a TokenSet including the `id_token`.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* @license
|
|
78
|
-
* Copyright 2026 Maincode
|
|
79
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
80
|
-
*
|
|
81
|
-
* Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
|
|
82
|
-
* Re-exports the OAuth primitives plus the higher-level login flow, file token
|
|
83
|
-
* store, and hardened token manager that the CLI (`packages/core`) and the
|
|
84
|
-
* Electron desktop app consume.
|
|
85
|
-
*/
|
|
86
|
-
/**
|
|
87
|
-
* @license
|
|
88
|
-
* Copyright 2026 Maincode
|
|
89
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
90
|
-
*
|
|
91
|
-
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
92
|
-
*
|
|
93
|
-
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
94
|
-
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
95
|
-
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
96
|
-
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
97
|
-
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
98
|
-
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
99
|
-
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
100
|
-
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
101
|
-
*/
|
package/chunks/chunk-ISW2QC5B.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{s as d}from"./chunk-XYA3SFGC.js";import{d as s}from"./chunk-XJDC3ZQZ.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();var u=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],p=new Set([...u,...s]),E=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",a="(?:0|[1-9]\\d{0,4})",c="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",f=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${a}$`),new RegExp(`^${o}-maincode\\.${c}(?:\\.${a})?$`)],l=41;function R(e){return e==="desktop"?"desktop":e===void 0||E.has(e)?"code_cli":"unknown"}function m(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function _(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>l||!f.some(n=>n.test(t))))return t}function C(e,t=process.platform){let n=R(e.getChannel?.()),r=_(e.getCliVersion?.());return{"x-matilda-reported-surface":n,"x-matilda-reported-os":m(t),"x-matilda-reported-process":n==="desktop"?"matilda-desktop":n==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":"matilda-client",...r?{"x-matilda-reported-version":r}:{}}}function O(e){return p.has(e.toLowerCase())}function g(e){let t=e??d;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function w(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&g(e.baseUrl)}export{C as a,O as b,w as c};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|