@maincode-ai/matilda-code 0.21.6 → 0.21.7-nightly.20260920.d953e31d2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/agent-OW4AMLGE.js +3 -0
- package/chunks/agent-headless-CXL5LO2G.js +3 -0
- package/chunks/{anthropicContentGenerator-EAQDRKHH.js → anthropicContentGenerator-SFJGSZHT.js} +1 -1
- package/chunks/{askUserQuestion-7II3GVHO.js → askUserQuestion-MJ4FTAOQ.js} +1 -1
- package/chunks/{chunk-VB4MJSMC.js → chunk-32PTAACU.js} +1 -1
- package/chunks/{chunk-OXHC3R2R.js → chunk-32T6RWWT.js} +1 -1
- package/chunks/{chunk-QF6BOPQB.js → chunk-34DXSYJZ.js} +2 -2
- package/chunks/chunk-3RD5BHRX.js +34 -0
- package/chunks/{chunk-BH56I7SB.js → chunk-3ZAMYREW.js} +1 -1
- package/chunks/{chunk-YTGWPLEA.js → chunk-5PMMY47S.js} +1 -1
- package/chunks/{chunk-BGZJUBRA.js → chunk-6B5BDE7S.js} +1 -1
- package/chunks/{chunk-IPL3QW4D.js → chunk-7PNIGVSD.js} +1 -1
- package/chunks/{chunk-OVC5Z3EX.js → chunk-B3NVKOSU.js} +1 -1
- package/chunks/{chunk-EU5CK2VJ.js → chunk-BUCTEJSK.js} +509 -509
- package/chunks/{chunk-4Z6HQEVC.js → chunk-DAFUAZBW.js} +2 -2
- package/chunks/{chunk-X4ML2NEE.js → chunk-DCQKJTAX.js} +2 -2
- package/chunks/chunk-EQEQPZLQ.js +8 -0
- package/chunks/{chunk-LNTO3FNQ.js → chunk-FRL6KOLY.js} +1 -1
- package/chunks/chunk-FWIVFCKF.js +8 -0
- package/chunks/chunk-INAZKGGR.js +8 -0
- package/chunks/chunk-LIWYWWOK.js +8 -0
- package/chunks/{chunk-FQ44TPC5.js → chunk-LSDMWVW6.js} +3 -3
- package/chunks/{chunk-AICUGYJK.js → chunk-MQUGY4PQ.js} +1 -1
- package/chunks/chunk-Q2I3ARPJ.js +8 -0
- package/chunks/{chunk-XITA5WMN.js → chunk-QHA3ZBRO.js} +1 -1
- package/chunks/chunk-RJX7DK4Y.js +27 -0
- package/chunks/chunk-ROETRE5J.js +9 -0
- package/chunks/{chunk-O3OUYCSO.js → chunk-S7G6QPEP.js} +1 -1
- package/chunks/chunk-VLYRNOD3.js +36 -0
- package/chunks/{chunk-C7L2FDS6.js → chunk-VPMGPS4S.js} +3 -3
- package/chunks/chunk-VWWEEU4V.js +9 -0
- package/chunks/chunk-VYTYYCBR.js +3 -0
- package/chunks/chunk-XCJYORZX.js +9 -0
- package/chunks/{chunk-UTS2D2OV.js → chunk-YNQQIE2C.js} +11 -11
- package/chunks/{computer-use-X7US5CFC.js → computer-use-75G7W4CF.js} +1 -1
- package/chunks/contextCommand-5AEUXP6K.js +3 -0
- package/chunks/{cron-create-HASFXYQL.js → cron-create-BTTPO3JC.js} +1 -1
- package/chunks/{cron-delete-AW4S5IYT.js → cron-delete-U55RHRID.js} +1 -1
- package/chunks/{cron-list-U5U5GO6A.js → cron-list-J4HRR46K.js} +1 -1
- package/chunks/{edit-CVHLH32T.js → edit-L42KW7KG.js} +1 -1
- package/chunks/{enter-worktree-DOV462JZ.js → enter-worktree-F7L46TR7.js} +1 -1
- package/chunks/{enterPlanMode-4Z32XTSV.js → enterPlanMode-SYIYUOBN.js} +1 -1
- package/chunks/{exit-worktree-SZWLWCNF.js → exit-worktree-44PVOBH5.js} +1 -1
- package/chunks/{exitPlanMode-MG7QZYZ7.js → exitPlanMode-RAZXQ7FT.js} +1 -1
- package/chunks/{geminiContentGenerator-S4NNKSEQ.js → geminiContentGenerator-24YINMHK.js} +1 -1
- package/chunks/glob-3733NSQF.js +22 -0
- package/chunks/{grep-CB6P3VIR.js → grep-X6BSJJ4L.js} +1 -1
- package/chunks/{keychain-token-storage-5MWTIAEL.js → keychain-token-storage-HAFQQIXL.js} +1 -1
- package/chunks/ls-CLDNF3YS.js +15 -0
- package/chunks/{lsp-ELR2BGT4.js → lsp-7SKRKR5Q.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-GHIMPOOE.js → matildaAgentContentGenerator-AAMXNN4G.js} +1 -1
- package/chunks/matildaContentGenerator-ARMO2LGC.js +8 -0
- package/chunks/{matildaOAuth2-5EYRIK66.js → matildaOAuth2-W2DQO2NK.js} +1 -1
- package/chunks/monitor-LJJFUT55.js +32 -0
- package/chunks/notebook-edit-TXRMUCSL.js +17 -0
- package/chunks/{openaiContentGenerator-O5Q5FHFD.js → openaiContentGenerator-QHSC43AC.js} +1 -1
- package/chunks/read-file-J5UBJYDO.js +3 -0
- package/chunks/ripGrep-ET7IOM4A.js +3 -0
- package/chunks/scheduler-KVTQ6P2T.js +8 -0
- package/chunks/{send-message-GFPVOTSZ.js → send-message-XXRROIL7.js} +1 -1
- package/chunks/{serve-VW4UWSX4.js → serve-ABWSIR7B.js} +21 -21
- package/chunks/shell-CLFIQYYM.js +3 -0
- package/chunks/{skill-JFIJEIFA.js → skill-T3MGV3F6.js} +1 -1
- package/chunks/src-3H56WVFR.js +3 -0
- package/chunks/symbol-search-3MVTK4KV.js +19 -0
- package/chunks/{syntheticOutput-XKGS6F2D.js → syntheticOutput-QEUQIVQJ.js} +1 -1
- package/chunks/task-create-AEJQ73GE.js +3 -0
- package/chunks/{task-list-V27WHHHJ.js → task-list-ZEJTNZ2O.js} +1 -1
- package/chunks/{task-stop-NON26GAN.js → task-stop-JO3CXG2K.js} +1 -1
- package/chunks/{task-update-DE7CUGPY.js → task-update-3YY37VFN.js} +1 -1
- package/chunks/{team-create-JEC4ZSNE.js → team-create-KX646U6L.js} +1 -1
- package/chunks/team-delete-4YYLUV23.js +8 -0
- package/chunks/{todoWrite-YIMKFWIL.js → todoWrite-7BZMVNBC.js} +1 -1
- package/chunks/{tool-search-HFOHXFK5.js → tool-search-OWJC3UTX.js} +1 -1
- package/chunks/{update-goal-IDTG4LI6.js → update-goal-CF6G57J7.js} +1 -1
- package/chunks/{web-fetch-EVO7GDEB.js → web-fetch-K575OWZ7.js} +1 -1
- package/chunks/{web-search-SJMJGGPE.js → web-search-F6JRBXFV.js} +1 -1
- package/chunks/{workflow-2H6H2FR4.js → workflow-UE6CXBGG.js} +2 -2
- package/chunks/write-file-OAKHVSC6.js +15 -0
- package/cli.js +444 -441
- package/package.json +2 -2
- package/chunks/agent-OP5PDZKJ.js +0 -3
- package/chunks/agent-headless-GLMZVYOK.js +0 -3
- package/chunks/chunk-2HFKTFO5.js +0 -9
- package/chunks/chunk-5QAKUC2D.js +0 -14
- package/chunks/chunk-EPA3A73R.js +0 -56
- package/chunks/chunk-FW6Z25AA.js +0 -3
- package/chunks/chunk-L5ASITMV.js +0 -9
- package/chunks/chunk-MW3LAIJW.js +0 -8
- package/chunks/chunk-N6BOYL6K.js +0 -27
- package/chunks/chunk-SOKNPND5.js +0 -8
- package/chunks/chunk-SWEYYDZO.js +0 -8
- package/chunks/chunk-U3O6TMV7.js +0 -8
- package/chunks/chunk-UHDKX2CR.js +0 -8
- package/chunks/chunk-VBOVIARK.js +0 -9
- package/chunks/contextCommand-F34RZJU6.js +0 -3
- package/chunks/glob-T2SHBIJY.js +0 -22
- package/chunks/ls-IBIDQ5NV.js +0 -15
- package/chunks/matildaContentGenerator-FI2P7XPI.js +0 -8
- package/chunks/monitor-O46CPAVO.js +0 -32
- package/chunks/notebook-edit-M4XPR4X3.js +0 -17
- package/chunks/read-file-4TZCSTH7.js +0 -3
- package/chunks/ripGrep-FTFD4K7L.js +0 -3
- package/chunks/scheduler-PRAGNX3C.js +0 -8
- package/chunks/shell-YO6J22BF.js +0 -3
- package/chunks/src-EYWD2F72.js +0 -3
- package/chunks/symbol-search-ZV6W6DPK.js +0 -19
- package/chunks/task-create-T43QIG2F.js +0 -3
- package/chunks/team-delete-LIEVUGIX.js +0 -8
- package/chunks/write-file-6A7X7F5R.js +0 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.21.
|
|
3
|
+
"version": "0.21.7-nightly.20260920.d953e31d2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.7-nightly.20260920.d953e31d2"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|
package/chunks/agent-OP5PDZKJ.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{ig as a,jg as b,kg as c,lg as d,mg as e,ng as f}from"./chunk-EU5CK2VJ.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-QF6BOPQB.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-UTS2D2OV.js";import"./chunk-XITA5WMN.js";import"./chunk-4Z6HQEVC.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{f as AgentTool,b as TOOL_REGISTRY_REBUILT,e as createApprovalModeOverride,c as hasRebuiltToolRegistry,d as rebuildToolRegistryOnOverride,a as resolveSubagentApprovalMode};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Jf as a,Kf as b,Lf as c}from"./chunk-EU5CK2VJ.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-QF6BOPQB.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-UTS2D2OV.js";import"./chunk-XITA5WMN.js";import"./chunk-4Z6HQEVC.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{c as AgentHeadless,a as ContextState,b as templateString};
|
package/chunks/chunk-2HFKTFO5.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{d as g,v as h}from"./chunk-X4ML2NEE.js";import{b}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-SWEYYDZO.js";import{Z as M,a as c}from"./chunk-5QAKUC2D.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=M("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new b,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
|
|
4
|
-
`,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
|
|
5
|
-
/**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2025 Matilda
|
|
8
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
9
|
-
*/
|
package/chunks/chunk-5QAKUC2D.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{e as $,l as k,n as gt}from"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";c();function G(t){return t instanceof Error&&"code"in t}function $t(t){return!t||typeof t!="object"?!1:!!(t instanceof Error&&t.name==="AbortError"||G(t)&&t.code==="ABORT_ERR")}function Bt(t){if(t instanceof Error){let e=t.cause;return e instanceof Error&&e.message!==t.message?`${t.message} (cause: ${e.message})`:t.message}try{return String(t)}catch{return"Failed to get error details"}}function Ot(t){if(typeof t!="object"||t===null)return;let e=t,n=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof n=="number"&&n>=100&&n<=599)return n;if(typeof e.message=="string"){let r=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(r){let o=Number(r[1]);if(o>=100&&o<=599)return o}}}function Wt(t){if(typeof t!="object"||t===null)return"unknown";let e=t instanceof Error&&t.constructor.name!=="Error"?t.constructor.name:void 0,n=t.type,r=e??n??(t instanceof Error?t.name:"unknown"),o=t instanceof Error?t.cause:void 0,i=o&&typeof o=="object"&&"code"in o?o.code:void 0;return i?`${r}:${i}`:r}var d=class extends Error{constructor(n,r){super(n);this.exitCode=r}},B=class extends d{constructor(e){super(e,41)}},O=class extends d{constructor(e){super(e,42)}},W=class extends d{constructor(e){super(e,44)}},E=class extends d{constructor(e){super(e,52)}},_=class extends d{constructor(e){super(e,53)}},F=class extends d{constructor(e){super(e,54)}},U=class extends d{constructor(e){super(e,55)}},H=class extends d{constructor(e){super(e,130)}},I=class extends Error{},L=class extends Error{},M=class extends Error{},z=class extends Error{constructor(n,r,o,i){super(n);this.categories=r;this.severity=o;this.assistantMessage=i;this.name="ContentBlockedError"}};function _t(t){if(t&&typeof t=="object"&&"response"in t){let n=pt(t);if(n.error&&n.error.message&&n.error.code)switch(n.error.code){case 400:return new M(n.error.message);case 401:return new L(n.error.message);case 403:return new I(n.error.message);default:}}return t}function pt(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}c();import dt from"node:fs";import p from"node:path";import f from"node:os";import*as V from"node:crypto";var P=".matilda",Kt="google_accounts.json",b=new Map,ft=1024;function Xt(){b.clear()}var J=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Zt=["file_path","path","filePath","notebook_path"],ht=(()=>{let t=J.source.slice(1,-1);return new RegExp(`\\\\([${t}])`,"g")})();function Yt(t){let e=f.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function qt(t){if(!t)return"";let e=t;return t.toLowerCase().startsWith("%userprofile%")?e=f.homedir()+t.substring(13):(t==="~"||t.startsWith("~/"))&&(e=f.homedir()+t.substring(1)),p.normalize(e)}function Qt(t,e=80){if(t.length<=e)return t;let n=p.sep,r="...";if(e<10)return t.substring(0,e-3)+r;let i=p.parse(t).root,u=t.substring(i.length).split(n).filter(a=>a!=="");if(u.length===0)return i.length<=e?i:i.substring(0,e-3)+r;if(u.length===1){let a=i+u[0];if(a.length<=e)return a;let h=Math.floor((e-3)/2),x=a.substring(0,h),R=a.substring(a.length-h);return`${x}${r}${R}`}let l=i+u[0],y=[];for(let a=u.length-1;a>=1;a--){let h=u[a],x=[h,...y].join(n),R=a>1,j;if(R?j=l+n+r+n+x:j=l+n+x,j.length<=e){if(y.unshift(h),a===1)return j}else break}if(y.length===0){let a=Math.floor((e-3)/2),h=t.substring(0,a),x=t.substring(t.length-a);return`${h}${r}${x}`}return l+n+r+n+y.join(n)}function te(t,e){let n=p.resolve(t),r=p.resolve(e);return Z(r,n)?p.relative(r,n)||".":n}function ee(t){let e="";for(let n=0;n<t.length;n++){let r=t[n],o=0;for(let g=n-1;g>=0&&t[g]==="\\";g--)o++;!(o%2===1)&&J.test(r)?e+="\\"+r:e+=r}return e}function ne(t){return f.platform()==="win32"?t:t.replace(ht,"$1")}function K(t){let e=f.platform()==="win32"?t.toLowerCase():t;return V.createHash("sha256").update(e).digest("hex")}function X(t){return(f.platform()==="win32"?t.toLowerCase():t).replace(/[^a-zA-Z0-9]/g,"-")}function Z(t,e){let r=f.platform()==="win32"?p.win32:p,o=r.relative(t,e);return!o.startsWith(`..${r.sep}`)&&o!==".."&&!r.isAbsolute(o)}function re(t,e){return t.some(n=>Z(n,e))}function mt(t=process.cwd(),e){let n=f.homedir();return e==="~"?n:e.startsWith("~/")?p.join(n,e.slice(2)):p.isAbsolute(e)?e:p.resolve(t,e)}function Dt(t,e,n={}){let{allowFiles:r=!1,allowExternalPaths:o=!1}=n,g=t.getWorkspaceContext().isPathWithinWorkspace(e);if(!o&&!g)throw new Error("Path is not within workspace");if(o&&!g)return;let u=b.get(e);if(u===void 0){try{u=dt.statSync(e).isDirectory()}catch(l){throw G(l)&&l.code==="ENOENT"?new Error(`Path does not exist: ${e}`):l}if(b.size>=ft){let l=b.keys().next().value;l!==void 0&&b.delete(l)}b.set(e,u)}if(!r&&!u)throw new Error(`Path is not a directory: ${e}`)}function se(t,e,n={}){let r=t.getTargetDir();if(!e)return r;let o=mt(r,e);return Dt(t,o,n),o}c();import*as s from"node:path";import*as m from"node:os";import*as S from"node:fs";import{AsyncLocalStorage as xt}from"node:async_hooks";var bt="google_accounts.json",Et="oauth_creds.json",Pt=[".matilda",".agents"],Y="tmp",wt="bin",vt="projects",yt="ide",jt="plans",St="debug",Ct="arena",D=class t{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new xt;constructor(e,n){this.targetDir=e,this.pinnedRuntimeBaseDir=n?t.resolvePath(n):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??t.getRuntimeBaseDir()}static resolvePath(e,n){let r=e;if(r==="~"||r.startsWith("~/")||r.startsWith("~\\")){let o=r==="~"?[]:r.slice(2).split(/[/\\]+/).filter(Boolean);r=s.join(m.homedir(),...o)}return s.isAbsolute(r)||(r=n?s.resolve(n,r):s.resolve(r)),r}static sanitizePlanSessionId(e){return s.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,n){return e?t.resolvePath(e,n):null}static setRuntimeBaseDir(e,n){t.runtimeBaseDir=t.resolveRuntimeBaseDir(e,n)}static runWithRuntimeBaseDir(e,n,r){let o=t.resolveRuntimeBaseDir(e,n);return t.runtimeBaseDirContext.run(o,r)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return t.resolveRuntimeBaseDir(e)??t.getGlobalMatildaDir();let n=t.runtimeBaseDirContext.getStore();return n!==void 0?n??t.getGlobalMatildaDir():t.runtimeBaseDir?t.runtimeBaseDir:t.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return t.resolvePath(e);let n=m.homedir();return n?s.join(n,P):s.join(m.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return s.join(t.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return s.join(t.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return s.join(t.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return s.join(t.getGlobalMatildaDir(),bt)}static getUserCommandsDir(){return s.join(t.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return s.join(t.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return s.join(t.getRuntimeBaseDir(),Y)}static getGlobalDebugDir(){return s.join(t.getRuntimeBaseDir(),St)}static getDebugLogPath(e){return s.join(t.getGlobalDebugDir(),`${e}.txt`)}static getGlobalIdeDir(){return s.join(t.getGlobalMatildaDir(),yt)}static resolvePathThroughExistingAncestor(e){let n=e;for(;;)try{let r=S.realpathSync(n),o=s.relative(n,e);return s.join(r,o)}catch(r){if(r.code!=="ENOENT")throw r;let o=s.dirname(n);if(o===n)return e;n=o}}static isPathWithinDirectory(e,n){let r=t.resolvePathThroughExistingAncestor(n),o=t.resolvePathThroughExistingAncestor(e),i=s.relative(r,o);return i===""||!i.startsWith("..")&&!s.isAbsolute(i)}static assertPathWithinDirectory(e,n,r){if(!t.isPathWithinDirectory(e,n))throw new E(r)}static getPlansDir(e,n){let r=n?.trim();if(r){if(!e)throw new E("projectRoot is required when plansDirectory is configured.");let o=s.resolve(e),i=t.resolvePath(r,o);return t.assertPathWithinDirectory(i,o,"plansDirectory must resolve within the project root."),i}return s.join(t.getGlobalMatildaDir(),jt)}static getPlanFilePath(e,n,r){return s.join(t.getPlansDir(n,r),`${t.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return s.join(t.getGlobalMatildaDir(),wt)}static getGlobalArenaDir(){return s.join(t.getGlobalMatildaDir(),Ct)}getMatildaDir(){return s.join(this.targetDir,P)}getProjectDir(){let e=X(this.getProjectRoot()),n=s.join(this.getRuntimeBaseDir(),vt);return s.join(n,e)}getProjectTempDir(){let e=K(this.getProjectRoot()),n=s.join(this.getRuntimeBaseDir(),Y);return s.join(n,e)}getToolResultsDir(){return s.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){S.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return s.join(t.getGlobalMatildaDir(),Et)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return s.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return s.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return s.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return s.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return s.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return s.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=m.homedir()||m.tmpdir();return Pt.map(n=>n===P?s.join(t.getGlobalMatildaDir(),"skills"):s.join(e,n,"skills"))}static getUserExtensionsDir(){return s.join(t.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return s.join(this.getProjectTempDir(),"shell_history")}};c();import{promises as N}from"node:fs";import q from"node:path";async function Q(t,e,n){let{fallbackCopy:r=!0}=n??{},o=q.dirname(t),i=q.relative(o,e);try{await N.unlink(t)}catch{}try{await N.symlink(i,t);return}catch{}if(r)try{await N.copyFile(e,t)}catch{}}c();gt();c();var tt,et;function De(t,e){tt=t,et=e}function nt(){return tt}function xe(){return et}function rt(t){let e=t?.spanContext();return e&&$(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function At(){try{return rt(k.getActiveSpan())}catch{return null}}function Tt(){try{let t=nt();return rt(t?k.getSpan(t):void 0)}catch{return null}}function st(){return At()??Tt()}function ye(t){let e=(t.traceFlags&255).toString(16).padStart(2,"0");return`00-${t.traceId}-${t.spanId}-${e}`}var ot=!1;function je(t){ot=t}function Se(){return ot}c();import{promises as it}from"node:fs";import Rt from"node:path";import{AsyncLocalStorage as kt}from"node:async_hooks";import It from"node:util";var v=null,A=null,T=!1,at=null,ct=new kt;function ut(){let t=process.env.MATILDA_DEBUG_LOG_FILE;if(!t)return!1;let e=t.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function w(){return ct.getStore()??at}function lt(){let t=D.getGlobalDebugDir();return(!v||A!==t)&&(A=t,v=it.mkdir(t,{recursive:!0}).then(()=>{}).catch(()=>{T=!0,v=null,A=null})),v??Promise.resolve()}function Lt(t){return t.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:It.inspect(e)).join(" ")}function Mt(t,e,n,r){let o=new Date().toISOString(),i=n?` [${n}]`:"",g=r?` [trace_id=${r.traceId} span_id=${r.spanId}]`:"";return`${o} [${t}]${i}${g} ${e}
|
|
4
|
-
`}function C(t,e,n,r){if(!ut())return;let o=t.getSessionId(),i=D.getDebugLogPath(o),g=Lt(r),u=st(),l=Mt(e,g,n,u);lt().then(()=>it.appendFile(i,l,"utf8")).catch(()=>{T=!0})}function Ne(){return T}function $e(){T=!1,v=null,A=null}var Gt="latest";function Nt(t){if(!ut())return;let e=Rt.join(D.getGlobalDebugDir(),Gt),n=D.getDebugLogPath(t);lt().then(()=>Q(e,n,{fallbackCopy:!1})).catch(()=>{})}function Be(t){at=t??null,t&&Nt(t.getSessionId())}function Oe(t,e){return ct.run(t,e)}function We(t){return{isEnabled:()=>w()!==null,debug:(...e)=>{let n=w();n&&C(n,"DEBUG",t,e)},info:(...e)=>{let n=w();n&&C(n,"INFO",t,e)},warn:(...e)=>{let n=w();n&&C(n,"WARN",t,e)},error:(...e)=>{let n=w();n&&C(n,"ERROR",t,e)}}}export{G as a,$t as b,Bt as c,Ot as d,Wt as e,d as f,B as g,O as h,W as i,E as j,_ as k,F as l,U as m,H as n,I as o,L as p,M as q,z as r,_t as s,P as t,Kt as u,Xt as v,J as w,Zt as x,Yt as y,qt as z,Qt as A,te as B,ee as C,ne as D,K as E,X as F,Z as G,re as H,mt as I,Dt as J,se as K,Pt as L,D as M,Q as N,De as O,xe as P,At as Q,st as R,ye as S,je as T,Se as U,Ne as V,$e as W,Be as X,Oe as Y,We as Z};
|
|
5
|
-
/**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2025 Google LLC
|
|
8
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
9
|
-
*/
|
|
10
|
-
/**
|
|
11
|
-
* @license
|
|
12
|
-
* Copyright 2025 Matilda
|
|
13
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
14
|
-
*/
|
package/chunks/chunk-EPA3A73R.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as ls}from"./chunk-U3O6TMV7.js";import{c as yr,f as Te}from"./chunk-XITA5WMN.js";import{M as Zn,N as es,O as qt,Q as ts,R as Cr,S as rs,a as Vn,g as ve,h as Kn,la as as}from"./chunk-4Z6HQEVC.js";import{a as is}from"./chunk-DC7LAFZZ.js";import{a as Xn,g as zn,k as Yn,l as mr,o as ns,t as ss,v as os}from"./chunk-O3OUYCSO.js";import{e as Jn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as Qn,n as br}from"./chunk-SDTWBD62.js";import{b as rn}from"./chunk-ESSYHTAZ.js";import{Z as he,b as qn,p as tn}from"./chunk-5QAKUC2D.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 nn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return nn=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 Jt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Xt=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 me({message:r,cause:Xt(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)}},me=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{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 ${},ht=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},mt=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 _o=/^[a-z][a-z0-9+.-]*:/i,cs=n=>_o.test(n),W=n=>(W=Array.isArray,W(n)),sn=W;function us(n){return typeof n!="object"?{}:n??{}}function fs(n){if(!n)return!0;for(let e in n)return!1;return!0}function ps(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ds=(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 hs=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 bs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function bo(){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 Co=()=>{let n=bo();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(Deno.build.os),"X-Stainless-Arch":ms(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":gs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ms(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=yo();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 yo(){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 ms=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",gs=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"),_s,Cs=()=>_s??(_s=Co());a();function ys(){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 on(...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 wr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function an(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 ws(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 As=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var Ar="RFC3986",ln=n=>String(n),xr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ln},cn="RFC1738";a();a();var Ir=(n,e)=>(Ir=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ir(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var un=1024,xs=(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+=un){let u=o.length>=un?o.slice(l,l+un):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===cn&&(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 Is(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function fn(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 Rs={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Os=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Ps,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xs,encodeValuesOnly:!1,format:Ar,formatter:ln,indices:!1,serializeDate(n){return(Ps??(Ps=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function xo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var pn={};function Ss(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,J=!1;for(;(U=U.get(pn))!==void 0&&!J;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");J=!0}typeof U.get(pn)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=fn(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(xo(w)||Is(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=fn(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),G=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return G+"[]";for(let T=0;T<E.length;++T){let M=E[T],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Wn===null)continue;let en=p&&l?M.replace(/\./g,"%2E"):M,mo=W(w)?typeof t=="function"?t(G,en):G:G+(p?"."+en:"["+en+"]");O.set(n,S);let Hn=new WeakMap;Hn.set(pn,O),Os(H,Ss(Wn,mo,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Hn))}return H}function Io(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=Ar;if(typeof n.format<"u"){if(!Ir(xr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=xr[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in Rs?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 dn(n,e={}){let t=n,r=Io(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=Rs[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||Os(i,Ss(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 Ts(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 Es;function gt(n){let e;return(Es??(e=new globalThis.TextEncoder,Es=e.encode.bind(e)))(n)}var vs;function hn(n){let e;return(vs??(e=new globalThis.TextDecoder,vs=e.decode.bind(e)))(n)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),A(this,X,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,X,Ts([c(this,X,"f"),t]),"f");let r=[],s;for(;(s=Ro(c(this,X,"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(hn(c(this,X,"f").subarray(0,c(this,V,"f")-1))),A(this,X,c(this,X,"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=hn(c(this,X,"f").subarray(0,o));r.push(i),A(this,X,c(this,X,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,X,"f").length?this.decode(`
|
|
4
|
-
`):[]}};X=new WeakMap,V=new WeakMap;ke.NEWLINE_CHARS=new Set([`
|
|
5
|
-
`,"\r"]);ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ro(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 ks(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 Rr={off:0,error:200,warn:300,info:400,debug:500},mn=(n,e,t)=>{if(n){if(ps(Rr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Rr))}`)}};function Kt(){}function Pr(n,e,t){return!e||Rr[n]>Rr[t]?Kt:e[n].bind(e)}var Oo={error:Kt,warn:Kt,info:Kt,debug:Kt},Ms=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Oo;let r=Ms.get(e);if(r&&r[0]===t)return r[1];let s={error:Pr("error",e,t),warn:Pr("warn",e,t),info:Pr("info",e,t),debug:Pr("debug",e,t)};return Ms.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 So(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(Jt(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 ke,u=an(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(Jt(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 on({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
|
-
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*So(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 gn,r=new ke,s=an(n.body);for await(let o of Eo(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*Eo(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=ks(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var gn=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
7
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=vo(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function vo(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function Or(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return v(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):re.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return _n(p,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,le({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function _n(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}a();var Yt,Me=class n extends Promise{constructor(e,t,r=Or){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Yt.set(this,void 0),A(this,Yt,e,"f")}_thenUnwrap(e){return new n(c(this,Yt,"f"),this.responsePromise,async(t,r)=>_n(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Yt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Yt=new WeakMap;var Sr,Er=class{constructor(e,t,r,s){Sr.set(this,void 0),A(this,Sr,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Sr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Sr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qt=class extends Me{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await Or(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends Er{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Er{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...us(this.options.query),after:t}}:null}};a();a();a();var Cn=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function _t(n,e,t){return Cn(),new File(n,e??"unknown_file",t)}function Zt(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}var yn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var K=async(n,e)=>({...n,body:await Mo(n.body,e)}),$s=new WeakMap;function ko(n){let e=typeof n=="function"?n:n.fetch,t=$s.get(e);if(t)return t;let r=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return $s.set(e,r),r}var Mo=async(n,e)=>{if(!await ko(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>bn(t,r,s))),t},$o=n=>n instanceof Blob&&"name"in n;var bn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,_t([await t.blob()],Zt(t)));else if(yn(t))n.append(e,_t([await new Response(wr(t)).blob()],Zt(t)));else if($o(t))n.append(e,t,Zt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>bn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>bn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Ns=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",No=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Ns(n),Lo=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function vr(n,e,t){if(Cn(),n=await n,No(n))return n instanceof File?n:_t([await n.arrayBuffer()],n.name);if(Lo(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),_t(await wn(s),e,t)}let r=await wn(n);if(e||(e=Zt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return _t(r,e,t)}async function wn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Ns(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(yn(n))for await(let t of n)e.push(...await wn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Fo(n)}`)}return e}function Fo(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var m=class{constructor(e){this._client=e}};a();a();a();function Fs(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ls=Object.freeze(Object.create(null)),Do=(n=Fs)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,p,b)=>{/[?#]/.test(p)&&(s=!0);let f=r[b],x=(s?encodeURIComponent:n)(""+f);return b!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ls)??Ls)?.toString)&&(x=f+"",o.push({start:g.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+p+(b===r.length?"":x)},""),l=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(l))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((g,p)=>g.start-p.start),o.length>0){let g=0,p=o.reduce((b,f)=>{let x=" ".repeat(f.start-g),C="^".repeat(f.length);return g=f.start+f.length,b+x+C},"");throw new y(`Path parameters result in path with invalid segments:
|
|
8
|
-
${o.map(b=>b.error).join(`
|
|
9
|
-
`)}
|
|
10
|
-
${i}
|
|
11
|
-
${p}`)}return i},h=Do(Fs);var $e=class extends m{list(e,t={},r){return this._client.getAPIList(h`/chat/completions/${e}/messages`,R,{query:t,...r})}};a();a();a();a();function Us(n){return typeof n.parse=="function"}a();var bt=n=>n?.role==="assistant",An=n=>n?.role==="tool";a();var xn,Tr,kr,er,tr,Mr,rr,ce,nr,$r,Nr,Ct,Ds,be=class{constructor(){xn.add(this),this.controller=new AbortController,Tr.set(this,void 0),kr.set(this,()=>{}),er.set(this,()=>{}),tr.set(this,void 0),Mr.set(this,()=>{}),rr.set(this,()=>{}),ce.set(this,{}),nr.set(this,!1),$r.set(this,!1),Nr.set(this,!1),Ct.set(this,!1),A(this,Tr,new Promise((e,t)=>{A(this,kr,e,"f"),A(this,er,t,"f")}),"f"),A(this,tr,new Promise((e,t)=>{A(this,Mr,e,"f"),A(this,rr,t,"f")}),"f"),c(this,Tr,"f").catch(()=>{}),c(this,tr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,xn,"m",Ds).bind(this))},0)}_connected(){this.ended||(c(this,kr,"f").call(this),this._emit("connect"))}get ended(){return c(this,nr,"f")}get errored(){return c(this,$r,"f")}get aborted(){return c(this,Nr,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,ce,"f")[e];if(!r)return this;let s=r.findIndex(o=>o.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{A(this,Ct,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){A(this,Ct,!0,"f"),await c(this,tr,"f")}_emit(e,...t){if(c(this,nr,"f"))return;e==="end"&&(A(this,nr,!0,"f"),c(this,Mr,"f").call(this));let r=c(this,ce,"f")[e];if(r&&(c(this,ce,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Tr=new WeakMap,kr=new WeakMap,er=new WeakMap,tr=new WeakMap,Mr=new WeakMap,rr=new WeakMap,ce=new WeakMap,nr=new WeakMap,$r=new WeakMap,Nr=new WeakMap,Ct=new WeakMap,xn=new WeakSet,Ds=function(e){if(A(this,$r,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new k),e instanceof k)return A(this,Nr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};a();function sr(n){return n?.$brand==="auto-parseable-response-format"}function Ne(n){return n?.$brand==="auto-parseable-tool"}function Gs(n,e){return!e||!In(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:or(n,e)}function or(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new ht;if(r.finish_reason==="content_filter")throw new mt;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>Wo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Bo(e,r.message.content):null}}});return{...n,choices:t}}function Bo(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Wo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ne(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function js(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return Ne(t)||t?.function.strict||!1}function In(n){return sr(n.response_format)?!0:n.tools?.some(e=>Ne(e)||e.type==="function"&&e.function.strict===!0)??!1}function Bs(n){for(let e of n??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,Pn,Lr,Rn,On,Sn,Ws,Hs,Ho=10,yt=class extends be{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),An(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(bt(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",Pn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",Lr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",Rn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",On).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",Sn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,q,"m",Lr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",Pn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",Rn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",On).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",Sn).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,q,"m",Ws).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(or(o,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let s="tool",{tool_choice:o="auto",stream:i,...l}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:d=Ho}=r||{},g=t.tools.map(f=>{if(Ne(f)){if(!f.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of g)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let b="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){let C=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0]?.message;if(!C)throw new y("missing message in ChatCompletion response");if(!C.tool_calls?.length)return;for(let P of C.tool_calls){if(P.type!=="function")continue;let O=P.id,{name:w,arguments:U}=P.function,S=p[w];if(S){if(u&&u!==w){let D=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(p).map(G=>JSON.stringify(G)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}let J;try{J=Us(S)?await S.parse(U):U}catch(D){let G=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:O,content:G});continue}let H=await S.function(J,this),E=c(this,q,"m",Hs).call(this,H);if(this._addMessage({role:s,tool_call_id:O,content:E}),u)return}}}};q=new WeakSet,Pn=function(){return c(this,q,"m",Lr).call(this).content??null},Lr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(bt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Rn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},On=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(An(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Sn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ws=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Hs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ir=class n extends yt{static runTools(e,t,r){let s=new n,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),bt(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var j={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},En=class extends Error{},vn=class extends Error{};function qo(n,e=j.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Jo(n.trim(),e)}var Jo=(n,e)=>{let t=n.length,r=0,s=b=>{throw new En(`${b} at position ${r}`)},o=b=>{throw new vn(`${b} at position ${r}`)},i=()=>(p(),r>=t&&s("Unexpected end of input"),n[r]==='"'?l():n[r]==="{"?u():n[r]==="["?d():n.substring(r,r+4)==="null"||j.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||j.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||j.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||j.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||j.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||j.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let b=r,f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(b,++r-Number(f)))}catch(x){o(String(x))}else if(j.STR&e)try{return JSON.parse(n.substring(b,r-Number(f))+'"')}catch{return JSON.parse(n.substring(b,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let b={};try{for(;n[r]!=="}";){if(p(),r>=t&&j.OBJ&e)return b;let f=l();p(),r++;try{let x=i();Object.defineProperty(b,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(j.OBJ&e)return b;throw x}p(),n[r]===","&&r++}}catch{if(j.OBJ&e)return b;s("Expected '}' at end of object")}return r++,b},d=()=>{r++;let b=[];try{for(;n[r]!=="]";)b.push(i()),p(),n[r]===","&&r++}catch{if(j.ARR&e)return b;s("Expected ']' at end of array")}return r++,b},g=()=>{if(r===0){n==="-"&&j.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(j.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}o(String(f))}}let b=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(j.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(b,r))}catch{n.substring(b,r)==="-"&&j.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(b,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
|
|
12
|
-
\r `.includes(n[r]);)r++};return i()},Tn=n=>qo(n,j.ALL^j.NUM);var L,ue,wt,Ce,kn,Fr,Mn,$n,Nn,Ur,Ln,qs,Le=class n extends yt{constructor(e){super(),L.add(this),ue.set(this,void 0),wt.set(this,void 0),Ce.set(this,void 0),A(this,ue,e,"f"),A(this,wt,[],"f")}get currentChatCompletionSnapshot(){return c(this,Ce,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new n(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,L,"m",kn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)c(this,L,"m",Mn).call(this,i);if(o.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Ur).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,L,"m",kn).call(this),this._connected();let s=re.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(c(this,L,"m",Ur).call(this)),c(this,L,"m",Mn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Ur).call(this))}[(ue=new WeakMap,wt=new WeakMap,Ce=new WeakMap,L=new WeakSet,kn=function(){this.ended||A(this,Ce,void 0,"f")},Fr=function(t){let r=c(this,wt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,wt,"f")[t.index]=r,r)},Mn=function(t){if(this.ended)return;let r=c(this,L,"m",qs).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let o=r.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=c(this,L,"m",Fr).call(this,o);o.finish_reason&&(c(this,L,"m",Nn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",$n).call(this,o,i.current_tool_call_index));for(let l of s.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(c(this,L,"m",Nn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",$n).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[l.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:l.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(u?.type,void 0))}}},$n=function(t,r){if(c(this,L,"m",Fr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=c(this,ue,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ne(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Nn=function(t){let r=c(this,L,"m",Fr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,L,"m",Ln).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ur=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Ce,"f");if(!t)throw new y("request ended without sending any chunks");return A(this,Ce,void 0,"f"),A(this,wt,[],"f"),Xo(t,c(this,ue,"f"))},Ln=function(){let t=c(this,ue,"f")?.response_format;return sr(t)?t:null},qs=function(t){var r,s,o,i;let l=c(this,Ce,"f"),{choices:u,...d}=t;l?Object.assign(l,d):l=A(this,Ce,{...d,choices:[]},"f");for(let{delta:g,finish_reason:p,index:b,logprobs:f=null,...x}of t.choices){let C=l.choices[b];if(C||(C=l.choices[b]={finish_reason:p,index:b,message:{},logprobs:f,...x}),f)if(!C.logprobs)C.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(C.logprobs,D),H&&((r=C.logprobs).content??(r.content=[]),C.logprobs.content.push(...H)),E&&((s=C.logprobs).refusal??(s.refusal=[]),C.logprobs.refusal.push(...E))}if(p&&(C.finish_reason=p,c(this,ue,"f")&&In(c(this,ue,"f")))){if(p==="length")throw new ht;if(p==="content_filter")throw new mt}if(Object.assign(C,x),!g)continue;let{content:P,refusal:O,function_call:w,role:U,tool_calls:S,...J}=g;if(Object.assign(C.message,J),O&&(C.message.refusal=(C.message.refusal||"")+O),U&&(C.message.role=U),w&&(C.message.function_call?(w.name&&(C.message.function_call.name=w.name),w.arguments&&((o=C.message.function_call).arguments??(o.arguments=""),C.message.function_call.arguments+=w.arguments)):C.message.function_call=w),P&&(C.message.content=(C.message.content||"")+P,!C.message.refusal&&c(this,L,"m",Ln).call(this)&&(C.message.parsed=Tn(C.message.content))),S){C.message.tool_calls||(C.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:G,...T}of S){let M=(i=C.message.tool_calls)[H]??(i[H]={});Object.assign(M,T),E&&(M.id=E),D&&(M.type=D),G&&(M.function??(M.function={name:G.name??"",arguments:""})),G?.name&&(M.function.name=G.name),G?.arguments&&(M.function.arguments+=G.arguments,js(c(this,ue,"f"),M)&&(M.function.parsed_arguments=Tn(M.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Xo(n,e){let{id:t,choices:r,created:s,model:o,system_fingerprint:i,...l}=n,u={...l,id:t,choices:r.map(({message:d,finish_reason:g,index:p,logprobs:b,...f})=>{if(!g)throw new y(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:C,tool_calls:P,...O}=d,w=d.role;if(!w)throw new y(`missing role for choice ${p}`);if(C){let{arguments:U,name:S}=C;if(U==null)throw new y(`missing function_call.arguments for choice ${p}`);if(!S)throw new y(`missing function_call.name for choice ${p}`);return{...f,message:{content:x,function_call:{arguments:U,name:S},role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}return P?{...f,index:p,finish_reason:g,logprobs:b,message:{...O,role:w,content:x,refusal:d.refusal??null,tool_calls:P.map((U,S)=>{let{function:J,type:H,id:E,...D}=U,{arguments:G,name:T,...M}=J||{};if(E==null)throw new y(`missing choices[${p}].tool_calls[${S}].id
|
|
13
|
-
${Dr(n)}`);if(H==null)throw new y(`missing choices[${p}].tool_calls[${S}].type
|
|
14
|
-
${Dr(n)}`);if(T==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.name
|
|
15
|
-
${Dr(n)}`);if(G==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.arguments
|
|
16
|
-
${Dr(n)}`);return{...D,id:E,type:H,function:{...M,name:T,arguments:G}}})}}:{...f,message:{...O,content:x,role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Gs(u,e)}function Dr(n){return JSON.stringify(n)}var ar=class n extends Le{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new n(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var fe=class extends m{constructor(){super(...arguments),this.messages=new $e(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(h`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(h`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/chat/completions/${e}`,t)}parse(e,t){return Bs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>or(r,e))}runTools(e,t){return e.stream?ar.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return Le.createChatCompletion(this._client,e,t)}};fe.Messages=$e;var ye=class extends m{constructor(){super(...arguments),this.completions=new fe(this._client)}};ye.Completions=fe;a();a();a();a();a();var Js=Symbol("brand.privateNullableHeaders");function*Ko(n){if(!n)return;if(Js in n){let{values:r,nulls:s}=n;yield*r.entries();for(let o of s)yield[o,null];return}let e=!1,t;n instanceof Headers?t=n.entries():sn(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){let s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=sn(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,l])}}var _=n=>{let e=new Headers,t=new Set;for(let r of n){let s=new Set;for(let[o,i]of Ko(r)){let l=o.toLowerCase();s.has(l)||(e.delete(o),s.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[Js]:!0,values:e,nulls:t}};var At=class extends m{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var xt=class extends m{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var It=class extends m{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends m{constructor(){super(...arguments),this.transcriptions=new xt(this._client),this.translations=new It(this._client),this.speech=new At(this._client)}};se.Transcriptions=xt;se.Translations=It;se.Speech=At;a();var Fe=class extends m{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(h`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",R,{query:e,...t})}cancel(e,t){return this._client.post(h`/batches/${e}/cancel`,t)}};a();a();var Pt=class extends m{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(h`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(h`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Rt=class extends m{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Ot=class extends m{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends m{constructor(){super(...arguments),this.sessions=new Rt(this._client),this.transcriptionSessions=new Ot(this._client)}};we.Sessions=Rt;we.TranscriptionSessions=Ot;a();a();var St=class extends m{create(e,t,r){return this._client.post(h`/threads/${e}/messages`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(h`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(h`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/threads/${e}/messages`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(h`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Et=class extends m{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(h`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...o}=t;return this._client.getAPIList(h`/threads/${s}/runs/${e}/steps`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Xs=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};a();var Ae=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,De,Fn,oe,Gr,Y,Ge,vt,Ue,Wr,z,jr,Br,ur,lr,cr,Vs,Ks,zs,Ys,Qs,Zs,eo,pe=class extends be{constructor(){super(...arguments),B.add(this),Fn.set(this,[]),oe.set(this,{}),Gr.set(this,{}),Y.set(this,void 0),Ge.set(this,void 0),vt.set(this,void 0),Ue.set(this,void 0),Wr.set(this,void 0),z.set(this,void 0),jr.set(this,void 0),Br.set(this,void 0),ur.set(this,void 0)}[(Fn=new WeakMap,oe=new WeakMap,Gr=new WeakMap,Y=new WeakMap,Ge=new WeakMap,vt=new WeakMap,Ue=new WeakMap,Wr=new WeakMap,z=new WeakMap,jr=new WeakMap,Br=new WeakMap,ur=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new De;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=re.fromReadableStream(e,this.controller);for await(let o of s)c(this,B,"m",lr).call(this,o);if(s.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new De;return o._run(()=>o._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static createThreadAssistantStream(e,t,r){let s=new De;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let o=new De;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,jr,"f")}currentRun(){return c(this,Br,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,ur,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Gr,"f"))}async finalRun(){if(await this.done(),!c(this,Ge,"f"))throw Error("Final run was not received.");return c(this,Ge,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)c(this,B,"m",lr).call(this,l);if(i.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}async _createAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Vt(o)&&Vt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Vt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}};De=pe,lr=function(e){if(!this.ended)switch(A(this,jr,e,"f"),c(this,B,"m",zs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,B,"m",eo).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,B,"m",Ks).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,B,"m",Vs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},cr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!c(this,Ge,"f"))throw Error("Final run has not been received");return c(this,Ge,"f")},Vs=function(e){let[t,r]=c(this,B,"m",Qs).call(this,e,c(this,Y,"f"));A(this,Y,t,"f"),c(this,Gr,"f")[t.id]=t;for(let s of r){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=c(this,vt,"f")){if(c(this,Ue,"f"))switch(c(this,Ue,"f").type){case"text":this._emit("textDone",c(this,Ue,"f").text,c(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Ue,"f").image_file,c(this,Y,"f"));break}A(this,vt,s.index,"f")}A(this,Ue,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,vt,"f")!==void 0){let s=e.data.content[c(this,vt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Y,"f"));break;case"text":this._emit("textDone",s.text,c(this,Y,"f"));break}}c(this,Y,"f")&&this._emit("messageDone",e.data),A(this,Y,void 0,"f")}},Ks=function(e){let t=c(this,B,"m",Ys).call(this,e);switch(A(this,ur,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,z,"f")&&this._emit("toolCallDone",c(this,z,"f")),A(this,Wr,o.index,"f"),A(this,z,t.step_details.tool_calls[o.index],"f"),c(this,z,"f")&&this._emit("toolCallCreated",c(this,z,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":A(this,ur,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},zs=function(e){c(this,Fn,"f").push(e),this._emit("event",e)},Ys=function(e){switch(e.event){case"thread.run.step.created":return c(this,oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,oe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=De.accumulateDelta(t,r.delta);c(this,oe,"f")[e.data.id]=s}return c(this,oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,oe,"f")[e.data.id]=e.data;break}if(c(this,oe,"f")[e.data.id])return c(this,oe,"f")[e.data.id];throw new Error("No snapshot available")},Qs=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=c(this,B,"m",Zs).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Zs=function(e,t){return De.accumulateDelta(t,e)},eo=function(e){switch(A(this,Br,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":A(this,Ge,e.data,"f"),c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends m{constructor(){super(...arguments),this.steps=new Et(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(h`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(h`/threads/${s}/runs/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(h`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/threads/${e}/runs`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(h`/threads/${s}/runs/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(h`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Et;var xe=class extends m{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new St(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(h`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(h`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends m{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new Pt(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=Pt;ie.Threads=xe;a();var Be=class extends m{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var Tt=class extends m{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(h`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var We=class extends m{constructor(){super(...arguments),this.content=new Tt(this._client)}create(e,t,r){return this._client.post(h`/containers/${e}/files`,K({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(h`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(h`/containers/${e}/files`,R,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(h`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};We.Content=Tt;var Ie=class extends m{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(h`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=We;a();var He=class extends m{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";r&&v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?o:(v(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let u=l.embedding;l.embedding=Xs(u)}),i)))}};a();a();a();var kt=class extends m{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(h`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(h`/evals/${s}/runs/${e}/output_items`,R,{query:o,...r})}};var qe=class extends m{constructor(){super(...arguments),this.outputItems=new kt(this._client)}create(e,t,r){return this._client.post(h`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(h`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(h`/evals/${e}/runs`,R,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(h`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(h`/evals/${s}/runs/${e}`,r)}};qe.OutputItems=kt;var Pe=class extends m{constructor(){super(...arguments),this.runs=new qe(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(h`/evals/${e}`,t)}update(e,t,r){return this._client.post(h`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/evals/${e}`,t)}};Pe.Runs=qe;a();var Je=class extends m{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(h`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/files/${e}`,t)}content(e,t){return this._client.get(h`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ee(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};a();a();var Mt=class extends m{};a();a();var $t=class extends m{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Xe=class extends m{constructor(){super(...arguments),this.graders=new $t(this._client)}};Xe.Graders=$t;a();a();var Nt=class extends m{create(e,t,r){return this._client.getAPIList(h`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(h`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(h`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Ve=class extends m{constructor(){super(...arguments),this.permissions=new Nt(this._client)}};Ve.Permissions=Nt;a();a();var Lt=class extends m{list(e,t={},r){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...r})}};var Ke=class extends m{constructor(){super(...arguments),this.checkpoints=new Lt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(h`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...t})}cancel(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/events`,R,{query:t,...r})}pause(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/resume`,t)}};Ke.Checkpoints=Lt;var Q=class extends m{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ke(this._client),this.checkpoints=new Ve(this._client),this.alpha=new Xe(this._client)}};Q.Methods=Mt;Q.Jobs=Ke;Q.Checkpoints=Ve;Q.Alpha=Xe;a();a();var Ft=class extends m{};var Re=class extends m{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var ze=class extends m{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};a();var Ye=class extends m{retrieve(e,t){return this._client.get(h`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(h`/models/${e}`,t)}};a();var Qe=class extends m{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function to(n,e){return!e||!yi(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Un(n,e)}function Un(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:xi(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Ci(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Hr(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let s of r.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Ci(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function yi(n){return!!sr(n.text?.format)}function wi(n){return n?.$brand==="auto-parseable-tool"}function Ai(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function xi(n,e){let t=Ai(n.tools??[],e.name);return{...e,...e,parsed_arguments:wi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Hr(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}a();var Ut,qr,Oe,Jr,ro,no,so,oo,Xr=class n extends be{constructor(e){super(),Ut.add(this),qr.set(this,void 0),Oe.set(this,void 0),Jr.set(this,void 0),A(this,qr,e,"f")}static createResponse(e,t,r){let s=new n(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,Ut,"m",ro).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)c(this,Ut,"m",no).call(this,l,i);if(o.controller.signal?.aborted)throw new k;return c(this,Ut,"m",so).call(this)}[(qr=new WeakMap,Oe=new WeakMap,Jr=new WeakMap,Ut=new WeakSet,ro=function(){this.ended||A(this,Oe,void 0,"f")},no=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Ut,"m",oo).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new y(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},so=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Oe,"f");if(!t)throw new y("request ended without sending any events");A(this,Oe,void 0,"f");let r=Ii(t,c(this,qr,"f"));return A(this,Jr,r,"f"),r},oo=function(t){let r=c(this,Oe,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=A(this,Oe,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{A(this,Oe,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,Jr,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Ii(n,e){return to(n,e)}a();var Dt=class extends m{list(e,t={},r){return this._client.getAPIList(h`/responses/${e}/input_items`,R,{query:t,...r})}};var Se=class extends m{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Hr(r),r))}retrieve(e,t={},r){return this._client.get(h`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Hr(s),s))}delete(e,t){return this._client.delete(h`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Un(r,e))}stream(e,t){return Xr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(h`/responses/${e}/cancel`,t)}};Se.InputItems=Dt;a();a();var Gt=class extends m{create(e,t,r){return this._client.post(h`/uploads/${e}/parts`,K({body:t,...r},this._client))}};var Ee=class extends m{constructor(){super(...arguments),this.parts=new Gt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(h`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(h`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=Gt;a();a();a();var io=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var jt=class extends m{create(e,t,r){return this._client.post(h`/vector_stores/${e}/file_batches`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(h`/vector_stores/${s}/file_batches/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(h`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...o}=t;return this._client.getAPIList(h`/vector_stores/${s}/file_batches/${e}/files`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=s?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,u=t.values(),d=[...r];async function g(b){for(let f of b){let x=await l.files.create({file:f,purpose:"assistants"},s);d.push(x.id)}}let p=Array(i).fill(u).map(g);return await io(p),await this.createAndPoll(e,{file_ids:d})}};a();var Bt=class extends m{create(e,t,r){return this._client.post(h`/vector_stores/${e}/files`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(h`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...o}=t;return this._client.post(h`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/vector_stores/${e}/files`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(h`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(h`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var de=class extends m{constructor(){super(...arguments),this.files=new Bt(this._client),this.fileBatches=new jt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(h`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(h`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(h`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};de.Files=Bt;de.FileBatches=jt;a();var Wt,ao,Vr,Ze=class extends m{constructor(){super(...arguments),Wt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Wt,"m",ao).call(this,r);let o=_([t]).values,i=c(this,Wt,"m",Vr).call(this,o,"webhook-signature"),l=c(this,Wt,"m",Vr).call(this,o,"webhook-timestamp"),u=c(this,Wt,"m",Vr).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Z("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-d>s)throw new Z("Webhook timestamp is too old");if(d>g+s)throw new Z("Webhook timestamp is too new");let p=i.split(" ").map(C=>C.startsWith("v1,")?C.substring(3):C),b=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let C of p)try{let P=Buffer.from(C,"base64");if(await crypto.subtle.verify("HMAC",x,P,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Wt=new WeakSet,ao=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Vr=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Dn,Gn,Kr,lo,I=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Dn.add(this),Kr.set(this,void 0),this.completions=new Be(this),this.chat=new ye(this),this.embeddings=new He(this),this.files=new Je(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ye(this),this.fineTuning=new Q(this),this.graders=new Re(this),this.vectorStores=new de(this),this.webhooks=new Ze(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Se(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let l={apiKey:t,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&bs())throw new y(`It looks like you're running in a browser-like environment.
|
|
17
|
-
|
|
18
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
19
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
20
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
21
|
-
|
|
22
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
23
|
-
|
|
24
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
25
|
-
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Gn.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=mn(l.logLevel,"ClientOptions.logLevel",this)??mn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ys(),A(this,Kr,As,"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 dn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${nn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Dn,"m",lo).call(this)&&r||this.baseURL,o=cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return fs(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Me(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,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(Xt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Jt(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 me({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 ws(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=>Xt(E).message),S=hs(U),J=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:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,J,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&&ds("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))}:{},...Cs(),"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:wr(e)}:c(this,Kr,"f").call(this,{body:e,headers:r})}};Gn=I,Kr=new WeakMap,Dn=new WeakSet,lo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Gn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=me;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=vr;I.Completions=Be;I.Chat=ye;I.Embeddings=He;I.Files=Je;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ye;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Ze;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function vi(n){return n.toLowerCase().includes("matilda3")}function Ti(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??{}))Qn(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=vi(e.model)?s.messages.map(Ti):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=os(e.model,"output"),s=ss(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 ki=he("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=mr?.endsWith("/")?mr.slice(0,-1):mr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&ki.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??{}))!es(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,Zn(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(),x=b||Object.keys(f).length>0;if(x){p.delete(gr),p.delete(_r);for(let[P,O]of Object.entries(f))p.set(P,O);let C=p.get("x-stainless-retry-count");p.has(gr)&&C!==null&&/^[1-9][0-9]*$/.test(C)&&p.set(_r,"retry")}this.cliConfig.getChannel()===void 0&&ts({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let C=await l(d,x?{...g,headers:p}:g);return rs({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),C}catch(C){throw Cr(C,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),C}}: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 zr(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 Mi(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var et=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Mi;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?Ni(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=$i(i);return zr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function $i(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
|
|
26
|
-
|
|
27
|
-
`);return{...n,content:t}}function Ni(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 tt=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 Li=["api.minimaxi.com","api.minimax.io"],Fi=[".minimaxi.com",".minimax.io"],rt=class extends F{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return Li.includes(t)?!0:Fi.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var co="api.mistral.ai",Ui=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Di(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===co||t.endsWith(`.${co}`)}catch{return!1}}function Gi(n){if(Di(n))return!0;let e=n.model?.toLowerCase()??"";return Ui.some(t=>e.includes(t))}var nt=class extends F{static isMistralProvider=Gi;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(ji)}}};function ji(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Bi(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 st=class extends F{constructor(e,t){super(e,t)}static isMiMoProvider=Bi;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(zr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var Wi=he("STREAMING_TOOL_CALL_PARSER"),Yr=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),Wi.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(){return this.collectCompletedToolCalls({allowJsonRepair:!0})}getStrictCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!1})}collectCompletedToolCalls({allowJsonRepair:e}){let t=[],r=new Set;for(let[s,o]of this.buffers.entries()){let i=this.toolCallMeta.get(s);if(i?.name){let l=this.depths.get(s)||0,u=this.inStrings.get(s)||!1;if(l>0||u)continue;if(i.id){if(r.has(i.id))continue;r.add(i.id)}let d;if(!o.trim())d={};else try{d=JSON.parse(o)}catch{if(!e)continue;let g=Xn(o,null);if(!g||typeof g!="object")continue;d=g}t.push({id:i.id,name:i.name,args:d,index:s})}}return t}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,t]of this.buffers.entries()){let r=this.toolCallMeta.get(e),s=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(s>0||o)return!0;if(!r?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var uo=16e3,fo=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
28
|
-
`,Qr=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?rn(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ve.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?rn(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 Qr(g)}let u=ve.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)}if(!o&&!i){let l=ve.flushOpenAIStreamToGemini(t);l&&(yield l,i=!0)}o&&!i&&(yield o)}catch(l){if(l instanceof Qr)throw Te(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 Jn;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=ve.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 ve.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,fr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
|
|
29
|
-
`):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=uo)return r;let s=uo-fo.length;return`${fo}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let d=r?.[l],g=u?e.config?.[u]:void 0,p=u?t[u]:void 0;return d!==void 0?d:g!==void 0?g:p},o=(l,u,d)=>{let g=s(u,d);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Kn.getStore()?.(i),zn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(Te(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new Yr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new Vn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Hi=he("OPENAI_ERROR"),dr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=Te(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Hi.error("OpenAI API Error:",i),o?new Error(`${i}
|
|
30
|
-
|
|
31
|
-
${this.getTimeoutTroubleshootingTips()}`):s}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e?.code,s=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||r==="ETIMEDOUT"||r==="ESOCKETTIMEDOUT"||s==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,r){let s=Math.round((Date.now()-t.startTime)/1e3);return r?`Request timeout after ${s}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
32
|
-
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
33
|
-
`)}`}};var po=he("OPENAI"),ot=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(qn(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new ls().calculateTokens(e)).totalTokens}}catch(t){po.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=Te(r);throw po.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var hr=class extends ot{contentGeneratorConfig;cliConfig;channel;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return Zr(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let r=()=>super.generateContentStream(e,t),s=await this.withTokenRefresh(r);return this.iterateWithAuthRetry(s,r)}async*iterateWithAuthRetry(e,t){let r=!1;try{for await(let s of e)r||=(s.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield s;return}catch(s){if(!Zr(s))throw s;if(r)throw new tn("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw ho(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await as({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(r){throw Cr(r,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),r}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[is]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!Zr(t))throw t;await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(r){throw ho(r)}}}};function ho(n){return Zr(n)?new tn("Matilda session expired and could not be refreshed. Run /auth to reconnect."):n}function Zr(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=Number(t.status??t.statusCode??t.code);return r>=400&&r<600?r===401||r===403:e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function g_(n,e){let t=qi(n,e);return ae.isMatildaCompatibleProvider(n)?new hr(n,e,t):new ot(n,e,t)}function qi(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):et.isDeepSeekProvider(t)?new et(n,e):st.isMiMoProvider(t)?new st(n,e):tt.isOpenRouterProvider(t)?new tt(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):rt.isMiniMaxProvider(t)?new rt(n,e):nt.isMistralProvider(t)?new nt(n,e):new F(n,e)}export{ae as a,et as b,tt as c,rt as d,nt as e,st as f,pr as g,dr as h,ot as i,hr as j,g_ as k,qi as l};
|
|
34
|
-
/**
|
|
35
|
-
* @license
|
|
36
|
-
* Copyright 2025 Matilda
|
|
37
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
38
|
-
*/
|
|
39
|
-
/**
|
|
40
|
-
* @license
|
|
41
|
-
* Copyright 2026 Maincode
|
|
42
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
43
|
-
*
|
|
44
|
-
* OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
|
|
45
|
-
*
|
|
46
|
-
* Emulates Grok Build's automatic credential refresh
|
|
47
|
-
* (docs: "Automatic Credential Refresh"):
|
|
48
|
-
* 1. Before each request: ensure a fresh access token (re-read disk; refresh
|
|
49
|
-
* when within the early-invalidation window / already expired).
|
|
50
|
-
* 2. On 401 Unauthorized: force-refresh and retry the request once.
|
|
51
|
-
* 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
|
|
52
|
-
*
|
|
53
|
-
* Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
|
|
54
|
-
* createContentGenerator time, so idle sessions past access-token expiry
|
|
55
|
-
* failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
|
|
56
|
-
*/
|
package/chunks/chunk-FW6Z25AA.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as g}from"./chunk-TISQNFB5.js";import{c as p}from"./chunk-SWEYYDZO.js";import{E as f,M as d,Z as m}from"./chunk-5QAKUC2D.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=m("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new g,h.set(e,t)),t}function c(e){return s.join(d.getGlobalTempDir(),f(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await p(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
|
package/chunks/chunk-L5ASITMV.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Z as f}from"./chunk-5QAKUC2D.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"<").replace(/>/g,">")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
|
|
4
|
-
${this.stopReason}`}},m=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"decision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.decision;if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}}isPermissionDenied(){return this.getPermissionDecision()?.behavior==="deny"}getDenyMessage(){return this.getPermissionDecision()?.message}shouldInterrupt(){return this.getPermissionDecision()?.interrupt===!0}getUpdatedToolInput(){return this.getPermissionDecision()?.updatedInput}getUpdatedPermissions(){return this.getPermissionDecision()?.updatedPermissions}},b=(n=>(n.PermissionPrompt="permission_prompt",n.IdlePrompt="idle_prompt",n.AuthSuccess="auth_success",n.ElicitationDialog="elicitation_dialog",n))(b||{}),H=(t=>(t.Startup="startup",t.Resume="resume",t.Clear="clear",t.Compact="compact",t.Branch="branch",t))(H||{}),I=(t=>(t.Default="default",t.Plan="plan",t.AutoEdit="auto_edit",t.Auto="auto",t.Bogan="bogan",t))(I||{}),T=(t=>(t.Clear="clear",t.Logout="logout",t.PromptInputExit="prompt_input_exit",t.Bypass_permissions_disabled="bypass_permissions_disabled",t.Other="other",t))(T||{}),y=(s=>(s.Manual="manual",s.Auto="auto",s))(y||{}),R=(s=>(s.Manual="manual",s.Auto="auto",s))(R||{}),w=(n=>(n.Bash="Bash",n.Explorer="Explorer",n.Plan="Plan",n.Custom="Custom",n))(w||{});function A(o,e){let s=new Map(o.map(n=>[n.id,n])),u={created:[],completed:[]};for(let n of e){let t=s.get(n.id);t?t.status!=="completed"&&n.status==="completed"&&u.completed.push(n):u.created.push(n)}return u}export{h as a,_ as b,P as c,E as d,S as e,v as f,O as g,C as h,U as i,r as j,p as k,a as l,c as m,d as n,l as o,g as p,m as q,b as r,H as s,I as t,T as u,y as v,R as w,w as x,A as y};
|
|
5
|
-
/**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2026 Matilda Team
|
|
8
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
9
|
-
*/
|
package/chunks/chunk-MW3LAIJW.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Z as d}from"./chunk-5QAKUC2D.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Google LLC
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|