@maincode-ai/matilda-code 0.20.0 → 0.20.1

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.
Files changed (63) hide show
  1. package/bundled/mainy/docs/features/headless.md +37 -0
  2. package/bundled/mainy/docs/features/mcp.md +3 -3
  3. package/chunks/{agent-N5H7ZVZN.js → agent-CE34X462.js} +1 -1
  4. package/chunks/{agent-headless-LBLAX66M.js → agent-headless-CNI7H4BU.js} +1 -1
  5. package/chunks/{anthropicContentGenerator-DKMAJXYA.js → anthropicContentGenerator-ATLOKYPR.js} +1 -1
  6. package/chunks/chunk-3YLXGE6T.js +8 -0
  7. package/chunks/{chunk-GTR4V2PV.js → chunk-DC7LAFZZ.js} +1 -1
  8. package/chunks/chunk-DHBNZZZO.js +95 -0
  9. package/chunks/{chunk-KP6BLFQS.js → chunk-GIIMOLLN.js} +1 -1
  10. package/chunks/chunk-IMYUVCF7.js +27 -0
  11. package/chunks/{chunk-3KCDX6MY.js → chunk-ISW2QC5B.js} +1 -1
  12. package/chunks/{chunk-RO6LKQPB.js → chunk-J56KRT6Z.js} +458 -458
  13. package/chunks/chunk-OCXGNAAT.js +8 -0
  14. package/chunks/{chunk-Z7OHKQ7V.js → chunk-OQVITNHW.js} +1 -1
  15. package/chunks/{chunk-QT4UNNZ4.js → chunk-SKBC2YV2.js} +4 -4
  16. package/chunks/{chunk-XXZH7C44.js → chunk-SS5WUOSJ.js} +1 -1
  17. package/chunks/chunk-T75X5DJI.js +101 -0
  18. package/chunks/{chunk-TRM7SXZ5.js → chunk-WUQZ3WFM.js} +1 -1
  19. package/chunks/chunk-XJDC3ZQZ.js +8 -0
  20. package/chunks/{computer-use-LG4QQFMP.js → computer-use-4533FJAL.js} +1 -1
  21. package/chunks/contextCommand-M7LA5BRD.js +3 -0
  22. package/chunks/edit-U4P4JWQ6.js +38 -0
  23. package/chunks/{enter-worktree-OIP2B3NM.js → enter-worktree-CUDNIQNH.js} +1 -1
  24. package/chunks/enterPlanMode-SUTLQUZO.js +18 -0
  25. package/chunks/{exit-worktree-VN5I5XWV.js → exit-worktree-72O3N4X4.js} +1 -1
  26. package/chunks/{exitPlanMode-HE6EEGTO.js → exitPlanMode-ZP75YCUK.js} +14 -14
  27. package/chunks/geminiContentGenerator-KPR5Q3XX.js +8 -0
  28. package/chunks/{glob-EGOAJNOQ.js → glob-V7YUXA6Z.js} +1 -1
  29. package/chunks/{grep-JYHW6SSG.js → grep-WOVNDJPG.js} +1 -1
  30. package/chunks/{matildaAgentContentGenerator-AKNRQW6A.js → matildaAgentContentGenerator-Y5CHD2WJ.js} +1 -1
  31. package/chunks/matildaContentGenerator-F2DTT47Z.js +8 -0
  32. package/chunks/matildaOAuth2-LKOMJUC6.js +3 -0
  33. package/chunks/{monitor-IDNOTNUP.js → monitor-G7G765XR.js} +1 -1
  34. package/chunks/{notebook-edit-4VBYBZFJ.js → notebook-edit-QK7K5ALF.js} +1 -1
  35. package/chunks/{openaiContentGenerator-WTRQK5RJ.js → openaiContentGenerator-XLDE2S4K.js} +1 -1
  36. package/chunks/ripGrep-W5JZVWA4.js +3 -0
  37. package/chunks/{scheduler-AOKJEAXJ.js → scheduler-C7N3Q67S.js} +1 -1
  38. package/chunks/{serve-2JJY265V.js → serve-WDV5Q7R4.js} +1 -1
  39. package/chunks/shell-IEGVNM6S.js +3 -0
  40. package/chunks/src-Y3JZTLKR.js +3 -0
  41. package/chunks/{team-create-Z6636NPD.js → team-create-OPP7B3G2.js} +1 -1
  42. package/chunks/{update-goal-DH2TEYYU.js → update-goal-6WDBMJ2I.js} +1 -1
  43. package/chunks/{web-fetch-5F7C7MXU.js → web-fetch-QP42GV23.js} +1 -1
  44. package/chunks/{web-search-W2FYCGK5.js → web-search-FURCBRRK.js} +1 -1
  45. package/chunks/{workflow-M7KXXDO6.js → workflow-B3DRPVNT.js} +2 -2
  46. package/chunks/write-file-T7MBHX53.js +11 -0
  47. package/cli.js +476 -456
  48. package/package.json +2 -2
  49. package/chunks/chunk-7VGUNT5L.js +0 -8
  50. package/chunks/chunk-CLUEFPSU.js +0 -8
  51. package/chunks/chunk-CYTN3WRM.js +0 -101
  52. package/chunks/chunk-IB7TWUWM.js +0 -90
  53. package/chunks/chunk-LLQVLTPB.js +0 -27
  54. package/chunks/contextCommand-7KHYFQ6G.js +0 -3
  55. package/chunks/edit-U4PMKZYZ.js +0 -38
  56. package/chunks/enterPlanMode-6LZSSWFT.js +0 -17
  57. package/chunks/geminiContentGenerator-GWGLIDJJ.js +0 -8
  58. package/chunks/matildaContentGenerator-MXP3V2UQ.js +0 -8
  59. package/chunks/matildaOAuth2-2IUZAZEO.js +0 -3
  60. package/chunks/ripGrep-DOB57AMM.js +0 -3
  61. package/chunks/shell-WFONAKPV.js +0 -3
  62. package/chunks/src-IHYMMU26.js +0 -3
  63. package/chunks/write-file-O4DJX4LP.js +0 -11
