@maincode-ai/matilda-code 0.19.2 → 0.19.5
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-HMAY5XP7.js +3 -0
- package/chunks/agent-headless-NWRQLNNS.js +3 -0
- package/chunks/{anthropicContentGenerator-BRG6WZK3.js → anthropicContentGenerator-CZLOMDXF.js} +11 -11
- package/chunks/{askUserQuestion-QPVUWJCI.js → askUserQuestion-V5YLTC4J.js} +1 -1
- package/chunks/{ca-D7YSARXX.js → ca-UW3G7H5I.js} +1 -1
- package/chunks/chunk-2FX4655X.js +101 -0
- package/chunks/{chunk-2MEHZGZJ.js → chunk-2XZIKUB6.js} +1 -1
- package/chunks/{chunk-RDNFN7GJ.js → chunk-3E62XAAL.js} +1 -1
- package/chunks/{chunk-X2SJJ7RN.js → chunk-3GAKPC2I.js} +2 -2
- package/chunks/chunk-3KCDX6MY.js +8 -0
- package/chunks/{chunk-X6DODPXG.js → chunk-5U3A6KMU.js} +1 -1
- package/chunks/chunk-7VGUNT5L.js +8 -0
- package/chunks/{chunk-XKNSVSWD.js → chunk-AEEMG76V.js} +2 -2
- package/chunks/chunk-C6SSPIF3.js +56 -0
- package/chunks/{chunk-DY6PIAAY.js → chunk-CFBZKYFB.js} +1 -1
- package/chunks/chunk-CLUEFPSU.js +8 -0
- package/chunks/chunk-FSRNEJQB.js +8 -0
- package/chunks/chunk-KP6BLFQS.js +12 -0
- package/chunks/{chunk-4M4CUQUR.js → chunk-NDR7ZFUA.js} +1 -1
- package/chunks/{chunk-CNHY7623.js → chunk-SUORCDGS.js} +1 -1
- package/chunks/{chunk-KMU5KAYC.js → chunk-WPZEF752.js} +490 -505
- package/chunks/chunk-XXZH7C44.js +34 -0
- package/chunks/{chunk-LN2DRVOB.js → chunk-XYA3SFGC.js} +1 -1
- package/chunks/{computer-use-MJ7WGSXA.js → computer-use-B2345U7U.js} +1 -1
- package/chunks/contextCommand-ZTMOL6TC.js +3 -0
- package/chunks/{cron-create-K35JKX3K.js → cron-create-JHL5JGIM.js} +1 -1
- package/chunks/{cron-delete-7B65R7JC.js → cron-delete-K2R3KI2W.js} +1 -1
- package/chunks/{cron-list-FCX6HCY7.js → cron-list-R3YHZBHA.js} +1 -1
- package/chunks/{de-ME75AM7Q.js → de-QSFN3SRK.js} +1 -1
- package/chunks/{edit-Y7NFRYDN.js → edit-YI2KTC5G.js} +1 -1
- package/chunks/{en-KVT5FJKO.js → en-ZU6RPTEW.js} +2 -2
- package/chunks/{enter-worktree-PVVX5BLF.js → enter-worktree-2V2D7CYW.js} +1 -1
- package/chunks/{enterPlanMode-VVRE4YBV.js → enterPlanMode-ZUCJBK26.js} +1 -1
- package/chunks/{exit-worktree-LDIOV4NM.js → exit-worktree-TNMQ6BJQ.js} +1 -1
- package/chunks/{exitPlanMode-AR4QZ4EF.js → exitPlanMode-3V2VGFJI.js} +1 -1
- package/chunks/{fr-V3O5JG5W.js → fr-FKTJ4COX.js} +2 -2
- package/chunks/geminiContentGenerator-DLT3FIFM.js +8 -0
- package/chunks/{glob-6H2PV6X4.js → glob-DK4XLD6I.js} +1 -1
- package/chunks/grep-HHKDBU7B.js +22 -0
- package/chunks/{ja-ZOFFSG6C.js → ja-GKS4GLZP.js} +1 -1
- package/chunks/{ls-ZSHUDEJV.js → ls-4QPI2E7A.js} +1 -1
- package/chunks/{lsp-DW3UNQQ6.js → lsp-P3GKBOP3.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-B7FZY5QT.js → matildaAgentContentGenerator-WANX4W2Y.js} +9 -9
- package/chunks/matildaContentGenerator-YNM53I6M.js +8 -0
- package/chunks/monitor-JVPMYOZ2.js +32 -0
- package/chunks/notebook-edit-TSASMGK7.js +17 -0
- package/chunks/openaiContentGenerator-5VMLKMVG.js +3 -0
- package/chunks/{pt-K2W3KMTP.js → pt-VIW62ZAE.js} +1 -1
- package/chunks/{read-file-MUUE7CJM.js → read-file-HEVXSNSO.js} +1 -1
- package/chunks/ripGrep-UCUYOKAZ.js +3 -0
- package/chunks/{ru-KICZRPMQ.js → ru-FSSACF4A.js} +1 -1
- package/chunks/scheduler-LXGHE7LL.js +8 -0
- package/chunks/{send-message-BPTEYK4Y.js → send-message-K3T7GVHO.js} +1 -1
- package/chunks/{serve-DAFPBR3R.js → serve-F2OU5GL5.js} +1 -1
- package/chunks/shell-5CG25UXX.js +3 -0
- package/chunks/{skill-D23JCWUG.js → skill-YXHHDMLR.js} +1 -1
- package/chunks/src-4KXRVNR5.js +3 -0
- package/chunks/{symbol-search-3E5XK5S6.js → symbol-search-WVNUJRET.js} +1 -1
- package/chunks/{syntheticOutput-NSQJLEEY.js → syntheticOutput-LLA4WQR7.js} +1 -1
- package/chunks/{task-create-TQI5N4YR.js → task-create-ZZTSVXZN.js} +1 -1
- package/chunks/{task-list-DQBF34BK.js → task-list-6I64SK7E.js} +1 -1
- package/chunks/{task-stop-5R44O4NK.js → task-stop-UKRXMCZV.js} +1 -1
- package/chunks/{task-update-PL2JDIF6.js → task-update-XZWORLJB.js} +1 -1
- package/chunks/{team-create-B3K7PIQ5.js → team-create-ESOAIRWA.js} +1 -1
- package/chunks/{team-delete-LWX4LMFZ.js → team-delete-DEPXAMUE.js} +1 -1
- package/chunks/{todoWrite-V4DQMEDR.js → todoWrite-DKJAYA4S.js} +1 -1
- package/chunks/{tool-search-UA3I7UV3.js → tool-search-47TA6SG4.js} +1 -1
- package/chunks/update-goal-DH2TEYYU.js +16 -0
- package/chunks/{web-fetch-XRYT2EOQ.js → web-fetch-5F7C7MXU.js} +1 -1
- package/chunks/{web-search-MD3V4NBD.js → web-search-N6QM6PXT.js} +1 -1
- package/chunks/{workflow-A2P7P7KO.js → workflow-AGPUPU65.js} +2 -2
- package/chunks/write-file-XJ2S7TR3.js +11 -0
- package/chunks/{zh-C5PHBN3U.js → zh-I4FV25MS.js} +2 -2
- package/chunks/{zh-TW-IYMR6KR3.js → zh-TW-7HNBEDIB.js} +2 -2
- package/cli.js +462 -461
- package/locales/ca.js +6 -2
- package/locales/de.js +5 -3
- package/locales/en.js +7 -4
- package/locales/fr.js +4 -2
- package/locales/ja.js +6 -2
- package/locales/pt.js +4 -2
- package/locales/ru.js +4 -2
- package/locales/zh-TW.js +7 -4
- package/locales/zh.js +7 -4
- package/package.json +2 -2
- package/chunks/agent-XKRS7SDN.js +0 -3
- package/chunks/agent-headless-5UTXGWJL.js +0 -3
- package/chunks/chunk-APVMKC4S.js +0 -101
- package/chunks/chunk-OQ73WWR4.js +0 -8
- package/chunks/chunk-R6YTDM76.js +0 -8
- package/chunks/chunk-S32ZN6LD.js +0 -12
- package/chunks/chunk-WQNABJ5R.js +0 -38
- package/chunks/contextCommand-AGXIRVKU.js +0 -3
- package/chunks/geminiContentGenerator-35P4NFWN.js +0 -8
- package/chunks/grep-OMYHSNBF.js +0 -22
- package/chunks/matildaContentGenerator-DQOUSFU3.js +0 -8
- package/chunks/monitor-LY6HMAGP.js +0 -32
- package/chunks/notebook-edit-PY3T4RHL.js +0 -17
- package/chunks/openaiContentGenerator-A42WRFRC.js +0 -3
- package/chunks/ripGrep-BJRH2OAQ.js +0 -3
- package/chunks/scheduler-MFP5BJTP.js +0 -8
- package/chunks/shell-YAP6NQTT.js +0 -3
- package/chunks/src-77YCXW6G.js +0 -3
- package/chunks/write-file-TTOYKZTG.js +0 -11
package/chunks/chunk-WQNABJ5R.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as Kn}from"./chunk-QCIDUZV6.js";import{a as Jn,b as Vn,c as zn}from"./chunk-R6YTDM76.js";import{c as mr,f as ve}from"./chunk-S4K76QPI.js";import{a as jn,b as st,c as Gn}from"./chunk-APVMKC4S.js";import{a as Vr,e as Bn,j as Wn,o as Hn,q as qn,s as Xn,t as dr}from"./chunk-LN2DRVOB.js";import{e as Dn}from"./chunk-4J6DC24J.js";import{b as zr}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Un}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function w(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var Kr=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Kr=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Ht(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var qt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var b=class extends Error{},$=class n extends b{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:qt(t)});let o=t?.error;return e===400?new ot(e,o,r,s):e===401?new it(e,o,r,s):e===403?new at(e,o,r,s):e===404?new lt(e,o,r,s):e===409?new ct(e,o,r,s):e===422?new ut(e,o,r,s):e===429?new ft(e,o,r,s):e>=500?new pt(e,o,r,s):new n(e,o,r,s)}},M=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},ot=class extends ${},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends b{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var no=/^[a-z][a-z0-9+.-]*:/i,Qn=n=>no.test(n),W=n=>(W=Array.isArray,W(n)),Qr=W;function Yn(n){return typeof n!="object"?{}:n??{}}function Zn(n){if(!n)return!0;for(let e in n)return!1;return!0}function es(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Xt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ts=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${n} must be an integer`);if(e<0)throw new b(`${n} must be a positive integer`);return e};var rs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var is=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function so(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var oo=()=>{let n=so();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(Deno.build.os),"X-Stainless-Arch":ns(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ns(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=io();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function io(){if(typeof navigator>"u"||!navigator)return null;let n=[{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 n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ns=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ss=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),os,as=()=>os??(os=oo());a();function ls(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Yr(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function hr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Yr({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Zr(n){if(n[Symbol.asyncIterator])return n;let e=n.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}}}async function cs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var us=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var gr="RFC3986",en=n=>String(n),_r={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:en},tn="RFC1738";a();a();var br=(n,e)=>(br=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),br(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var rn=1024,fs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=rn){let u=o.length>=rn?o.slice(l,l+rn):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===tn&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function ps(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function nn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ms={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},hs=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},ds,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fs,encodeValuesOnly:!1,format:gr,formatter:en,indices:!1,serializeDate(n){return(ds??(ds=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function co(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var sn={};function gs(n,e,t,r,s,o,i,l,u,d,g,p,y,f,x,A,R,S){let C=n,U=S,O=0,X=!1;for(;(U=U.get(sn))!==void 0&&!X;){let T=U.get(n);if(O+=1,typeof T<"u"){if(T===O)throw new RangeError("Cyclic object value");X=!0}typeof U.get(sn)>"u"&&(O=0)}if(typeof d=="function"?C=d(e,C):C instanceof Date?C=y?.(C):t==="comma"&&W(C)&&(C=nn(C,function(T){return T instanceof Date?y?.(T):T})),C===null){if(o)return u&&!A?u(e,N.encoder,R,"key",f):e;C=""}if(co(C)||ps(C)){if(u){let T=A?e:u(e,N.encoder,R,"key",f);return[x?.(T)+"="+x?.(u(C,N.encoder,R,"value",f))]}return[x?.(e)+"="+x?.(String(C))]}let H=[];if(typeof C>"u")return H;let E;if(t==="comma"&&W(C))A&&u&&(C=nn(C,u)),E=[{value:C.length>0?C.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(C);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(C)&&C.length===1?D+"[]":D;if(s&&W(C)&&C.length===0)return j+"[]";for(let T=0;T<E.length;++T){let k=E[T],Fn=typeof k=="object"&&typeof k.value<"u"?k.value:C[k];if(i&&Fn===null)continue;let Jr=p&&l?k.replace(/\./g,"%2E"):k,to=W(C)?typeof t=="function"?t(j,Jr):j:j+(p?"."+Jr:"["+Jr+"]");S.set(n,O);let Ln=new WeakMap;Ln.set(sn,S),hs(H,gs(Fn,to,t,r,s,o,i,l,t==="comma"&&A&&W(C)?null:u,d,g,p,y,f,x,A,R,Ln))}return H}function uo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=gr;if(typeof n.format<"u"){if(!br(_r,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=_r[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ms?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function on(n,e={}){let t=n,r=uo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ms[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let y=0;y<s.length;++y){let f=s[y];r.skipNulls&&t[f]===null||hs(i,gs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function ys(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var _s;function ht(n){let e;return(_s??(e=new globalThis.TextEncoder,_s=e.encode.bind(e)))(n)}var bs;function an(n){let e;return(bs??(e=new globalThis.TextDecoder,bs=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),w(this,J,new Uint8Array,"f"),w(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ht(e):e;w(this,J,ys([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=po(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){w(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(an(c(this,J,"f").subarray(0,c(this,V,"f")-1))),w(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),w(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=an(c(this,J,"f").subarray(0,o));r.push(i),w(this,J,c(this,J,"f").subarray(s.index),"f"),w(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
|
|
4
|
-
`):[]}};J=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
|
|
5
|
-
`,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function po(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Cs(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Cr={off:0,error:200,warn:300,info:400,debug:500},ln=(n,e,t)=>{if(n){if(es(Cr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Cr))}`)}};function Jt(){}function yr(n,e,t){return!e||Cr[n]>Cr[t]?Jt:e[n].bind(e)}var mo={error:Jt,warn:Jt,info:Jt,debug:Jt},ws=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return mo;let r=ws.get(e);if(r&&r[0]===t)return r[1];let s={error:yr("error",e,t),warn:yr("warn",e,t),info:yr("info",e,t),debug:yr("debug",e,t)};return ws.set(e,[t,s]),s}var ae=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Vt,re=class n{constructor(e,t,r){this.iterator=e,Vt.set(this,void 0),this.controller=t,w(this,Vt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of ho(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let d;try{d=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(d&&d.error)throw new $(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new Te,u=Zr(e);for await(let d of u)for(let g of l.decode(d))yield g;for(let d of l.flush())yield d}async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,Vt,"f")),new n(()=>s(t),this.controller,c(this,Vt,"f"))]}toReadableStream(){let e=this,t;return Yr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=ht(JSON.stringify(s)+`
|
|
6
|
-
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*ho(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new b("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new b("Attempted to iterate over a response with no body");let t=new cn,r=new Te,s=Zr(n.body);for await(let o of go(s))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*go(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ht(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=Cs(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var cn=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(`
|
|
7
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=_o(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function _o(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function wr(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return v(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):re.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return un(p,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,ae({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function un(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}a();var zt,Me=class n extends Promise{constructor(e,t,r=wr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,zt.set(this,void 0),w(this,zt,e,"f")}_thenUnwrap(e){return new n(c(this,zt,"f"),this.responsePromise,async(t,r)=>un(e(await this.parseResponse(t,r),r),r.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("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,zt,"f"),e))),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)}};zt=new WeakMap;var Ar,xr=class{constructor(e,t,r,s){Ar.set(this,void 0),w(this,Ar,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Ar,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Kt=class extends Me{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await wr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},P=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Yn(this.options.query),after:t}}:null}};a();a();a();var pn=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function gt(n,e,t){return pn(),new File(n,e??"unknown_file",t)}function Qt(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}var dn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var z=async(n,e)=>({...n,body:await Co(n.body,e)}),As=new WeakMap;function yo(n){let e=typeof n=="function"?n:n.fetch,t=As.get(e);if(t)return t;let r=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return As.set(e,r),r}var Co=async(n,e)=>{if(!await yo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>fn(t,r,s))),t},wo=n=>n instanceof Blob&&"name"in n;var fn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,gt([await t.blob()],Qt(t)));else if(dn(t))n.append(e,gt([await new Response(hr(t)).blob()],Qt(t)));else if(wo(t))n.append(e,t,Qt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>fn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>fn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var xs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Ao=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&xs(n),xo=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Ir(n,e,t){if(pn(),n=await n,Ao(n))return n instanceof File?n:gt([await n.arrayBuffer()],n.name);if(xo(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),gt(await mn(s),e,t)}let r=await mn(n);if(e||(e=Qt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return gt(r,e,t)}async function mn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(xs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(dn(n))for await(let t of n)e.push(...await mn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Io(n)}`)}return e}function Io(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var h=class{constructor(e){this._client=e}};a();a();a();function Ps(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Is=Object.freeze(Object.create(null)),Ro=(n=Ps)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,p,y)=>{/[?#]/.test(p)&&(s=!0);let f=r[y],x=(s?encodeURIComponent:n)(""+f);return y!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Is)??Is)?.toString)&&(x=f+"",o.push({start:g.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+p+(y===r.length?"":x)},""),l=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(l))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((g,p)=>g.start-p.start),o.length>0){let g=0,p=o.reduce((y,f)=>{let x=" ".repeat(f.start-g),A="^".repeat(f.length);return g=f.start+f.length,y+x+A},"");throw new b(`Path parameters result in path with invalid segments:
|
|
8
|
-
${o.map(y=>y.error).join(`
|
|
9
|
-
`)}
|
|
10
|
-
${i}
|
|
11
|
-
${p}`)}return i},m=Ro(Ps);var ke=class extends h{list(e,t={},r){return this._client.getAPIList(m`/chat/completions/${e}/messages`,P,{query:t,...r})}};a();a();a();a();function Rs(n){return typeof n.parse=="function"}a();var _t=n=>n?.role==="assistant",hn=n=>n?.role==="tool";a();var gn,Pr,Rr,Yt,Zt,Sr,er,le,tr,Or,Er,bt,Ss,be=class{constructor(){gn.add(this),this.controller=new AbortController,Pr.set(this,void 0),Rr.set(this,()=>{}),Yt.set(this,()=>{}),Zt.set(this,void 0),Sr.set(this,()=>{}),er.set(this,()=>{}),le.set(this,{}),tr.set(this,!1),Or.set(this,!1),Er.set(this,!1),bt.set(this,!1),w(this,Pr,new Promise((e,t)=>{w(this,Rr,e,"f"),w(this,Yt,t,"f")}),"f"),w(this,Zt,new Promise((e,t)=>{w(this,Sr,e,"f"),w(this,er,t,"f")}),"f"),c(this,Pr,"f").catch(()=>{}),c(this,Zt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,gn,"m",Ss).bind(this))},0)}_connected(){this.ended||(c(this,Rr,"f").call(this),this._emit("connect"))}get ended(){return c(this,tr,"f")}get errored(){return c(this,Or,"f")}get aborted(){return c(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,le,"f")[e];if(!r)return this;let s=r.findIndex(o=>o.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,bt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,bt,!0,"f"),await c(this,Zt,"f")}_emit(e,...t){if(c(this,tr,"f"))return;e==="end"&&(w(this,tr,!0,"f"),c(this,Sr,"f").call(this));let r=c(this,le,"f")[e];if(r&&(c(this,le,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Pr=new WeakMap,Rr=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,Sr=new WeakMap,er=new WeakMap,le=new WeakMap,tr=new WeakMap,Or=new WeakMap,Er=new WeakMap,bt=new WeakMap,gn=new WeakSet,Ss=function(e){if(w(this,Or,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return w(this,Er,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){let t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};a();function rr(n){return n?.$brand==="auto-parseable-response-format"}function $e(n){return n?.$brand==="auto-parseable-tool"}function Os(n,e){return!e||!_n(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:nr(n,e)}function nr(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new dt;if(r.finish_reason==="content_filter")throw new mt;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>vo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Eo(e,r.message.content):null}}});return{...n,choices:t}}function Eo(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function vo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$e(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Es(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return $e(t)||t?.function.strict||!1}function _n(n){return rr(n.response_format)?!0:n.tools?.some(e=>$e(e)||e.type==="function"&&e.function.strict===!0)??!1}function vs(n){for(let e of n??[]){if(e.type!=="function")throw new b(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new b(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,bn,vr,yn,Cn,wn,Ts,Ms,To=10,yt=class extends be{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),hn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new b("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",bn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",yn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",Cn).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",wn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,q,"m",vr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",bn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",yn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",Cn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",wn).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,q,"m",Ts).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(nr(o,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let s="tool",{tool_choice:o="auto",stream:i,...l}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:d=To}=r||{},g=t.tools.map(f=>{if($e(f)){if(!f.$callback)throw new b("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of g)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let y="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){let A=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0]?.message;if(!A)throw new b("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let R of A.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:C,arguments:U}=R.function,O=p[C];if(O){if(u&&u!==C){let D=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(p).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}let X;try{X=Rs(O)?await O.parse(U):U}catch(D){let j=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:S,content:j});continue}let H=await O.function(X,this),E=c(this,q,"m",Ms).call(this,H);if(this._addMessage({role:s,tool_call_id:S,content:E}),u)return}}}};q=new WeakSet,bn=function(){return c(this,q,"m",vr).call(this).content??null},vr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(_t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new b("stream ended without producing a ChatCompletionMessage with role=assistant")},yn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_t(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Cn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(hn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},wn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ts=function(e){if(e.n!=null&&e.n>1)throw new b("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ms=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var sr=class n extends yt{static runTools(e,t,r){let s=new n,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),_t(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var G={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},An=class extends Error{},xn=class extends Error{};function Mo(n,e=G.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return ko(n.trim(),e)}var ko=(n,e)=>{let t=n.length,r=0,s=y=>{throw new An(`${y} at position ${r}`)},o=y=>{throw new xn(`${y} at position ${r}`)},i=()=>(p(),r>=t&&s("Unexpected end of input"),n[r]==='"'?l():n[r]==="{"?u():n[r]==="["?d():n.substring(r,r+4)==="null"||G.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||G.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||G.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||G.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||G.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||G.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let y=r,f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(y,++r-Number(f)))}catch(x){o(String(x))}else if(G.STR&e)try{return JSON.parse(n.substring(y,r-Number(f))+'"')}catch{return JSON.parse(n.substring(y,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let y={};try{for(;n[r]!=="}";){if(p(),r>=t&&G.OBJ&e)return y;let f=l();p(),r++;try{let x=i();Object.defineProperty(y,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(G.OBJ&e)return y;throw x}p(),n[r]===","&&r++}}catch{if(G.OBJ&e)return y;s("Expected '}' at end of object")}return r++,y},d=()=>{r++;let y=[];try{for(;n[r]!=="]";)y.push(i()),p(),n[r]===","&&r++}catch{if(G.ARR&e)return y;s("Expected ']' at end of array")}return r++,y},g=()=>{if(r===0){n==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(G.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}o(String(f))}}let y=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(G.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(y,r))}catch{n.substring(y,r)==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(y,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
|
|
12
|
-
\r `.includes(n[r]);)r++};return i()},In=n=>Mo(n,G.ALL^G.NUM);var F,ce,Ct,ye,Pn,Tr,Rn,Sn,On,Mr,En,ks,Ne=class n extends yt{constructor(e){super(),F.add(this),ce.set(this,void 0),Ct.set(this,void 0),ye.set(this,void 0),w(this,ce,e,"f"),w(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return c(this,ye,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new n(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)c(this,F,"m",Rn).call(this,i);if(o.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this),this._connected();let s=re.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(c(this,F,"m",Mr).call(this)),c(this,F,"m",Rn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}[(ce=new WeakMap,Ct=new WeakMap,ye=new WeakMap,F=new WeakSet,Pn=function(){this.ended||w(this,ye,void 0,"f")},Tr=function(t){let r=c(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Ct,"f")[t.index]=r,r)},Rn=function(t){if(this.ended)return;let r=c(this,F,"m",ks).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let o=r.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=c(this,F,"m",Tr).call(this,o);o.finish_reason&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index));for(let l of s.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[l.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:l.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(u?.type,void 0))}}},Sn=function(t,r){if(c(this,F,"m",Tr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=c(this,ce,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:$e(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},On=function(t){let r=c(this,F,"m",Tr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,F,"m",En).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Mr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,ye,"f");if(!t)throw new b("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,Ct,[],"f"),$o(t,c(this,ce,"f"))},En=function(){let t=c(this,ce,"f")?.response_format;return rr(t)?t:null},ks=function(t){var r,s,o,i;let l=c(this,ye,"f"),{choices:u,...d}=t;l?Object.assign(l,d):l=w(this,ye,{...d,choices:[]},"f");for(let{delta:g,finish_reason:p,index:y,logprobs:f=null,...x}of t.choices){let A=l.choices[y];if(A||(A=l.choices[y]={finish_reason:p,index:y,message:{},logprobs:f,...x}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(A.logprobs,D),H&&((r=A.logprobs).content??(r.content=[]),A.logprobs.content.push(...H)),E&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...E))}if(p&&(A.finish_reason=p,c(this,ce,"f")&&_n(c(this,ce,"f")))){if(p==="length")throw new dt;if(p==="content_filter")throw new mt}if(Object.assign(A,x),!g)continue;let{content:R,refusal:S,function_call:C,role:U,tool_calls:O,...X}=g;if(Object.assign(A.message,X),S&&(A.message.refusal=(A.message.refusal||"")+S),U&&(A.message.role=U),C&&(A.message.function_call?(C.name&&(A.message.function_call.name=C.name),C.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=C.arguments)):A.message.function_call=C),R&&(A.message.content=(A.message.content||"")+R,!A.message.refusal&&c(this,F,"m",En).call(this)&&(A.message.parsed=In(A.message.content))),O){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:j,...T}of O){let k=(i=A.message.tool_calls)[H]??(i[H]={});Object.assign(k,T),E&&(k.id=E),D&&(k.type=D),j&&(k.function??(k.function={name:j.name??"",arguments:""})),j?.name&&(k.function.name=j.name),j?.arguments&&(k.function.arguments+=j.arguments,Es(c(this,ce,"f"),k)&&(k.function.parsed_arguments=In(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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 re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function $o(n,e){let{id:t,choices:r,created:s,model:o,system_fingerprint:i,...l}=n,u={...l,id:t,choices:r.map(({message:d,finish_reason:g,index:p,logprobs:y,...f})=>{if(!g)throw new b(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:A,tool_calls:R,...S}=d,C=d.role;if(!C)throw new b(`missing role for choice ${p}`);if(A){let{arguments:U,name:O}=A;if(U==null)throw new b(`missing function_call.arguments for choice ${p}`);if(!O)throw new b(`missing function_call.name for choice ${p}`);return{...f,message:{content:x,function_call:{arguments:U,name:O},role:C,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:y}}return R?{...f,index:p,finish_reason:g,logprobs:y,message:{...S,role:C,content:x,refusal:d.refusal??null,tool_calls:R.map((U,O)=>{let{function:X,type:H,id:E,...D}=U,{arguments:j,name:T,...k}=X||{};if(E==null)throw new b(`missing choices[${p}].tool_calls[${O}].id
|
|
13
|
-
${kr(n)}`);if(H==null)throw new b(`missing choices[${p}].tool_calls[${O}].type
|
|
14
|
-
${kr(n)}`);if(T==null)throw new b(`missing choices[${p}].tool_calls[${O}].function.name
|
|
15
|
-
${kr(n)}`);if(j==null)throw new b(`missing choices[${p}].tool_calls[${O}].function.arguments
|
|
16
|
-
${kr(n)}`);return{...D,id:E,type:H,function:{...k,name:T,arguments:j}}})}}:{...f,message:{...S,content:x,role:C,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Os(u,e)}function kr(n){return JSON.stringify(n)}var or=class n extends Ne{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new n(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var ue=class extends h{constructor(){super(...arguments),this.messages=new ke(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(m`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(m`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/chat/completions/${e}`,t)}parse(e,t){return vs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>nr(r,e))}runTools(e,t){return e.stream?or.runTools(this._client,e,t):sr.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};ue.Messages=ke;var Ce=class extends h{constructor(){super(...arguments),this.completions=new ue(this._client)}};Ce.Completions=ue;a();a();a();a();a();var $s=Symbol("brand.privateNullableHeaders");function*Fo(n){if(!n)return;if($s in n){let{values:r,nulls:s}=n;yield*r.entries();for(let o of s)yield[o,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Qr(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){let s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Qr(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,l])}}var _=n=>{let e=new Headers,t=new Set;for(let r of n){let s=new Set;for(let[o,i]of Fo(r)){let l=o.toLowerCase();s.has(l)||(e.delete(o),s.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[$s]:!0,values:e,nulls:t}};var wt=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var At=class extends h{create(e,t){return this._client.post("/audio/transcriptions",z({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var xt=class extends h{create(e,t){return this._client.post("/audio/translations",z({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends h{constructor(){super(...arguments),this.transcriptions=new At(this._client),this.translations=new xt(this._client),this.speech=new wt(this._client)}};se.Transcriptions=At;se.Translations=xt;se.Speech=wt;a();var Fe=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(m`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",P,{query:e,...t})}cancel(e,t){return this._client.post(m`/batches/${e}/cancel`,t)}};a();a();var It=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Pt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Rt=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends h{constructor(){super(...arguments),this.sessions=new Pt(this._client),this.transcriptionSessions=new Rt(this._client)}};we.Sessions=Pt;we.TranscriptionSessions=Rt;a();a();var St=class extends h{create(e,t,r){return this._client.post(m`/threads/${e}/messages`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/messages`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Ot=class extends h{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(m`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...o}=t;return this._client.getAPIList(m`/threads/${s}/runs/${e}/steps`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Ns=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};a();var Ae=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,Ue,vn,oe,$r,Q,De,Et,Le,Lr,K,Nr,Fr,lr,ir,ar,Fs,Ls,Us,Ds,js,Gs,Bs,fe=class extends be{constructor(){super(...arguments),B.add(this),vn.set(this,[]),oe.set(this,{}),$r.set(this,{}),Q.set(this,void 0),De.set(this,void 0),Et.set(this,void 0),Le.set(this,void 0),Lr.set(this,void 0),K.set(this,void 0),Nr.set(this,void 0),Fr.set(this,void 0),lr.set(this,void 0)}[(vn=new WeakMap,oe=new WeakMap,$r=new WeakMap,Q=new WeakMap,De=new WeakMap,Et=new WeakMap,Le=new WeakMap,Lr=new WeakMap,K=new WeakMap,Nr=new WeakMap,Fr=new WeakMap,lr=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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})}}static fromReadableStream(e){let t=new Ue;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=re.fromReadableStream(e,this.controller);for await(let o of s)c(this,B,"m",ir).call(this,o);if(s.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static createThreadAssistantStream(e,t,r){let s=new Ue;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Nr,"f")}currentRun(){return c(this,Fr,"f")}currentMessageSnapshot(){return c(this,Q,"f")}currentRunStepSnapshot(){return c(this,lr,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,$r,"f"))}async finalRun(){if(await this.done(),!c(this,De,"f"))throw Error("Final run was not received.");return c(this,De,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)c(this,B,"m",ir).call(this,l);if(i.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}async _createAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Xt(o)&&Xt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Xt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}};Ue=fe,ir=function(e){if(!this.ended)switch(w(this,Nr,e,"f"),c(this,B,"m",Us).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,B,"m",Bs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,B,"m",Ls).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,B,"m",Fs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ar=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");if(!c(this,De,"f"))throw Error("Final run has not been received");return c(this,De,"f")},Fs=function(e){let[t,r]=c(this,B,"m",js).call(this,e,c(this,Q,"f"));w(this,Q,t,"f"),c(this,$r,"f")[t.id]=t;for(let s of r){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=c(this,Et,"f")){if(c(this,Le,"f"))switch(c(this,Le,"f").type){case"text":this._emit("textDone",c(this,Le,"f").text,c(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Le,"f").image_file,c(this,Q,"f"));break}w(this,Et,s.index,"f")}w(this,Le,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Et,"f")!==void 0){let s=e.data.content[c(this,Et,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Q,"f"));break;case"text":this._emit("textDone",s.text,c(this,Q,"f"));break}}c(this,Q,"f")&&this._emit("messageDone",e.data),w(this,Q,void 0,"f")}},Ls=function(e){let t=c(this,B,"m",Ds).call(this,e);switch(w(this,lr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,Lr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,K,"f")&&this._emit("toolCallDone",c(this,K,"f")),w(this,Lr,o.index,"f"),w(this,K,t.step_details.tool_calls[o.index],"f"),c(this,K,"f")&&this._emit("toolCallCreated",c(this,K,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,lr,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Us=function(e){c(this,vn,"f").push(e),this._emit("event",e)},Ds=function(e){switch(e.event){case"thread.run.step.created":return c(this,oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,oe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=Ue.accumulateDelta(t,r.delta);c(this,oe,"f")[e.data.id]=s}return c(this,oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,oe,"f")[e.data.id]=e.data;break}if(c(this,oe,"f")[e.data.id])return c(this,oe,"f")[e.data.id];throw new Error("No snapshot available")},js=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=c(this,B,"m",Gs).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Gs=function(e,t){return Ue.accumulateDelta(t,e)},Bs=function(e){switch(w(this,Fr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":w(this,De,e.data,"f"),c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends h{constructor(){super(...arguments),this.steps=new Ot(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(m`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/runs/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/runs`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(m`/threads/${s}/runs/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return fe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Ot;var xe=class extends h{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new St(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return fe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends h{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new It(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=It;ie.Threads=xe;a();var Ge=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var vt=class extends h{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var Be=class extends h{constructor(){super(...arguments),this.content=new vt(this._client)}create(e,t,r){return this._client.post(m`/containers/${e}/files`,z({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/containers/${e}/files`,P,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(m`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};Be.Content=vt;var Ie=class extends h{constructor(){super(...arguments),this.files=new Be(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(m`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=Be;a();var We=class extends h{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";r&&v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?o:(v(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let u=l.embedding;l.embedding=Ns(u)}),i)))}};a();a();a();var Tt=class extends h{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(m`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(m`/evals/${s}/runs/${e}/output_items`,P,{query:o,...r})}};var He=class extends h{constructor(){super(...arguments),this.outputItems=new Tt(this._client)}create(e,t,r){return this._client.post(m`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(m`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/evals/${e}/runs`,P,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(m`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(m`/evals/${s}/runs/${e}`,r)}};He.OutputItems=Tt;var Pe=class extends h{constructor(){super(...arguments),this.runs=new He(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(m`/evals/${e}`,t)}update(e,t,r){return this._client.post(m`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/evals/${e}`,t)}};Pe.Runs=He;a();var qe=class extends h{create(e,t){return this._client.post("/files",z({body:e,...t},this._client))}retrieve(e,t){return this._client.get(m`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/files/${e}`,t)}content(e,t){return this._client.get(m`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ee(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};a();a();var Mt=class extends h{};a();a();var kt=class extends h{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Xe=class extends h{constructor(){super(...arguments),this.graders=new kt(this._client)}};Xe.Graders=kt;a();a();var $t=class extends h{create(e,t,r){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(m`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Je=class extends h{constructor(){super(...arguments),this.permissions=new $t(this._client)}};Je.Permissions=$t;a();a();var Nt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,P,{query:t,...r})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new Nt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(m`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",P,{query:e,...t})}cancel(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,P,{query:t,...r})}pause(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Nt;var Y=class extends h{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Je(this._client),this.alpha=new Xe(this._client)}};Y.Methods=Mt;Y.Jobs=Ve;Y.Checkpoints=Je;Y.Alpha=Xe;a();a();var Ft=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var ze=class extends h{createVariation(e,t){return this._client.post("/images/variations",z({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",z({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};a();var Ke=class extends h{retrieve(e,t){return this._client.get(m`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(m`/models/${e}`,t)}};a();var Qe=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function Ws(n,e){return!e||!ai(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Tn(n,e)}function Tn(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:ui(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:ii(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Ur(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let s of r.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function ii(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function ai(n){return!!rr(n.text?.format)}function li(n){return n?.$brand==="auto-parseable-tool"}function ci(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function ui(n,e){let t=ci(n.tools??[],e.name);return{...e,...e,parsed_arguments:li(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Ur(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}a();var Lt,Dr,Se,jr,Hs,qs,Xs,Js,Gr=class n extends be{constructor(e){super(),Lt.add(this),Dr.set(this,void 0),Se.set(this,void 0),jr.set(this,void 0),w(this,Dr,e,"f")}static createResponse(e,t,r){let s=new n(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,Lt,"m",Hs).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)c(this,Lt,"m",qs).call(this,l,i);if(o.controller.signal?.aborted)throw new M;return c(this,Lt,"m",Xs).call(this)}[(Dr=new WeakMap,Se=new WeakMap,jr=new WeakMap,Lt=new WeakSet,Hs=function(){this.ended||w(this,Se,void 0,"f")},qs=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Lt,"m",Js).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new b(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new b(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Xs=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,Se,"f");if(!t)throw new b("request ended without sending any events");w(this,Se,void 0,"f");let r=fi(t,c(this,Dr,"f"));return w(this,jr,r,"f"),r},Js=function(t){let r=c(this,Se,"f");if(!r){if(t.type!=="response.created")throw new b(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=w(this,Se,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new b(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new b(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Se,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{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})}}async finalResponse(){await this.done();let e=c(this,jr,"f");if(!e)throw new b("stream ended without producing a ChatCompletion");return e}};function fi(n,e){return Ws(n,e)}a();var Ut=class extends h{list(e,t={},r){return this._client.getAPIList(m`/responses/${e}/input_items`,P,{query:t,...r})}};var Oe=class extends h{constructor(){super(...arguments),this.inputItems=new Ut(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ur(r),r))}retrieve(e,t={},r){return this._client.get(m`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ur(s),s))}delete(e,t){return this._client.delete(m`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Tn(r,e))}stream(e,t){return Gr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(m`/responses/${e}/cancel`,t)}};Oe.InputItems=Ut;a();a();var Dt=class extends h{create(e,t,r){return this._client.post(m`/uploads/${e}/parts`,z({body:t,...r},this._client))}};var Ee=class extends h{constructor(){super(...arguments),this.parts=new Dt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(m`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(m`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=Dt;a();a();a();var Vs=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var jt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/file_batches/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(m`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...o}=t;return this._client.getAPIList(m`/vector_stores/${s}/file_batches/${e}/files`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=s?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,u=t.values(),d=[...r];async function g(y){for(let f of y){let x=await l.files.create({file:f,purpose:"assistants"},s);d.push(x.id)}}let p=Array(i).fill(u).map(g);return await Vs(p),await this.createAndPoll(e,{file_ids:d})}};a();var Gt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/files`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...o}=t;return this._client.post(m`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/vector_stores/${e}/files`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(m`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var pe=class extends h{constructor(){super(...arguments),this.files=new Gt(this._client),this.fileBatches=new jt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(m`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};pe.Files=Gt;pe.FileBatches=jt;a();var Bt,zs,Br,Ye=class extends h{constructor(){super(...arguments),Bt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Bt,"m",zs).call(this,r);let o=_([t]).values,i=c(this,Bt,"m",Br).call(this,o,"webhook-signature"),l=c(this,Bt,"m",Br).call(this,o,"webhook-timestamp"),u=c(this,Bt,"m",Br).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Z("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-d>s)throw new Z("Webhook timestamp is too old");if(d>g+s)throw new Z("Webhook timestamp is too new");let p=i.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let R=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",x,R,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Bt=new WeakSet,zs=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Br=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Mn,kn,Wr,Ks,I=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Mn.add(this),Wr.set(this,void 0),this.completions=new Ge(this),this.chat=new Ce(this),this.embeddings=new We(this),this.files=new qe(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ke(this),this.fineTuning=new Y(this),this.graders=new Re(this),this.vectorStores=new pe(this),this.webhooks=new Ye(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Oe(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new b("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let l={apiKey:t,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&is())throw new b(`It looks like you're running in a browser-like environment.
|
|
17
|
-
|
|
18
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
19
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
20
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
21
|
-
|
|
22
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
23
|
-
|
|
24
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
25
|
-
`);this.baseURL=l.baseURL,this.timeout=l.timeout??kn.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=ln(l.logLevel,"ClientOptions.logLevel",this)??ln(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ls(),w(this,Wr,us,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return on(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${Kr()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Mn,"m",Ks).call(this)&&r||this.baseURL,o=Qn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Zn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Me(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,ae({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new M;let y=new AbortController,f=await this.fetchWithTimeout(l,i,u,y).catch(qt),x=Date.now();if(f instanceof Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new M;let C=Ht(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${C?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${C?"timed out":"failed"} (${S})`,ae({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${C?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${C?"timed out":"failed"} (error; no more retries left)`,ae({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),C?new ge:new he({cause:f})}let A=[...f.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,C])=>", "+S+": "+JSON.stringify(C)).join(""),R=`[${d}${g}${A}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let S=await this.shouldRetry(f);if(t&&S){let E=`retrying, ${t} attempts remaining`;return await cs(f.body),v(this).info(`${R} - ${E}`),v(this).debug(`[${d}] response error (${E})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let C=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${C}`);let U=await f.text().catch(E=>qt(E).message),O=rs(U),X=O?void 0:U;throw v(this).debug(`[${d}] response error (${C})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,O,X,f.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:y,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Kt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async 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,r,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ts("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...as(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:hr(e)}:c(this,Wr,"f").call(this,{body:e,headers:r})}};kn=I,Wr=new WeakMap,Mn=new WeakSet,Ks=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=kn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=b;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=M;I.NotFoundError=lt;I.ConflictError=ct;I.RateLimitError=ft;I.BadRequestError=ot;I.AuthenticationError=it;I.InternalServerError=pt;I.PermissionDeniedError=at;I.UnprocessableEntityError=ut;I.InvalidWebhookSignatureError=Z;I.toFile=Ir;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ke;I.FineTuning=Y;I.Graders=Re;I.VectorStores=pe;I.Webhooks=Ye;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Oe;I.Evals=Pe;I.Containers=Ie;a();function _i(n){return n.toLowerCase().includes("matilda3")}function bi(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var L=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};return r?{...s,...r}:s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=_i(e.model)?s.messages.map(bi):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=qn(e.model,"output"),s=Hn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Wt=class extends L{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var yi=me("MatildaOpenAICompatibleProvider"),de=class n extends L{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=dr?.endsWith("/")?dr.slice(0,-1):dr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&yi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))Vn(o)||(s[o]=i);return zn(this.contentGeneratorConfig)&&Object.assign(s,Jn(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Xn,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,d)=>!(d===s&&s!==-1||d===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Hr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function cr(n){let e=n.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 Ci(n){return cr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends L{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ci;static isDeepSeekHostname=cr;buildRequest(e,t){let r=super.buildRequest(e,t),s=cr(this.contentGeneratorConfig)?Ai(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=wi(i);return Hr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function wi(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
|
|
26
|
-
|
|
27
|
-
`);return{...n,content:t}}function Ai(n){let e=n,t=e.reasoning,r=t?.effort;if(typeof r!="string"||!r)return n;let s={...e};if(typeof s.reasoning_effort!="string"||!s.reasoning_effort){let o=r;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),s.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete s.reasoning;else if(t){let{effort:o,...i}=t;s.reasoning=i}return s}a();var et=class extends L{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};a();var xi=["api.minimaxi.com","api.minimax.io"],Ii=[".minimaxi.com",".minimax.io"],tt=class extends L{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return xi.includes(t)?!0:Ii.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var Qs="api.mistral.ai",Pi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ri(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Qs||t.endsWith(`.${Qs}`)}catch{return!1}}function Si(n){if(Ri(n))return!0;let e=n.model?.toLowerCase()??"";return Pi.some(t=>e.includes(t))}var rt=class extends L{static isMistralProvider=Si;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Oi)}}};function Oi(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Ei(n){let e=n.baseUrl??"";if(e)try{let r=new URL(e).hostname.toLowerCase();if(r==="xiaomimimo.com"||r.endsWith(".xiaomimimo.com"))return!0}catch{}return(n.model??"").toLowerCase().startsWith("mimo-")}var nt=class extends L{constructor(e,t){super(e,t)}static isMiMoProvider=Ei;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Hr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var vi=me("STREAMING_TOOL_CALL_PARSER"),qr=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,r,s){let o=e,i=!!(r&&this.idToIndexMap.has(r));if(r)if(this.idToIndexMap.has(r))o=this.idToIndexMap.get(r);else{if(this.buffers.has(e)){let R=this.buffers.get(e),S=this.depths.get(e),C=this.toolCallMeta.get(e);if(R.trim()&&S===0&&C?.id&&C.id!==r)try{JSON.parse(R),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let R=this.buffers.get(e);if(this.depths.get(e)>0||!R.trim())o=e;else try{JSON.parse(R),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let l=this.buffers.get(o),u=this.depths.get(o);if(i&&l.trim()&&u===0)try{return JSON.parse(l),vi.debug(`Ignoring replay chunk for completed toolCall id=${r}`),{complete:!1}}catch{}let d=this.toolCallMeta.get(o);r&&(d.id=r),s&&(d.name=s);let g=this.inStrings.get(o),p=this.escapes.get(o),y=l+t;this.buffers.set(o,y);let f=u,x=g,A=p;for(let R of t)x||(R==="{"||R==="["?f++:(R==="}"||R==="]")&&f--),R==='"'&&!A&&(x=!x),A=R==="\\"&&!A;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,A),f===0&&y.trim().length>0)try{return{complete:!0,value:JSON.parse(y)}}catch(R){if(x)try{return{complete:!0,value:JSON.parse(y+'"'),repaired:!0}}catch{}return{complete:!1,error:R instanceof Error?R:new Error(String(R))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[],t=new Set;for(let[r,s]of this.buffers.entries()){let o=this.toolCallMeta.get(r);if(o?.name&&s.trim()){if(o.id){if(t.has(o.id))continue;t.add(o.id)}let i={};try{i=JSON.parse(s)}catch{if(this.inStrings.get(r))try{i=JSON.parse(s+'"')}catch{i=Vr(s,{})}else i=Vr(s,{})}e.push({id:o.id,name:o.name,args:i,index:r})}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),r=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!r?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,r]of this.buffers.entries()){let s=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(s>0||!r.trim()))e=Math.max(e,t);else if(r.trim())try{JSON.parse(r)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e]of this.buffers.entries()){if(!this.toolCallMeta.get(e)?.name)continue;let r=this.depths.get(e)||0,s=this.inStrings.get(e)||!1;if(r>0||s)return!0}return!1}};var Ys=16e3,Zs=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
28
|
-
`,Xr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},ur=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0;try{let l=await this.client.chat.completions.create(r,{signal:i?.signal});return st.convertOpenAIResponseToGemini(l,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0,l;try{l=await this.client.chat.completions.create(r,{signal:i?.signal})}catch(p){throw i?.abort(),p}if(!i)return this.processStreamWithLogging(l,s,e);let u=i,d=this.processStreamWithLogging(l,s,e);async function*g(){try{yield*d}finally{u.abort()}}return g()})}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Xr(g)}let u=st.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Xr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Dn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=st.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await st.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,y=(r.model??"").toLowerCase();if(de.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(y.startsWith("matilda")||y==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,cr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile;if(e==="matilda-core")return!0;if(e==="matilda-code")return!1;let t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(t.endsWith("/api/v1/code"))return!1;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
|
|
29
|
-
`):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=Ys)return r;let s=Ys-Zs.length;return`${Zs}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let d=r?.[l],g=u?e.config?.[u]:void 0,p=u?t[u]:void 0;return d!==void 0?d:g!==void 0?g:p},o=(l,u,d)=>{let g=s(u,d);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Gn.getStore()?.(i),Bn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(ve(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new qr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new jn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Ti=me("OPENAI_ERROR"),fr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=ve(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Ti.error("OpenAI API Error:",i),o?new Error(`${i}
|
|
30
|
-
|
|
31
|
-
${this.getTimeoutTroubleshootingTips()}`):s}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e?.code,s=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||r==="ETIMEDOUT"||r==="ESOCKETTIMEDOUT"||s==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,r){let s=Math.round((Date.now()-t.startTime)/1e3);return r?`Request timeout after ${s}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
32
|
-
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
33
|
-
`)}`}};var eo=me("OPENAI"),pr=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new fr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new ur(s)}shouldSuppressErrorLogging(e,t){return!!(Un(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new Kn().calculateTokens(e)).totalTokens}}catch(t){eo.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=ve(r);throw eo.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};function Hg(n,e){let t=Mi(n,e);return new pr(n,e,t)}function Mi(n,e){let t=n||e.getContentGeneratorConfig();return de.isMatildaCompatibleProvider(t)?new de(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Wt.isModelScopeProvider(t)?new Wt(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new L(n,e)}export{de as a,Ze as b,et as c,tt as d,rt as e,nt as f,ur as g,fr as h,pr as i,Hg as j,Mi as k};
|
|
34
|
-
/**
|
|
35
|
-
* @license
|
|
36
|
-
* Copyright 2025 Matilda
|
|
37
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
38
|
-
*/
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{c as a,d as b,e as c}from"./chunk-RDNFN7GJ.js";import"./chunk-XKNSVSWD.js";import"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as g}from"./chunk-EMWHQSMS.js";import{g as m}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as p}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";p();p();var a=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{};return{...e,httpOptions:{...i??{},headers:{...s,...r}}}})():e;this.googleGenAI=new m(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,u)=>{let l=r[s];return i!==void 0?i:l!==void 0?l:u};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function G(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.19.2 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let d=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${d}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new a({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{a as GeminiContentGenerator,G as createGeminiContentGenerator};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Google LLC
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/grep-OMYHSNBF.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Be as Y,Sc as S,pj as z,ta as K}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as q}from"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import{g as U,i as V,p as H,q as _}from"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{C as O,F as W,J as F,Y as j,a as I,c as y}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as B}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";B();import Z from"node:fs/promises";import P from"node:path";import{EOL as tt}from"node:os";import{spawn as J}from"node:child_process";var N=j("GREP"),M=class extends U{constructor(r,s){super(s);this.config=r;this.fileExclusions=r.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let r=this.config.getWorkspaceContext(),s=P.resolve(this.config.getTargetDir(),this.params.path);return r.isPathWithinWorkspace(s)||W(q(),s)?"allow":"ask"}async execute(r){try{let s=[],i;if(this.params.path){let t=F(this.config,this.params.path,{allowExternalPaths:!0});s.push(t),i=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();s.push(...t),i=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let l=[];for(let t of s){let o=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:r});if(s.length>1)for(let a of o)P.isAbsolute(a.filePath)||(a.filePath=P.resolve(t,a.filePath));l.push(...o)}if(s.length>1){let t=new Set;l=l.filter(o=>{let a=`${o.filePath}:${o.lineNumber}`;return t.has(a)?!1:(t.add(a),!0)})}let f=this.params.glob?` (filter: "${this.params.glob}")`:"";if(l.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${i}${f}.`,returnDisplay:"No matches found"};let h=this.config.getTruncateToolOutputThreshold(),w=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),$=!1,L=l;l.length>w&&(L=l.slice(0,w),$=!0);let E=l.length,x=E===1?"match":"matches",G=`Found ${E} ${x} for pattern "${this.params.pattern}" ${i}${f}:
|
|
4
|
-
---
|
|
5
|
-
`,v=L.reduce((t,o)=>{let a=o.filePath;return t[a]||(t[a]=[]),t[a].push(o),t[a].sort((k,C)=>k.lineNumber-C.lineNumber),t},{}),n="",g=[],m=!1,c=(t,o)=>Number.isFinite(h)&&n.length+t.length>h?(n+=t.slice(0,Math.max(h-n.length,0)),n+="...",o&&g.push(o),m=!0,!1):(n+=t,o&&g.push(o),!0);for(let t in v){if(!c(`File: ${t}
|
|
6
|
-
`))break;let o=!1;for(let a of v[t]){let k=a.line.trim();if(!c(`L${a.lineNumber}: ${k}
|
|
7
|
-
`,a)){o=!0;break}}if(o||!c(`---
|
|
8
|
-
`))break}let b=n.split(`
|
|
9
|
-
`).filter(t=>t.trim()&&!t.startsWith("File:")&&!t.startsWith("---")).length,p=G+n;if($||m){let t=E-b;p+=` [${t} ${t===1?"line":"lines"} truncated] ...`}let u=`Found ${E} ${x}`;($||m)&&(u+=" (truncated)");let T=Array.from(new Set(g.map(t=>t.absoluteFilePath).filter(t=>t!=="")));return await z(this.config,T),{llmContent:p.trim(),returnDisplay:u,resultFilePaths:T}}catch(s){N.error(`Error during GrepLogic execution: ${s}`);let i=y(s);return{llmContent:`Error during grep search operation: ${i}`,returnDisplay:`Error: ${i}`,error:{message:i,type:"grep_execution_error"}}}}parseGrepOutput(r,s){let i=[];if(!r)return i;let l=r.split(tt);for(let f of l){if(!f.trim())continue;let h=f.indexOf(":");if(h===-1)continue;let w=f.indexOf(":",h+1);if(w===-1)continue;let $=f.substring(0,h),L=f.substring(h+1,w),E=f.substring(w+1),x=parseInt(L,10);if(!isNaN(x)){let G=P.resolve(s,$),v=P.relative(s,G);i.push({filePath:v||P.basename(G),absoluteFilePath:G,lineNumber:x,line:E.replace(/\r$/,"")})}}return i}getDescription(){let r=`'${this.params.pattern}' in path '${this.params.path||"./"}'`;return this.params.glob&&(r+=` (filter: '${this.params.glob}')`),r}async performGrepSearch(r){let{pattern:s,path:i,glob:l}=r,f="none";try{if(K(i)&&S("git").available){f="git grep";let n=["grep","--untracked","-n","-E","--ignore-case",s];l&&n.push("--",l);try{let g=await new Promise((m,c)=>{let e=J("git",n,{cwd:i,windowsHide:!0}),b=[],p=[];e.stdout.on("data",u=>b.push(u)),e.stderr.on("data",u=>p.push(u)),e.on("error",u=>c(new Error(`Failed to start git grep: ${u.message}`))),e.on("close",u=>{let T=Buffer.concat(b).toString("utf8"),t=Buffer.concat(p).toString("utf8");u===0?m(T):u===1?m(""):c(new Error(`git grep exited with code ${u}: ${t}`))})});return this.parseGrepOutput(g,i)}catch(g){N.debug(`GrepLogic: git grep failed: ${y(g)}. Falling back...`)}}let{available:$}=S("grep");if($){f="system grep";let n=["-r","-n","-H","-E"];this.fileExclusions.getGlobExcludes().map(c=>{let e=c;return e.startsWith("**/")&&(e=e.substring(3)),e.endsWith("/**")?e=e.slice(0,-3):e.endsWith("/")&&(e=e.slice(0,-1)),e&&!e.includes("/")&&!e.includes("*")?e:null}).filter(c=>!!c).forEach(c=>n.push(`--exclude-dir=${c}`)),l&&n.push(`--include=${l}`),n.push(s),n.push(".");try{let c=await new Promise((e,b)=>{let p=J("grep",n,{cwd:i,windowsHide:!0}),u=[],T=[],t=d=>u.push(d),o=d=>{let D=d.toString();!D.includes("Permission denied")&&!/grep:.*: Is a directory/i.test(D)&&T.push(d)},a=d=>{C(),b(new Error(`Failed to start system grep: ${d.message}`))},k=d=>{let D=Buffer.concat(u).toString("utf8"),A=Buffer.concat(T).toString("utf8").trim();C(),d===0?e(D):d===1?e(""):A?b(new Error(`System grep exited with code ${d}: ${A}`)):e("")},C=()=>{p.stdout.removeListener("data",t),p.stderr.removeListener("data",o),p.removeListener("error",a),p.removeListener("close",k),p.connected&&p.disconnect()};p.stdout.on("data",t),p.stderr.on("data",o),p.on("error",a),p.on("close",k)});return this.parseGrepOutput(c,i)}catch(c){N.debug(`GrepLogic: System grep failed: ${y(c)}. Falling back...`)}}N.debug("GrepLogic: Falling back to JavaScript grep implementation."),f="javascript fallback";let L=l||"**/*",E=this.fileExclusions.getGlobExcludes(),x=Y(L,{cwd:i,dot:!0,ignore:E,absolute:!0,nodir:!0,signal:r.signal}),G=new RegExp(s,"i"),v=[];for await(let n of x){let g=n;try{(await Z.readFile(g,"utf8")).split(/\r?\n/).forEach((e,b)=>{G.test(e)&&v.push({filePath:P.relative(i,g)||P.basename(g),absoluteFilePath:g,lineNumber:b+1,line:e})})}catch(m){(!I(m)||m.code!=="ENOENT")&&N.debug(`GrepLogic: Could not read/process ${g}: ${y(m)}`)}}return v}catch(h){throw N.error(`GrepLogic: Error in performGrepSearch (Strategy: ${f}): ${y(h)}`),h}}},X=class R extends V{constructor(r){super(R.Name,_.GREP,`A powerful search tool for finding patterns in files
|
|
10
|
-
|
|
11
|
-
Usage:
|
|
12
|
-
- ALWAYS use Grep for search tasks. NEVER invoke \`grep\` or \`rg\` as a Bash command. The Grep tool has been optimized for correct permissions and access.
|
|
13
|
-
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
14
|
-
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx")
|
|
15
|
-
- Case-insensitive by default
|
|
16
|
-
- Use Agent tool for open-ended searches requiring multiple rounds
|
|
17
|
-
`,"search",{properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},limit:{type:"number",description:"Limit output to first N matching lines. Optional - shows all matches if not specified."}},required:["pattern"],type:"object"});this.config=r}static Name=H.GREP;get maxOutputChars(){return 2e4}validateToolParamValues(r){try{new RegExp(r.pattern)}catch(s){return`Invalid regular expression pattern: ${r.pattern}. Error: ${y(s)}`}if(r.path){r.path=O(r.path.trim());try{F(this.config,r.path,{allowExternalPaths:!0})}catch(s){return y(s)}}return null}createInvocation(r){return new M(this.config,r)}};export{X as GrepTool};
|
|
18
|
-
/**
|
|
19
|
-
* @license
|
|
20
|
-
* Copyright 2025 Google LLC
|
|
21
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
22
|
-
*/
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as s,i as o}from"./chunk-WQNABJ5R.js";import"./chunk-QCIDUZV6.js";import"./chunk-R6YTDM76.js";import"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import{b as u}from"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import{e as d}from"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as i}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var c=class extends o{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new s(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=d.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||u,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await t();throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{c as MatildaContentGenerator};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Matilda
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Ac as et,Dc as ot,Ec as A,Jc as C,Kc as nt,Oc as it,Wh as P,Yh as lt,ie as rt,pc as tt,te as st,ye as L,ze as at}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import{g as Z,i as q,p as Y,q as Q}from"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{G as J,Y as K,c as m}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as H}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";H();import{spawn as ct}from"node:child_process";import mt from"node:path";import{randomUUID as wt}from"node:crypto";var u=K("MONITOR"),Et=1e3,O=1e4,St=3e5,N=6e5,dt=80,R=4096,ut=5,ft=1e3;function pt(l){return l.length>dt?l.slice(0,dt-1)+"\u2026":l}var kt=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result"]),xt=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function gt(l){let y="";for(let t=0;t<l.length;t++){let o=l.charCodeAt(t);if(o===9){y+=l[t];continue}o<32||o>=128&&o<=159||(y+=l[t])}return y=y.replace(xt,(t,o,a)=>kt.has(String(a).toLowerCase())?o==="/"?`</\u200B${a}>`:`<\u200B${a}>`:t),y}var U=class extends Z{constructor(t,o){super(o);this.config=t}callId;setCallId(t){this.callId=t}getDescription(){let t=this.params.description||C(this.params.command).spawnCommand;return`Monitor: ${pt(t)}`}async getDefaultPermission(){let t=C(this.params.command).safetyCommand;try{if(await L(t))return"allow"}catch(o){u.warn("AST read-only check failed, falling back to ask:",o)}return"ask"}async getConfirmationDetails(t){let o=C(this.params.command),a=ot(o.safetyCommand),f=[];for(let s of a){let p=!1;try{p=await L(s)}catch(d){u.warn("AST read-only check failed for monitor sub-command, falling back to ask:",d)}p||f.push(s)}let S=f.length>0?f:a,M=[...new Set(S.map(s=>A(s)).filter(s=>!!s))],v=[];try{let s=[];for(let p of S){let d=await at(p);s.push(...d)}v=[...new Set(s)].map(p=>`Monitor(${p})`)}catch(s){u.warn("Failed to extract monitor command rules:",s),v=[`Monitor(${o.safetyCommand})`]}let i=it(o.safetyCommand,this.params.command),c={type:"exec",title:"Monitor",command:o.spawnCommand,rootCommand:M.join(", ")||(A(o.safetyCommand)??o.spawnCommand),permissionRules:v,onConfirm:async(s,p)=>{}};return i&&(c.warnings=i),c}async execute(t){if(t.aborted)return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."};let o=C(this.params.command),a=o.spawnCommand;o.strippedTrailingAmp&&u.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding");let f=gt(this.params.description||a),S=pt(f),M=Math.min(this.params.max_events??Et,O),v=Math.min(this.params.idle_timeout_ms??St,N),i=`mon_${wt().replace(/-/g,"").slice(0,16)}`,c=this.config.getMonitorRegistry(),s=tt()??void 0;if(c.getRunning().length>=P)return{llmContent:`Cannot start monitor: maximum concurrent monitors (${P}) reached. Stop an existing monitor first.`,returnDisplay:"Monitor rejected: too many concurrent monitors."};let d=new AbortController,g={monitorId:i,command:a,description:f,status:"running",startTime:Date.now(),abortController:d,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents:M,idleTimeoutMs:v,droppedLines:0,outputFile:lt(this.config.storage.getProjectDir(),this.config.getSessionId(),i),...s?{ownerAgentId:s}:{}},{executable:yt,argsPrefix:vt}=et(),n;try{n=ct(yt,[...vt,a],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,MATILDA_CODE:"1",TERM:"dumb",PAGER:"cat",...st()}})}catch(e){return{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}g.pid=n.pid;let b=!1,w,D=e=>{w??=e};n.on("error",D);let B={value:""},G={value:""},k=ut,I=Date.now(),$=e=>{let r=gt(e);if(r.length===0||r.trim().length===0)return;let T=Date.now(),_=T-I;if(_<0)u.warn(`Monitor ${i}: clock moved backwards by ${-_}ms, resetting refill timestamp`),I=T;else{let h=Math.floor(_/ft);h>0&&(k=Math.min(ut,k+h),I+=h*ft)}k>0?(k--,c.emitEvent(i,r)):g.droppedLines++},j=()=>{for(let e of[B,G]){let r=e.value.trim();r.length>0&&$(r),e.value=""}},Tt=()=>{if(!(b||!n.pid))if(process.platform==="win32")ct("taskkill",["/pid",n.pid.toString(),"/f","/t"],{stdio:"ignore"}).on("error",r=>u.warn(`Monitor taskkill failed for pid ${n.pid}: ${m(r)}`));else{try{process.kill(-n.pid,"SIGTERM")}catch(e){u.warn(`Monitor ${i} SIGTERM failed (pid=${n.pid}): ${m(e)}`)}setTimeout(()=>{if(!b&&n.pid)try{process.kill(-n.pid,"SIGKILL")}catch(e){u.warn(`Monitor ${i} SIGKILL escalation failed (pid=${n.pid}): ${m(e)}`)}},200).unref?.()}},E=()=>{j(),Tt()};d.signal.addEventListener("abort",E,{once:!0}),d.signal.aborted&&E();try{c.register(g)}catch(e){return E(),d.signal.removeEventListener("abort",E),n.stdout?.destroy?.(),n.stderr?.destroy?.(),n.removeListener("error",D),n.on("error",()=>{}),{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}let z=(e,r)=>{if(g.status!=="running")return;let T=rt(r.toString("utf-8"));if(e.value+=T,!e.value.includes(`
|
|
4
|
-
`)&&e.value.length>R){let h=e.value.trim();h.length>0&&$(h.slice(0,R)+"..."),e.value="";return}let _=e.value.split(`
|
|
5
|
-
`);e.value=_.pop()??"";for(let h of _){let x=h.trim();if(x.length===0)continue;let bt=x.length>R?x.slice(0,R)+"...":x;$(bt)}};n.stdout?.on("data",e=>z(B,e)),n.stderr?.on("data",e=>z(G,e));let F=!1,X=()=>{F||(F=!0,j(),d.signal.removeEventListener("abort",E),g.droppedLines>0&&u.info(`Monitor ${i} dropped ${g.droppedLines} lines due to throttling`))},V=null,_t=(e,r)=>{g.status==="running"&&(d.signal.aborted?c.cancel(i):e!==null&&e!==0?c.fail(i,`Exit code ${e}`):r?c.fail(i,`Killed by signal ${r}`):c.complete(i,e))},Ct=(e,r)=>{b=!0,V={code:e,sig:r}},Mt=(e,r)=>{b=!0,X();let T=V??{code:e,sig:r};_t(T.code,T.sig)},W=e=>{b=!0,X(),g.status==="running"&&c.fail(i,m(e))};return n.on("exit",Ct),n.on("close",Mt),n.on("error",W),n.removeListener("error",D),w?(W(w),{llmContent:`Monitor failed to start: ${m(w)}`,returnDisplay:`Monitor failed: ${m(w)}`}):{llmContent:`Monitor started.
|
|
6
|
-
id: ${i}
|
|
7
|
-
command: ${a}
|
|
8
|
-
description: ${f}
|
|
9
|
-
max_events: ${M}
|
|
10
|
-
idle_timeout: ${v}ms
|
|
11
|
-
Events will be delivered as notifications. The monitor auto-stops after ${M} events or ${v}ms of silence.
|
|
12
|
-
To inspect: /tasks (text) or the interactive Background tasks dialog (focus the footer Background tasks pill, then Enter \u2014 detail view + live updates).`,returnDisplay:`Monitor started: ${S} (${i})`}}},ht=class l extends q{constructor(t){super(l.Name,Q.MONITOR,`Starts a long-running shell command and streams its stdout/stderr as event notifications back to you.
|
|
13
|
-
|
|
14
|
-
Use this tool for:
|
|
15
|
-
- Watching log files: \`tail -f /var/log/app.log\`
|
|
16
|
-
- Monitoring build output: \`npm run build --watch\`
|
|
17
|
-
- Polling for state changes: \`while true; do curl -s http://localhost:8080/health; sleep 1; done\`
|
|
18
|
-
- Watching file changes: \`fswatch -r ./src\`
|
|
19
|
-
|
|
20
|
-
Each output line from the command becomes a notification event delivered to you. The monitor runs in the background \u2014 you can continue working while it streams events.
|
|
21
|
-
|
|
22
|
-
**Auto-stop:** The monitor automatically stops after max_events (default 1000) events or after idle_timeout_ms (default 5 minutes) of silence. The process is killed when the monitor stops.
|
|
23
|
-
|
|
24
|
-
**Do NOT use this tool for:**
|
|
25
|
-
- One-shot commands (use run_shell_command instead)
|
|
26
|
-
- Commands you need the full output from (use run_shell_command instead)
|
|
27
|
-
- Commands with no output (use run_shell_command with is_background: true instead)`,"execute",{type:"object",properties:{command:{type:"string",description:"Shell command to run and monitor. Each output line (stdout and stderr) becomes an event notification."},description:{type:"string",description:'Brief description of what this monitor watches (e.g., "webpack build output"). Truncated to 80 characters in display.'},max_events:{type:"number",description:"Stop the monitor after this many events. Default 1000. Max 10000."},idle_timeout_ms:{type:"number",description:"Stop the monitor if no output for this many milliseconds. Default 300000 (5 min). Max 600000."},directory:{type:"string",description:"(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be within the workspace."}},required:["command"],additionalProperties:!1},!0,!1,!0,!1,"monitor watch tail log stream background");this.config=t}static Name=Y.MONITOR;validateToolParamValues(t){if(typeof t.command!="string"||!C(t.command).analysisCommand)return"Command cannot be empty.";if(nt(t.command))return'Monitor commands must not contain non-final top-level background operators. Remove "&" and let the monitor manage process lifetime.';if(t.max_events!==void 0){if(typeof t.max_events!="number"||!Number.isInteger(t.max_events)||t.max_events<=0)return"max_events must be a positive integer.";if(t.max_events>O)return`max_events cannot exceed ${O}.`}if(t.idle_timeout_ms!==void 0){if(typeof t.idle_timeout_ms!="number"||!Number.isInteger(t.idle_timeout_ms)||t.idle_timeout_ms<=0)return"idle_timeout_ms must be a positive integer.";if(t.idle_timeout_ms>N)return`idle_timeout_ms cannot exceed ${N}ms (10 minutes).`}if(t.directory){if(!mt.isAbsolute(t.directory))return"Directory must be an absolute path.";let o=mt.resolve(t.directory),a=this.config.storage.getUserSkillsDirs();if(J(a,o))return"Explicitly running monitor commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.";if(!this.config.getWorkspaceContext().isPathWithinWorkspace(t.directory))return`Directory '${t.directory}' is not within any of the registered workspace directories.`}return null}createInvocation(t){return new U(this.config,t)}toAutoClassifierInput(t){let o={command:t.command};return t.directory&&(o.directory=t.directory),o}};export{ht as MonitorTool,gt as sanitizeMonitorLine};
|
|
28
|
-
/**
|
|
29
|
-
* @license
|
|
30
|
-
* Copyright 2025 Matilda
|
|
31
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
32
|
-
*/
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as Z}from"./chunk-I55PXD4N.js";import{Ca as R,He as X,be as D,ce as Y,fc as Q,we as y}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{J as B,K as k,L as U,Lb as z,M as K,N as q,O as b,P as W,Q as j,R as C,S as J,T as V,U as w,V as M,_c as H,ca as G}from"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import{g as $,i as L,p as c,q as x}from"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{A as N,C as T,Y as F,z as _}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();import*as E from"node:fs";import*as m from"node:path";var ee=F("NOTEBOOK_EDIT");function g(d,r,t){return ee.debug("prior-read-rejected",{path:d,reason:r,type:t.type,displayMessage:t.displayMessage}),t}var u=class extends Error{constructor(t,e){super(t);this.type=e;this.name="NotebookEditError"}};function te(d,r){if(r==="delete")return"";if(typeof d!="string")throw new u(`new_source is required when edit_mode is "${r}".`,"invalid_tool_params");return d}function I(d,r){return d?q(d,r):`cell-${r}`}function oe(d,r,t){if(!r){if(t==="insert")return-1;throw new u("cell_id is required for replace and delete operations.","invalid_tool_params")}if(W(d,r))throw new u(`Cell ID "${r}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params");let e=j(d,r);if(e===-1)throw new u(`Cell with ID "${r}" not found in notebook.`,"notebook_cell_not_found");return e}function ie(d,r,t,e){let o={cell_type:r,metadata:{},source:w(t,e)},i=J(d);return i&&(o.id=i),M(o,r),o}function O(d,r){let t;try{t=k(d)}catch(a){throw new u(a instanceof Error?a.message:String(a),"notebook_invalid_json")}let e=r.edit_mode??"replace",o=te(r.new_source,e),i=b(t),n=oe(t,r.cell_id,e),l=C(t),p=U(d),s=(a,f)=>{let h=e==="insert"||e==="delete";return{...f,updatedContent:K(a,p),requiresReadAfterWrite:h&&!(i&&b(a))}};switch(e){case"insert":{let a=r.cell_type??"code",f=n===-1?0:n+1,h=ie(t,a,o,V(t,f));return t.cells.splice(f,0,h),s(t,{editedCellId:I(h,f),editedCellType:a,language:l,mode:e})}case"delete":{let[a]=t.cells.splice(n,1);return s(t,{editedCellId:I(a,n),editedCellType:a?.cell_type,language:l,mode:e})}case"replace":{let a=t.cells[n];if(!a)throw new u(`Cell index ${n} is out of range.`,"notebook_cell_not_found");let f=r.cell_type??a.cell_type;return a.source=w(o,Array.isArray(a.source)),M(a,f),s(t,{editedCellId:I(a,n),editedCellType:f,language:l,mode:e})}default:throw new u(`Unsupported notebook edit mode: ${e}`,"invalid_tool_params")}}function re(d,r,t){let e,o;try{e=k(r),o=k(d)}catch(i){throw new u(i instanceof Error?i.message:String(i),"notebook_invalid_json")}return{updatedContent:r,editedCellId:t.cell_id??"user-modified-notebook",editedCellType:void 0,language:C(e),mode:t.edit_mode??"replace",requiresReadAfterWrite:!b(o)||!b(e)}}async function A(d,r,t={}){if(d.getFileReadCacheDisabled())return{ok:!0};let e;try{e=await E.promises.stat(r)}catch(i){let n=i?.code;return n==="ENOENT"?t.expectExisting?g(r,"missing-after-read",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} disappeared after it was read. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${c.READ_FILE} first.`}):{ok:!0}:g(r,"stat-failed",{ok:!1,type:"prior_read_verification_failed",rawMessage:`Could not stat ${r} to verify prior notebook read (${n??"unknown error"}). Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${r}; re-run ${c.READ_FILE} before editing this notebook.`})}if(e.isDirectory())return g(r,"target-is-directory",{ok:!1,type:"target_is_directory",rawMessage:`${r} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."});if(!e.isFile())return g(r,"target-not-regular-file",{ok:!1,type:"target_not_regular_file",rawMessage:`${r} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."});let o=d.getFileReadCache().check(e);return o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadWasFull?{ok:!0}:o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadWasFull?g(r,"truncated-cache-entry",{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."}):o.state==="stale"?g(r,"stale-cache-entry",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} has been modified since you last read it. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${c.READ_FILE} first.`}):g(r,`cache-${o.state}`,{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} has not been fully read in this session. Use the ${c.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${c.READ_FILE} required before editing this notebook.`})}var P=class extends ${constructor(t,e,o){super(e);this.config=t;this.modifyMetadata=o}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){let t=N(this.params.notebook_path,this.config.getTargetDir()),e=this.params.edit_mode??"replace",o=this.params.cell_id??"beginning";return`${e} notebook cell ${o} in ${_(t)}`}async getDefaultPermission(){return"ask"}async getConfirmationDetails(t){let e=await this.prepareEdit(t),o=m.basename(this.params.notebook_path),i=R(o,e.originalContent,e.updatedContent,"Current","Proposed",D);return{type:"edit",title:`Confirm Notebook Edit: ${_(N(this.params.notebook_path,this.config.getTargetDir()))}`,fileName:o,filePath:this.params.notebook_path,fileDiff:i,originalContent:e.originalContent,newContent:e.updatedContent,onConfirm:async l=>{l==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async prepareEdit(t){let e=await A(this.config,this.params.notebook_path);if(!e.ok)throw new y(e.rawMessage,e.type);let o,i=!1,n,l="lf";try{let s=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});o=s.content,i=s._meta?.bom??!1,n=s._meta?.encoding,l=s._meta?.lineEnding??X(s.content)}catch(s){throw t.aborted?s:s?.code==="ENOENT"?new y(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found"):new y(`Error reading notebook: ${s instanceof Error?s.message:String(s)}`,"read_content_failure")}let p=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!p.ok)throw new y(p.rawMessage,p.type);try{return this.modifyMetadata?.modifiedNotebookContent!==void 0?{...re(o,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}:{...O(o,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}}catch(s){throw s instanceof u?new y(s.message,s.type):s}}async execute(t){let e;try{e=await this.prepareEdit(t)}catch(o){if(t.aborted)throw o;let i=o instanceof y?o.errorType:"notebook_edit_failure",n=o instanceof Error?o.message:String(o);return{llmContent:n,returnDisplay:`Error: ${n}`,error:{message:n,type:i}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}let o=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!o.ok)return{llmContent:o.rawMessage,returnDisplay:`Error: ${o.displayMessage}`,error:{message:o.rawMessage,type:o.type}};await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:e.updatedContent,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}}),this.modifyMetadata?.modifiedByUser||Q.getInstance().recordEdit(this.params.notebook_path,e.originalContent,e.updatedContent);try{let a=E.statSync(this.params.notebook_path),f=this.config.getFileReadCache();e.requiresReadAfterWrite?f.invalidate(a):f.recordWrite(this.params.notebook_path,a,{cacheable:!1})}catch(a){ee.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${a instanceof Error?a.message:String(a)}`)}let i=m.basename(this.params.notebook_path),n=R(i,e.originalContent,e.updatedContent,"Current","Proposed",D),l=Y(i,e.originalContent,this.modifyMetadata?.aiProposedContent??e.updatedContent,e.updatedContent);z(this.config,new H(S.Name,"update",e.updatedContent.split(`
|
|
4
|
-
`).length,G(this.params.notebook_path),".ipynb",e.language));let p={fileDiff:n,fileName:i,originalContent:e.originalContent,newContent:e.updatedContent,diffStat:l},s=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated. Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${e.mode} cell ${e.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated. ${e.mode} cell ${e.editedCellId}.${e.mode==="delete"?"":`
|
|
5
|
-
|
|
6
|
-
Updated source:
|
|
7
|
-
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
${B(this.params.new_source??"")}`}`;try{let a=await Z(this.config,this.params.notebook_path);a&&(s+=`
|
|
11
|
-
|
|
12
|
-
${a}`)}catch{}return{llmContent:s,returnDisplay:p,resultFilePaths:[this.params.notebook_path]}}catch(o){let i=o instanceof Error?o.message:String(o);return{llmContent:`Error writing notebook: ${i}`,returnDisplay:`Error writing notebook: ${i}`,error:{message:i,type:"file_write_failure"}}}}},S=class d extends L{constructor(t){super(d.Name,x.NOTEBOOK_EDIT,`Edits a Jupyter notebook (.ipynb) safely at the cell level. Use this instead of ${c.EDIT} or ${c.WRITE_FILE} for notebook cells. Supports replacing, inserting, and deleting cells. Always read the notebook first with ${c.READ_FILE}; then use the cell IDs shown in that output.`,"edit",{properties:{notebook_path:{description:"Absolute path to the Jupyter notebook file to edit. Must end with .ipynb.",type:"string"},cell_id:{description:"Target cell ID from read_file output, or cell-N 0-based fallback. Required for replace and delete. For insert, the new cell is inserted after this cell; if omitted, inserted at the beginning.",type:"string"},new_source:{description:"New source content for replace and insert operations. Not required for delete.",type:"string"},cell_type:{description:"Cell type for inserted cells or type conversion on replace.",type:"string",enum:["code","markdown"]},edit_mode:{description:"Notebook edit operation. Defaults to replace.",type:"string",enum:["replace","insert","delete"]}},required:["notebook_path"],additionalProperties:!1,type:"object"});this.config=t}static Name=c.NOTEBOOK_EDIT;modifyMetadataByParams=new WeakMap;modifyMetadataByKey=new Map;validateToolParamValues(t){if(t.notebook_path=T(t.notebook_path.trim()),!t.notebook_path)return"The 'notebook_path' parameter must be non-empty.";if(!m.isAbsolute(t.notebook_path))return`Notebook path must be absolute: ${t.notebook_path}`;if(m.extname(t.notebook_path).toLowerCase()!==".ipynb")return"File must be a Jupyter notebook (.ipynb). Use the edit tool for other file types.";let e=t.edit_mode??"replace";return["replace","insert","delete"].includes(e)?t.cell_type&&!["code","markdown"].includes(t.cell_type)?"cell_type must be 'code' or 'markdown'.":e!=="insert"&&!t.cell_id?"cell_id is required for replace and delete operations.":e!=="delete"&&typeof t.new_source!="string"?`new_source is required when edit_mode is "${e}".`:this.config.getFileService().shouldMatildaIgnoreFile(t.notebook_path)?`File path '${t.notebook_path}' is ignored by .matildaignore pattern(s).`:null:"edit_mode must be 'replace', 'insert', or 'delete'."}createInvocation(t){return new P(this.config,t,this.consumeModifyMetadata(t))}getModifyMetadataKey(t){return JSON.stringify({notebook_path:T(t.notebook_path.trim()),cell_id:t.cell_id,new_source:t.new_source,cell_type:t.cell_type,edit_mode:t.edit_mode})}rememberModifyMetadata(t,e){this.modifyMetadataByParams.set(t,e);let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o)??[];i.push(e),this.modifyMetadataByKey.set(o,i)}consumeModifyMetadata(t){let e=this.modifyMetadataByParams.get(t);if(e)return this.modifyMetadataByParams.delete(t),this.removeQueuedModifyMetadata(t,e),e;let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o),n=i?.shift();return i&&i.length===0&&this.modifyMetadataByKey.delete(o),n}removeQueuedModifyMetadata(t,e){let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o);if(!i)return;let n=i.indexOf(e);n!==-1&&i.splice(n,1),i.length===0&&this.modifyMetadataByKey.delete(o)}getModifyContext(t){let e=new Map,o=async i=>{let n=e.get(i.notebook_path);if(n!==void 0)return n;let{content:l}=await this.config.getFileSystemService().readTextFile({path:i.notebook_path});return e.set(i.notebook_path,l),l};return{getFilePath:i=>i.notebook_path,getCurrentContent:async i=>o(i),getProposedContent:async i=>{let n=await o(i);return O(n,i).updatedContent},createUpdatedParams:(i,n,l)=>{let p=this.modifyMetadataByParams.get(l)?.aiProposedContent;if(p===void 0)try{p=O(i,l).updatedContent}catch{p=n}let s={...l};return this.rememberModifyMetadata(s,{aiProposedContent:p,modifiedByUser:!0,modifiedNotebookContent:n}),s}}}};export{S as NotebookEditTool,O as applyNotebookEdit};
|
|
13
|
-
/**
|
|
14
|
-
* @license
|
|
15
|
-
* Copyright 2026 Matilda Team
|
|
16
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
17
|
-
*/
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l}from"./chunk-WQNABJ5R.js";import"./chunk-QCIDUZV6.js";import"./chunk-R6YTDM76.js";import"./chunk-S4K76QPI.js";import{b as a}from"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{h as ContentGenerationPipeline,c as DeepSeekOpenAICompatibleProvider,i as EnhancedErrorHandler,b as MatildaOpenAICompatibleProvider,g as MiMoOpenAICompatibleProvider,e as MiniMaxOpenAICompatibleProvider,f as MistralOpenAICompatibleProvider,a as OpenAIContentConverter,j as OpenAIContentGenerator,d as OpenRouterOpenAICompatibleProvider,k as createOpenAIContentGenerator,l as determineProvider};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{qj as a,rj as b}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as RipGrepTool,a as _resetRipGrepCachesForTest};
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as E}from"./chunk-7ZATDBWL.js";import{Pa as P}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{L as l,Y as c}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as s}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";s();import{stat as V}from"node:fs/promises";import{join as p}from"node:path";s();import{readdir as N,stat as H,rm as F,rmdir as A}from"node:fs/promises";import{join as y}from"node:path";var k=c("HOUSEKEEPING"),U=24*60*60*1e3,$=60*60*1e3,_=20;function T(e){let t=e>0?e*U:$;return new Date(Date.now()-t)}async function b(e){let t={removed:0,errors:0},r=y(l.getGlobalMatildaDir(),P),i=e.excludeSessionIds??new Set,o;try{o=await N(r,{withFileTypes:!0})}catch(n){return G(n)||k.error("readdir failed",n),t}let a=o.filter(n=>n.isDirectory()&&!i.has(n.name)).map(n=>y(r,n.name));for(let n=0;n<a.length;n+=_){let v=a.slice(n,n+_);await Promise.all(v.map(async g=>{try{(await H(g)).mtime<e.cutoffDate&&(await F(g,{recursive:!0,force:!0}),t.removed++)}catch(w){t.errors++,k.error(`failed to sweep ${g}`,w)}}))}return await A(r).catch(()=>{}),t}function G(e){return e?.code==="ENOENT"}s();import{mkdir as Y,open as K,stat as I,unlink as D,writeFile as j}from"node:fs/promises";import{dirname as B}from"node:path";var m=c("HOUSEKEEPING"),q=24*60*60*1e3,J=60*60*1e3;async function R(e,t){let r=e.minIntervalMs??q,i=e.staleLockMs??J;if(await Y(B(e.lockPath),{recursive:!0,mode:448}).catch(()=>{}),await C(e.markerPath,r,e.name))return!1;let o=await h(e.lockPath);if(!o){try{let a=await I(e.lockPath);Date.now()-a.mtimeMs>i&&(await D(e.lockPath).catch(()=>{}),o=await h(e.lockPath))}catch{o=await h(e.lockPath)}if(!o)return m.debug(`${e.name}: skipping, lock held`),!1}try{if(await C(e.markerPath,r,e.name))return!1;let a=!1;try{await t(),a=!0}finally{if(a)try{await j(e.markerPath,new Date().toISOString())}catch(n){m.debug(`${e.name}: marker write failed (cleanup succeeded)`,n)}}return a}finally{await D(e.lockPath).catch(()=>{m.debug(`${e.name}: lock unlink failed (harmless)`)})}}async function C(e,t,r){try{let i=await I(e),o=Date.now()-i.mtimeMs;if(o<t)return m.debug(`${r}: skipping, ran ${o}ms ago`),!0}catch{}return!1}async function h(e){try{return await(await K(e,"wx")).close(),!0}catch(t){if(t?.code==="EEXIST")return!1;throw t}}var u=c("HOUSEKEEPING"),O=10*60*1e3,W=24*60*60*1e3,X=60*1e3,z=7*24*60*60*1e3,Q=60*1e3,f=".file-history-cleanup",d=!1;function pe(e,t){d||(d=!0,Z(e,t).catch(r=>{d=!1,u.error("scheduleFirstPass failed; chain will retry on next start",r)}))}async function Z(e,t){let r=p(l.getGlobalMatildaDir(),f),i=await L(r)?Q:O;u.debug(`first pass in ${i/1e3}s`),setTimeout(()=>S(e,t),i).unref()}async function L(e){try{let t=await V(e);return Date.now()-t.mtimeMs>z}catch{return!0}}async function M(e,t){if(E()<X){u.debug("user active, deferring 10 min"),setTimeout(()=>S(e,t),O).unref();return}try{await x(e,t)}catch(r){u.error("housekeeping pass failed; will retry next cycle",r)}setTimeout(()=>S(e,t),W).unref()}function S(e,t){M(e,t).catch(r=>{u.error("runPass rejected unexpectedly",r)})}async function x(e,t){let r=t.merged.general?.cleanupPeriodDays??30,i=T(r),o=e.getSessionId(),a=l.getGlobalMatildaDir();await R({name:"file-history-cleanup",markerPath:p(a,f),lockPath:p(a,f+".lock")},async()=>{let n=await b({cutoffDate:i,excludeSessionIds:new Set([o])});u.debug(`file-history: removed=${n.removed} errors=${n.errors}`)})}function Se(){d=!1}var we=L,Pe=x,Ee=M,ye=f;export{ye as _FILE_HISTORY_MARKER_FOR_TESTING,we as _needsCatchUpForTesting,Se as _resetForTesting,Pe as _runHousekeepingForTesting,Ee as _runPassForTesting,pe as startBackgroundHousekeeping};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Google LLC
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/shell-YAP6NQTT.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Ke as a,Le as b,Me as c,Ne as d,Oe as e,Pe as f}from"./chunk-KMU5KAYC.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-APVMKC4S.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as OUTPUT_UPDATE_INTERVAL_MS,f as ShellTool,e as ShellToolInvocation,c as buildLongRunningForegroundHint,d as detectBlockedSleepPattern,a as parseNumstat};
|