@maincode-ai/matilda-code 0.19.6 → 0.19.7

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 (37) hide show
  1. package/chunks/{agent-NN3YCAQH.js → agent-JAZ2R5P5.js} +1 -1
  2. package/chunks/{agent-headless-GCUE63J5.js → agent-headless-HUDZQCLT.js} +1 -1
  3. package/chunks/{anthropicContentGenerator-CZLOMDXF.js → anthropicContentGenerator-DKMAJXYA.js} +1 -1
  4. package/chunks/{chunk-RAHHGBHX.js → chunk-4EZRS6DY.js} +1 -1
  5. package/chunks/{chunk-TZIIADJW.js → chunk-4ROBKRWY.js} +2 -2
  6. package/chunks/{chunk-NRPYZBZX.js → chunk-DF4ZZ3BH.js} +1 -1
  7. package/chunks/chunk-GTR4V2PV.js +8 -0
  8. package/chunks/{chunk-ETVBCNID.js → chunk-MHGRKMUG.js} +1 -1
  9. package/chunks/{chunk-OREAJC5D.js → chunk-UOF5DCHP.js} +10 -3
  10. package/chunks/{chunk-OGLMWPGR.js → chunk-YCINFF22.js} +2 -2
  11. package/chunks/{computer-use-AM62LD63.js → computer-use-BCNVOJO6.js} +1 -1
  12. package/chunks/{contextCommand-CWNMYXES.js → contextCommand-7XW5T2FM.js} +1 -1
  13. package/chunks/{edit-PJD2ABCG.js → edit-O5534MIA.js} +1 -1
  14. package/chunks/{enter-worktree-MTT3VNXA.js → enter-worktree-NWECAVR5.js} +1 -1
  15. package/chunks/{enterPlanMode-KJSXKSQX.js → enterPlanMode-Z5CC6RK4.js} +1 -1
  16. package/chunks/{exit-worktree-CX2HMIRN.js → exit-worktree-5QTROW2K.js} +1 -1
  17. package/chunks/{exitPlanMode-QQ7DSRYT.js → exitPlanMode-VT42OYWF.js} +1 -1
  18. package/chunks/{geminiContentGenerator-HZHMNMGX.js → geminiContentGenerator-DROE6XUC.js} +1 -1
  19. package/chunks/{glob-L6LCKWIV.js → glob-FWADRNRL.js} +1 -1
  20. package/chunks/{grep-PIJYRFHS.js → grep-OFTEAZOC.js} +1 -1
  21. package/chunks/{matildaAgentContentGenerator-Y2ECTUZO.js → matildaAgentContentGenerator-J3PXQMRW.js} +1 -1
  22. package/chunks/{matildaContentGenerator-HATVJLJF.js → matildaContentGenerator-6WVY252A.js} +1 -1
  23. package/chunks/{monitor-A3RDX2JT.js → monitor-W2IPT7L4.js} +1 -1
  24. package/chunks/{notebook-edit-5KEG5MTP.js → notebook-edit-E2RFMINC.js} +1 -1
  25. package/chunks/{openaiContentGenerator-XI6SCJ2G.js → openaiContentGenerator-PGCPCIUM.js} +1 -1
  26. package/chunks/{ripGrep-PXECRMR2.js → ripGrep-CKRSCA2H.js} +1 -1
  27. package/chunks/{scheduler-XG6XEE2W.js → scheduler-AQ72BFMX.js} +1 -1
  28. package/chunks/{serve-RZQK4PGY.js → serve-VAU7AZ4D.js} +1 -1
  29. package/chunks/{shell-CGATWESB.js → shell-LMX4PBFS.js} +1 -1
  30. package/chunks/{src-D4A3YMBH.js → src-3ZEKD73Z.js} +1 -1
  31. package/chunks/{team-create-WADAQUBF.js → team-create-YCCOH5ZI.js} +1 -1
  32. package/chunks/{web-search-XR5V4QRH.js → web-search-LUARHW3X.js} +1 -1
  33. package/chunks/{workflow-NTYIHQG2.js → workflow-7JKMNIOX.js} +2 -2
  34. package/chunks/{write-file-THZKUU47.js → write-file-QR6KKYVC.js} +1 -1
  35. package/cli.js +371 -371
  36. package/package.json +2 -2
  37. package/chunks/chunk-FSRNEJQB.js +0 -8
