@maincode-ai/matilda-code 0.21.11-nightly.20261020.022e2cc37 → 0.21.11-preview.0
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-BU623AHW.js +3 -0
- package/chunks/agent-headless-T24DLERB.js +3 -0
- package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js} +1 -1
- package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-2QI4NSFJ.js} +1 -1
- package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
- package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
- package/chunks/{chunk-2HQMJ2IU.js → chunk-2MOGYHWM.js} +1 -1
- package/chunks/{chunk-7R2762AQ.js → chunk-3WBC3IIX.js} +546 -544
- package/chunks/{chunk-T4P4KEDW.js → chunk-6E766NPX.js} +1 -1
- package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
- package/chunks/{chunk-BBFEZFSW.js → chunk-6RCVKDFR.js} +1 -1
- package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
- package/chunks/{chunk-FMT6S22S.js → chunk-AQQOBDEP.js} +11 -11
- package/chunks/{chunk-SNLH42QJ.js → chunk-CZGZ3KK7.js} +1 -1
- package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
- package/chunks/{chunk-XCFLI3OC.js → chunk-ET7ZXQ3A.js} +1 -1
- package/chunks/{chunk-QXOH5UM2.js → chunk-F62NM4KX.js} +1 -1
- package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
- package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
- package/chunks/{chunk-QGU4TQKH.js → chunk-I5H6ZXLS.js} +10 -10
- package/chunks/{chunk-25NCTG5H.js → chunk-JA43M5MZ.js} +53 -51
- package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
- package/chunks/{chunk-QYVJEL6C.js → chunk-KLWMEGO4.js} +1 -1
- package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
- package/chunks/{chunk-5427BPR2.js → chunk-MCQUPLRE.js} +1 -1
- package/chunks/{chunk-QN6WSWMM.js → chunk-MO2HXJG5.js} +1 -1
- package/chunks/{chunk-MP6D7B5B.js → chunk-P3G4HEXP.js} +2 -2
- package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
- package/chunks/{chunk-Y7O6DI35.js → chunk-PW3LFA6D.js} +1 -1
- package/chunks/{chunk-W5CGKUM4.js → chunk-S3CWEVTS.js} +1 -1
- package/chunks/{chunk-YMIF2DMT.js → chunk-VTGICC67.js} +1 -1
- package/chunks/{chunk-SPW5DXX4.js → chunk-WV3IUPZS.js} +1 -1
- package/chunks/chunk-WXCEBLRE.js +56 -0
- package/chunks/{chunk-WHG6N5X2.js → chunk-YRQP3SLC.js} +1 -1
- package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
- package/chunks/chunk-ZYCVL46M.js +27 -0
- package/chunks/{computer-use-HDAHXM46.js → computer-use-2UBC2SKZ.js} +1 -1
- package/chunks/contextCommand-CRHIC6JS.js +3 -0
- package/chunks/{cron-create-2UI4AT4Q.js → cron-create-FMTLQJXE.js} +1 -1
- package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-LWKY3QSE.js} +1 -1
- package/chunks/{cron-list-YYAXNHB6.js → cron-list-DJTIFK2L.js} +1 -1
- package/chunks/edit-MR52FAWW.js +43 -0
- package/chunks/{enter-worktree-YI7BKDPH.js → enter-worktree-HFTCLHRB.js} +1 -1
- package/chunks/{enterPlanMode-SZ3D3XRT.js → enterPlanMode-R54IR74J.js} +1 -1
- package/chunks/{exit-worktree-L6OTJIBF.js → exit-worktree-NK6IMLGE.js} +1 -1
- package/chunks/{exitPlanMode-PSXDKAXV.js → exitPlanMode-X2M6ZV3X.js} +1 -1
- package/chunks/{geminiContentGenerator-UWXILFM2.js → geminiContentGenerator-KKK5RWAE.js} +1 -1
- package/chunks/{glob-5DANZVAI.js → glob-RKSORKHR.js} +1 -1
- package/chunks/{goal-tools-AIYULJ6L.js → goal-tools-RSICRXWC.js} +1 -1
- package/chunks/{grep-B4KG4R5T.js → grep-7O4QFORW.js} +1 -1
- package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
- package/chunks/{ls-YWZU3FYL.js → ls-JYJXFSXN.js} +1 -1
- package/chunks/{lsp-4CJDKEEC.js → lsp-DYDK6XCS.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-EC6EONBZ.js → matildaAgentContentGenerator-JRJ35MC7.js} +1 -1
- package/chunks/{matildaContentGenerator-TGMDURRB.js → matildaContentGenerator-3EXH3FBK.js} +1 -1
- package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-XE7AHBSI.js} +1 -1
- package/chunks/{monitor-D7TU3DUW.js → monitor-7O2YTGFR.js} +1 -1
- package/chunks/{notebook-edit-V5XE473Y.js → notebook-edit-6SCNZBO3.js} +1 -1
- package/chunks/{openaiContentGenerator-PYFTHLLU.js → openaiContentGenerator-5SBB3YKW.js} +1 -1
- package/chunks/read-file-DZTYS4MO.js +3 -0
- package/chunks/ripGrep-LVBZPZPH.js +3 -0
- package/chunks/{scheduler-B54AG3CC.js → scheduler-NPTZJ56A.js} +1 -1
- package/chunks/{send-message-OO2HAKCC.js → send-message-P3SMWNEE.js} +1 -1
- package/chunks/{serve-YRXZONLX.js → serve-3VNHJIGD.js} +1 -1
- package/chunks/shell-SXPNBWTX.js +3 -0
- package/chunks/{skill-6JH5WZFP.js → skill-OQVVXONF.js} +1 -1
- package/chunks/src-PJF3I6FQ.js +3 -0
- package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-EAIZPWN7.js} +1 -1
- package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-432LXITX.js} +1 -1
- package/chunks/task-create-Z3QRCMX4.js +3 -0
- package/chunks/{task-detach-I67ZE5MX.js → task-detach-XMSJ3HBM.js} +1 -1
- package/chunks/{task-list-5BGX4G5N.js → task-list-MNHMRJN3.js} +1 -1
- package/chunks/{task-stop-ERI5X4AO.js → task-stop-NTS62FLG.js} +1 -1
- package/chunks/{task-update-CD3W556L.js → task-update-DA5K2V7E.js} +1 -1
- package/chunks/{team-create-RBYPBWMT.js → team-create-AATX26NE.js} +1 -1
- package/chunks/{team-delete-5U3GBFKJ.js → team-delete-RRYZ6KMB.js} +1 -1
- package/chunks/todoWrite-Y6RP55AO.js +3 -0
- package/chunks/{tool-search-JFCD5W5M.js → tool-search-EZAYWDKE.js} +1 -1
- package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-ZTPXSREL.js} +1 -1
- package/chunks/{web-search-OX2DPEVN.js → web-search-XQUIZARL.js} +1 -1
- package/chunks/{workflow-AVVQMK4O.js → workflow-J6YT6B4V.js} +2 -2
- package/chunks/{write-file-CCYKY44V.js → write-file-MO5WWZWG.js} +1 -1
- package/cli.js +396 -390
- package/package.json +2 -2
- package/chunks/agent-5PW6CQEM.js +0 -3
- package/chunks/agent-headless-PMTZCOCR.js +0 -3
- package/chunks/chunk-GV25S54K.js +0 -54
- package/chunks/chunk-HWOQNYAO.js +0 -27
- package/chunks/contextCommand-ZZLLOKVS.js +0 -3
- package/chunks/edit-DOPUXY2Q.js +0 -39
- package/chunks/read-file-6EAPS2KG.js +0 -3
- package/chunks/ripGrep-FOKCJ3KE.js +0 -3
- package/chunks/shell-NG54W6TS.js +0 -3
- package/chunks/src-5ZUUXCSI.js +0 -3
- package/chunks/task-create-EBJD55TB.js +0 -3
- package/chunks/todoWrite-2RIXEZK7.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{pg as a,qg as b,rg as c,sg as d,tg as e,ug as f}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{Pf as a,Qf as b,Rf as c}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.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/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as xr,b as Tr}from"./chunk-QN6Y6NPA.js";import{a as M,b as rt,c as Se,d as Pn}from"./chunk-4Q2SNBUH.js";import{a as En}from"./chunk-ODZOYHIC.js";import{c as An,f as we}from"./chunk-GUFIMKF5.js";import{b as _n,c as wn,d as Sn,g as nt,o as Cn,t as xn,v as Tn}from"./chunk-SUH3UUWZ.js";import{b as ee,e as tt}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as kn}from"./chunk-SDTWBD62.js";import{ba as bn}from"./chunk-MH2P4YXC.js";import{a as Cr}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";import{a as et,d as _e,f as jt}from"./chunk-OWGSC52X.js";var jn=_e((oo,Ln)=>{"use strict";c();var Or=et("util"),Br=Cr();Ln.exports=function(r){if(typeof r=="number")return r;var e=Br(r);if(e===void 0){var t=new Error(Or.format("humanize-ms(%j) result undefined",r));console.warn(t.stack)}return e}});var ct=_e((ao,qn)=>{"use strict";c();qn.exports={CURRENT_ID:Symbol("agentkeepalive#currentId"),CREATE_ID:Symbol("agentkeepalive#createId"),INIT_SOCKET:Symbol("agentkeepalive#initSocket"),CREATE_HTTPS_CONNECTION:Symbol("agentkeepalive#createHttpsConnection"),SOCKET_CREATED_TIME:Symbol("agentkeepalive#socketCreatedTime"),SOCKET_NAME:Symbol("agentkeepalive#socketName"),SOCKET_REQUEST_COUNT:Symbol("agentkeepalive#socketRequestCount"),SOCKET_REQUEST_FINISHED_COUNT:Symbol("agentkeepalive#socketRequestFinishedCount")}});var Kt=_e((uo,$n)=>{"use strict";c();var Lr=et("http").Agent,$t=jn(),P=et("util").debuglog("agentkeepalive"),{INIT_SOCKET:Dn,CURRENT_ID:ut,CREATE_ID:Nn,SOCKET_CREATED_TIME:Un,SOCKET_NAME:R,SOCKET_REQUEST_COUNT:v,SOCKET_REQUEST_FINISHED_COUNT:j}=ct(),Ht=1,Gt=parseInt(process.version.split(".",1)[0].substring(1));Gt>=11&&Gt<=12?Ht=2:Gt>=13&&(Ht=3);function ke(r){console.log("[agentkeepalive:deprecated] %s",r)}var Jt=class extends Lr{constructor(e){e=e||{},e.keepAlive=e.keepAlive!==!1,e.freeSocketTimeout===void 0&&(e.freeSocketTimeout=4e3),e.keepAliveTimeout&&(ke("options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.keepAliveTimeout,delete e.keepAliveTimeout),e.freeSocketKeepAliveTimeout&&(ke("options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.freeSocketKeepAliveTimeout,delete e.freeSocketKeepAliveTimeout),e.timeout===void 0&&(e.timeout=Math.max(e.freeSocketTimeout*2,8e3)),e.timeout=$t(e.timeout),e.freeSocketTimeout=$t(e.freeSocketTimeout),e.socketActiveTTL=e.socketActiveTTL?$t(e.socketActiveTTL):0,super(e),this[ut]=0,this.createSocketCount=0,this.createSocketCountLastCheck=0,this.createSocketErrorCount=0,this.createSocketErrorCountLastCheck=0,this.closeSocketCount=0,this.closeSocketCountLastCheck=0,this.errorSocketCount=0,this.errorSocketCountLastCheck=0,this.requestCount=0,this.requestCountLastCheck=0,this.timeoutSocketCount=0,this.timeoutSocketCountLastCheck=0,this.on("free",t=>{let n=this.calcSocketTimeout(t);n>0&&t.timeout!==n&&t.setTimeout(n)})}get freeSocketKeepAliveTimeout(){return ke("agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead"),this.options.freeSocketTimeout}get timeout(){return ke("agent.timeout is deprecated, please use agent.options.timeout instead"),this.options.timeout}get socketActiveTTL(){return ke("agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead"),this.options.socketActiveTTL}calcSocketTimeout(e){let t=this.options.freeSocketTimeout,n=this.options.socketActiveTTL;if(n){let s=Date.now()-e[Un],o=n-s;if(o<=0)return o;t&&o<t&&(t=o)}if(t)return e.freeSocketTimeout||e.freeSocketKeepAliveTimeout||t}keepSocketAlive(e){let t=super.keepSocketAlive(e);if(!t)return t;let n=this.calcSocketTimeout(e);return typeof n>"u"?!0:n<=0?(P("%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s",e[R],e[v],e[j],n),!1):(e.timeout!==n&&e.setTimeout(n),!0)}reuseSocket(...e){super.reuseSocket(...e);let t=e[0],n=e[1];n.reusedSocket=!0;let s=this.options.timeout;Ce(t)!==s&&(t.setTimeout(s),P("%s reset timeout to %sms",t[R],s)),t[v]++,P("%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms",t[R],t[v],t[j],Ce(t))}[Nn](){let e=this[ut]++;return this[ut]===Number.MAX_SAFE_INTEGER&&(this[ut]=0),e}[Dn](e,t){t.timeout&&(Ce(e)||e.setTimeout(t.timeout)),this.options.keepAlive&&e.setNoDelay(!0),this.createSocketCount++,this.options.socketActiveTTL&&(e[Un]=Date.now()),e[R]=`sock[${this[Nn]()}#${t._agentKey}]`.split("-----BEGIN",1)[0],e[v]=1,e[j]=0,jr(this,e,t)}createConnection(e,t){let n=!1,s=(i,a)=>{if(!n){if(n=!0,i)return this.createSocketErrorCount++,t(i);this[Dn](a,e),t(i,a)}},o=super.createConnection(e,s);return o&&s(null,o),o}get statusChanged(){let e=this.createSocketCount!==this.createSocketCountLastCheck||this.createSocketErrorCount!==this.createSocketErrorCountLastCheck||this.closeSocketCount!==this.closeSocketCountLastCheck||this.errorSocketCount!==this.errorSocketCountLastCheck||this.timeoutSocketCount!==this.timeoutSocketCountLastCheck||this.requestCount!==this.requestCountLastCheck;return e&&(this.createSocketCountLastCheck=this.createSocketCount,this.createSocketErrorCountLastCheck=this.createSocketErrorCount,this.closeSocketCountLastCheck=this.closeSocketCount,this.errorSocketCountLastCheck=this.errorSocketCount,this.timeoutSocketCountLastCheck=this.timeoutSocketCount,this.requestCountLastCheck=this.requestCount),e}getCurrentStatus(){return{createSocketCount:this.createSocketCount,createSocketErrorCount:this.createSocketErrorCount,closeSocketCount:this.closeSocketCount,errorSocketCount:this.errorSocketCount,timeoutSocketCount:this.timeoutSocketCount,requestCount:this.requestCount,freeSockets:Wt(this.freeSockets),sockets:Wt(this.sockets),requests:Wt(this.requests)}}};function Ce(r){return r.timeout||r._idleTimeout}function jr(r,e,t){P("%s create, timeout %sms",e[R],Ce(e));function n(){if(!e._httpMessage&&e[v]===1)return;e[j]++,r.requestCount++,P("%s(requests: %s, finished: %s) free",e[R],e[v],e[j]);let u=r.getName(t);e.writable&&r.requests[u]&&r.requests[u].length&&(e[v]++,P("%s(requests: %s, finished: %s) will be reuse on agent free event",e[R],e[v],e[j]))}e.on("free",n);function s(u){P("%s(requests: %s, finished: %s) close, isError: %s",e[R],e[v],e[j],u),r.closeSocketCount++}e.on("close",s);function o(){let u=e.listeners("timeout").length,l=Ce(e),y=e._httpMessage,g=y&&y.listeners("timeout").length||0;P("%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s",e[R],e[v],e[j],l,u,Ht,!!y,g),P.enabled&&P("timeout listeners: %s",e.listeners("timeout").map(_=>_.name).join(", ")),r.timeoutSocketCount++;let h=r.getName(t);if(r.freeSockets[h]&&r.freeSockets[h].indexOf(e)!==-1)e.destroy(),r.removeSocket(e,t),P("%s is free, destroy quietly",e[R]);else if(g===0){let _=new Error("Socket timeout");_.code="ERR_SOCKET_TIMEOUT",_.timeout=l,e.destroy(_),r.removeSocket(e,t),P("%s destroy with timeout error",e[R])}}e.on("timeout",o);function i(u){let l=e.listeners("error").length;P("%s(requests: %s, finished: %s) error: %s, listenerCount: %s",e[R],e[v],e[j],u,l),r.errorSocketCount++,l===1&&(P("%s emit uncaught error event",e[R]),e.removeListener("error",i),e.emit("error",u))}e.on("error",i);function a(){P("%s(requests: %s, finished: %s) agentRemove",e[R],e[v],e[j]),e.removeListener("close",s),e.removeListener("error",i),e.removeListener("free",n),e.removeListener("timeout",o),e.removeListener("agentRemove",a)}e.on("agentRemove",a)}$n.exports=Jt;function Wt(r){let e={};for(let t in r)e[t]=r[t].length;return e}});var Hn=_e((fo,Wn)=>{"use strict";c();var Xt=et("https").Agent,qr=Kt(),{INIT_SOCKET:Dr,CREATE_HTTPS_CONNECTION:Gn}=ct(),xe=class extends qr{constructor(e){super(e),this.defaultPort=443,this.protocol="https:",this.maxCachedSessions=this.options.maxCachedSessions,this.maxCachedSessions===void 0&&(this.maxCachedSessions=100),this._sessionCache={map:{},list:[]}}createConnection(e,t){let n=this[Gn](e,t);return this[Dr](n,e),n}};xe.prototype[Gn]=Xt.prototype.createConnection;["getName","_getSession","_cacheSession","_evictSession"].forEach(function(r){typeof Xt.prototype[r]=="function"&&(xe.prototype[r]=Xt.prototype[r])});Wn.exports=xe});var Kn=_e((po,Te)=>{"use strict";c();var Jn=Kt();Te.exports=Jn;Te.exports.HttpAgent=Jn;Te.exports.HttpsAgent=Hn();Te.exports.constants=ct()});c();c();c();c();c();var te="0.36.3";c();c();c();var Rn=!1,ne,qt,Ar,Er,Pr,Mn,Rr,st,Dt,vn,Nt,ot,In;function Fn(r,e={auto:!1}){if(Rn)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(ne)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${ne}'\``);Rn=e.auto,ne=r.kind,qt=r.fetch,Ar=r.Request,Er=r.Response,Pr=r.Headers,Mn=r.FormData,Rr=r.Blob,st=r.File,Dt=r.ReadableStream,vn=r.getMultipartRequestOptions,Nt=r.getDefaultAgent,ot=r.fileFromPath,In=r.isFsReadStream}c();var X=jt(xr(),1);c();c();import{inspect as Ir}from"util";c();var On=r=>r instanceof rt;c();import{deprecate as vr}from"util";var Bn=vr(()=>{},'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');var B=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},it,L,Ut,at=class{constructor(e){it.add(this),L.set(this,new Map),e&&(Bn(),e.forEach(({name:t,value:n,fileName:s})=>this.append(t,n,s)))}static[(L=new WeakMap,it=new WeakSet,Symbol.hasInstance)](e){return!!(e&&M(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&M(e.append)&&M(e.set)&&M(e.get)&&M(e.getAll)&&M(e.has)&&M(e.delete)&&M(e.entries)&&M(e.values)&&M(e.keys)&&M(e[Symbol.iterator])&&M(e.forEach))}append(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!0,rawValue:t,argsLength:arguments.length})}set(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!1,rawValue:t,argsLength:arguments.length})}get(e){let t=B(this,L,"f").get(String(e));return t?t[0]:null}getAll(e){let t=B(this,L,"f").get(String(e));return t?t.slice():[]}has(e){return B(this,L,"f").has(String(e))}delete(e){B(this,L,"f").delete(String(e))}*keys(){for(let e of B(this,L,"f").keys())yield e}*entries(){for(let e of this.keys()){let t=this.getAll(e);for(let n of t)yield[e,n]}}*values(){for(let[,e]of this)yield e}[(Ut=function({name:t,rawValue:n,append:s,fileName:o,argsLength:i}){let a=s?"append":"set";if(i<2)throw new TypeError(`Failed to execute '${a}' on 'FormData': 2 arguments required, but only ${i} present.`);t=String(t);let u;if(Pn(n))u=o===void 0?n:new Se([n],o,{type:n.type,lastModified:n.lastModified});else if(On(n))u=new Se([n],o===void 0?"blob":o,{type:n.type});else{if(o)throw new TypeError(`Failed to execute '${a}' on 'FormData': parameter 2 is not of type 'Blob'.`);u=String(n)}let l=B(this,L,"f").get(t);if(!l)return void B(this,L,"f").set(t,[u]);if(!s)return void B(this,L,"f").set(t,[u]);l.push(u)},Symbol.iterator)](){return this.entries()}forEach(e,t){for(let[n,s]of this)e.call(t,s,n,this)}get[Symbol.toStringTag](){return"FormData"}[Ir.custom](){return this[Symbol.toStringTag]}};var Zt=jt(Kn(),1),Yn=jt(Tr(),1);import{ReadStream as Kr}from"node:fs";c();c();c();var Xn="abcdefghijklmnopqrstuvwxyz0123456789";function Nr(){let r=16,e="";for(;r--;)e+=Xn[Math.random()*Xn.length<<0];return e}var zn=Nr;c();var Ur=r=>Object.prototype.toString.call(r).slice(8,-1).toLowerCase();function $r(r){if(Ur(r)!=="object")return!1;let e=Object.getPrototypeOf(r);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}var zt=$r;c();var Gr=r=>String(r).replace(/\r|\n/g,(e,t,n)=>e==="\r"&&n[t+1]!==`
|
|
3
|
+
import{a as xr,b as Tr}from"./chunk-QN6Y6NPA.js";import{a as M,b as rt,c as Se,d as Pn}from"./chunk-4Q2SNBUH.js";import{a as En}from"./chunk-GOJCMVJJ.js";import{c as An,f as we}from"./chunk-YV3PUOBU.js";import{b as _n,c as wn,d as Sn,g as nt,o as Cn,t as xn,v as Tn}from"./chunk-JCE3JAVC.js";import{b as ee,e as tt}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as kn}from"./chunk-SDTWBD62.js";import{ba as bn}from"./chunk-27Q5KW3A.js";import{a as Cr}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";import{a as et,d as _e,f as jt}from"./chunk-OWGSC52X.js";var jn=_e((oo,Ln)=>{"use strict";c();var Or=et("util"),Br=Cr();Ln.exports=function(r){if(typeof r=="number")return r;var e=Br(r);if(e===void 0){var t=new Error(Or.format("humanize-ms(%j) result undefined",r));console.warn(t.stack)}return e}});var ct=_e((ao,qn)=>{"use strict";c();qn.exports={CURRENT_ID:Symbol("agentkeepalive#currentId"),CREATE_ID:Symbol("agentkeepalive#createId"),INIT_SOCKET:Symbol("agentkeepalive#initSocket"),CREATE_HTTPS_CONNECTION:Symbol("agentkeepalive#createHttpsConnection"),SOCKET_CREATED_TIME:Symbol("agentkeepalive#socketCreatedTime"),SOCKET_NAME:Symbol("agentkeepalive#socketName"),SOCKET_REQUEST_COUNT:Symbol("agentkeepalive#socketRequestCount"),SOCKET_REQUEST_FINISHED_COUNT:Symbol("agentkeepalive#socketRequestFinishedCount")}});var Kt=_e((uo,$n)=>{"use strict";c();var Lr=et("http").Agent,$t=jn(),P=et("util").debuglog("agentkeepalive"),{INIT_SOCKET:Dn,CURRENT_ID:ut,CREATE_ID:Nn,SOCKET_CREATED_TIME:Un,SOCKET_NAME:R,SOCKET_REQUEST_COUNT:v,SOCKET_REQUEST_FINISHED_COUNT:j}=ct(),Ht=1,Gt=parseInt(process.version.split(".",1)[0].substring(1));Gt>=11&&Gt<=12?Ht=2:Gt>=13&&(Ht=3);function ke(r){console.log("[agentkeepalive:deprecated] %s",r)}var Jt=class extends Lr{constructor(e){e=e||{},e.keepAlive=e.keepAlive!==!1,e.freeSocketTimeout===void 0&&(e.freeSocketTimeout=4e3),e.keepAliveTimeout&&(ke("options.keepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.keepAliveTimeout,delete e.keepAliveTimeout),e.freeSocketKeepAliveTimeout&&(ke("options.freeSocketKeepAliveTimeout is deprecated, please use options.freeSocketTimeout instead"),e.freeSocketTimeout=e.freeSocketKeepAliveTimeout,delete e.freeSocketKeepAliveTimeout),e.timeout===void 0&&(e.timeout=Math.max(e.freeSocketTimeout*2,8e3)),e.timeout=$t(e.timeout),e.freeSocketTimeout=$t(e.freeSocketTimeout),e.socketActiveTTL=e.socketActiveTTL?$t(e.socketActiveTTL):0,super(e),this[ut]=0,this.createSocketCount=0,this.createSocketCountLastCheck=0,this.createSocketErrorCount=0,this.createSocketErrorCountLastCheck=0,this.closeSocketCount=0,this.closeSocketCountLastCheck=0,this.errorSocketCount=0,this.errorSocketCountLastCheck=0,this.requestCount=0,this.requestCountLastCheck=0,this.timeoutSocketCount=0,this.timeoutSocketCountLastCheck=0,this.on("free",t=>{let n=this.calcSocketTimeout(t);n>0&&t.timeout!==n&&t.setTimeout(n)})}get freeSocketKeepAliveTimeout(){return ke("agent.freeSocketKeepAliveTimeout is deprecated, please use agent.options.freeSocketTimeout instead"),this.options.freeSocketTimeout}get timeout(){return ke("agent.timeout is deprecated, please use agent.options.timeout instead"),this.options.timeout}get socketActiveTTL(){return ke("agent.socketActiveTTL is deprecated, please use agent.options.socketActiveTTL instead"),this.options.socketActiveTTL}calcSocketTimeout(e){let t=this.options.freeSocketTimeout,n=this.options.socketActiveTTL;if(n){let s=Date.now()-e[Un],o=n-s;if(o<=0)return o;t&&o<t&&(t=o)}if(t)return e.freeSocketTimeout||e.freeSocketKeepAliveTimeout||t}keepSocketAlive(e){let t=super.keepSocketAlive(e);if(!t)return t;let n=this.calcSocketTimeout(e);return typeof n>"u"?!0:n<=0?(P("%s(requests: %s, finished: %s) free but need to destroy by TTL, request count %s, diff is %s",e[R],e[v],e[j],n),!1):(e.timeout!==n&&e.setTimeout(n),!0)}reuseSocket(...e){super.reuseSocket(...e);let t=e[0],n=e[1];n.reusedSocket=!0;let s=this.options.timeout;Ce(t)!==s&&(t.setTimeout(s),P("%s reset timeout to %sms",t[R],s)),t[v]++,P("%s(requests: %s, finished: %s) reuse on addRequest, timeout %sms",t[R],t[v],t[j],Ce(t))}[Nn](){let e=this[ut]++;return this[ut]===Number.MAX_SAFE_INTEGER&&(this[ut]=0),e}[Dn](e,t){t.timeout&&(Ce(e)||e.setTimeout(t.timeout)),this.options.keepAlive&&e.setNoDelay(!0),this.createSocketCount++,this.options.socketActiveTTL&&(e[Un]=Date.now()),e[R]=`sock[${this[Nn]()}#${t._agentKey}]`.split("-----BEGIN",1)[0],e[v]=1,e[j]=0,jr(this,e,t)}createConnection(e,t){let n=!1,s=(i,a)=>{if(!n){if(n=!0,i)return this.createSocketErrorCount++,t(i);this[Dn](a,e),t(i,a)}},o=super.createConnection(e,s);return o&&s(null,o),o}get statusChanged(){let e=this.createSocketCount!==this.createSocketCountLastCheck||this.createSocketErrorCount!==this.createSocketErrorCountLastCheck||this.closeSocketCount!==this.closeSocketCountLastCheck||this.errorSocketCount!==this.errorSocketCountLastCheck||this.timeoutSocketCount!==this.timeoutSocketCountLastCheck||this.requestCount!==this.requestCountLastCheck;return e&&(this.createSocketCountLastCheck=this.createSocketCount,this.createSocketErrorCountLastCheck=this.createSocketErrorCount,this.closeSocketCountLastCheck=this.closeSocketCount,this.errorSocketCountLastCheck=this.errorSocketCount,this.timeoutSocketCountLastCheck=this.timeoutSocketCount,this.requestCountLastCheck=this.requestCount),e}getCurrentStatus(){return{createSocketCount:this.createSocketCount,createSocketErrorCount:this.createSocketErrorCount,closeSocketCount:this.closeSocketCount,errorSocketCount:this.errorSocketCount,timeoutSocketCount:this.timeoutSocketCount,requestCount:this.requestCount,freeSockets:Wt(this.freeSockets),sockets:Wt(this.sockets),requests:Wt(this.requests)}}};function Ce(r){return r.timeout||r._idleTimeout}function jr(r,e,t){P("%s create, timeout %sms",e[R],Ce(e));function n(){if(!e._httpMessage&&e[v]===1)return;e[j]++,r.requestCount++,P("%s(requests: %s, finished: %s) free",e[R],e[v],e[j]);let u=r.getName(t);e.writable&&r.requests[u]&&r.requests[u].length&&(e[v]++,P("%s(requests: %s, finished: %s) will be reuse on agent free event",e[R],e[v],e[j]))}e.on("free",n);function s(u){P("%s(requests: %s, finished: %s) close, isError: %s",e[R],e[v],e[j],u),r.closeSocketCount++}e.on("close",s);function o(){let u=e.listeners("timeout").length,l=Ce(e),y=e._httpMessage,g=y&&y.listeners("timeout").length||0;P("%s(requests: %s, finished: %s) timeout after %sms, listeners %s, defaultTimeoutListenerCount %s, hasHttpRequest %s, HttpRequest timeoutListenerCount %s",e[R],e[v],e[j],l,u,Ht,!!y,g),P.enabled&&P("timeout listeners: %s",e.listeners("timeout").map(_=>_.name).join(", ")),r.timeoutSocketCount++;let h=r.getName(t);if(r.freeSockets[h]&&r.freeSockets[h].indexOf(e)!==-1)e.destroy(),r.removeSocket(e,t),P("%s is free, destroy quietly",e[R]);else if(g===0){let _=new Error("Socket timeout");_.code="ERR_SOCKET_TIMEOUT",_.timeout=l,e.destroy(_),r.removeSocket(e,t),P("%s destroy with timeout error",e[R])}}e.on("timeout",o);function i(u){let l=e.listeners("error").length;P("%s(requests: %s, finished: %s) error: %s, listenerCount: %s",e[R],e[v],e[j],u,l),r.errorSocketCount++,l===1&&(P("%s emit uncaught error event",e[R]),e.removeListener("error",i),e.emit("error",u))}e.on("error",i);function a(){P("%s(requests: %s, finished: %s) agentRemove",e[R],e[v],e[j]),e.removeListener("close",s),e.removeListener("error",i),e.removeListener("free",n),e.removeListener("timeout",o),e.removeListener("agentRemove",a)}e.on("agentRemove",a)}$n.exports=Jt;function Wt(r){let e={};for(let t in r)e[t]=r[t].length;return e}});var Hn=_e((fo,Wn)=>{"use strict";c();var Xt=et("https").Agent,qr=Kt(),{INIT_SOCKET:Dr,CREATE_HTTPS_CONNECTION:Gn}=ct(),xe=class extends qr{constructor(e){super(e),this.defaultPort=443,this.protocol="https:",this.maxCachedSessions=this.options.maxCachedSessions,this.maxCachedSessions===void 0&&(this.maxCachedSessions=100),this._sessionCache={map:{},list:[]}}createConnection(e,t){let n=this[Gn](e,t);return this[Dr](n,e),n}};xe.prototype[Gn]=Xt.prototype.createConnection;["getName","_getSession","_cacheSession","_evictSession"].forEach(function(r){typeof Xt.prototype[r]=="function"&&(xe.prototype[r]=Xt.prototype[r])});Wn.exports=xe});var Kn=_e((po,Te)=>{"use strict";c();var Jn=Kt();Te.exports=Jn;Te.exports.HttpAgent=Jn;Te.exports.HttpsAgent=Hn();Te.exports.constants=ct()});c();c();c();c();c();var te="0.36.3";c();c();c();var Rn=!1,ne,qt,Ar,Er,Pr,Mn,Rr,st,Dt,vn,Nt,ot,In;function Fn(r,e={auto:!1}){if(Rn)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(ne)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${ne}'\``);Rn=e.auto,ne=r.kind,qt=r.fetch,Ar=r.Request,Er=r.Response,Pr=r.Headers,Mn=r.FormData,Rr=r.Blob,st=r.File,Dt=r.ReadableStream,vn=r.getMultipartRequestOptions,Nt=r.getDefaultAgent,ot=r.fileFromPath,In=r.isFsReadStream}c();var X=jt(xr(),1);c();c();import{inspect as Ir}from"util";c();var On=r=>r instanceof rt;c();import{deprecate as vr}from"util";var Bn=vr(()=>{},'Constructor "entries" argument is not spec-compliant and will be removed in next major release.');var B=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},it,L,Ut,at=class{constructor(e){it.add(this),L.set(this,new Map),e&&(Bn(),e.forEach(({name:t,value:n,fileName:s})=>this.append(t,n,s)))}static[(L=new WeakMap,it=new WeakSet,Symbol.hasInstance)](e){return!!(e&&M(e.constructor)&&e[Symbol.toStringTag]==="FormData"&&M(e.append)&&M(e.set)&&M(e.get)&&M(e.getAll)&&M(e.has)&&M(e.delete)&&M(e.entries)&&M(e.values)&&M(e.keys)&&M(e[Symbol.iterator])&&M(e.forEach))}append(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!0,rawValue:t,argsLength:arguments.length})}set(e,t,n){B(this,it,"m",Ut).call(this,{name:e,fileName:n,append:!1,rawValue:t,argsLength:arguments.length})}get(e){let t=B(this,L,"f").get(String(e));return t?t[0]:null}getAll(e){let t=B(this,L,"f").get(String(e));return t?t.slice():[]}has(e){return B(this,L,"f").has(String(e))}delete(e){B(this,L,"f").delete(String(e))}*keys(){for(let e of B(this,L,"f").keys())yield e}*entries(){for(let e of this.keys()){let t=this.getAll(e);for(let n of t)yield[e,n]}}*values(){for(let[,e]of this)yield e}[(Ut=function({name:t,rawValue:n,append:s,fileName:o,argsLength:i}){let a=s?"append":"set";if(i<2)throw new TypeError(`Failed to execute '${a}' on 'FormData': 2 arguments required, but only ${i} present.`);t=String(t);let u;if(Pn(n))u=o===void 0?n:new Se([n],o,{type:n.type,lastModified:n.lastModified});else if(On(n))u=new Se([n],o===void 0?"blob":o,{type:n.type});else{if(o)throw new TypeError(`Failed to execute '${a}' on 'FormData': parameter 2 is not of type 'Blob'.`);u=String(n)}let l=B(this,L,"f").get(t);if(!l)return void B(this,L,"f").set(t,[u]);if(!s)return void B(this,L,"f").set(t,[u]);l.push(u)},Symbol.iterator)](){return this.entries()}forEach(e,t){for(let[n,s]of this)e.call(t,s,n,this)}get[Symbol.toStringTag](){return"FormData"}[Ir.custom](){return this[Symbol.toStringTag]}};var Zt=jt(Kn(),1),Yn=jt(Tr(),1);import{ReadStream as Kr}from"node:fs";c();c();c();var Xn="abcdefghijklmnopqrstuvwxyz0123456789";function Nr(){let r=16,e="";for(;r--;)e+=Xn[Math.random()*Xn.length<<0];return e}var zn=Nr;c();var Ur=r=>Object.prototype.toString.call(r).slice(8,-1).toLowerCase();function $r(r){if(Ur(r)!=="object")return!1;let e=Object.getPrototypeOf(r);return e==null?!0:(e.constructor&&e.constructor.toString())===Object.toString()}var zt=$r;c();var Gr=r=>String(r).replace(/\r|\n/g,(e,t,n)=>e==="\r"&&n[t+1]!==`
|
|
4
4
|
`||e===`
|
|
5
5
|
`&&n[t-1]!=="\r"?`\r
|
|
6
6
|
`:e),Vt=Gr;c();var Wr=r=>String(r).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),Qt=Wr;c();c();var Hr=r=>typeof r=="function",U=Hr;var re=r=>!!(r&&typeof r=="object"&&U(r.constructor)&&r[Symbol.toStringTag]==="File"&&U(r.stream)&&r.name!=null&&r.size!=null&&r.lastModified!=null);c();var Vn=r=>!!(r&&U(r.constructor)&&r[Symbol.toStringTag]==="FormData"&&U(r.append)&&U(r.getAll)&&U(r.entries)&&U(r[Symbol.iterator]));var Ae=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},w=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},lt,K,Ee,ft,Pe,se,Re,Me,ht,Yt,Jr={enableAdditionalHeaders:!1},dt=class{constructor(e,t,n){if(lt.add(this),K.set(this,`\r
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as r}from"./chunk-ILBTI4K5.js";import"./chunk-47XR7IMP.js";import{g as m,i as h,p as f,q as g}from"./chunk-
|
|
3
|
+
import{a as r}from"./chunk-ILBTI4K5.js";import"./chunk-47XR7IMP.js";import{g as m,i as h,p as f,q as g}from"./chunk-6E766NPX.js";import{ba as d}from"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as p}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";p();var a=d("ASK_USER_QUESTION"),b=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
4
4
|
1. Gather user preferences or requirements
|
|
5
5
|
2. Clarify ambiguous instructions
|
|
6
6
|
3. Get decisions on implementation choices as you work
|
|
@@ -22,8 +22,8 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
22
22
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
23
23
|
|
|
24
24
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
25
|
-
`);this.baseURL=c.baseURL,this.timeout=c.timeout??En.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=tn(c.logLevel,"ClientOptions.logLevel",this)??tn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Xn(),w(this,Fr,zn,"f"),this._options=c,this.apiKey=t,this.organization=n,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 g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Zr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${qr()}`}makeStatusError(e,t,n,s){return N.generate(e,t,n,s)}buildURL(e,t,n){let s=!l(this,Rn,"m",Ns).call(this)&&n||this.baseURL,o=Mn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return jn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:a,url:c,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(T(this).debug(`[${m}] sending request`,ce({retryOfRequestLogID:n,method:s.method,url:c,options:s,headers:a.headers})),s.signal?.aborted)throw new v;let y=new AbortController,f=await this.fetchWithTimeout(c,a,u,y).catch(Ut),P=Date.now();if(f instanceof Error){let E=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new v;let x=Bt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return T(this).info(`[${m}] connection ${x?"timed out":"failed"} - ${E}`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (${E})`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),this.retryRequest(s,t,n??m);throw T(this).info(`[${m}] connection ${x?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (error; no more retries left)`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),x?new ge:new me({cause:f})}let A=[...f.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,x])=>", "+E+": "+JSON.stringify(x)).join(""),k=`[${m}${_}${A}] ${a.method} ${c} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-p}ms`;if(!f.ok){let E=await this.shouldRetry(f);if(t&&E){let O=`retrying, ${t} attempts remaining`;return await Vn(f.body),T(this).info(`${k} - ${O}`),T(this).debug(`[${m}] response error (${O})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),this.retryRequest(s,t,n??m,f.headers)}let x=E?"error; no more retries left":"error; not retryable";T(this).info(`${k} - ${x}`);let j=await f.text().catch(O=>Ut(O).message),C=Un(j),J=C?void 0:j;throw T(this).debug(`[${m}] response error (${x})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,C,J,f.headers)}return T(this).info(k),T(this).debug(`[${m}] response start`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),{response:f,options:s,controller:y,requestLogID:m,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Jt(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,_={signal:s.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(_.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,_)}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,n,s){let o,a=s?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(o=u)}let c=s?.get("retry-after");if(c&&!o){let u=parseFloat(c);Number.isNaN(u)?o=Date.parse(c)-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 te(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:c}=n,u=this.buildURL(o,a,c);"timeout"in n&&Bn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:m,body:_}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:m,retryCount:t});return{req:{method:s,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=g([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))}:{},...Jn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:cr(e)}:l(this,Fr,"f").call(this,{body:e,headers:n})}};En=R,Fr=new WeakMap,Rn=new WeakSet,Ns=function(){return this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=En;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=b;R.APIError=N;R.APIConnectionError=me;R.APIConnectionTimeoutError=ge;R.APIUserAbortError=v;R.NotFoundError=st;R.ConflictError=ot;R.RateLimitError=at;R.BadRequestError=tt;R.AuthenticationError=rt;R.InternalServerError=lt;R.PermissionDeniedError=nt;R.UnprocessableEntityError=it;R.InvalidWebhookSignatureError=ee;R.toFile=br;R.Completions=Ue;R.Chat=we;R.Embeddings=He;R.Files=Ge;R.Images=ze;R.Audio=oe;R.Moderations=Qe;R.Models=Ke;R.FineTuning=Z;R.Graders=Re;R.VectorStores=he;R.Webhooks=Ye;R.Beta=ae;R.Batches=Me;R.Uploads=ve;R.Responses=Ce;R.Evals=Se;R.Containers=Pe;i();function Tn(r){return r instanceof Error&&"code"in r}function Lm(r){return!r||typeof r!="object"?!1:!!(r instanceof v||r instanceof Error&&r.name==="AbortError"||Tn(r)&&r.code==="ABORT_ERR")}function Bm(r){if(r instanceof Error){let e=r.cause;return e instanceof Error&&e.message!==r.message?`${r.message} (cause: ${e.message})`:r.message}try{return String(r)}catch{return"Failed to get error details"}}function Um(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof t=="number"&&t>=100&&t<=599)return t;if(typeof e.message=="string"){let n=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(n){let s=Number(n[1]);if(s>=100&&s<=599)return s}}}function Wm(r){if(typeof r!="object"||r===null)return"unknown";let e=r instanceof Error&&r.constructor.name!=="Error"?r.constructor.name:void 0,t=r.type,n=e??t??(r instanceof Error?r.name:"unknown"),s=r instanceof Error?r.cause:void 0,o=s&&typeof s=="object"&&"code"in s?s.code:void 0;return o?`${n}:${o}`:n}var le=class extends Error{constructor(t,n){super(t);this.exitCode=n}},Ms=class extends le{constructor(e){super(e,41)}},Fs=class extends le{constructor(e){super(e,42)}},js=class extends le{constructor(e){super(e,44)}},or=class extends le{constructor(e){super(e,52)}},Ls=class extends le{constructor(e){super(e,53)}},Bs=class extends le{constructor(e){super(e,54)}},Us=class extends le{constructor(e){super(e,55)}},Ws=class extends le{constructor(e){super(e,130)}},Cn=class extends Error{},vn=class extends Error{},On=class extends Error{},Hs=class extends Error{status=403;code="ACCOUNT_INACTIVE";title="Account access restricted";constructor(){super("Your account is suspended or restricted from sending messages. Contact Matilda support to review your access. Signing in again will not remove this restriction."),this.name="AccountRestrictedError"}};function Hm(r){if(!r||typeof r!="object")return!1;let e=r;if(e.status!==void 0&&Number(e.status)!==403)return!1;let t=e.error;return e.code==="ACCOUNT_INACTIVE"||t==="account_inactive"||typeof t=="object"&&t!==null&&"code"in t&&t.code==="ACCOUNT_INACTIVE"}var qs=class extends Error{constructor(t,n,s,o){super(t);this.categories=n;this.severity=s;this.assistantMessage=o;this.name="ContentBlockedError"}};function qm(r){if(r&&typeof r=="object"&&"response"in r){let t=Ei(r);if(t.error&&t.error.message&&t.error.code)switch(t.error.code){case 400:return new On(t.error.message);case 401:return new vn(t.error.message);case 403:return new Cn(t.error.message);default:}}return r}function Ei(r){return typeof r.response?.data=="string"?JSON.parse(r.response?.data):r.response?.data}i();import Ci from"node:fs";import Q from"node:path";import Oe from"node:os";import*as Gs from"node:crypto";var ir=".matilda",Qm="google_accounts.json",Lt=new Map,vi=1024;function Ym(){Lt.clear()}var Js=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Zm=["file_path","path","filePath","notebook_path"],Oi=(()=>{let r=Js.source.slice(1,-1);return new RegExp(`\\\\([${r}])`,"g")})();function eg(r){let e=Oe.homedir();return r.startsWith(e)?r.replace(e,"~"):r}function tg(r){if(!r)return"";let e=r;return r.toLowerCase().startsWith("%userprofile%")?e=Oe.homedir()+r.substring(13):(r==="~"||r.startsWith("~/"))&&(e=Oe.homedir()+r.substring(1)),Q.normalize(e)}function rg(r,e=80){if(r.length<=e)return r;let t=Q.sep,n="...";if(e<10)return r.substring(0,e-3)+n;let o=Q.parse(r).root,c=r.substring(o.length).split(t).filter(_=>_!=="");if(c.length===0)return o.length<=e?o:o.substring(0,e-3)+n;if(c.length===1){let _=o+c[0];if(_.length<=e)return _;let p=Math.floor((e-3)/2),y=_.substring(0,p),f=_.substring(_.length-p);return`${y}${n}${f}`}let u=o+c[0],m=[];for(let _=c.length-1;_>=1;_--){let p=c[_],y=[p,...m].join(t),f=_>1,P;if(f?P=u+t+n+t+y:P=u+t+y,P.length<=e){if(m.unshift(p),_===1)return P}else break}if(m.length===0){let _=Math.floor((e-3)/2),p=r.substring(0,_),y=r.substring(r.length-_);return`${p}${n}${y}`}return u+t+n+t+m.join(t)}function ng(r,e){let t=Q.resolve(r),n=Q.resolve(e);return zs(n,t)?Q.relative(n,t)||".":t}function sg(r){let e="";for(let t=0;t<r.length;t++){let n=r[t],s=0;for(let a=t-1;a>=0&&r[a]==="\\";a--)s++;!(s%2===1)&&Js.test(n)?e+="\\"+n:e+=n}return e}function og(r){return Oe.platform()==="win32"?r:r.replace(Oi,"$1")}function Xs(r){let e=Oe.platform()==="win32"?r.toLowerCase():r;return Gs.createHash("sha256").update(e).digest("hex")}function Vs(r){return(Oe.platform()==="win32"?r.toLowerCase():r).replace(/[^a-zA-Z0-9]/g,"-")}function zs(r,e){let n=Oe.platform()==="win32"?Q.win32:Q,s=n.relative(r,e);return!s.startsWith(`..${n.sep}`)&&s!==".."&&!n.isAbsolute(s)}function ig(r,e){return r.some(t=>zs(t,e))}function Ti(r=process.cwd(),e){let t=Oe.homedir();return e==="~"?t:e.startsWith("~/")?Q.join(t,e.slice(2)):Q.isAbsolute(e)?e:Q.resolve(r,e)}function ki(r,e,t={}){let{allowFiles:n=!1,allowExternalPaths:s=!1}=t,a=r.getWorkspaceContext().isPathWithinWorkspace(e);if(!s&&!a)throw new Error("Path is not within workspace");if(s&&!a)return;let c=Lt.get(e);if(c===void 0){try{c=Ci.statSync(e).isDirectory()}catch(u){throw Tn(u)&&u.code==="ENOENT"?new Error(`Path does not exist: ${e}`):u}if(Lt.size>=vi){let u=Lt.keys().next().value;u!==void 0&&Lt.delete(u)}Lt.set(e,c)}if(!n&&!c)throw new Error(`Path is not a directory: ${e}`)}function ag(r,e){let t=r.getTranscriptPath?.();return!!t&&Q.resolve(e)===Q.resolve(t)}function lg(r,e,t={}){let n=r.getTargetDir();if(!e)return n;let s=Ti(n,e);return ki(r,s,t),s}i();import*as I from"node:path";import*as Ze from"node:os";import*as jr from"node:fs";import{AsyncLocalStorage as $i}from"node:async_hooks";var Di="google_accounts.json",Ni="oauth_creds.json",Mi=[".matilda",".agents"],Ks="tmp",Fi="bin",ji="projects",Li="ide",Bi="plans",Ui="debug",Wi="arena",et=class r{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new $i;constructor(e,t){this.targetDir=e,this.pinnedRuntimeBaseDir=t?r.resolvePath(t):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??r.getRuntimeBaseDir()}static resolvePath(e,t){let n=e;if(n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let s=n==="~"?[]:n.slice(2).split(/[/\\]+/).filter(Boolean);n=I.join(Ze.homedir(),...s)}return I.isAbsolute(n)||(n=t?I.resolve(t,n):I.resolve(n)),n}static sanitizePlanSessionId(e){return I.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,t){return e?r.resolvePath(e,t):null}static setRuntimeBaseDir(e,t){r.runtimeBaseDir=r.resolveRuntimeBaseDir(e,t)}static runWithRuntimeBaseDir(e,t,n){let s=r.resolveRuntimeBaseDir(e,t);return r.runtimeBaseDirContext.run(s,n)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return r.resolveRuntimeBaseDir(e)??r.getGlobalMatildaDir();let t=r.runtimeBaseDirContext.getStore();return t!==void 0?t??r.getGlobalMatildaDir():r.runtimeBaseDir?r.runtimeBaseDir:r.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return r.resolvePath(e);let t=Ze.homedir();return t?I.join(t,ir):I.join(Ze.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return I.join(r.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return I.join(r.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return I.join(r.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return I.join(r.getGlobalMatildaDir(),Di)}static getUserCommandsDir(){return I.join(r.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return I.join(r.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return I.join(r.getRuntimeBaseDir(),Ks)}static getGlobalDebugDir(){return I.join(r.getRuntimeBaseDir(),Ui)}static getDebugLogPath(e){return I.join(r.getGlobalDebugDir(),`${e}.txt`)}static getGlobalIdeDir(){return I.join(r.getGlobalMatildaDir(),Li)}static resolvePathThroughExistingAncestor(e){let t=e;for(;;)try{let n=jr.realpathSync(t),s=I.relative(t,e);return I.join(n,s)}catch(n){if(n.code!=="ENOENT")throw n;let s=I.dirname(t);if(s===t)return e;t=s}}static isPathWithinDirectory(e,t){let n=r.resolvePathThroughExistingAncestor(t),s=r.resolvePathThroughExistingAncestor(e),o=I.relative(n,s);return o===""||!o.startsWith("..")&&!I.isAbsolute(o)}static assertPathWithinDirectory(e,t,n){if(!r.isPathWithinDirectory(e,t))throw new or(n)}static getPlansDir(e,t){let n=t?.trim();if(n){if(!e)throw new or("projectRoot is required when plansDirectory is configured.");let s=I.resolve(e),o=r.resolvePath(n,s);return r.assertPathWithinDirectory(o,s,"plansDirectory must resolve within the project root."),o}return I.join(r.getGlobalMatildaDir(),Bi)}static getPlanFilePath(e,t,n){return I.join(r.getPlansDir(t,n),`${r.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return I.join(r.getGlobalMatildaDir(),Fi)}static getGlobalArenaDir(){return I.join(r.getGlobalMatildaDir(),Wi)}getMatildaDir(){return I.join(this.targetDir,ir)}getProjectDir(){let e=Vs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ji);return I.join(t,e)}getProjectTempDir(){let e=Xs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),Ks);return I.join(t,e)}getToolResultsDir(){return I.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){jr.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return I.join(r.getGlobalMatildaDir(),Ni)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return I.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return I.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return I.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return I.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return I.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return I.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=Ze.homedir()||Ze.tmpdir();return Mi.map(t=>t===ir?I.join(r.getGlobalMatildaDir(),"skills"):I.join(e,t,"skills"))}static getUserExtensionsDir(){return I.join(r.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return I.join(this.getProjectTempDir(),"shell_history")}};i();import{promises as kn}from"node:fs";import Qs from"node:path";async function Ys(r,e,t){let{fallbackCopy:n=!0}=t??{},s=Qs.dirname(r),o=Qs.relative(s,e);try{await kn.unlink(r)}catch{}try{await kn.symlink(o,r);return}catch{}if(n)try{await kn.copyFile(e,r)}catch{}}i();fo();i();var Zs,eo;function xg(r,e){Zs=r,eo=e}function to(){return Zs}function Ag(){return eo}function ro(r){let e=r?.spanContext();return e&&Nn(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function Hi(){try{return ro(Hr.getActiveSpan())}catch{return null}}function qi(){try{let r=to();return ro(r?Hr.getSpan(r):void 0)}catch{return null}}function no(){return Hi()??qi()}function Cg(r){let e=(r.traceFlags&255).toString(16).padStart(2,"0");return`00-${r.traceId}-${r.spanId}-${e}`}var so=!1;function vg(r){so=r}function Og(){return so}i();import{promises as oo}from"node:fs";import Gi from"node:path";import{AsyncLocalStorage as Ji}from"node:async_hooks";import Xi from"node:util";var lr=null,Br=null,Ur=!1,io=null,ao=new Ji;function lo(){let r=process.env.MATILDA_DEBUG_LOG_FILE;if(!r)return!1;let e=r.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function ar(){return ao.getStore()??io}function co(){let r=et.getGlobalDebugDir();return(!lr||Br!==r)&&(Br=r,lr=oo.mkdir(r,{recursive:!0}).then(()=>{}).catch(()=>{Ur=!0,lr=null,Br=null})),lr??Promise.resolve()}function Vi(r){return r.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:Xi.inspect(e)).join(" ")}function zi(r,e,t,n){let s=new Date().toISOString(),o=t?` [${t}]`:"",a=n?` [trace_id=${n.traceId} span_id=${n.spanId}]`:"";return`${s} [${r}]${o}${a} ${e}
|
|
26
|
-
`}function Lr(r,e,t,n){if(!lo())return;let s=r.getSessionId(),o=et.getDebugLogPath(s),a=
|
|
25
|
+
`);this.baseURL=c.baseURL,this.timeout=c.timeout??En.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=tn(c.logLevel,"ClientOptions.logLevel",this)??tn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Xn(),w(this,Fr,zn,"f"),this._options=c,this.apiKey=t,this.organization=n,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 g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Zr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${qr()}`}makeStatusError(e,t,n,s){return N.generate(e,t,n,s)}buildURL(e,t,n){let s=!l(this,Rn,"m",Ns).call(this)&&n||this.baseURL,o=Mn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return jn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:a,url:c,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(T(this).debug(`[${m}] sending request`,ce({retryOfRequestLogID:n,method:s.method,url:c,options:s,headers:a.headers})),s.signal?.aborted)throw new v;let y=new AbortController,f=await this.fetchWithTimeout(c,a,u,y).catch(Ut),P=Date.now();if(f instanceof Error){let E=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new v;let x=Bt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return T(this).info(`[${m}] connection ${x?"timed out":"failed"} - ${E}`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (${E})`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),this.retryRequest(s,t,n??m);throw T(this).info(`[${m}] connection ${x?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${m}] connection ${x?"timed out":"failed"} (error; no more retries left)`,ce({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),x?new ge:new me({cause:f})}let A=[...f.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,x])=>", "+E+": "+JSON.stringify(x)).join(""),k=`[${m}${_}${A}] ${a.method} ${c} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-p}ms`;if(!f.ok){let E=await this.shouldRetry(f);if(t&&E){let O=`retrying, ${t} attempts remaining`;return await Vn(f.body),T(this).info(`${k} - ${O}`),T(this).debug(`[${m}] response error (${O})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),this.retryRequest(s,t,n??m,f.headers)}let x=E?"error; no more retries left":"error; not retryable";T(this).info(`${k} - ${x}`);let j=await f.text().catch(O=>Ut(O).message),C=Un(j),J=C?void 0:j;throw T(this).debug(`[${m}] response error (${x})`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,C,J,f.headers)}return T(this).info(k),T(this).debug(`[${m}] response start`,ce({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),{response:f,options:s,controller:y,requestLogID:m,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Jt(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,_={signal:s.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(_.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,_)}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,n,s){let o,a=s?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(o=u)}let c=s?.get("retry-after");if(c&&!o){let u=parseFloat(c);Number.isNaN(u)?o=Date.parse(c)-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 te(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:c}=n,u=this.buildURL(o,a,c);"timeout"in n&&Bn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:m,body:_}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:m,retryCount:t});return{req:{method:s,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=g([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))}:{},...Jn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:cr(e)}:l(this,Fr,"f").call(this,{body:e,headers:n})}};En=R,Fr=new WeakMap,Rn=new WeakSet,Ns=function(){return this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=En;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=b;R.APIError=N;R.APIConnectionError=me;R.APIConnectionTimeoutError=ge;R.APIUserAbortError=v;R.NotFoundError=st;R.ConflictError=ot;R.RateLimitError=at;R.BadRequestError=tt;R.AuthenticationError=rt;R.InternalServerError=lt;R.PermissionDeniedError=nt;R.UnprocessableEntityError=it;R.InvalidWebhookSignatureError=ee;R.toFile=br;R.Completions=Ue;R.Chat=we;R.Embeddings=He;R.Files=Ge;R.Images=ze;R.Audio=oe;R.Moderations=Qe;R.Models=Ke;R.FineTuning=Z;R.Graders=Re;R.VectorStores=he;R.Webhooks=Ye;R.Beta=ae;R.Batches=Me;R.Uploads=ve;R.Responses=Ce;R.Evals=Se;R.Containers=Pe;i();function Tn(r){return r instanceof Error&&"code"in r}function Bm(r){return!r||typeof r!="object"?!1:!!(r instanceof v||r instanceof Error&&r.name==="AbortError"||Tn(r)&&r.code==="ABORT_ERR")}function Um(r){if(r instanceof Error){let e=r.cause;return e instanceof Error&&e.message!==r.message?`${r.message} (cause: ${e.message})`:r.message}try{return String(r)}catch{return"Failed to get error details"}}function Wm(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof t=="number"&&t>=100&&t<=599)return t;if(typeof e.message=="string"){let n=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(n){let s=Number(n[1]);if(s>=100&&s<=599)return s}}}function Hm(r){if(typeof r!="object"||r===null)return"unknown";let e=r instanceof Error&&r.constructor.name!=="Error"?r.constructor.name:void 0,t=r.type,n=e??t??(r instanceof Error?r.name:"unknown"),s=r instanceof Error?r.cause:void 0,o=s&&typeof s=="object"&&"code"in s?s.code:void 0;return o?`${n}:${o}`:n}var le=class extends Error{constructor(t,n){super(t);this.exitCode=n}},Ms=class extends le{constructor(e){super(e,41)}},Fs=class extends le{constructor(e){super(e,42)}},js=class extends le{constructor(e){super(e,44)}},or=class extends le{constructor(e){super(e,52)}},Ls=class extends le{constructor(e){super(e,53)}},Bs=class extends le{constructor(e){super(e,54)}},Us=class extends le{constructor(e){super(e,55)}},Ws=class extends le{constructor(e){super(e,130)}},Cn=class extends Error{},vn=class extends Error{},On=class extends Error{},Hs=class extends Error{status=403;code="ACCOUNT_INACTIVE";title="Account access restricted";constructor(){super("Your account is suspended or restricted from sending messages. Contact Matilda support to review your access. Signing in again will not remove this restriction."),this.name="AccountRestrictedError"}};function qm(r){if(!r||typeof r!="object")return!1;let e=r;if(e.status!==void 0&&Number(e.status)!==403)return!1;let t=e.error;return e.code==="ACCOUNT_INACTIVE"||t==="account_inactive"||typeof t=="object"&&t!==null&&"code"in t&&t.code==="ACCOUNT_INACTIVE"}var qs=class extends Error{constructor(t,n,s,o){super(t);this.categories=n;this.severity=s;this.assistantMessage=o;this.name="ContentBlockedError"}};function Gm(r){if(r&&typeof r=="object"&&"response"in r){let t=Ei(r);if(t.error&&t.error.message&&t.error.code)switch(t.error.code){case 400:return new On(t.error.message);case 401:return new vn(t.error.message);case 403:return new Cn(t.error.message);default:}}return r}function Ei(r){return typeof r.response?.data=="string"?JSON.parse(r.response?.data):r.response?.data}i();import Ci from"node:fs";import Q from"node:path";import Oe from"node:os";import*as Gs from"node:crypto";var ir=".matilda",Ym="google_accounts.json",Lt=new Map,vi=1024;function Zm(){Lt.clear()}var Js=/[ \t()[\]{};|*?$`'"#&<>!~,]/,eg=["file_path","path","filePath","notebook_path"],Oi=(()=>{let r=Js.source.slice(1,-1);return new RegExp(`\\\\([${r}])`,"g")})();function tg(r){let e=Oe.homedir();return r.startsWith(e)?r.replace(e,"~"):r}function rg(r){if(!r)return"";let e=r;return r.toLowerCase().startsWith("%userprofile%")?e=Oe.homedir()+r.substring(13):(r==="~"||r.startsWith("~/"))&&(e=Oe.homedir()+r.substring(1)),Q.normalize(e)}function ng(r,e=80){if(r.length<=e)return r;let t=Q.sep,n="...";if(e<10)return r.substring(0,e-3)+n;let o=Q.parse(r).root,c=r.substring(o.length).split(t).filter(_=>_!=="");if(c.length===0)return o.length<=e?o:o.substring(0,e-3)+n;if(c.length===1){let _=o+c[0];if(_.length<=e)return _;let p=Math.floor((e-3)/2),y=_.substring(0,p),f=_.substring(_.length-p);return`${y}${n}${f}`}let u=o+c[0],m=[];for(let _=c.length-1;_>=1;_--){let p=c[_],y=[p,...m].join(t),f=_>1,P;if(f?P=u+t+n+t+y:P=u+t+y,P.length<=e){if(m.unshift(p),_===1)return P}else break}if(m.length===0){let _=Math.floor((e-3)/2),p=r.substring(0,_),y=r.substring(r.length-_);return`${p}${n}${y}`}return u+t+n+t+m.join(t)}function sg(r,e){let t=Q.resolve(r),n=Q.resolve(e);return zs(n,t)?Q.relative(n,t)||".":t}function og(r){let e="";for(let t=0;t<r.length;t++){let n=r[t],s=0;for(let a=t-1;a>=0&&r[a]==="\\";a--)s++;!(s%2===1)&&Js.test(n)?e+="\\"+n:e+=n}return e}function ig(r){return Oe.platform()==="win32"?r:r.replace(Oi,"$1")}function Xs(r){let e=Oe.platform()==="win32"?r.toLowerCase():r;return Gs.createHash("sha256").update(e).digest("hex")}function Vs(r){return(Oe.platform()==="win32"?r.toLowerCase():r).replace(/[^a-zA-Z0-9]/g,"-")}function zs(r,e){let n=Oe.platform()==="win32"?Q.win32:Q,s=n.relative(r,e);return!s.startsWith(`..${n.sep}`)&&s!==".."&&!n.isAbsolute(s)}function ag(r,e){return r.some(t=>zs(t,e))}function Ti(r=process.cwd(),e){let t=Oe.homedir();return e==="~"?t:e.startsWith("~/")?Q.join(t,e.slice(2)):Q.isAbsolute(e)?e:Q.resolve(r,e)}function ki(r,e,t={}){let{allowFiles:n=!1,allowExternalPaths:s=!1}=t,a=r.getWorkspaceContext().isPathWithinWorkspace(e);if(!s&&!a)throw new Error("Path is not within workspace");if(s&&!a)return;let c=Lt.get(e);if(c===void 0){try{c=Ci.statSync(e).isDirectory()}catch(u){throw Tn(u)&&u.code==="ENOENT"?new Error(`Path does not exist: ${e}`):u}if(Lt.size>=vi){let u=Lt.keys().next().value;u!==void 0&&Lt.delete(u)}Lt.set(e,c)}if(!n&&!c)throw new Error(`Path is not a directory: ${e}`)}function lg(r,e){let t=r.getTranscriptPath?.();return!!t&&Q.resolve(e)===Q.resolve(t)}function cg(r,e,t={}){let n=r.getTargetDir();if(!e)return n;let s=Ti(n,e);return ki(r,s,t),s}i();import*as I from"node:path";import*as Ze from"node:os";import*as jr from"node:fs";import{AsyncLocalStorage as $i}from"node:async_hooks";var Di="google_accounts.json",Ni="oauth_creds.json",Mi=[".matilda",".agents"],Ks="tmp",Fi="bin",ji="projects",Li="ide",Bi="plans",Ui="debug",Wi="crash",Hi="arena",et=class r{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new $i;constructor(e,t){this.targetDir=e,this.pinnedRuntimeBaseDir=t?r.resolvePath(t):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??r.getRuntimeBaseDir()}static resolvePath(e,t){let n=e;if(n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let s=n==="~"?[]:n.slice(2).split(/[/\\]+/).filter(Boolean);n=I.join(Ze.homedir(),...s)}return I.isAbsolute(n)||(n=t?I.resolve(t,n):I.resolve(n)),n}static sanitizePlanSessionId(e){return I.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,t){return e?r.resolvePath(e,t):null}static setRuntimeBaseDir(e,t){r.runtimeBaseDir=r.resolveRuntimeBaseDir(e,t)}static runWithRuntimeBaseDir(e,t,n){let s=r.resolveRuntimeBaseDir(e,t);return r.runtimeBaseDirContext.run(s,n)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return r.resolveRuntimeBaseDir(e)??r.getGlobalMatildaDir();let t=r.runtimeBaseDirContext.getStore();return t!==void 0?t??r.getGlobalMatildaDir():r.runtimeBaseDir?r.runtimeBaseDir:r.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return r.resolvePath(e);let t=Ze.homedir();return t?I.join(t,ir):I.join(Ze.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return I.join(r.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return I.join(r.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return I.join(r.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return I.join(r.getGlobalMatildaDir(),Di)}static getUserCommandsDir(){return I.join(r.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return I.join(r.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return I.join(r.getRuntimeBaseDir(),Ks)}static getGlobalDebugDir(){return I.join(r.getRuntimeBaseDir(),Ui)}static getDebugLogPath(e){return I.join(r.getGlobalDebugDir(),`${e}.txt`)}static getGlobalCrashDir(){return I.join(r.getRuntimeBaseDir(),Wi)}static getGlobalIdeDir(){return I.join(r.getGlobalMatildaDir(),Li)}static resolvePathThroughExistingAncestor(e){let t=e;for(;;)try{let n=jr.realpathSync(t),s=I.relative(t,e);return I.join(n,s)}catch(n){if(n.code!=="ENOENT")throw n;let s=I.dirname(t);if(s===t)return e;t=s}}static isPathWithinDirectory(e,t){let n=r.resolvePathThroughExistingAncestor(t),s=r.resolvePathThroughExistingAncestor(e),o=I.relative(n,s);return o===""||!o.startsWith("..")&&!I.isAbsolute(o)}static assertPathWithinDirectory(e,t,n){if(!r.isPathWithinDirectory(e,t))throw new or(n)}static getPlansDir(e,t){let n=t?.trim();if(n){if(!e)throw new or("projectRoot is required when plansDirectory is configured.");let s=I.resolve(e),o=r.resolvePath(n,s);return r.assertPathWithinDirectory(o,s,"plansDirectory must resolve within the project root."),o}return I.join(r.getGlobalMatildaDir(),Bi)}static getPlanFilePath(e,t,n){return I.join(r.getPlansDir(t,n),`${r.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return I.join(r.getGlobalMatildaDir(),Fi)}static getGlobalArenaDir(){return I.join(r.getGlobalMatildaDir(),Hi)}getMatildaDir(){return I.join(this.targetDir,ir)}getProjectDir(){let e=Vs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ji);return I.join(t,e)}getProjectTempDir(){let e=Xs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),Ks);return I.join(t,e)}getToolResultsDir(){return I.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){jr.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return I.join(r.getGlobalMatildaDir(),Ni)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return I.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return I.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return I.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return I.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return I.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return I.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=Ze.homedir()||Ze.tmpdir();return Mi.map(t=>t===ir?I.join(r.getGlobalMatildaDir(),"skills"):I.join(e,t,"skills"))}static getUserExtensionsDir(){return I.join(r.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return I.join(this.getProjectTempDir(),"shell_history")}};i();import{promises as kn}from"node:fs";import Qs from"node:path";async function Ys(r,e,t){let{fallbackCopy:n=!0}=t??{},s=Qs.dirname(r),o=Qs.relative(s,e);try{await kn.unlink(r)}catch{}try{await kn.symlink(o,r);return}catch{}if(n)try{await kn.copyFile(e,r)}catch{}}i();fo();i();var Zs,eo;function Ag(r,e){Zs=r,eo=e}function to(){return Zs}function Ig(){return eo}function ro(r){let e=r?.spanContext();return e&&Nn(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function qi(){try{return ro(Hr.getActiveSpan())}catch{return null}}function Gi(){try{let r=to();return ro(r?Hr.getSpan(r):void 0)}catch{return null}}function no(){return qi()??Gi()}function vg(r){let e=(r.traceFlags&255).toString(16).padStart(2,"0");return`00-${r.traceId}-${r.spanId}-${e}`}var so=!1;function Og(r){so=r}function Tg(){return so}i();import{promises as oo}from"node:fs";import Ji from"node:path";import{AsyncLocalStorage as Xi}from"node:async_hooks";import Vi from"node:util";var lr=null,Br=null,Ur=!1,io=null,ao=new Xi;function lo(){let r=process.env.MATILDA_DEBUG_LOG_FILE;if(!r)return!1;let e=r.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function ar(){return ao.getStore()??io}function co(){let r=et.getGlobalDebugDir();return(!lr||Br!==r)&&(Br=r,lr=oo.mkdir(r,{recursive:!0}).then(()=>{}).catch(()=>{Ur=!0,lr=null,Br=null})),lr??Promise.resolve()}function zi(r){return r.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:Vi.inspect(e)).join(" ")}function Ki(r,e,t,n){let s=new Date().toISOString(),o=t?` [${t}]`:"",a=n?` [trace_id=${n.traceId} span_id=${n.spanId}]`:"";return`${s} [${r}]${o}${a} ${e}
|
|
26
|
+
`}function Lr(r,e,t,n){if(!lo())return;let s=r.getSessionId(),o=et.getDebugLogPath(s),a=zi(n),c=no(),u=Ki(e,a,t,c);co().then(()=>oo.appendFile(o,u,"utf8")).catch(()=>{Ur=!0})}function Ug(){return Ur}function Wg(){Ur=!1,lr=null,Br=null}var Qi="latest";function Yi(r){if(!lo())return;let e=Ji.join(et.getGlobalDebugDir(),Qi),t=et.getDebugLogPath(r);co().then(()=>Ys(e,t,{fallbackCopy:!1})).catch(()=>{})}function Hg(r){io=r??null,r&&Yi(r.getSessionId())}function qg(r,e){return ao.run(r,e)}function Gg(r){return{isEnabled:()=>ar()!==null,debug:(...e)=>{let t=ar();t&&Lr(t,"DEBUG",r,e)},info:(...e)=>{let t=ar();t&&Lr(t,"INFO",r,e)},warn:(...e)=>{let t=ar();t&&Lr(t,"WARN",r,e)},error:(...e)=>{let t=ar();t&&Lr(t,"ERROR",r,e)}}}export{R as a,Tn as b,Bm as c,Um as d,Wm as e,Hm as f,le as g,Ms as h,Fs as i,js as j,or as k,Ls as l,Bs as m,Us as n,Ws as o,Cn as p,vn as q,On as r,Hs as s,qm as t,qs as u,Gm as v,ir as w,Ym as x,Zm as y,Js as z,eg as A,tg as B,rg as C,ng as D,sg as E,og as F,ig as G,Xs as H,Vs as I,zs as J,ag as K,Ti as L,ki as M,lg as N,cg as O,Mi as P,et as Q,Ys as R,Ag as S,Ig as T,qi as U,no as V,vg as W,Og as X,Tg as Y,Ug as Z,Wg as _,Hg as $,qg as aa,Gg as ba};
|
|
27
27
|
/**
|
|
28
28
|
* @license
|
|
29
29
|
* Copyright 2025 Google LLC
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{b as f}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-
|
|
3
|
+
import{b as f}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-LUNDTQ3G.js";import{H as d,Q as m,ba as p}from"./chunk-27Q5KW3A.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=p("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 f,h.set(e,t)),t}function c(e){return s.join(m.getGlobalTempDir(),d(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 g(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};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{b as X,h as T}from"./chunk-
|
|
3
|
+
import{b as X,h as T}from"./chunk-S3CWEVTS.js";import{b as P}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-LUNDTQ3G.js";import{b as l,ba as $}from"./chunk-27Q5KW3A.js";import{b as _}from"./chunk-GZPNIYVZ.js";import{f as W}from"./chunk-OWGSC52X.js";_();var R=W(X(),1);import*as d from"node:fs/promises";import{constants as B}from"node:fs";import*as b from"node:path";var f=$("AGENTS_TEAM_TASKS"),v=32768,A=16;function C(r){if(!r)return;let e=Buffer.byteLength(JSON.stringify(r),"utf-8");if(e>v)throw new Error(`Task metadata is too large (${e} bytes; max ${v}). Trim the payload or store the bulk content elsewhere.`)}var K={retries:{retries:30,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:r=>{f.warn("task lock compromised:",r?.message??r)}},j=new Map;function q(r){let e=j.get(r);return e||(e=new P,j.set(r,e)),e}async function h(r,e,t){return q(r).runExclusive(async()=>{let a;try{a=await R.default.lock(r,K)}catch(o){if(l(o)&&o.code==="ENOENT")return t();throw o}try{return await e()}finally{await a()}})}var z="__reciprocal__",L=new Map;function Y(r){let e=L.get(r);return e||(e=new P,L.set(r,e)),e}function G(r){if(!/^[1-9]\d*$/.test(r))throw new Error(`Invalid task ID "${r}". Task IDs must be positive integers.`)}function m(r,e){return G(e),b.join(T(r),`${e}.json`)}var O=new Set;function ie(r){return O.add(r),()=>{O.delete(r)}}function k(r){for(let e of O)try{e(r)}catch(t){f.warn(`task update listener failed: ${t}`)}}async function oe(r,e){C(e.metadata);let t=T(r);await d.mkdir(t,{recursive:!0});let a=15;for(let o=0;o<a;o++){let c=await I(t),s={id:c,subject:e.subject,description:e.description,activeForm:e.activeForm,owner:e.owner,status:"pending",blocks:[],blockedBy:[],metadata:e.metadata},n=b.join(t,`${c}.json`);try{await(await d.open(n,B.O_WRONLY|B.O_CREAT|B.O_EXCL)).close()}catch(i){if(l(i)&&i.code==="EEXIST")continue;throw i}try{await g(n,s)}catch(i){throw await d.unlink(n).catch(()=>{}),i}return k(r),s}throw new Error(`Failed to create task after ${a} attempts (ID contention).`)}async function ce(r,e){let t=m(r,e);try{let a=await d.readFile(t,"utf-8");return JSON.parse(a)}catch(a){if(l(a)&&a.code==="ENOENT")return;throw a}}var p=class extends Error{constructor(t,a,o){super(`Task #${t} is owned by "${o}". Only the leader or the owner can change status / owner / subject / description / blocks.`);this.taskId=t;this.callerName=a;this.actualOwner=o;this.name="TaskOwnershipError"}};async function F(r,e,t,a){let o=m(r,e);return h(o,async()=>{let c;try{c=await d.readFile(o,"utf-8")}catch(n){if(l(n)&&n.code==="ENOENT")return;throw n}let s=JSON.parse(c);if(a?.callerName!==void 0&&a.callerName!==z&&(t.status!==void 0||t.owner!==void 0||t.subject!==void 0||t.description!==void 0||(t.addBlocks?.length??0)>0||(t.addBlockedBy?.length??0)>0)&&s.owner&&s.owner!==a.callerName)throw new p(e,a.callerName,s.owner);if(t.addBlocks?.length){let n=new Set(s.blocks);for(let i of t.addBlocks)n.add(i);s.blocks=Array.from(n)}if(t.addBlockedBy?.length){let n=new Set(s.blockedBy);for(let i of t.addBlockedBy)n.add(i);s.blockedBy=Array.from(n)}if(t.status!==void 0&&(s.status=t.status,t.status==="completed"&&s.blocks.length>0&&await V(r,e,s.blocks)),t.owner!==void 0&&(s.owner=t.owner?t.owner:void 0),t.subject!==void 0&&(s.subject=t.subject),t.description!==void 0&&(s.description=t.description),t.activeForm!==void 0&&(s.activeForm=t.activeForm??void 0),t.metadata!==void 0){s.metadata=s.metadata??{};for(let[n,i]of Object.entries(t.metadata))n==="__proto__"||n==="constructor"||n==="prototype"||(i===null?delete s.metadata[n]:s.metadata[n]=i);Object.keys(s.metadata).length===0&&(s.metadata=void 0),C(s.metadata)}return await g(o,s),k(r),s},()=>{})}async function de(r,e,t){let a=m(r,e),o=await h(a,async()=>{let s;try{let i=await d.readFile(a,"utf-8");s=JSON.parse(i)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}if(t?.callerName!==void 0&&s.owner&&s.owner!==t.callerName)throw new p(e,t.callerName,s.owner);let n=new Set([...s.blocks,...s.blockedBy]);n.delete(e);try{await d.unlink(a)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}return n},()=>null);if(o===null)return!1;let c=await Promise.allSettled(Array.from(o).map(s=>Q(r,s,e)));for(let s of c)s.status==="rejected"&&f.warn(`deleteTask(${e}): edge cleanup failed: ${s.reason}`);return k(r),!0}async function Q(r,e,t){let a=m(r,e);await h(a,async()=>{try{let o=await d.readFile(a,"utf-8"),c=JSON.parse(o),s=c.blocks.length,n=c.blockedBy.length;if(c.blocks=c.blocks.filter(i=>i!==t),c.blockedBy=c.blockedBy.filter(i=>i!==t),c.blocks.length===s&&c.blockedBy.length===n)return;await g(a,c)}catch(o){if(l(o)&&o.code==="ENOENT")return;throw o}},()=>{})}async function x(r,e){let t=T(r),a;try{a=await d.readdir(t)}catch(n){if(l(n)&&n.code==="ENOENT")return[];let i=n instanceof Error?n.message:String(n);throw f.warn(`Failed to list tasks dir ${t}: ${i}`),n instanceof Error?n:new Error(i)}let o=a.filter(n=>n.endsWith(".json")),c=[];for(let n=0;n<o.length;n+=A){let i=o.slice(n,n+A),w=await Promise.all(i.map(async D=>{let y=b.join(t,D),S;try{S=await d.readFile(y,"utf-8")}catch(u){if(l(u)&&u.code==="ENOENT")return;let E=u instanceof Error?u.message:String(u);f.warn(`Failed to read task file ${y}: ${E}`);return}if(S.trim()!=="")try{return JSON.parse(S)}catch(u){let E=u instanceof Error?u.message:String(u);f.warn(`Quarantining corrupt task file ${y}: ${E}`);let J=`${y}.corrupt-${Date.now()}`;try{await d.rename(y,J)}catch(N){let U=N instanceof Error?N.message:String(N);f.warn(`Failed to quarantine ${y}: ${U}`)}return}}));c.push(...w)}let s=c.filter(n=>n!==void 0);return s.sort((n,i)=>Number(n.id)-Number(i.id)),e?s.filter(n=>!(e.status!==void 0&&n.status!==e.status||e.owner!==void 0&&n.owner!==e.owner||e.blockedBy!==void 0&&!n.blockedBy.includes(e.blockedBy))):s}async function le(r){let e=T(r);await d.rm(e,{recursive:!0,force:!0}),k(r)}async function V(r,e,t){let a=await Promise.allSettled(t.map(async o=>{let c=m(r,o);await h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(w){if(l(w)&&w.code==="ENOENT")return;throw w}let n=JSON.parse(s),i=n.blockedBy.length;n.blockedBy=n.blockedBy.filter(w=>w!==e),n.blockedBy.length!==i&&await g(c,n)},()=>{})}));for(let o of a)o.status==="rejected"&&f.warn(`unblockDependents(${e}): ${o.reason}`);k(r)}async function ue(r,e,t){await F(r,e,{addBlocks:[t]}),await F(r,t,{addBlockedBy:[e]})}async function fe(r,e,t,a){return a?.checkAgentBusy?Y(t).runExclusive(()=>M(r,e,t,a,!0)):M(r,e,t,a,!1)}async function M(r,e,t,a,o){if(o&&await H(r,t))return;let c=m(r,e);return h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(i){if(l(i)&&i.code==="ENOENT")return;throw i}let n=JSON.parse(s);if(n.status==="pending"&&!n.owner)return n.owner=a?.ownerName??t,n.status="in_progress",await g(c,n),k(r),n},()=>{})}async function H(r,e){let t=await x(r,{status:"in_progress"}),a=e.split("@")[0];return t.some(o=>o.owner===e||o.owner===a)}async function Z(r,e,t){let a=m(r,e);return h(a,async()=>{let o;try{o=await d.readFile(a,"utf-8")}catch(s){if(l(s)&&s.code==="ENOENT")return!1;throw s}let c=JSON.parse(o);return c.status!=="in_progress"||c.owner!==t?!1:(c.owner=void 0,c.status="pending",await g(a,c),!0)},()=>!1)}async function we(r,e){let t=e.split("@")[0],o=(await x(r,{status:"in_progress"})).filter(i=>i.owner===e||i.owner===t),c=await Promise.allSettled(o.map(i=>Z(r,i.id,i.owner))),s=c.filter(i=>i.status==="rejected");s.length>0&&f.warn(`unassignTeammateTasks: ${s.length}/${o.length} task(s) failed to unassign for ${e}`);let n=c.filter(i=>i.status==="fulfilled"&&i.value===!0).length;return n>0&&k(r),n}async function ge(r){let e=await x(r),t=new Map;for(let a of e){if(!a.owner)continue;let o=t.get(a.owner)??{inProgress:0,completed:0};a.status==="in_progress"?o.inProgress++:a.status==="completed"&&o.completed++,t.set(a.owner,o)}return t}async function I(r){let e;try{e=await d.readdir(r)}catch{return"1"}let t=0;for(let a of e){if(!a.endsWith(".json"))continue;let o=parseInt(a.replace(".json",""),10);!isNaN(o)&&o>t&&(t=o)}return String(t+1)}export{z as a,G as b,m as c,ie as d,k as e,oe as f,ce as g,p as h,F as i,de as j,x as k,le as l,ue as m,fe as n,Z as o,we as p,ge as q};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Matilda
|