@@ -0,0 +1,8 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{w as n}from"./chunk-UY2R3ZQ4.js";import{b as e}from"./chunk-GZPNIYVZ.js";e();import a from"node:path";function g(r,i){if(r.getApprovalMode()!=="bogan")return null;let o=a.resolve(i),s=r.getProjectRoot?.()??r.getTargetDir();if(n(o,s))return null;let t=r.getWorkspaceContext?.();if(!t||t.isPathWithinWorkspace(o))return null;let p=t.getDirectories?.()??[r.getTargetDir()];return`Refusing out-of-workspace write in BOGAN mode: ${o}. Workspace root(s): ${p.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.`}export{g as a};
4
+ /**
5
+ * @license
6
+ * Copyright 2025 Matilda Team
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{bh as T}from"./chunk-RO6LKQPB.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var W=e=>{process.stdout.write(e.endsWith(`
3
+ import{ch as T}from"./chunk-J56KRT6Z.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var W=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as rs}from"./chunk-QCIDUZV6.js";import{a as es,b as ts,c as qt}from"./chunk-3KCDX6MY.js";import{a as ns}from"./chunk-GTR4V2PV.js";import{c as yr,f as ve}from"./chunk-S4K76QPI.js";import{a as qn,b as ot,c as Xn,x as Qn}from"./chunk-CYTN3WRM.js";import{a as Zr,e as Jn,j as Vn,o as Kn,q as zn,s as Yn,t as hr}from"./chunk-XYA3SFGC.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{a as gr,b as _r,e as Zn,m as br}from"./chunk-CLUEFPSU.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(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 tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=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 Xt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Jt=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 y=class extends Error{},$=class n extends y{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:Jt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=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."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{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 fo=/^[a-z][a-z0-9+.-]*:/i,ss=n=>fo.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function os(n){return typeof n!="object"?{}:n??{}}function is(n){if(!n)return!0;for(let e in n)return!1;return!0}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ls=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var cs=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 ds=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function po(){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 mo=()=>{let n=po();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":us(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":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ho();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 ho(){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 us=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=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"),ps,ms=()=>ps??(ps=mo());a();function hs(){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 nn(...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 Cr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(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 gs(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 _s=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var wr="RFC3986",on=n=>String(n),Ar={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var xr=(n,e)=>(xr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xr(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,bs=(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+=ln){let u=o.length>=ln?o.slice(l,l+ln):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===an&&(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 ys(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(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 ws={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},As=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Cs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bs,encodeValuesOnly:!1,format:wr,formatter:on,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function bo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function xs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,X=!1;for(;(U=U.get(un))!==void 0&&!X;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");X=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(bo(w)||ys(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Qr=p&&l?M.replace(/\./g,"%2E"):M,co=W(w)?typeof t=="function"?t(j,Qr):j:j+(p?"."+Qr:"["+Qr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),As(H,xs(Gn,co,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function yo(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=wr;if(typeof n.format<"u"){if(!xr(Ar,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Ar[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ws?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 fn(n,e={}){let t=n,r=yo(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=ws[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||As(i,xs(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 Rs(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 Is;function gt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}var Ps;function pn(n){let e;return(Ps??(e=new globalThis.TextDecoder,Ps=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),A(this,J,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,J,Rs([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=wo(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,J,"f").subarray(0,c(this,V,"f")-1))),A(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,J,"f").subarray(0,o));r.push(i),A(this,J,c(this,J,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
3
+ import{a as ns}from"./chunk-QCIDUZV6.js";import{a as ts,b as rs,c as qt}from"./chunk-ISW2QC5B.js";import{c as yr,f as ve}from"./chunk-S4K76QPI.js";import{a as qn,b as ot,c as Xn,x as Zn}from"./chunk-T75X5DJI.js";import{a as Yn}from"./chunk-DC7LAFZZ.js";import{a as Zr,e as Jn,j as Vn,o as Kn,q as zn,s as Qn,t as hr}from"./chunk-XYA3SFGC.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as es,n as br}from"./chunk-XJDC3ZQZ.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(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 tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=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 Xt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Jt=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 y=class extends Error{},$=class n extends y{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:Jt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=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."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{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 fo=/^[a-z][a-z0-9+.-]*:/i,ss=n=>fo.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function os(n){return typeof n!="object"?{}:n??{}}function is(n){if(!n)return!0;for(let e in n)return!1;return!0}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ls=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var cs=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 ds=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function po(){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 mo=()=>{let n=po();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":us(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":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ho();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 ho(){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 us=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=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"),ps,ms=()=>ps??(ps=mo());a();function hs(){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 nn(...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 Cr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(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 gs(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 _s=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var wr="RFC3986",on=n=>String(n),Ar={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var xr=(n,e)=>(xr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xr(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,bs=(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+=ln){let u=o.length>=ln?o.slice(l,l+ln):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===an&&(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 ys(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(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 ws={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},As=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Cs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bs,encodeValuesOnly:!1,format:wr,formatter:on,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function bo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function xs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,X=!1;for(;(U=U.get(un))!==void 0&&!X;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");X=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(bo(w)||ys(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Qr=p&&l?M.replace(/\./g,"%2E"):M,co=W(w)?typeof t=="function"?t(j,Qr):j:j+(p?"."+Qr:"["+Qr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),As(H,xs(Gn,co,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function yo(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=wr;if(typeof n.format<"u"){if(!xr(Ar,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Ar[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ws?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 fn(n,e={}){let t=n,r=yo(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=ws[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||As(i,xs(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 Rs(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 Is;function gt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}var Ps;function pn(n){let e;return(Ps??(e=new globalThis.TextDecoder,Ps=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),A(this,J,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,J,Rs([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=wo(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,J,"f").subarray(0,c(this,V,"f")-1))),A(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,J,"f").subarray(0,o));r.push(i),A(this,J,c(this,J,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
4
4
  `):[]}};J=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
5
5
  `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wo(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 Os(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 Pr={off:0,error:200,warn:300,info:400,debug:500},dn=(n,e,t)=>{if(n){if(as(Pr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Pr))}`)}};function Kt(){}function Ir(n,e,t){return!e||Pr[n]>Pr[t]?Kt:e[n].bind(e)}var Ao={error:Kt,warn:Kt,info:Kt,debug:Kt},Ss=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Ao;let r=Ss.get(e);if(r&&r[0]===t)return r[1];let s={error:Ir("error",e,t),warn:Ir("warn",e,t),info:Ir("info",e,t),debug:Ir("debug",e,t)};return Ss.set(e,[t,s]),s}var le=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 zt,re=class n{constructor(e,t,r){this.iterator=e,zt.set(this,void 0),this.controller=t,A(this,zt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of xo(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(Xt(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=sn(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 y("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(Xt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(zt=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,zt,"f")),new n(()=>s(t),this.controller,c(this,zt,"f"))]}toReadableStream(){let e=this,t;return nn({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=gt(JSON.stringify(s)+`
6
6
  `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*xo(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("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 y("Attempted to iterate over a response with no body");let t=new mn,r=new Te,s=sn(n.body);for await(let o of Io(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*Io(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"?gt(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=Os(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var mn=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(`
@@ -22,15 +22,15 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
22
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
23
23
 
24
24
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
25
- `);this.baseURL=l.baseURL,this.timeout=l.timeout??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??hs(),A(this,Vr,_s,"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 fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",no).call(this)&&r||this.baseURL,o=ss(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return is(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 ke(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`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Jt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Xt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await gs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Jt(E).message),S=cs(U),X=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,X,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,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 Qt(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&&ls("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))}:{},...ms(),"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:Cr(e)}:c(this,Vr,"f").call(this,{body:e,headers:r})}};Un=I,Vr=new WeakMap,Fn=new WeakSet,no=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=Er;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=Ke;I.Audio=se;I.Moderations=Ye;I.Models=ze;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Qe;I.Beta=ie;I.Batches=Le;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Pi(n){return n.toLowerCase().includes("matilda3")}function Ri(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 F=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};for(let[o,i]of Object.entries(r??{}))Zn(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("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=Pi(e.model)?s.messages.map(Ri):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=zn(e.model,"output"),s=Kn(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 Ht=class extends F{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 Oi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{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=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Oi.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??{}))!ts(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,es(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Yn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br();if(!b&&Object.keys(f).length===0)return l(d,g);p.delete(gr),p.delete(_r);for(let[C,P]of Object.entries(f))p.set(C,P);let x=p.get("x-stainless-retry-count");return p.has(gr)&&x!==null&&/^[1-9][0-9]*$/.test(x)&&p.set(_r,"retry"),l(d,{...g,headers:p})}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}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 Kr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(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 Si(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Si;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?vi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Ei(i);return Kr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Ei(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(`
25
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??hs(),A(this,Vr,_s,"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 fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",no).call(this)&&r||this.baseURL,o=ss(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return is(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 ke(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`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Jt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Xt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await gs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Jt(E).message),S=cs(U),X=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,X,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,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 Qt(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&&ls("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))}:{},...ms(),"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:Cr(e)}:c(this,Vr,"f").call(this,{body:e,headers:r})}};Un=I,Vr=new WeakMap,Fn=new WeakSet,no=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=Er;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=Ke;I.Audio=se;I.Moderations=Ye;I.Models=ze;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Qe;I.Beta=ie;I.Batches=Le;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Pi(n){return n.toLowerCase().includes("matilda3")}function Ri(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 F=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};for(let[o,i]of Object.entries(r??{}))es(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("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=Pi(e.model)?s.messages.map(Ri):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=zn(e.model,"output"),s=Kn(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 Ht=class extends F{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 Oi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{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=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Oi.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??{}))!rs(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,ts(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Qn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br();if(!b&&Object.keys(f).length===0)return l(d,g);p.delete(gr),p.delete(_r);for(let[C,P]of Object.entries(f))p.set(C,P);let x=p.get("x-stainless-retry-count");return p.has(gr)&&x!==null&&/^[1-9][0-9]*$/.test(x)&&p.set(_r,"retry"),l(d,{...g,headers:p})}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}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 Kr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(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 Si(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Si;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?vi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Ei(i);return Kr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Ei(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
26
 
27
27
  `);return{...n,content:t}}function vi(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 F{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 Ti=["api.minimaxi.com","api.minimax.io"],ki=[".minimaxi.com",".minimax.io"],tt=class extends F{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return Ti.includes(t)?!0:ki.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var so="api.mistral.ai",Mi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function $i(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===so||t.endsWith(`.${so}`)}catch{return!1}}function Ni(n){if($i(n))return!0;let e=n.model?.toLowerCase()??"";return Mi.some(t=>e.includes(t))}var rt=class extends F{static isMistralProvider=Ni;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Li)}}};function Li(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Fi(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 F{constructor(e,t){super(e,t)}static isMiMoProvider=Fi;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Kr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var Ui=me("STREAMING_TOOL_CALL_PARSER"),zr=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 P=this.buffers.get(e),O=this.depths.get(e),w=this.toolCallMeta.get(e);if(P.trim()&&O===0&&w?.id&&w.id!==r)try{JSON.parse(P),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let P=this.buffers.get(e);if(this.depths.get(e)>0||!P.trim())o=e;else try{JSON.parse(P),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),Ui.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),b=l+t;this.buffers.set(o,b);let f=u,x=g,C=p;for(let P of t)x||(P==="{"||P==="["?f++:(P==="}"||P==="]")&&f--),P==='"'&&!C&&(x=!x),C=P==="\\"&&!C;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,C),f===0&&b.trim().length>0)try{return{complete:!0,value:JSON.parse(b)}}catch(P){if(x)try{return{complete:!0,value:JSON.parse(b+'"'),repaired:!0}}catch{}return{complete:!1,error:P instanceof Error?P:new Error(String(P))}}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=Zr(s,{})}else i=Zr(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 oo=16e3,io=`[Earlier content omitted to fit Matilda Core external API limits]
28
- `,Yr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=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?en(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ot.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}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 Yr(g)}let u=ot.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 Yr)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 Hn;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=ot.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 ot.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,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="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,fr(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(`
28
+ `,Yr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=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?en(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ot.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}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 Yr(g)}let u=ot.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 Yr)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 Hn;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=ot.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 ot.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,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="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,fr(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,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;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
29
  `):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=oo)return r;let s=oo-io.length;return`${io}${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 Xn.getStore()?.(i),Jn.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 zr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new qn: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 Di=me("OPENAI_ERROR"),dr=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)||Di.error("OpenAI API Error:",i),o?new Error(`${i}
30
30
 
31
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
32
  ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
33
- `)}`}};var ao=me("OPENAI"),st=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(Wn(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 rs().calculateTokens(e)).totalTokens}}catch(t){ao.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 ao.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var mr=class extends st{contentGeneratorConfig;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e}shouldSuppressErrorLogging(e,t){return lo(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.withTokenRefresh(()=>super.generateContentStream(e,t))}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t=await Qn({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh});t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[ns]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!lo(t))throw t;return await this.applyValidToken({forceRefresh:!0}),await e()}}};function lo(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function l_(n,e){let t=ji(n,e);return ae.isMatildaCompatibleProvider(n)?new mr(n,e,t):new st(n,e,t)}function ji(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new F(n,e)}export{ae as a,Ze as b,et as c,tt as d,rt as e,nt as f,pr as g,dr as h,st as i,mr as j,l_ as k,ji as l};
33
+ `)}`}};var ao=me("OPENAI"),st=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(Wn(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 ns().calculateTokens(e)).totalTokens}}catch(t){ao.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 ao.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var mr=class extends st{contentGeneratorConfig;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e}shouldSuppressErrorLogging(e,t){return lo(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.withTokenRefresh(()=>super.generateContentStream(e,t))}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t=await Zn({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh});t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[Yn]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!lo(t))throw t;return await this.applyValidToken({forceRefresh:!0}),await e()}}};function lo(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function l_(n,e){let t=ji(n,e);return ae.isMatildaCompatibleProvider(n)?new mr(n,e,t):new st(n,e,t)}function ji(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new F(n,e)}export{ae as a,Ze as b,et as c,tt as d,rt as e,nt as f,pr as g,dr as h,st as i,mr as j,l_ as k,ji as l};
34
34
  /**
35
35
  * @license
36
36
  * Copyright 2025 Matilda
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{j as C}from"./chunk-CLUEFPSU.js";import{Y as p}from"./chunk-QWBNNEV2.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();var u=new Map;function ge(e,t){return e===t?!0:!e||!t?!1:_(e)===_(t)}function _(e){let t={};for(let n of Object.keys(e).sort()){let o=e[n];o!==void 0&&(t[n]=o)}return JSON.stringify(t)}function v(e){return u.get(e)}function I(e,t){u.set(e,t)}function R(e){let t=u.get(e);return u.delete(e),t}function L(e,t){let n=u.get(e);if(!n)return;let o={...n,iterations:n.iterations+1,lastReason:t};return u.set(e,o),o}function fe(e,t,n){let o=u.get(e);if(!o)return;let i={...o,status:t,statusNote:t==="active"?void 0:n?.trim()||o.statusNote};return t==="active"&&delete i.statusNote,u.set(e,i),i}function M(e){return e.status??"active"}function pe(){u.clear(),b.clear(),k.clear()}var b=new Map;function me(e,t){b.set(e,t)}function w(e){b.delete(e)}function N(e,t){K(e,t);let n=b.get(e);if(n)try{n(t)}catch{}}var k=new Map;function K(e,t){k.set(e,t)}function ye(e){return k.get(e)}function Ge(e,t){if(!t){k.delete(e);return}k.set(e,t)}g();g();var A=p("ERROR_REPORT");async function j(e,t,n,o="general"){let i;e instanceof Error?i={message:e.message,stack:e.stack}:typeof e=="object"&&e!==null&&"message"in e?i={message:String(e.message)}:i={message:String(e)};let r={error:i};n&&(r.context=n);let s=`${t} [${o}]`,c;try{c=JSON.stringify(r,null,2)}catch(l){A.error(`${s} Could not stringify report content (likely due to context):`,l,e);try{c=JSON.stringify({error:i},null,2),A.error(s,c)}catch(f){A.error(`${s} Failed to stringify minimal error report:`,f,e)}return}A.error(s,c)}var h=p("GOAL_JUDGE"),q=`You are evaluating a stop-condition hook in an autonomous coding agent.
3
+ import{k as C}from"./chunk-XJDC3ZQZ.js";import{Y as p}from"./chunk-QWBNNEV2.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();var u=new Map;function ge(e,t){return e===t?!0:!e||!t?!1:_(e)===_(t)}function _(e){let t={};for(let n of Object.keys(e).sort()){let o=e[n];o!==void 0&&(t[n]=o)}return JSON.stringify(t)}function v(e){return u.get(e)}function I(e,t){u.set(e,t)}function R(e){let t=u.get(e);return u.delete(e),t}function L(e,t){let n=u.get(e);if(!n)return;let o={...n,iterations:n.iterations+1,lastReason:t};return u.set(e,o),o}function fe(e,t,n){let o=u.get(e);if(!o)return;let i={...o,status:t,statusNote:t==="active"?void 0:n?.trim()||o.statusNote};return t==="active"&&delete i.statusNote,u.set(e,i),i}function M(e){return e.status??"active"}function pe(){u.clear(),b.clear(),k.clear()}var b=new Map;function me(e,t){b.set(e,t)}function w(e){b.delete(e)}function N(e,t){K(e,t);let n=b.get(e);if(n)try{n(t)}catch{}}var k=new Map;function K(e,t){k.set(e,t)}function ye(e){return k.get(e)}function Ge(e,t){if(!t){k.delete(e);return}k.set(e,t)}g();g();var A=p("ERROR_REPORT");async function j(e,t,n,o="general"){let i;e instanceof Error?i={message:e.message,stack:e.stack}:typeof e=="object"&&e!==null&&"message"in e?i={message:String(e.message)}:i={message:String(e)};let r={error:i};n&&(r.context=n);let s=`${t} [${o}]`,c;try{c=JSON.stringify(r,null,2)}catch(l){A.error(`${s} Could not stringify report content (likely due to context):`,l,e);try{c=JSON.stringify({error:i},null,2),A.error(s,c)}catch(f){A.error(`${s} Failed to stringify minimal error report:`,f,e)}return}A.error(s,c)}var h=p("GOAL_JUDGE"),q=`You are evaluating a stop-condition hook in an autonomous coding agent.
4
4
  Read the conversation transcript above carefully, then judge whether the
5
5
  user-provided condition is satisfied.
6
6
 
@@ -0,0 +1,101 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as L,d as st}from"./chunk-4F4DA5UI.js";import{a as dt,b as ke,c as ct,d as ut}from"./chunk-DC7LAFZZ.js";import{a as it,b as rt,e as xe,n as lt,q as B,r as pt}from"./chunk-XYA3SFGC.js";import{b as A,e as K}from"./chunk-4J6DC24J.js";import{a as at}from"./chunk-XJDC3ZQZ.js";import{Jc as tt,Kc as nt,Mb as Ze,Mc as ot,Pb as Qe,Rb as et,Sa as F,Wa as ve,Xa as _e,Ya as be,eb as Ie,f as P,fb as $,tb as Q,ub as ee}from"./chunk-CFBZKYFB.js";import{b as gt}from"./chunk-3YLXGE6T.js";import{L as Xe,Y as I,c as qe,d as H,e as V}from"./chunk-QWBNNEV2.js";import{h as k,l as Se,n as qt}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();f();var te=I("TAGGED_THINKING_PARSER"),ft=["<think>","<thinking>"],ht=["</think>","</thinking>"],Xt=Math.max(...ft.map(t=>t.length),...ht.map(t=>t.length));function we(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Zt(t,e,n){let o=t.length-e;return o<=0||o>Xt?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function Qt(t,e,n){return n.find(o=>t.startsWith(o,e))}var Re=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){let s=this.mode==="text"?ft:ht,l=Qt(o,a,s);if(l){te.debug(`taggedThinking: detected tag "${l}" at offset ${a}`),we(i,r,this.mode),r="",this.mode=this.mode==="text"?"thought":"text",a+=l.length;continue}if(!n&&Zt(o,a,s))break;r+=this.buffer[a],a+=1}return a<this.buffer.length?(we(i,r,this.mode),this.buffer=this.buffer.slice(a),te.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),i):(this.buffer="",this.mode==="thought"&&r&&te.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),we(i,r,this.mode),te.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),i)}};function mt(t){return new Re().parse(t,!0)}var w=I("CONVERTER"),vt="(attached media from previous tool call)";function _t(t){let e=t.prompt_tokens||0,n=t.completion_tokens||0,o=t.total_tokens||0,i=t.prompt_tokens_details,r=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details?.reasoning_tokens||0,s=t.usage_is_incomplete===!0||n>0&&e===0||o>0&&e===0&&n===0,l=e,d=n,c=o;return c===0&&(l>0||d>0)&&(c=l+d),{promptTokenCount:l,candidatesTokenCount:d,totalTokenCount:c,cachedContentTokenCount:r,thoughtsTokenCount:a,...s?{usageIsIncomplete:!0}:{}}}var en=64,Ct=1024;function yt(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,i=n>=Ct&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=en?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<Ct&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function bt(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function tn(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=bt(r.parameters)),a&&(a=rt(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function nn(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return rn(t,o),an(t.contents,o,e),o=St(o),n.cleanOrphanToolCalls&&(o=fn(o),o=St(o)),o}function on(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let p of o)typeof p=="string"?r.push(p):"text"in p&&p.text?"thought"in p&&p.thought?i.push(p.text):r.push(p.text):"functionCall"in p&&p.functionCall&&(a.push({id:p.functionCall.id||`call_${s}`,type:"function",function:{name:p.functionCall.name||"",arguments:JSON.stringify(p.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},d=i.join("");d&&(l.reasoning_content=d),a.length>0&&(l.tool_calls=a);let c=gn(n?.finishReason),g=t.usageMetadata,u={prompt_tokens:g?.promptTokenCount||0,completion_tokens:g?.candidatesTokenCount||0,total_tokens:g?.totalTokenCount||0};g?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:g.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:u}}function rn(t,e){if(!t.config?.systemInstruction)return;let n=xt(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function an(t,e,n){if(Array.isArray(t))for(let o of t)Tt(o,e,n);else t&&Tt(t,e,n)}function Tt(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!cn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,d=new Set,c=new Set,g=[];for(let u of o){if(typeof u=="string"){r.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&i==="assistant"&&u.text&&a.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&r.push({type:"text",text:u.text});let m=It(u,n);if(m&&i==="user"&&r.push(m),"functionCall"in u&&u.functionCall&&i==="assistant"){let h=u.functionCall.id;if(h){if(d.has(h)){w.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}d.add(h)}s.push({id:h||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&i==="user"){let h=u.functionResponse.id;if(h){if(c.has(h))continue;c.add(h)}let p=ln(u.functionResponse,n);if(p){if(n.splitToolMedia&&Array.isArray(p.content)){let C=[],y=[];for(let T of p.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
4
+ `);p.content=T||"[media attached in following user message]",g.push(...C)}}e.push(p)}}}if(g.length>0&&e.push({role:"user",content:[{type:"text",text:vt},...g]}),i==="assistant"){if(r.length===0&&s.length===0&&a.length===0)return;let m={role:"assistant",content:r.filter(p=>p.type==="text").map(p=>p.text).join("")||(a.length>0?"":null)};s.length>0&&(m.tool_calls=s);let h=a.join("");h&&(m.reasoning_content=h),e.push(m);return}r.length>0&&e.push({role:"user",content:r})}function sn(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function ln(t,e){let n=sn(t.response),o=[];n&&o.push({type:"text",text:n});for(let i of t.parts||[]){if("text"in i&&typeof i.text=="string"){i.text.length>0&&o.push({type:"text",text:i.text});continue}let r=It(i,e);r&&o.push(r)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function It(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,i=At(o),r=t.inlineData.displayName||o;if(i==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("image",r,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:U("pdf",r,e);if(i==="audio"){if(!n.audio)return U("audio",r,e);let a=dn(o);if(a)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:a}}}return i==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:U("video",r,e):{type:"text",text:`Unsupported inline media type: ${o} (${r}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",i=t.fileData.fileUri,r=t.fileData.mimeType,a=At(r);if(a==="image")return n.image?{type:"image_url",image_url:{url:i}}:U("image",o,e);if(r==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:i}}:U("pdf",o,e);if(a==="video")return n.video?{type:"video_url",video_url:{url:i}}:U("video",o,e);let s=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${r}${s}.`}}return null}function U(t,e,n){w.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
5
+ /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function At(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function dn(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function cn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function xt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>xt(e)).filter(Boolean).join(`
6
+ `):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
7
+ `)||""}function Ee(t,e,n=!0){return e.responseParsingOptions?.taggedThinkingTags?e.taggedThinkingParser?e.taggedThinkingParser.parse(t,n):mt(t):t?[{text:t}]:[]}function un(t,e){let n=t.choices?.[0],o=new K;if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let r=n.message.reasoning_content??n.message.reasoning;r&&i.push({text:r,thought:!0})}if(n.message.content&&i.push(...Ee(n.message.content,e)),n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a={};r.function.arguments&&(a=it(r.function.arguments,{})),i.push({functionCall:{id:r.id,name:r.function.name,args:a}})}}o.candidates=[{content:{parts:i,role:"model"},finishReason:kt(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=_t(t.usage)),o}function pn(t,e){let n=t.choices?.[0],o=new K,i=e.toolCallParser;if(!i)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let d=n.delta?.reasoning_content??n.delta?.reasoning;if(d){let c=yt(d,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&r.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let d=yt(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(d||n.finish_reason)&&r.push(...Ee(d,e,!!n.finish_reason))}else n.finish_reason&&r.push(...Ee("",e,!0));if(n.delta?.tool_calls)for(let d of n.delta.tool_calls){let c=d.index??0;d.function?.arguments?i.addChunk(c,d.function.arguments,d.id,d.function.name):i.addChunk(c,"",d.id,d.function?.name)}let a=!1;if(n.finish_reason){a=i.hasIncompleteToolCalls();let d=i.getCompletedToolCalls();for(let c of d)c.name&&r.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let s=a&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:r,role:"model"},index:0,safetyRatings:[]};s&&(l.finishReason=kt(s)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=_t(t.usage)),o}function kt(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function gn(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Pe(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function Mt(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===vt}function fn(t){let e=[],n=new Map,o=new Map,i=new Map,r=new Set,a=new Set;for(let s=0;s<t.length;s+=1){let l=t[s];if(Pe(l)){let d=[],c=new Set;for(let C of l.tool_calls){let y=C.id;!y||a.has(y)||c.has(y)||(c.add(y),d.push(C))}let g=new Set,u=[],m=[],h=!1;for(let C=s+1;C<t.length;C+=1){let y=t[C];if(y.role==="tool"&&"tool_call_id"in y){if(!y.tool_call_id){h=!1;continue}c.has(y.tool_call_id)&&!g.has(y.tool_call_id)?(g.add(y.tool_call_id),u.push(C),h=!0):h=!1;continue}if(Mt(y)){h&&m.push(C);continue}if(!(y.role==="assistant"&&!Pe(y)))break}let p=d.filter(C=>g.has(C.id));for(let C of p)a.add(C.id);n.set(s,p),o.set(s,u),i.set(s,m)}}for(let s=0;s<t.length;s+=1){if(r.has(s))continue;let l=t[s];if(Pe(l)){let d=l.reasoning_content,c=n.get(s)??[];if(c.length>0){let g={...l};g.tool_calls=c,e.push(g);for(let u of o.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}for(let u of i.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}}else if(typeof l.content=="string"&&l.content.trim()||d){let g={...l};delete g.tool_calls,e.push(g)}else w.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?w.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):Mt(l)?w.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function St(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let i="tool_calls"in o?o.tool_calls||[]:[],r="tool_calls"in n?n.tool_calls||[]:[],a=o.content,s=n.content,l=Array.isArray(a)||Array.isArray(s),d;if(l){let g=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[],u=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[];d=[...g,...u]}else d=[typeof a=="string"?a:"",typeof s=="string"?s:""].filter(Boolean).join("")||null;let c=[...i,...r];o.content=d||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var ne={convertGeminiToolParametersToOpenAI:bt,convertGeminiToolsToOpenAI:tn,convertGeminiRequestToOpenAI:nn,convertGeminiResponseToOpenAI:on,convertOpenAIResponseToGemini:un,convertOpenAIChunkToGemini:pn};f();import*as _ from"node:path";import{promises as re}from"node:fs";f();f();import hn from"crypto";var ie=new Uint8Array(256),oe=ie.length;function Oe(){return oe>ie.length-16&&(hn.randomFillSync(ie),oe=0),ie.slice(oe,oe+=16)}f();var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function wt(t,e=0){return M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]}f();f();import mn from"crypto";var Le={randomUUID:mn.randomUUID};function Cn(t,e,n){if(Le.randomUUID&&!e&&!t)return Le.randomUUID();t=t||{};let o=t.random||(t.rng||Oe)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return wt(o)}var Ue=Cn;import*as E from"os";var ae=I("OPENAI_LOGGER"),yn="########",Tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function An(t,e){let n=e||process.cwd();if(!t)return _.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=_.join(E.homedir(),t.slice(1)):_.isAbsolute(t)||(o=_.resolve(n,t)),_.normalize(o)}function Rt(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function Mn(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function Sn(t){if(t)return F(t)?Rt(t):Rt(Mn(t))}function vn(t){if(!t)return;let e=t.indexOf(yn);if(e>0)return t.slice(0,e);if(Tn.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function _n(t){let e=t?.trim(),n=vn(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var W=class{logDir;initialized=!1;constructor(e,n){this.logDir=An(e,n)}async initialize(){if(!this.initialized)try{await re.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw ae.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,i){this.initialized||await this.initialize();let r=new Date().toISOString().replace(/:/g,"-"),a=Ue().slice(0,8),s=Sn(i),l=s?`openai-${r}-${a}-${s}.json`:`openai-${r}-${a}.json`,d=_.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:_n(i),system:{hostname:E.hostname(),platform:E.platform(),release:E.release(),nodeVersion:process.version}};try{return await re.writeFile(d,JSON.stringify(c,null,2),"utf-8"),d}catch(g){throw ae.error("Failed to write OpenAI log file:",g),new Error(`Failed to write OpenAI log file: ${g}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await re.readdir(this.logDir)).filter(i=>i.startsWith("openai-")&&i.endsWith(".json")).map(i=>_.join(this.logDir,i)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(ae.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await re.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw ae.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Fo=new W;f();var se="$runtime|";function jo(t){let e=t;for(;e.startsWith(se);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}f();var le=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Pt=["model","apiKey","apiKeyEnvKey","baseUrl"],de=[...Pt,...le],Wo={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},Jo={openai:st,"matilda-oauth":L},ce=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Yo=ce.map(t=>t.id);f();f();f();f();qt();f();import{AsyncLocalStorage as bn}from"node:async_hooks";var Et=new bn;f();function Ot(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(In)}function In(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function Lt(){let t=at.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var D=I("LOGGING_CONTENT_GENERATOR"),xn=4096,Ut="...[truncated]",kn=xn-Ut.length,J=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new W(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let i=JSON.stringify(e);Ze(this.config,new tt(n,o,i,P.getStore()))}_logApiResponse(e,n,o,i,r,a){et(this.config,new ot(e,o,n,i,this.generatorAuthType,r,a,P.getStore()))}_logApiError(e,n,o,i,r){let a=qe(o),s=V(o),l=o?.requestID||o?.request_id||e,d=H(o);Qe(this.config,new nt({responseId:l,model:i,durationMs:n,promptId:r,authType:this.generatorAuthType,errorMessage:a,errorType:s,statusCode:d,subagentName:P.getStore()}))}safelyLogApiError(e,n,o,i,r){try{this._logApiError(e,n,o,i,r)}catch(a){D.warn("Failed to log API error:",a)}}safelyLogApiResponse(e,n,o,i,r,a){try{this._logApiResponse(e,n,o,i,r,a)}catch(s){D.warn("Failed to log API response:",s)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=Lt(),i=Ie(e.model,n);try{i.setAttribute("llm_request.stream",!1)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession();try{xe.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools));let d=await k.with(r,async()=>{s||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),g=Date.now()-a,u=s?void 0:this.extractResponseText(c);s||be(this.config,i,u),this.safelyLogApiResponse(c.responseId??"",g,this.getClientVisibleModelId(e.model,c.modelVersion),n,c.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(m){D.warn("Failed to log OpenAI interaction:",m)}return c});return $(i,{success:!0,inputTokens:d.usageMetadata?.promptTokenCount,outputTokens:d.usageMetadata?.candidatesTokenCount,cachedInputTokens:d.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-a,responseId:d.responseId||void 0,finishReason:d.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:d.usageMetadata?.thoughtsTokenCount,subagentName:P.getStore()||void 0,...o}),d}catch(d){let c=Date.now()-a,g=e.config?.abortSignal?.aborted??!1;throw $(i,{success:!1,durationMs:c,error:g?ee:Q,errorType:V(d),errorStatusCode:H(d),subagentName:P.getStore()||void 0,...o}),await k.with(r,async()=>{this.safelyLogApiError("",c,d,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,d,n)}catch(u){D.warn("Failed to log OpenAI interaction:",u)}}),d}}async generateContentStream(e,n){let o=Lt(),i=Ie(e.model,n);try{i.setAttribute("llm_request.stream",!0)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=F(n),l=this.startCaptureSession(),d;try{xe.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools)),d=await k.with(r,async()=>(s||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(g){let u=Date.now()-a;k.with(r,()=>this.safelyLogApiError("",u,g,e.model,n));let m=e.config?.abortSignal?.aborted??!1;$(i,{success:!1,durationMs:u,error:m?ee:Q,errorType:V(g),errorStatusCode:H(g),subagentName:P.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,g,n)}catch(h){D.warn("Failed to log OpenAI interaction:",h)}throw g}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(g){D.warn("Failed to resolve OpenAI request:",g)}return k.with(r,()=>this.loggingStreamWrapper(d,a,n,e.model,c,i,r,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():Et.run(i=>{e=i},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,i,r,a,s,l,d){let c=F(o),g=!c||!!this.openaiLogger,u=[],m="",h="",p,C=!1,y,T,S=P.getStore(),R,j=!1,X=v=>s?k.with(s,v):v(),Yt=5*6e4,x,We=a?()=>{j||(x!==void 0&&clearTimeout(x),x=setTimeout(()=>{try{a.setAttribute("stream.timed_out",!0)}catch{}$(a,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:S||void 0,...d}),j=!0},Yt),x.unref())}:void 0;We?.();try{for await(let b of e){!m&&b.responseId&&(m=b.responseId),!h&&b.modelVersion&&(h=b.modelVersion),g&&u.push(b),b.usageMetadata&&(p=b.usageMetadata);let Ye=b.candidates?.[0];Ye?.finishReason&&(y=Ye.finishReason),R===void 0&&Ot(b)&&(R=Date.now()-n),We?.(),yield b}x!==void 0&&(clearTimeout(x),x=void 0);let v=Date.now()-n,Z=g?this.consolidateGeminiResponsesForLogging(u):void 0,Je=c?void 0:this.extractResponseText(Z);j||(X(()=>this.safelyLogApiResponse(m,v,this.getClientVisibleModelId(i,h),o,p,Je)),!c&&a&&be(this.config,a,Je),await X(()=>this.safelyLogOpenAIInteraction(r,Z,void 0,o)))}catch(v){if(C=!0,T=v,!j){let Z=Date.now()-n;X(()=>this.safelyLogApiError(m,Z,v,this.getClientVisibleModelId(i,h),o)),await X(()=>this.safelyLogOpenAIInteraction(r,void 0,v,o))}throw v}finally{if(x!==void 0&&clearTimeout(x),a&&!j){let v=l?.aborted??!1;$(a,{success:!C,inputTokens:p?.promptTokenCount,outputTokens:p?.candidatesTokenCount,cachedInputTokens:p?.cachedContentTokenCount,ttftMs:R,durationMs:Date.now()-n,error:C?v?ee:Q:void 0,responseId:m||void 0,finishReason:y,thoughtsTokenCount:p?.thoughtsTokenCount,subagentName:S||void 0,errorType:T?V(T):void 0,errorStatusCode:T?H(T):void 0,...d})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ne.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),i={model:e.model,messages:o};return e.config?.tools&&(i.tools=await ne.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(i.temperature=e.config.temperature),e.config?.topP!==void 0&&(i.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(i.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(i.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(i.frequency_penalty=e.config.frequencyPenalty),i}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,i){if(!this.openaiLogger||!e)return;let r=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,r,o instanceof Error?o:o?new Error(String(o)):void 0,i)}async safelyLogOpenAIInteraction(e,n,o,i){try{await this.logOpenAIInteraction(e,n,o,i)}catch(r){D.warn("Failed to log OpenAI interaction:",r)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new K;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),ne.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new K,o=[],i=new Map,r,a;for(let d of e){d.usageMetadata&&(a=d.usageMetadata);let c=d.candidates?.[0];c?.finishReason&&(r=c.finishReason);let g=c?.content?.parts??[];for(let u of g){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let m=u.functionCall.id||u.functionCall.name||"tool_call",h=i.get(m),p={functionCall:u.functionCall};h!==void 0?o[h]=p:(i.set(m,o.length),o.push(p));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let s=e[e.length-1],l=s.candidates?.[0];return n.responseId=s.responseId,n.createTime=s.createTime,n.modelVersion=s.modelVersion,n.promptFeedback=s.promptFeedback,n.usageMetadata=a,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...r?{finishReason:r}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",i=!1,r=!1,a=s=>{if(i=!0,r)return;let l=kn-o.length;if(s.length<=l){o+=s;return}o+=s.slice(0,Math.max(0,l)),r=!0};for(let s of n){if(typeof s=="string"){a(s);continue}"text"in s&&typeof s.text=="string"&&!("thought"in s&&s.thought)&&a(s.text)}if(i)return r?`${o}${Ut}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let r=o.text,a=r?String(r):"",s=a?`${a}
8
+ ${n}`:n;return{...o,text:s}}return e}};f();function Dt(t){switch(t){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Gt(t){switch(t){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var O=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends O{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let i=e||"(unknown)",r=n||"(unknown)";super(`Missing credentials for modelProviders model '${r}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${i}[].envKey.`:`Configure modelProviders.${i}[].envKey and set that environment variable.`))}},pe=class extends O{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},ge=class extends O{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},fe=class extends O{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},he=class extends O{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},me=class extends O{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import Rn from"node:process";f();var Nt={image:!0,pdf:!0,audio:!0,video:!0},wn=[[/^gemini-3/,Nt],[/^gemini-/,Nt],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Y(t){let e=lt(t);for(let[n,o]of wn)if(n.test(e))return{...o};return{}}f();var Kt=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new Ce(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||L}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),o=new Set,i=[];for(let l of n)o.has(l)||(o.add(l),i.push(l));let r=[];i.includes("matilda-oauth")&&r.push("matilda-oauth");for(let l of i)l!=="matilda-oauth"&&r.push(l);let a=this.getRuntimeModelOption(),s=[];for(let l of r)a&&a.authType===l&&s.push(a),s.push(...this.modelRegistry.getModelsForAuthType(l));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===ke&&e?.envKey===dt&&e?.baseUrl===ut&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?ke:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?ct:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===L){this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(i){throw this.rollbackToStateSnapshot(o),i}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Y(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=B(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let i=this.extractRuntimeModelSnapshotId(n);if(i){await this.switchToRuntimeModel(i);return}let r=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let a=e!==this.currentAuthType;this.currentAuthType=e;let s=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!s)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=r.generationConfig.model||"",d=!a&&l?this.modelRegistry.getModel(e,l,r.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,c=e!=="matilda-oauth"&&!a&&!!r.generationConfig.apiKey&&!!s.envKey&&d?.envKey===s.envKey&&d.baseUrl===s.baseUrl,g=c?r.generationConfig.apiKey:void 0,u=c?r.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,u&&(this.generationConfigSources.apiKey=t.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0;let m=a?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,m)}catch(a){throw this.rollbackToStateSnapshot(r),a}}buildRuntimeModelSnapshotId(e,n){return`${se}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(se))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of le)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:i}=this._generationConfig;if(!(!n||!e||!o||!i)&&!this.modelRegistry.hasModel(e,n,i))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let r=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);r.apiKey=o,r.baseUrl=i,r.modelId=n;let a=this.buildRuntimeModelSnapshotId(r.authType,r.modelId);a!==r.id&&(this.runtimeModelSnapshots.delete(r.id),r.id=a,this.runtimeModelSnapshots.set(a,r),this.activeRuntimeModelSnapshotId=a),r.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of de)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),e.envKey!==void 0){let o=Rn.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of le)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=B(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Y(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),i=this.modelRegistry.getModel(n,e);return!i||!o||i.envKey!==o.envKey||i.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,r=n?this.modelRegistry.getModel(e,n,i)??this.modelRegistry.getModel(e,n):void 0;if(r){let m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==r.envKey||this._generationConfig.baseUrl!==r.baseUrl),h=o===e&&this._generationConfig.model===n&&!m,p=h?this._generationConfig.apiKey:void 0,C=h&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,y=this.generationConfigSources.baseUrl,T=h&&!!this._generationConfig.baseUrl&&(y?.kind==="cli"||y?.kind==="env"||y?.kind==="settings"),S=T?this._generationConfig.baseUrl:void 0,R=T&&y?{...y}:void 0;this.applyResolvedModelDefaults(r),h&&!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,s=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&s?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let g=this.modelRegistry.getDefaultModelForAuthType(e);if(g){this.applyResolvedModelDefaults(g),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,...r}=this._generationConfig,a=this.currentAuthType;if(!e||!a)return;if(this.modelRegistry.hasModel(a,e,o)){this.clearRuntimeModelSnapshotForAuthType(a);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(a,e),d={id:l,authType:a,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,generationConfig:r,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,d),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let i=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let r=i;this.onModelChange&&await this.onModelChange(n.authType,r)}catch(i){throw this.rollbackToStateSnapshot(o),i}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};f();import{readFileSync as Wn}from"node:fs";import{join as Jn}from"node:path";f();f();import{randomBytes as Pn,createHash as En}from"node:crypto";function Ft(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function De(){let t=Pn(32).toString("base64url"),e=En("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function q(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function Ge(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Ft(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let i=await o.json();if(!i.issuer||!i.authorization_endpoint||!i.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:i.issuer,authorization_endpoint:i.authorization_endpoint,token_endpoint:i.token_endpoint,device_authorization_endpoint:i.device_authorization_endpoint}}f();import{promises as ye,openSync as On,closeSync as Ln,unlinkSync as $t,statSync as Un}from"node:fs";import{dirname as Dn}from"node:path";var Gn=1e4,Nn=3e4,Kn=50;function Ne(t){let e=async()=>{try{let i=await ye.readFile(t,"utf8"),r=JSON.parse(i);return r&&typeof r=="object"?r:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},n=async i=>{await ye.mkdir(Dn(t),{recursive:!0}),await ye.writeFile(t,JSON.stringify(i,null,2),{mode:384}),await ye.chmod(t,384).catch(()=>{})};return{store:{async get(i){return(await e())[i]??null},async set(i,r){let a=await e();a[i]=r,await n(a)},async remove(i){let r=await e();i in r&&(delete r[i],await n(r))}},lock:Fn(`${t}.lock`)}}function Fn(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await $n(t);try{return await n()}finally{zn(t)}});return e=o.then(()=>{},()=>{}),o}}async function $n(t){let e=Date.now()+Gn;for(;;)try{Ln(On(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Un(t).mtimeMs>Nn){$t(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await jn(Kn)}}function zn(t){try{$t(t)}catch{}}function jn(t){return new Promise(e=>setTimeout(e,t))}f();var z=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Ke(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,i=null,r=async()=>{let l=await t.store.get(e);if(!l)return null;try{let d=JSON.parse(l);return d.accessToken?d:null}catch{return null}},a=l=>l.expiresAt-Date.now()>o,s=l=>t.lock(async()=>{let d=await r()??l;if(d.accessToken!==l.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new z("No refresh token available \u2014 sign in again.");let c=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:d.refreshToken})});if(!c.ok){let m=await c.text().catch(()=>"");throw c.status>=400&&c.status<500&&Hn(m)==="invalid_grant"?(await t.store.remove(e),new z):new Error(`Token refresh failed (${c.status})`)}let g=await c.json(),u=q(g,d);return await t.store.set(e,JSON.stringify(u)),u.accessToken});return{async getAccessToken(l){let d=await r();if(!d)throw new z("Not signed in.");return!l?.forceRefresh&&a(d)?d.accessToken:(i||(i=s(d).finally(()=>{i=null})),i)}}}function Hn(t){try{return JSON.parse(t).error}catch{return}}f();import{createServer as Vn}from"node:http";import{randomBytes as Bn}from"node:crypto";async function Fe(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=h=>t.onEvent?.(h),{codeVerifier:n,codeChallenge:o}=De(),i=Bn(16).toString("hex"),r=t.timeoutMs??5*60*1e3,a=t.transport.successRedirect;e({type:"state",status:"idle"});let s,l,d=new Promise((h,p)=>{s=h,l=p});d.catch(()=>{});let c=Vn((h,p)=>{let C=new URL(h.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){p.writeHead(404).end();return}let y=C.searchParams.get("error"),T=C.searchParams.get("state"),S=C.searchParams.get("code");if(y){zt(p,a,()=>l(new Error(`OAuth error: ${y}`)));return}if(T!==i){p.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){p.writeHead(400).end("Missing authorization code");return}zt(p,a,()=>s(S))}),g=await new Promise((h,p)=>{c.once("error",p),c.listen(t.transport.port??0,"127.0.0.1",()=>{h(c.address().port)})}),u=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),r),m=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",m,{once:!0});try{let h=`http://127.0.0.1:${g}/callback`,p=new URL(t.metadata.authorization_endpoint);p.searchParams.set("client_id",t.clientId),p.searchParams.set("response_type","code"),p.searchParams.set("redirect_uri",h),p.searchParams.set("code_challenge",o),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("state",i),p.searchParams.set("scope",t.scope??"openid offline_access");let C=p.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let y=await d;e({type:"state",status:"exchanging"});let T=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:y,code_verifier:n,redirect_uri:h})});if(!T.ok){let R=await T.text().catch(()=>"");throw new Error(`Token exchange failed (${T.status}): ${R}`)}let S=q(await T.json());return e({type:"state",status:"authenticated"}),S}catch(h){throw e({type:"state",status:"error"}),h}finally{clearTimeout(u),t.signal?.removeEventListener("abort",m),c.close()}}function zt(t,e,n){t.writeHead(302,{location:e}).end(n)}var $e="matilda-code",Te="MATILDA_API_KEY",Yn="openid profile email offline_access matilda:code",Ae="matilda";function ze(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function jt(){return Jn(Xe.getGlobalMatildaDir(),"matilda-auth.json")}function je(){return Ne(jt())}function qn(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function Xn(t,e){let n=qn(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Ht(t){try{return await Ge(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function N(){try{let t=Wn(jt(),"utf8"),n=JSON.parse(t)[Ae];if(!n)return null;let o=JSON.parse(n);return typeof o?.accessToken=="string"&&typeof o?.baseUrl=="string"?o:null}catch{return null}}async function Zn(t){await je().store.set(Ae,JSON.stringify(t)),process.env[Te]=t.accessToken}async function Qn(){await je().store.remove(Ae),delete process.env[Te]}function Cr(){let t=N();return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function yr(t){let e=N();if(e?.accessToken){let n=ze(e.baseUrl);await fetch(`${n}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(e.refreshToken?{refreshToken:e.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await Qn()}async function He(t){let e=N();if(!e||t?.baseUrl&&e.baseUrl!==t.baseUrl)return t?.fallbackAccessToken??process.env[Te]??"";let n=ze(e.baseUrl),o=await Ht(n),{store:i,lock:r}=je(),s=await eo(i,r,o.token_endpoint,e.baseUrl,t?.signal).getAccessToken({forceRefresh:t?.forceRefresh});return process.env[Te]=s,s}async function Tr(){await He();let t=N();if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function eo(t,e,n,o,i){return Ke({tokenEndpoint:n,clientId:$e,store:{get:async s=>{let l=JSON.parse(await t.get(s)??"{}");if(!l.accessToken)return null;let d={accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.accessTokenExpiresAt};return JSON.stringify(d)},set:async(s,l)=>{let d=JSON.parse(l),c=JSON.parse(await t.get(s)??"{}"),g={...c,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??c.refreshToken??"",baseUrl:c.baseUrl??o};await t.set(s,JSON.stringify(g))},remove:s=>t.remove(s)},storageKey:Ae,lock:e,fetchImpl:(s,l)=>fetch(s,{...l,signal:i}),expirySkewMs:3e5})}function to(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&gt()}async function Ar(t){let e=ze(t.baseUrl),n=await Ht(e),o="",i=s=>Fe({metadata:n,clientId:$e,scope:s,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent($e)}`},signal:t.signal,onEvent:l=>{l.type==="authorize_url"&&(o=l.url,t.onAuthorizeUrl?.(l.url))},openBrowser:async l=>{if(!(t.openBrowser===!1||!to()))try{let{default:d}=await import("./open-QQ7FWG4A.js");(await d(l)).once("error",()=>{})}catch{}}}),r;try{r=await i(Yn)}catch(s){if(s instanceof Error&&s.message.includes("invalid_scope"))r=await i("openid offline_access");else throw s}let a=Xn(r,t.baseUrl);return await Zn(a),{...a,authorizeUrl:o}}var G=(r=>(r.USE_OPENAI="openai",r.MATILDA_OAUTH="matilda-oauth",r.USE_GEMINI="gemini",r.USE_VERTEX_AI="vertex-ai",r.USE_ANTHROPIC="anthropic",r))(G||{}),no="MATILDA_AGENT_SDK",Me="MATILDA_API_KEY";function oo(t){if(t.apiKey||t.apiKeyEnvKey!==Me)return;let e=N();e?.accessToken&&(t.apiKey=e.accessToken,process.env[Me]=e.accessToken)}async function io(t){if(t.apiKeyEnvKey!==Me)return;let e=N();if(!e?.accessToken)return;let n=await He({baseUrl:t.baseUrl,fallbackAccessToken:e.accessToken});n&&(t.apiKey=n,process.env[Me]=n)}function ro(t){return t.matildaAgentSdk===!0||process.env[no]==="1"}function Ve(t,e,n){t[e]=n}function ao(t,e){return t?.[e]}function so(t,e,n,o,i){let r={...o||{}},a=i?.strictModelProvider===!0,s={...n||{},authType:e,proxy:t?.getProxy()};Ve(r,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Ve(r,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>ao(o,c)??{kind:"unknown"};for(let c of de)n&&c in n&&!r[c]&&Ve(r,c,l(c));oo(s);let d=Bt(s,a);if(!d.valid)throw new Error(d.errors.map(c=>c.message).join(`
9
+ `));return{config:s,sources:r}}function Bt(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new ue(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Dt(t.authType);n.push(new ge({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new pe(t.authType));else{let o=Gt(t.authType);n.push(new fe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new he({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new me)),{valid:n.length===0,errors:n}}function xr(t,e,n){return so(t,e,n).config}function Vt(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function kr(t,e,n){await io(t);let o=Bt(t,!1);if(!o.valid)throw new Error(o.errors.map(a=>a.message).join(`
10
+ `));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(ro(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-Y5CHD2WJ.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-XLDE2S4K.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-F2DTT47Z.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Vt(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-ATLOKYPR.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-KPR5Q3XX.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Vt(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
11
+ Please exit and restart Matilda to use the '${i}' provider.`,{cause:s}):a}return new J(r,e,t)}var Be=I("MODEL_REGISTRY");function Wt(t){if(Object.values(G).includes(t))return t}function lo(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function Jt(t,e){return e?`${t}\0${e}`:t}var Ce=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return pt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",ce),e)for(let[n,o]of Object.entries(e)){let i=Wt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let i of n){let r=Jt(i.id,i.baseUrl);if(o.has(r)){Be.warn(`Duplicate model id "${i.id}"${i.baseUrl?` with baseUrl "${i.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let a=this.resolveModelConfig(i,e);o.set(r,a)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??B(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let i=this.modelsByAuthType.get(e);if(!i)return;if(o)return i.get(Jt(n,o));let r=i.get(n);if(r)return r;for(let a of i.values())if(a.id===n)return a}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,L);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||lo(e.id))&&(o.modalities=Y(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let i=Wt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}};export{Re as a,ne as b,Et as c,An as d,W as e,Fo as f,Y as g,se as h,jo as i,le as j,Wo as k,Jo as l,ce as m,Yo as n,Jt as o,Ce as p,Kt as q,jt as r,N as s,Zn as t,Qn as u,Cr as v,yr as w,He as x,Tr as y,to as z,Ar as A,G as B,so as C,Bt as D,xr as E,kr as F};
12
+ /**
13
+ * @license
14
+ * Copyright 2025 Matilda
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Google LLC
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ /**
23
+ * @license
24
+ * Copyright 2025 Matilda Team
25
+ * SPDX-License-Identifier: Apache-2.0
26
+ */
27
+ /**
28
+ * @license
29
+ * Copyright 2026 Matilda Team
30
+ * SPDX-License-Identifier: Apache-2.0
31
+ */
32
+ /**
33
+ * @license
34
+ * Copyright 2026 Maincode
35
+ * SPDX-License-Identifier: Apache-2.0
36
+ *
37
+ * Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
38
+ * (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
39
+ * grant, and refresh. Vendored (as source) from matilda-core's
40
+ * `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
41
+ * (display identity) that the higher-level flows need. Node built-ins only —
42
+ * no third-party runtime dependencies.
43
+ */
44
+ /**
45
+ * @license
46
+ * Copyright 2026 Maincode
47
+ * SPDX-License-Identifier: Apache-2.0
48
+ *
49
+ * File-backed token store + cross-process lock. The store persists a JSON map
50
+ * (`{ [key]: value }`) at 0600 so callers can key several credentials in one
51
+ * file; the lock is an O_EXCL lockfile that serialises refreshes across
52
+ * processes (the guarantee a plaintext read/modify/write can't give).
53
+ */
54
+ /**
55
+ * @license
56
+ * Copyright 2026 Maincode
57
+ * SPDX-License-Identifier: Apache-2.0
58
+ *
59
+ * Hardened access-token manager: returns a valid access token, refreshing via
60
+ * core-auth's token endpoint when expired or forced. Single-flight within the
61
+ * process, serialised across processes by the store's lock, carries a prior
62
+ * refresh token forward when the response omits one, and evicts on a terminal
63
+ * `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
64
+ */
65
+ /**
66
+ * @license
67
+ * Copyright 2026 Maincode
68
+ * SPDX-License-Identifier: Apache-2.0
69
+ *
70
+ * Browser login orchestration: PKCE + a loopback capture server, driven off
71
+ * discovery metadata. Unlike a bare loopback helper, this emits lifecycle
72
+ * events for a UI, honours an AbortSignal, and — instead of serving its own
73
+ * HTML — 302-redirects the browser to an app-owned branded landing
74
+ * (`successRedirect`). Returns a TokenSet including the `id_token`.
75
+ */
76
+ /**
77
+ * @license
78
+ * Copyright 2026 Maincode
79
+ * SPDX-License-Identifier: Apache-2.0
80
+ *
81
+ * Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
82
+ * Re-exports the OAuth primitives plus the higher-level login flow, file token
83
+ * store, and hardened token manager that the CLI (`packages/core`) and the
84
+ * Electron desktop app consume.
85
+ */
86
+ /**
87
+ * @license
88
+ * Copyright 2026 Maincode
89
+ * SPDX-License-Identifier: Apache-2.0
90
+ *
91
+ * Matilda account auth for the CLI, backed by the shared client SDK.
92
+ *
93
+ * The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
94
+ * token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
95
+ * auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
96
+ * flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
97
+ * on-disk credential shape the rest of the CLI already reads, and surfacing the
98
+ * authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
99
+ * exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
100
+ * the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
101
+ */