@@ -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-FSRNEJQB.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-RAHHGBHX.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 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-4EZRS6DY.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(`
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,7 +22,7 @@ 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=12e4,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=12e4,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??{}))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(`
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
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(`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Ne as X,Pe as H,Yh as K}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import{i as S}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as B,i as G}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as ye}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",ue="https://matilda.maincode.com/assets/computer-use",me="https://github.com/trycua/cua/releases/download";function E(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function U(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ge(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${ue}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs-v${o}/${e}`),r}function J(e=process.env,t=l){return U("checksums.txt",e,t)}var he="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function V(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Y(e,t=process.env){let o=V(t[he]);return o!==void 0?o:V(e)}function fe(e=R()){return I(e,".matilda","computer-use")}function N(e=R(),t=l){return I(fe(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=E(t,o,r);return I(N(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ge(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(ye())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new H({command:this.binary,args:["mcp"],env:{...process.env}}),i=new X({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Q(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Q(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Q(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var M=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
3
+ import{Ne as X,Pe as H,Yh as K}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import{i as S}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as B,i as G}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as ye}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",ue="https://matilda.maincode.com/assets/computer-use",me="https://github.com/trycua/cua/releases/download";function E(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function U(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ge(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${ue}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs-v${o}/${e}`),r}function J(e=process.env,t=l){return U("checksums.txt",e,t)}var he="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function V(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Y(e,t=process.env){let o=V(t[he]);return o!==void 0?o:V(e)}function fe(e=R()){return I(e,".matilda","computer-use")}function N(e=R(),t=l){return I(fe(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=E(t,o,r);return I(N(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ge(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(ye())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new H({command:this.binary,args:["mcp"],env:{...process.env}}),i=new X({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Q(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Q(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Q(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var M=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
4
4
 
5
5
  Two addressing modes:
6
6
 
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{c as a,d as b,e as c}from"./chunk-ETVBCNID.js";import"./chunk-NRPYZBZX.js";import"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
3
+ import{c as a,d as b,e as c}from"./chunk-MHGRKMUG.js";import"./chunk-DF4ZZ3BH.js";import"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as G}from"./chunk-I55PXD4N.js";import{Kd as S,Ld as W,Ob as B,Sd as k,de as z,ee as T,ja as b,ke as q,le as H,oe as X}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import{Lb as $,Oa as M,_c as j,ca as O,ha as x,wc as F}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as U}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{i as R,p as v,q as A}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{A as C,C as L,Y as I,a as w,z as E}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as _ from"node:fs";import*as g from"node:path";y();var ne={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function P(r){if(r==="")return r;let t="";for(let e of r)t+=ne[e]??e;return t}var re=[r=>r,r=>r.trimEnd()];function oe(r){return P(r).trimEnd()}function V(r,t,e){if(t.length===0)return 0;if(t.length>r.length)return null;e:for(let i=0;i<=r.length-t.length;i++){for(let n=0;n<t.length;n++)if(e(r[i+n])!==e(t[n]))continue e;return i}return null}function ae(r){let t=r.split(`
3
+ import{a as G}from"./chunk-I55PXD4N.js";import{Kd as S,Ld as W,Ob as B,Sd as k,de as z,ee as T,ja as b,ke as q,le as H,oe as X}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import{Lb as $,Oa as M,_c as j,ca as O,ha as x,wc as F}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as U}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{i as R,p as v,q as A}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{A as C,C as L,Y as I,a as w,z as E}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as _ from"node:fs";import*as g from"node:path";y();var ne={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function P(r){if(r==="")return r;let t="";for(let e of r)t+=ne[e]??e;return t}var re=[r=>r,r=>r.trimEnd()];function oe(r){return P(r).trimEnd()}function V(r,t,e){if(t.length===0)return 0;if(t.length>r.length)return null;e:for(let i=0;i<=r.length-t.length;i++){for(let n=0;n<t.length;n++)if(e(r[i+n])!==e(t[n]))continue e;return i}return null}function ae(r){let t=r.split(`
4
4
  `),e=new Array(t.length+1),i=0;for(let n=0;n<t.length;n++)e[n]=i,i+=t[n].length,n<t.length-1&&(i+=1);return e[t.length]=r.length,{lines:t,offsets:e}}function K(r,t,e,i,n,o){if(n===0)return o?`
5
5
  `:"";let c=t[i]??0,s=i+n-1,l=(t[s]??0)+(e[s]?.length??0);if(o){let p=t[i+n];p!==void 0?l=p:r.endsWith(`
6
6
  `)&&(l=r.length)}return r.slice(c,l)}function se(r,t){let{lines:e,offsets:i}=ae(r),n=t.split(`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{dj as T,jf as W,rf as s}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as E,p as m,q as R}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as b}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
3
+ import{dj as T,jf as W,rf as s}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as E,p as m,q as R}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as b}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
4
4
 
5
5
  ## When to Use
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as l,i as m,p,q as c}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as s}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var h=s("ENTER_PLAN_MODE"),u=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
3
+ import"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as l,i as m,p,q as c}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as s}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var h=s("ENTER_PLAN_MODE"),u=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
4
4
 
5
5
  ## When to Use This Tool
6
6
  Use this tool when the task is not yet clear enough to safely execute, for example when it requires multi-file changes, design choices, investigation before a plan can be summarized, or when requirements are ambiguous. While investigating, if complexity rises or you find yourself repeatedly needing to ask the user, enter plan mode and consolidate a plan.
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{cj as C,ej as x,hf as k,kf as W,rf as l}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as E,i as R,p as c,q as T}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as b,a as $}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
3
+ import{cj as C,ej as x,hf as k,kf as W,rf as l}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as E,i as R,p as c,q as T}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as b,a as $}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
4
4
 
5
5
  ## Behavior
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as k}from"./chunk-ILBTI4K5.js";import{Cf as M,I as b,Ze as _}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as x,i as T,p as R,q as G}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as f}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();m();var $=f("GATE_REVIEW_AGENTS");function U(n){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
3
+ import{a as k}from"./chunk-ILBTI4K5.js";import{Cf as M,I as b,Ze as _}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as x,i as T,p as R,q as G}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as f}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();m();var $=f("GATE_REVIEW_AGENTS");function U(n){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
4
4
 
5
5
  1. **Request Fit** \u2014 Does the plan fulfill every part of the user's original request and respect all explicit constraints? Does it do anything the user explicitly asked NOT to do?
6
6
  2. **System Fit** \u2014 Does the plan align with the codebase structure, file paths, function names, permission model, and integration boundaries found during investigation?
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as g}from"./chunk-EMWHQSMS.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{e as d}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.19.6 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let f=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${f}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new p({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{p as GeminiContentGenerator,T as createGeminiContentGenerator};
3
+ import{a as g}from"./chunk-EMWHQSMS.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{e as d}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.19.7 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let f=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${f}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new p({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{p as GeminiContentGenerator,T as createGeminiContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{he as _,ie as j}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as M,i as C,p as N,q as A}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{C as $,F as O,J as v,Y as R,c as x}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
3
+ import{he as _,ie as j}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as M,i as C,p as N,q as A}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{C as $,F as O,J as v,Y as R,c as x}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
4
4
 
5
5
  [Search stopped after ${W/1e3}s before scanning the whole tree. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:o==="count"?`
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{$i as Y,_i as K,aa as q,ie as z,zc as F}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as _}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as U,i as V,p as H,q as J}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{C as O,F as W,J as S,Y as j,a as I,c as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as B}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";B();import tt from"node:fs/promises";import y from"node:path";import{EOL as et}from"node:os";import{spawn as X}from"node:child_process";var k=j("GREP"),M=class extends U{constructor(e,s){super(s);this.config=e;this.fileExclusions=e.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let e=this.config.getWorkspaceContext(),s=y.resolve(this.config.getTargetDir(),this.params.path);return e.isPathWithinWorkspace(s)||W(_(),s)?"allow":"ask"}async execute(e){try{let s=[],i;if(this.params.path){let t=S(this.config,this.params.path,{allowExternalPaths:!0});s.push(t),i=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();s.push(...t),i=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let l=[];for(let t of s){let o=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:e});if(s.length>1)for(let a of o)y.isAbsolute(a.filePath)||(a.filePath=y.resolve(t,a.filePath));l.push(...o)}if(s.length>1){let t=new Set;l=l.filter(o=>{let a=`${o.filePath}:${o.lineNumber}`;return t.has(a)?!1:(t.add(a),!0)})}let f=this.params.glob?` (filter: "${this.params.glob}")`:"";if(l.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${i}${f}.`,returnDisplay:"No matches found"};let h=this.config.getTruncateToolOutputThreshold(),w=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),$=!1,C=l;l.length>w&&(C=l.slice(0,w),$=!0);let E=l.length,x=E===1?"match":"matches",G=`Found ${E} ${x} for pattern "${this.params.pattern}" ${i}${f}:
3
+ import{$i as Y,_i as K,aa as q,ie as z,zc as F}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as _}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as U,i as V,p as H,q as J}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{C as O,F as W,J as S,Y as j,a as I,c as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as B}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";B();import tt from"node:fs/promises";import y from"node:path";import{EOL as et}from"node:os";import{spawn as X}from"node:child_process";var k=j("GREP"),M=class extends U{constructor(e,s){super(s);this.config=e;this.fileExclusions=e.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let e=this.config.getWorkspaceContext(),s=y.resolve(this.config.getTargetDir(),this.params.path);return e.isPathWithinWorkspace(s)||W(_(),s)?"allow":"ask"}async execute(e){try{let s=[],i;if(this.params.path){let t=S(this.config,this.params.path,{allowExternalPaths:!0});s.push(t),i=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();s.push(...t),i=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let l=[];for(let t of s){let o=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:e});if(s.length>1)for(let a of o)y.isAbsolute(a.filePath)||(a.filePath=y.resolve(t,a.filePath));l.push(...o)}if(s.length>1){let t=new Set;l=l.filter(o=>{let a=`${o.filePath}:${o.lineNumber}`;return t.has(a)?!1:(t.add(a),!0)})}let f=this.params.glob?` (filter: "${this.params.glob}")`:"";if(l.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${i}${f}.`,returnDisplay:"No matches found"};let h=this.config.getTruncateToolOutputThreshold(),w=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),$=!1,C=l;l.length>w&&(C=l.slice(0,w),$=!0);let E=l.length,x=E===1?"match":"matches",G=`Found ${E} ${x} for pattern "${this.params.pattern}" ${i}${f}:
4
4
  ---
5
5
  `,v=C.reduce((t,o)=>{let a=o.filePath;return t[a]||(t[a]=[]),t[a].push(o),t[a].sort((L,D)=>L.lineNumber-D.lineNumber),t},{}),n="",g=[],m=!1,c=(t,o)=>Number.isFinite(h)&&n.length+t.length>h?(n+=t.slice(0,Math.max(h-n.length,0)),n+="...",o&&g.push(o),m=!0,!1):(n+=t,o&&g.push(o),!0);for(let t in v){if(!c(`File: ${t}
6
6
  `))break;let o=!1;for(let a of v[t]){let L=a.line.trim();if(!c(`L${a.lineNumber}: ${L}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as I,b as F,c as U}from"./chunk-3KCDX6MY.js";import{b as x,x as $}from"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import{b as M,e as w}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{j as E,m as O}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import{p as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";b();b();var L="2026-06-23",W="auto",H="instant",J=12e4,g=18e4,V=5e4,v=16e3,X=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),B=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function K(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function A(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}function d(n,e){let o=A(n)?.[e];return typeof o=="string"?o:void 0}function j(n){return G(n)}function G(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
3
+ import{a as I,b as F,c as U}from"./chunk-3KCDX6MY.js";import{b as x,x as $}from"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import{b as M,e as w}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{j as E,m as O}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import{p as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";b();b();var L="2026-06-23",W="auto",H="instant",J=12e4,g=18e4,V=5e4,v=16e3,X=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),B=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function K(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function A(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}function d(n,e){let o=A(n)?.[e];return typeof o=="string"?o:void 0}function j(n){return G(n)}function G(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
4
  `):""}function u(n,e){if(n.length<=e)return n;let t=`
5
5
  [...omitted to fit Matilda native agent context...]
6
6
  `,o=e-t.length,s=Math.floor(o*.6),i=o-s;return`${n.slice(0,s)}${t}${n.slice(-i)}`}function z(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function Q(n){let e=A(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t}}function p(n){return JSON.stringify(n).length}function Y(n){if(p(n)<=g)return n;let e=`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as o,i as d}from"./chunk-OGLMWPGR.js";import"./chunk-QCIDUZV6.js";import"./chunk-3KCDX6MY.js";import"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import{b as u}from"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{j as s}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{e as c}from"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as i}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var l=class extends d{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new o(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=c.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||u,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await s("retry",t);throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{l as MatildaContentGenerator};
3
+ import{a as o,i as d}from"./chunk-YCINFF22.js";import"./chunk-QCIDUZV6.js";import"./chunk-3KCDX6MY.js";import"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import{b as u}from"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{j as s}from"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{e as c}from"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as i}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var l=class extends d{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new o(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=c.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||u,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await s("retry",t);throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{l as MatildaContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Fh as P,Hh as lt,Rd as rt,Yb as tt,ae as st,fe as L,ge as at,hc as et,kc as ot,lc as A,qc as C,rc as nt,vc as it}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as Z,i as q,p as Y,q as Q}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{G as J,Y as K,c as m}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as H}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";H();import{spawn as ct}from"node:child_process";import mt from"node:path";import{randomUUID as wt}from"node:crypto";var u=K("MONITOR"),Et=1e3,O=1e4,St=3e5,N=6e5,dt=80,R=4096,ut=5,ft=1e3;function pt(l){return l.length>dt?l.slice(0,dt-1)+"\u2026":l}var kt=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result"]),xt=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function gt(l){let y="";for(let t=0;t<l.length;t++){let o=l.charCodeAt(t);if(o===9){y+=l[t];continue}o<32||o>=128&&o<=159||(y+=l[t])}return y=y.replace(xt,(t,o,a)=>kt.has(String(a).toLowerCase())?o==="/"?`</\u200B${a}>`:`<\u200B${a}>`:t),y}var U=class extends Z{constructor(t,o){super(o);this.config=t}callId;setCallId(t){this.callId=t}getDescription(){let t=this.params.description||C(this.params.command).spawnCommand;return`Monitor: ${pt(t)}`}async getDefaultPermission(){let t=C(this.params.command).safetyCommand;try{if(await L(t))return"allow"}catch(o){u.warn("AST read-only check failed, falling back to ask:",o)}return"ask"}async getConfirmationDetails(t){let o=C(this.params.command),a=ot(o.safetyCommand),f=[];for(let s of a){let p=!1;try{p=await L(s)}catch(d){u.warn("AST read-only check failed for monitor sub-command, falling back to ask:",d)}p||f.push(s)}let S=f.length>0?f:a,M=[...new Set(S.map(s=>A(s)).filter(s=>!!s))],v=[];try{let s=[];for(let p of S){let d=await at(p);s.push(...d)}v=[...new Set(s)].map(p=>`Monitor(${p})`)}catch(s){u.warn("Failed to extract monitor command rules:",s),v=[`Monitor(${o.safetyCommand})`]}let i=it(o.safetyCommand,this.params.command),c={type:"exec",title:"Monitor",command:o.spawnCommand,rootCommand:M.join(", ")||(A(o.safetyCommand)??o.spawnCommand),permissionRules:v,onConfirm:async(s,p)=>{}};return i&&(c.warnings=i),c}async execute(t){if(t.aborted)return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."};let o=C(this.params.command),a=o.spawnCommand;o.strippedTrailingAmp&&u.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding");let f=gt(this.params.description||a),S=pt(f),M=Math.min(this.params.max_events??Et,O),v=Math.min(this.params.idle_timeout_ms??St,N),i=`mon_${wt().replace(/-/g,"").slice(0,16)}`,c=this.config.getMonitorRegistry(),s=tt()??void 0;if(c.getRunning().length>=P)return{llmContent:`Cannot start monitor: maximum concurrent monitors (${P}) reached. Stop an existing monitor first.`,returnDisplay:"Monitor rejected: too many concurrent monitors."};let d=new AbortController,g={monitorId:i,command:a,description:f,status:"running",startTime:Date.now(),abortController:d,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents:M,idleTimeoutMs:v,droppedLines:0,outputFile:lt(this.config.storage.getProjectDir(),this.config.getSessionId(),i),...s?{ownerAgentId:s}:{}},{executable:yt,argsPrefix:vt}=et(),n;try{n=ct(yt,[...vt,a],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,MATILDA_CODE:"1",TERM:"dumb",PAGER:"cat",...st()}})}catch(e){return{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}g.pid=n.pid;let b=!1,w,D=e=>{w??=e};n.on("error",D);let B={value:""},G={value:""},k=ut,I=Date.now(),$=e=>{let r=gt(e);if(r.length===0||r.trim().length===0)return;let T=Date.now(),_=T-I;if(_<0)u.warn(`Monitor ${i}: clock moved backwards by ${-_}ms, resetting refill timestamp`),I=T;else{let h=Math.floor(_/ft);h>0&&(k=Math.min(ut,k+h),I+=h*ft)}k>0?(k--,c.emitEvent(i,r)):g.droppedLines++},j=()=>{for(let e of[B,G]){let r=e.value.trim();r.length>0&&$(r),e.value=""}},Tt=()=>{if(!(b||!n.pid))if(process.platform==="win32")ct("taskkill",["/pid",n.pid.toString(),"/f","/t"],{stdio:"ignore"}).on("error",r=>u.warn(`Monitor taskkill failed for pid ${n.pid}: ${m(r)}`));else{try{process.kill(-n.pid,"SIGTERM")}catch(e){u.warn(`Monitor ${i} SIGTERM failed (pid=${n.pid}): ${m(e)}`)}setTimeout(()=>{if(!b&&n.pid)try{process.kill(-n.pid,"SIGKILL")}catch(e){u.warn(`Monitor ${i} SIGKILL escalation failed (pid=${n.pid}): ${m(e)}`)}},200).unref?.()}},E=()=>{j(),Tt()};d.signal.addEventListener("abort",E,{once:!0}),d.signal.aborted&&E();try{c.register(g)}catch(e){return E(),d.signal.removeEventListener("abort",E),n.stdout?.destroy?.(),n.stderr?.destroy?.(),n.removeListener("error",D),n.on("error",()=>{}),{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}let z=(e,r)=>{if(g.status!=="running")return;let T=rt(r.toString("utf-8"));if(e.value+=T,!e.value.includes(`
3
+ import{Fh as P,Hh as lt,Rd as rt,Yb as tt,ae as st,fe as L,ge as at,hc as et,kc as ot,lc as A,qc as C,rc as nt,vc as it}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as Z,i as q,p as Y,q as Q}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{G as J,Y as K,c as m}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as H}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";H();import{spawn as ct}from"node:child_process";import mt from"node:path";import{randomUUID as wt}from"node:crypto";var u=K("MONITOR"),Et=1e3,O=1e4,St=3e5,N=6e5,dt=80,R=4096,ut=5,ft=1e3;function pt(l){return l.length>dt?l.slice(0,dt-1)+"\u2026":l}var kt=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result"]),xt=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function gt(l){let y="";for(let t=0;t<l.length;t++){let o=l.charCodeAt(t);if(o===9){y+=l[t];continue}o<32||o>=128&&o<=159||(y+=l[t])}return y=y.replace(xt,(t,o,a)=>kt.has(String(a).toLowerCase())?o==="/"?`</\u200B${a}>`:`<\u200B${a}>`:t),y}var U=class extends Z{constructor(t,o){super(o);this.config=t}callId;setCallId(t){this.callId=t}getDescription(){let t=this.params.description||C(this.params.command).spawnCommand;return`Monitor: ${pt(t)}`}async getDefaultPermission(){let t=C(this.params.command).safetyCommand;try{if(await L(t))return"allow"}catch(o){u.warn("AST read-only check failed, falling back to ask:",o)}return"ask"}async getConfirmationDetails(t){let o=C(this.params.command),a=ot(o.safetyCommand),f=[];for(let s of a){let p=!1;try{p=await L(s)}catch(d){u.warn("AST read-only check failed for monitor sub-command, falling back to ask:",d)}p||f.push(s)}let S=f.length>0?f:a,M=[...new Set(S.map(s=>A(s)).filter(s=>!!s))],v=[];try{let s=[];for(let p of S){let d=await at(p);s.push(...d)}v=[...new Set(s)].map(p=>`Monitor(${p})`)}catch(s){u.warn("Failed to extract monitor command rules:",s),v=[`Monitor(${o.safetyCommand})`]}let i=it(o.safetyCommand,this.params.command),c={type:"exec",title:"Monitor",command:o.spawnCommand,rootCommand:M.join(", ")||(A(o.safetyCommand)??o.spawnCommand),permissionRules:v,onConfirm:async(s,p)=>{}};return i&&(c.warnings=i),c}async execute(t){if(t.aborted)return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."};let o=C(this.params.command),a=o.spawnCommand;o.strippedTrailingAmp&&u.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding");let f=gt(this.params.description||a),S=pt(f),M=Math.min(this.params.max_events??Et,O),v=Math.min(this.params.idle_timeout_ms??St,N),i=`mon_${wt().replace(/-/g,"").slice(0,16)}`,c=this.config.getMonitorRegistry(),s=tt()??void 0;if(c.getRunning().length>=P)return{llmContent:`Cannot start monitor: maximum concurrent monitors (${P}) reached. Stop an existing monitor first.`,returnDisplay:"Monitor rejected: too many concurrent monitors."};let d=new AbortController,g={monitorId:i,command:a,description:f,status:"running",startTime:Date.now(),abortController:d,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents:M,idleTimeoutMs:v,droppedLines:0,outputFile:lt(this.config.storage.getProjectDir(),this.config.getSessionId(),i),...s?{ownerAgentId:s}:{}},{executable:yt,argsPrefix:vt}=et(),n;try{n=ct(yt,[...vt,a],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,MATILDA_CODE:"1",TERM:"dumb",PAGER:"cat",...st()}})}catch(e){return{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}g.pid=n.pid;let b=!1,w,D=e=>{w??=e};n.on("error",D);let B={value:""},G={value:""},k=ut,I=Date.now(),$=e=>{let r=gt(e);if(r.length===0||r.trim().length===0)return;let T=Date.now(),_=T-I;if(_<0)u.warn(`Monitor ${i}: clock moved backwards by ${-_}ms, resetting refill timestamp`),I=T;else{let h=Math.floor(_/ft);h>0&&(k=Math.min(ut,k+h),I+=h*ft)}k>0?(k--,c.emitEvent(i,r)):g.droppedLines++},j=()=>{for(let e of[B,G]){let r=e.value.trim();r.length>0&&$(r),e.value=""}},Tt=()=>{if(!(b||!n.pid))if(process.platform==="win32")ct("taskkill",["/pid",n.pid.toString(),"/f","/t"],{stdio:"ignore"}).on("error",r=>u.warn(`Monitor taskkill failed for pid ${n.pid}: ${m(r)}`));else{try{process.kill(-n.pid,"SIGTERM")}catch(e){u.warn(`Monitor ${i} SIGTERM failed (pid=${n.pid}): ${m(e)}`)}setTimeout(()=>{if(!b&&n.pid)try{process.kill(-n.pid,"SIGKILL")}catch(e){u.warn(`Monitor ${i} SIGKILL escalation failed (pid=${n.pid}): ${m(e)}`)}},200).unref?.()}},E=()=>{j(),Tt()};d.signal.addEventListener("abort",E,{once:!0}),d.signal.aborted&&E();try{c.register(g)}catch(e){return E(),d.signal.removeEventListener("abort",E),n.stdout?.destroy?.(),n.stderr?.destroy?.(),n.removeListener("error",D),n.on("error",()=>{}),{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}let z=(e,r)=>{if(g.status!=="running")return;let T=rt(r.toString("utf-8"));if(e.value+=T,!e.value.includes(`
4
4
  `)&&e.value.length>R){let h=e.value.trim();h.length>0&&$(h.slice(0,R)+"..."),e.value="";return}let _=e.value.split(`
5
5
  `);e.value=_.pop()??"";for(let h of _){let x=h.trim();if(x.length===0)continue;let bt=x.length>R?x.slice(0,R)+"...":x;$(bt)}};n.stdout?.on("data",e=>z(B,e)),n.stderr?.on("data",e=>z(G,e));let F=!1,X=()=>{F||(F=!0,j(),d.signal.removeEventListener("abort",E),g.droppedLines>0&&u.info(`Monitor ${i} dropped ${g.droppedLines} lines due to throttling`))},V=null,_t=(e,r)=>{g.status==="running"&&(d.signal.aborted?c.cancel(i):e!==null&&e!==0?c.fail(i,`Exit code ${e}`):r?c.fail(i,`Killed by signal ${r}`):c.complete(i,e))},Ct=(e,r)=>{b=!0,V={code:e,sig:r}},Mt=(e,r)=>{b=!0,X();let T=V??{code:e,sig:r};_t(T.code,T.sig)},W=e=>{b=!0,X(),g.status==="running"&&c.fail(i,m(e))};return n.on("exit",Ct),n.on("close",Mt),n.on("error",W),n.removeListener("error",D),w?(W(w),{llmContent:`Monitor failed to start: ${m(w)}`,returnDisplay:`Monitor failed: ${m(w)}`}):{llmContent:`Monitor started.
6
6
  id: ${i}