@maincode-ai/matilda-code 0.21.10-preview.0 → 0.21.10-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +9 -0
  2. package/chunks/agent-XXSEYARS.js +3 -0
  3. package/chunks/agent-headless-YBWTAFUH.js +3 -0
  4. package/chunks/{anthropicContentGenerator-SFJGSZHT.js → anthropicContentGenerator-IYZILRDW.js} +1 -1
  5. package/chunks/{askUserQuestion-G2H4VCRY.js → askUserQuestion-XWHJY3DM.js} +1 -1
  6. package/chunks/{chunk-INAZKGGR.js → chunk-2HQMJ2IU.js} +1 -1
  7. package/chunks/chunk-2W6MZZHZ.js +39 -0
  8. package/chunks/{todoWrite-3XJNFIBR.js → chunk-4CSSDBOS.js} +2 -2
  9. package/chunks/{chunk-5PMMY47S.js → chunk-4FVBPNTZ.js} +1 -1
  10. package/chunks/{chunk-TFWOXSAP.js → chunk-4TQ7ABLG.js} +14 -14
  11. package/chunks/{chunk-X6BEBYGX.js → chunk-66NIIU2R.js} +9 -9
  12. package/chunks/{chunk-32PTAACU.js → chunk-ELH4YHJR.js} +1 -1
  13. package/chunks/{chunk-FWIVFCKF.js → chunk-FFFZ2QMG.js} +1 -1
  14. package/chunks/{chunk-KSNBNXBC.js → chunk-FRRBNNEB.js} +48 -48
  15. package/chunks/{chunk-EQEQPZLQ.js → chunk-GO2GA2GY.js} +1 -1
  16. package/chunks/{chunk-QHA3ZBRO.js → chunk-GUFIMKF5.js} +1 -1
  17. package/chunks/{chunk-H6WMNUW2.js → chunk-HOCFKXNJ.js} +1 -1
  18. package/chunks/{chunk-VWWEEU4V.js → chunk-JXUDKX6D.js} +1 -1
  19. package/chunks/{chunk-VLYRNOD3.js → chunk-MH2P4YXC.js} +10 -10
  20. package/chunks/{chunk-6Q6PMGBD.js → chunk-MKFQMX37.js} +1 -1
  21. package/chunks/{chunk-VYTYYCBR.js → chunk-NYEWHSBL.js} +1 -1
  22. package/chunks/{chunk-LIWYWWOK.js → chunk-ODZOYHIC.js} +1 -1
  23. package/chunks/{chunk-Q2I3ARPJ.js → chunk-QH7736R5.js} +1 -1
  24. package/chunks/chunk-QN6WSWMM.js +9 -0
  25. package/chunks/{chunk-RJX7DK4Y.js → chunk-S4UT3QLV.js} +1 -1
  26. package/chunks/chunk-SNLH42QJ.js +10 -0
  27. package/chunks/{chunk-SE3XDSIJ.js → chunk-SPW5DXX4.js} +1 -1
  28. package/chunks/{chunk-S7G6QPEP.js → chunk-SUH3UUWZ.js} +1 -1
  29. package/chunks/{chunk-PIFQEMZZ.js → chunk-T4P4KEDW.js} +8 -8
  30. package/chunks/chunk-TO3ID3JW.js +35 -0
  31. package/chunks/{chunk-6ZMDAPGZ.js → chunk-VVIJGBQK.js} +566 -545
  32. package/chunks/{chunk-DCQKJTAX.js → chunk-W5CGKUM4.js} +8 -3
  33. package/chunks/{chunk-2PPJ3MJT.js → chunk-WHG6N5X2.js} +1 -1
  34. package/chunks/{chunk-GWGQRU36.js → chunk-WJO3QSBJ.js} +1 -1
  35. package/chunks/{chunk-XCJYORZX.js → chunk-XCFLI3OC.js} +1 -1
  36. package/chunks/{chunk-IJUI5A6G.js → chunk-YMIF2DMT.js} +1 -1
  37. package/chunks/chunk-YSIECQIZ.js +113 -0
  38. package/chunks/{computer-use-QN46FSNK.js → computer-use-HX2LYMYD.js} +7 -7
  39. package/chunks/contextCommand-W7DBC37U.js +3 -0
  40. package/chunks/{cron-create-MILWOYF6.js → cron-create-2UI4AT4Q.js} +1 -1
  41. package/chunks/{cron-delete-IEOPMRWP.js → cron-delete-ZB6BOTFF.js} +1 -1
  42. package/chunks/{cron-list-GGBUA7S7.js → cron-list-YYAXNHB6.js} +1 -1
  43. package/chunks/{edit-7AZARQPL.js → edit-HFUF2RN3.js} +1 -1
  44. package/chunks/{enter-worktree-GKYG5CD2.js → enter-worktree-LFCL64PJ.js} +1 -1
  45. package/chunks/{enterPlanMode-ICTG6ULZ.js → enterPlanMode-TREN7ULJ.js} +1 -1
  46. package/chunks/{exit-worktree-ZWYXIEIC.js → exit-worktree-MH2J4P42.js} +1 -1
  47. package/chunks/{exitPlanMode-5BQ4MY5I.js → exitPlanMode-PQO3EFFT.js} +1 -1
  48. package/chunks/{geminiContentGenerator-APSI54U5.js → geminiContentGenerator-FE5UVAOZ.js} +1 -1
  49. package/chunks/glob-VZAYMEQA.js +22 -0
  50. package/chunks/goal-tools-JN27F5BA.js +12 -0
  51. package/chunks/grep-2VT5TSRU.js +22 -0
  52. package/chunks/{keychain-token-storage-HAFQQIXL.js → keychain-token-storage-54BNK6VH.js} +1 -1
  53. package/chunks/{ls-FQYKJYAK.js → ls-YWZU3FYL.js} +1 -1
  54. package/chunks/{lsp-FGMC4KSB.js → lsp-4CJDKEEC.js} +1 -1
  55. package/chunks/{matildaAgentContentGenerator-HVIGLQJZ.js → matildaAgentContentGenerator-EYETUHCZ.js} +1 -1
  56. package/chunks/matildaContentGenerator-IWKH3YC4.js +8 -0
  57. package/chunks/{matildaOAuth2-W2DQO2NK.js → matildaOAuth2-GRS5K3D4.js} +1 -1
  58. package/chunks/monitor-AMIVJKDL.js +32 -0
  59. package/chunks/notebook-edit-BQUXXNEO.js +17 -0
  60. package/chunks/{openaiContentGenerator-X6TFPZGL.js → openaiContentGenerator-4M7WBW3G.js} +1 -1
  61. package/chunks/read-file-FNJZCMIZ.js +3 -0
  62. package/chunks/ripGrep-UOEUWYVF.js +3 -0
  63. package/chunks/scheduler-ASQLD6BW.js +8 -0
  64. package/chunks/{send-message-5PJPE34J.js → send-message-OO2HAKCC.js} +1 -1
  65. package/chunks/{serve-24HVCLFM.js → serve-FIDAAJAB.js} +1 -1
  66. package/chunks/shell-S732E2W4.js +3 -0
  67. package/chunks/{skill-HWDNN7P7.js → skill-VXNOQCSI.js} +1 -1
  68. package/chunks/src-QZENX46P.js +3 -0
  69. package/chunks/{symbol-search-BSE3FWJX.js → symbol-search-ALYOX5JN.js} +1 -1
  70. package/chunks/{syntheticOutput-DX4NN34N.js → syntheticOutput-UASKABJH.js} +1 -1
  71. package/chunks/task-create-EBJD55TB.js +3 -0
  72. package/chunks/{task-detach-TGM25ZIU.js → task-detach-I67ZE5MX.js} +1 -1
  73. package/chunks/{task-list-AZLBAQVL.js → task-list-5BGX4G5N.js} +1 -1
  74. package/chunks/{task-stop-B5PTXVMO.js → task-stop-ERI5X4AO.js} +1 -1
  75. package/chunks/{task-update-ARPBRTC5.js → task-update-CD3W556L.js} +1 -1
  76. package/chunks/{team-create-D4N2QVBX.js → team-create-CXY3MRCE.js} +1 -1
  77. package/chunks/{team-delete-AGYMEW6E.js → team-delete-5U3GBFKJ.js} +1 -1
  78. package/chunks/todoWrite-YGG6AZ3A.js +3 -0
  79. package/chunks/{tool-search-LRVN3W5W.js → tool-search-AJ57WSJC.js} +1 -1
  80. package/chunks/{web-fetch-Y64RF72K.js → web-fetch-63M6GZQL.js} +1 -1
  81. package/chunks/{web-search-I3D4EN5B.js → web-search-OX2DPEVN.js} +1 -1
  82. package/chunks/{workflow-BSK53DUN.js → workflow-55OAJ6XH.js} +2 -2
  83. package/chunks/write-file-2TWXQRDB.js +15 -0
  84. package/cli.js +459 -462
  85. package/package.json +2 -2
  86. package/chunks/agent-U43GELHB.js +0 -3
  87. package/chunks/agent-headless-7STBERN4.js +0 -3
  88. package/chunks/chunk-2NBII5ND.js +0 -34
  89. package/chunks/chunk-BN2CPSZ5.js +0 -34
  90. package/chunks/chunk-HMZOLFRP.js +0 -10
  91. package/chunks/chunk-ROETRE5J.js +0 -9
  92. package/chunks/chunk-XJYPRCV7.js +0 -108
  93. package/chunks/contextCommand-7G5FHBBE.js +0 -3
  94. package/chunks/glob-NPEYXTA6.js +0 -22
  95. package/chunks/grep-4NQTKAN6.js +0 -22
  96. package/chunks/matildaContentGenerator-5VOBYNAJ.js +0 -8
  97. package/chunks/monitor-RMKMKOUY.js +0 -32
  98. package/chunks/notebook-edit-H3ZFKBLR.js +0 -17
  99. package/chunks/read-file-3J3ZMBI2.js +0 -3
  100. package/chunks/ripGrep-WDYTLRCE.js +0 -3
  101. package/chunks/scheduler-TKK5QECI.js +0 -8
  102. package/chunks/shell-YPEMRDRO.js +0 -3
  103. package/chunks/src-W5VAKS5Y.js +0 -3
  104. package/chunks/task-create-3PW7T36X.js +0 -3
  105. package/chunks/update-goal-KLUMJFUA.js +0 -16
  106. package/chunks/write-file-GDKSQBMU.js +0 -15
@@ -457,6 +457,15 @@ LSP server configuration is done through `.lsp.json` files in your project root
457
457
  | `advanced.bugCommand` | object | Configuration for the bug report command. Overrides the default URL for the `/bug` command. Properties: `urlTemplate` (string): A URL that can contain `{title}` and `{info}` placeholders. Example: `"bugCommand": { "urlTemplate": "https://bug.example.com/new?title={title}&info={info}" }` | `undefined` |
458
458
  | `plansDirectory` | string | Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. If unset, plan files are stored in `~/.matilda/plans`. **Requires restart.** If the directory is inside the project root, add it to `.gitignore` to avoid committing plan files. | `undefined` |
459
459
 
460
+ #### goal
461
+
462
+ How much a Goal may do on its own after you create it, or resume one whose budget is spent, before it stops and asks you to resume it. Raise these for long unattended runs. Changes apply to Goals created or resumed after a restart.
463
+
464
+ | Setting | Type | Description | Default |
465
+ | ------------------ | ------ | -------------------------------------------------------------------------------- | ---------- |
466
+ | `goal.tokenBudget` | number | Tokens a Goal may spend on its own. `-1` means unlimited. | `30000000` |
467
+ | `goal.turnBudget` | number | Goal turns that may finish before the Goal stops and asks. `-1` means unlimited. | `50` |
468
+
460
469
  #### mcpServers
461
470
 
462
471
  Configures connections to one or more Model-Context Protocol (MCP) servers for discovering and using custom tools. Matilda Code attempts to connect to each configured MCP server to discover available tools. If multiple MCP servers expose a tool with the same name, the tool names will be prefixed with the server alias you defined in the configuration (e.g., `serverAlias__actualToolName`) to avoid conflicts. Note that the system might strip certain schema properties from MCP tool definitions for compatibility. At least one of `command`, `url`, or `httpUrl` must be provided. If multiple are specified, the order of precedence is `httpUrl`, then `url`, then `command`.
@@ -0,0 +1,3 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{lg as a,mg as b,ng as c,og as d,pg as e,qg as f}from"./chunk-VVIJGBQK.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-TO3ID3JW.js";import"./chunk-MKFQMX37.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-4CSSDBOS.js";import"./chunk-JXUDKX6D.js";import"./chunk-66NIIU2R.js";import"./chunk-GUFIMKF5.js";import"./chunk-YSIECQIZ.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-FRRBNNEB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import"./chunk-T4P4KEDW.js";import"./chunk-S4UT3QLV.js";import"./chunk-XCFLI3OC.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.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{Mf as a,Nf as b,Of as c}from"./chunk-VVIJGBQK.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-TO3ID3JW.js";import"./chunk-MKFQMX37.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-4CSSDBOS.js";import"./chunk-JXUDKX6D.js";import"./chunk-66NIIU2R.js";import"./chunk-GUFIMKF5.js";import"./chunk-YSIECQIZ.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-FRRBNNEB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import"./chunk-T4P4KEDW.js";import"./chunk-S4UT3QLV.js";import"./chunk-XCFLI3OC.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.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};
@@ -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-LIWYWWOK.js";import{c as An,f as we}from"./chunk-QHA3ZBRO.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-S7G6QPEP.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{aa as bn}from"./chunk-VLYRNOD3.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-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]!==`
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-PIFQEMZZ.js";import{aa as d}from"./chunk-VLYRNOD3.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:
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-T4P4KEDW.js";import{ba as d}from"./chunk-MH2P4YXC.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
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as X,g as T}from"./chunk-DCQKJTAX.js";import{b as P}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-EQEQPZLQ.js";import{aa as $,b as l}from"./chunk-VLYRNOD3.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};
3
+ import{b as X,h as T}from"./chunk-W5CGKUM4.js";import{b as P}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-GO2GA2GY.js";import{b as l,ba as $}from"./chunk-MH2P4YXC.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
@@ -0,0 +1,39 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as ye}from"./chunk-ODZOYHIC.js";import{c as V,f as O}from"./chunk-GUFIMKF5.js";import{M as pe,N as ce,O as _,Q as de,R as F,S as me,a as re,g as R,h as ae,ha as ge,na as be}from"./chunk-YSIECQIZ.js";import{a as Ce}from"./chunk-DC7LAFZZ.js";import{a as oe,g as ie,k as se,l as N,o as ue,t as fe,v as he}from"./chunk-SUH3UUWZ.js";import{e as ne}from"./chunk-4J6DC24J.js";import{b as j,c as W,f as le,n as q}from"./chunk-SDTWBD62.js";import{b as z}from"./chunk-ESSYHTAZ.js";import{a as H,ba as P,c as Z,e as ee,q as J,s as te,t as K}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Me(a){return a.toLowerCase().includes("matilda3")}function ve(a){if(a.role!=="assistant")return a;let e=a;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?a:{...e,reasoning:e.reasoning_content}}var h=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:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,i]of Object.entries(n??{}))le(o)||(r[o]=i);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=V("openai",this.cliConfig.getProxy());return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...i||{}})}buildRequest(e,t){let n=this.contentGeneratorConfig.extra_body,r=this.applyOutputTokenLimit(e),o=Me(e.model)?r.messages.map(ve):r.messages;return{...r,messages:o,...n||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,n=he(e.model,"output"),r=fe(e.model),o;if(t!=null)r?o=Math.min(t,n):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=i?parseInt(i,10):NaN;!isNaN(s)&&s>0?o=r?Math.min(s,n):s:o=Math.min(n,8e3)}return{...e,max_tokens:o}}};var k=class extends h{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let n=super.buildRequest(e,t);return n.stream||delete n.stream_options,n}};p();p();var G=class extends Error{constructor(t,n){super(`No stream activity for ${t}ms after ${n} chunks.`);this.idleMs=t;this.chunksReceived=n;this.name="StreamInactivityTimeoutError"}code="ETIMEDOUT"};function Ae(a,e){return async(t,n)=>{let r=new AbortController,o=n?.signal??void 0,i=()=>r.abort(o?.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",i,{once:!0});let s=()=>o?.removeEventListener("abort",i),l;try{l=await a(t,{...n,signal:r.signal})}catch(C){throw s(),C}let m=l.headers.get("content-type")??"";if(!l.body||!m.includes("text/event-stream"))return l;let c=l.body.getReader(),f=0,u,b=new ReadableStream({async pull(C){let d=new Promise((g,E)=>{u=setTimeout(()=>E(new G(e,f)),e)});try{let g=await Promise.race([c.read(),d]);if(g.done){s(),C.close();return}f+=1,C.enqueue(g.value)}catch(g){s(),C.error(g),g instanceof G&&r.abort(g)}finally{clearTimeout(u)}},cancel(C){return clearTimeout(u),s(),c.cancel(C)}}),y=new Response(b,{status:l.status,statusText:l.statusText,headers:l.headers});return Object.defineProperty(y,"url",{value:l.url}),y}}var we=P("MatildaOpenAICompatibleProvider"),A=class a extends h{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:n}=e;if(t==="matilda-oauth"||!n)return!0;let r=n.endsWith("/")?n.slice(0,-1):n,o=null;try{o=new URL(r).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"),s=N?.endsWith("/")?N.slice(0,-1):N,l=!!(s&&r.toLowerCase()===s.toLowerCase());return s&&!i&&!l&&we.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,i]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=i);return _(this.contentGeneratorConfig)&&Object.assign(r,pe(this.cliConfig)),r}buildClient(){let{apiKey:e,baseUrl:t=se,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=V("openai",this.cliConfig.getProxy()),s=i?.fetch??globalThis.fetch,l=Ae(s,24e4),m=_(this.contentGeneratorConfig)?async(c,f)=>{let u=new Headers(c instanceof Request?c.headers:void 0);new Headers(f?.headers).forEach((d,g)=>{u.set(g,d)});let b=u.has(j)||u.has(W),y=q(),C=b||Object.keys(y).length>0;if(C){u.delete(j),u.delete(W);for(let[g,E]of Object.entries(y))u.set(g,E);let d=u.get("x-stainless-retry-count");u.has(j)&&d!==null&&/^[1-9][0-9]*$/.test(d)&&u.set(W,"retry")}this.cliConfig.getChannel()===void 0&&de({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let d=await l(c,C?{...f,headers:u}:f);return me({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),d}catch(d){throw F(d,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),d}}:void 0;return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...i||{},...m?{fetch:m}:{}})}buildRequest(e,t){let n=e.messages,r=e.tools;if(this.shouldEnableCacheControl()){let{messages:s,tools:l}=this.addCacheControl(e,e.stream?"all":"system_only");n=s,r=l}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:n,...r?{tools:r}:{},...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 n=e.messages,r=n.findIndex(l=>l.role==="system"),o=n.length-1,i=n.length===0?n:n.map((l,m)=>!(m===r&&r!==-1||m===o&&t==="all")||!("content"in l)||l.content===null||l.content===void 0?l:{...l,content:this.addCacheControlToContent(l.content)}),s=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:s}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],n=e.length-1;return t[n]={...t[n],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(a.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of a.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function B(a){if(a.role!=="assistant")return a;let e=a;return typeof e.reasoning_content=="string"?a:{...e,reasoning_content:""}}function S(a){let e=a.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 Ee(a){return S(a)?!0:(a.model??"").toLowerCase().includes("deepseek")}var T=class extends h{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ee;static isDeepSeekHostname=S;buildRequest(e,t){let n=super.buildRequest(e,t),r=S(this.contentGeneratorConfig)?Ge(n):n;if(!r.messages?.length)return r;let o=r.messages.map(i=>{let s=ke(i);return B(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ke(a){if(!("content"in a))return a;let{content:e}=a;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return a;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
4
+
5
+ `);return{...a,content:t}}function Ge(a){let e=a,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return a;let r={...e};if(typeof r.reasoning_effort!="string"||!r.reasoning_effort){let o=n;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),r.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete r.reasoning;else if(t){let{effort:o,...i}=t;r.reasoning=i}return r}p();var I=class extends h{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"}}};p();var _e=["api.minimaxi.com","api.minimax.io"],Se=[".minimaxi.com",".minimax.io"],M=class extends h{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return _e.includes(t)?!0:Se.some(n=>t.endsWith(n))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};p();var Pe="api.mistral.ai",Le=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ue(a){let e=a.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Pe||t.endsWith(`.${Pe}`)}catch{return!1}}function De(a){if(Ue(a))return!0;let e=a.model?.toLowerCase()??"";return Le.some(t=>e.includes(t))}var v=class extends h{static isMistralProvider=De;buildRequest(e,t){let n=super.buildRequest(e,t);return{...n,messages:n.messages.map(He)}}};function He(a){if(!("reasoning_content"in a))return a;let e={...a};return delete e.reasoning_content,e}p();function Ne(a){let e=a.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(a.model??"").toLowerCase().startsWith("mimo-")}var x=class extends h{constructor(e,t){super(e,t)}static isMiMoProvider=Ne;buildRequest(e,t){let n=super.buildRequest(e,t);return n.messages?.length?{...n,messages:n.messages.map(B)}:n}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};p();p();var je=P("STREAMING_TOOL_CALL_PARSER"),$=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,n,r){let o=e,i=!!(n&&this.idToIndexMap.has(n));if(n)if(this.idToIndexMap.has(n))o=this.idToIndexMap.get(n);else{if(this.buffers.has(e)){let d=this.buffers.get(e),g=this.depths.get(e),E=this.toolCallMeta.get(e);if(d.trim()&&g===0&&E?.id&&E.id!==n)try{JSON.parse(d),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(n,o)}else if(this.buffers.has(e)){let d=this.buffers.get(e);if(this.depths.get(e)>0||!d.trim())o=e;else try{JSON.parse(d),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 s=this.buffers.get(o),l=this.depths.get(o);if(i&&s.trim()&&l===0)try{return JSON.parse(s),je.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let m=this.toolCallMeta.get(o);n&&(m.id=n),r&&(m.name=r);let c=this.inStrings.get(o),f=this.escapes.get(o),u=s+t;this.buffers.set(o,u);let b=l,y=c,C=f;for(let d of t)y||(d==="{"||d==="["?b++:(d==="}"||d==="]")&&b--),d==='"'&&!C&&(y=!y),C=d==="\\"&&!C;if(this.depths.set(o,b),this.inStrings.set(o,y),this.escapes.set(o,C),b===0&&u.trim().length>0)try{return{complete:!0,value:JSON.parse(u)}}catch(d){if(y)try{return{complete:!0,value:JSON.parse(u+'"'),repaired:!0}}catch{}return{complete:!1,error:d instanceof Error?d:new Error(String(d))}}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=[],n=new Set;for(let[r,o]of this.buffers.entries()){let i=this.toolCallMeta.get(r);if(i?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(i.id){if(n.has(i.id))continue;n.add(i.id)}let m;if(!o.trim())m={};else try{m=JSON.parse(o)}catch{if(!e)continue;let c=oe(o,null);if(!c||typeof c!="object")continue;m=c}t.push({id:i.id,name:i.name,args:m,index:r})}}return t}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),n=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!n?.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,n]of this.buffers.entries()){let r=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(r>0||!n.trim()))e=Math.max(e,t);else if(n.trim())try{JSON.parse(n)}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 n=this.toolCallMeta.get(e),r=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(r>0||o)return!0;if(!n?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var Re=16e3,Oe=`[Earlier content omitted to fit Matilda Core external API limits]
6
+ `,X=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},L=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(n,r)=>{let o=e.config?.abortSignal,i=o?z(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:i?.signal,...s?{headers:s}:{}});return R.convertOpenAIResponseToGemini(l,r)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,i=o?z(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:i?.signal,...s?{headers:s}:{}})}catch(u){throw i?.abort(),u}if(!i)return this.processStreamWithLogging(l,r,e);let m=i,c=this.processStreamWithLogging(l,r,e);async function*f(){try{yield*c}finally{m.abort()}}return f()})}reportedOperationHeaders(){if(!_(this.contentGeneratorConfig))return;let e=q();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null,i=!1;try{for await(let s of e){if(s.choices?.[0]?.finish_reason==="error_finish"){let c=s.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new X(c)}let l=R.convertOpenAIChunkToGemini(s,t);if(l.candidates?.[0]?.content?.parts?.length===0&&!l.candidates?.[0]?.finishReason&&!l.usageMetadata)continue;if(i){if(l.usageMetadata){let c=o;c&&(c.usageMetadata=l.usageMetadata)}r.push(l);continue}this.handleChunkMerging(l,r,c=>{o=c})&&(o?(yield o,i=!0):yield l)}if(!o&&!i){let s=R.flushOpenAIStreamToGemini(t);s&&(yield s,i=!0)}o&&!i&&(yield o)}catch(s){if(s instanceof X)throw O(s);await this.handleError(s,t,n)}}handleChunkMerging(e,t,n){let r=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(r){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),n(i)}else t.push(e),n(e);return!1}else if(o){let i=t[t.length-1],s=new ne;return s.candidates=i.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=i.usageMetadata,s.responseId=e.responseId,s.createTime=e.createTime,s.modelVersion=e.modelVersion,s.promptFeedback=e.promptFeedback,t[t.length-1]=s,n(s),!0}return t.push(e),!0}async buildRequest(e,t,n,r){let o=R.convertGeminiRequestToOpenAI(e,n),i=this.shouldUseMatildaCoreRequestProfile(),s=i?this.toMatildaCoreUserMessages(o):o,l={model:n.model,messages:s,...this.buildGenerateContentConfig(e)};r?(l.stream=!0,l.stream_options={include_usage:!0}):l.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await R.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let m=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let f=m,u=(n.model??"").toLowerCase();if(A.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(u.startsWith("matilda")||u==="coder-model")){f.enable_thinking=!1;let b=f.chat_template_kwargs;typeof b=="object"&&b!==null&&"enable_thinking"in b&&(f.chat_template_kwargs={...b,enable_thinking:!1})}"reasoning"in f&&delete f.reasoning,"reasoning_effort"in f&&delete f.reasoning_effort,S(this.contentGeneratorConfig)&&(f.thinking={type:"disabled"})}return m}toMatildaCoreUserMessages(e){let t=e.filter(n=>n.role==="user").map(n=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(n.content))})).filter(n=>n.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 n=this.contentGeneratorConfig.customHeaders??{};return Object.entries(n).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(`
7
+ `):""}sanitizeMatildaUserContent(e){let n=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(n.length<=Re)return n;let r=Re-Oe.length;return`${Oe}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let m=n?.[s],c=l?e.config?.[l]:void 0,f=l?t[l]:void 0;return m!==void 0?m:c!==void 0?c:f},o=(s,l,m)=>{let c=r(l,m);return c!==void 0?{[s]:c}:{}};if(n!==void 0){let s=e.config?.maxOutputTokens;return{...n,...s!==void 0&&n.max_tokens!==void 0?{max_tokens:s}:{}}}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,n,r){let o=this.createRequestContext(e,n);try{let i=await this.buildRequest(e,t,o,n);return ae.getStore()?.(i),ie.recordOpenAIWireRequest(i),await r(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(O(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new $:void 0,i=this.config.provider.getResponseParsingOptions?.(),s=t&&i?.taggedThinkingTags?new re:void 0;return{model:n,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:r.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...s?{taggedThinkingParser:s}:{}}}};p();var We=P("OPENAI_ERROR"),U=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=O(e),o=!(r instanceof G)&&this.isTimeoutError(r),i=this.buildErrorMessage(r,t,o);if(this.shouldSuppressErrorLogging(r,n)||We.error("OpenAI API Error:",i),o){let s=new Error(`${i}
8
+
9
+ ${this.getTimeoutTroubleshootingTips()}`,{cause:r}),l=ee(r);throw l!==void 0?Object.assign(s,{status:l}):s}throw r}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(),n=e?.code,r=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")||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||r==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,n){let r=Math.round((Date.now()-t.startTime)/1e3);return n?`Request timeout after ${r}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
10
+ ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
11
+ `)}`}};var Te=P("OPENAI"),w=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new U((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new L(r)}shouldSuppressErrorLogging(e,t){return!!(Z(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 ye().calculateTokens(e)).totalTokens}}catch(t){Te.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(n=>typeof n=="string"?n:"parts"in n&&n.parts?n.parts.map(r=>typeof r=="string"?r:"text"in r&&r.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(n=>typeof n=="string"?n:"text"in n?n.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(n){let r=O(n);throw Te.error("OpenAI API Embedding Error:",r),new Error(`OpenAI API error: ${r instanceof Error?r.message:String(r)}`)}}useSummarizedThinking(){return!1}};p();var D=class extends w{contentGeneratorConfig;cliConfig;channel;constructor(e,t,n){super(e,t,n),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return Ie(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=()=>super.generateContentStream(e,t),r=await this.withTokenRefresh(n);return this.iterateWithAuthRetry(r,n)}async*iterateWithAuthRetry(e,t){let n=!1;try{for await(let r of e)n||=(r.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield r;return}catch(r){if(!this.isSessionAuthError(r))throw this.toAuthRecoveryError(r);if(n)throw new J("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw this.toAuthRecoveryError(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await be({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(n){throw F(n,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),n}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[Ce]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!this.isSessionAuthError(t))throw this.toAuthRecoveryError(t);await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(n){throw this.toAuthRecoveryError(n)}}}isSessionAuthError(e){return Ie(e)&&ge({baseUrl:this.contentGeneratorConfig.baseUrl,channel:this.channel})}toAuthRecoveryError(e){return K(e)?new te:this.isSessionAuthError(e)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):e}};function Ie(a){if(!a||K(a))return!1;let e=a instanceof Error?a.message.toLowerCase():String(a).toLowerCase(),t=a,n=Number(t.status??t.statusCode??t.code);return n>=400&&n<600?n===401:e.includes("unauthorized")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("token")&&e.includes("expired")}function _n(a,e){let t=qe(a,e);return A.isMatildaCompatibleProvider(a)?new D(a,e,t):new w(a,e,t)}function qe(a,e){let t=a||e.getContentGeneratorConfig();return A.isMatildaCompatibleProvider(t)?new A(a,e):T.isDeepSeekProvider(t)?new T(a,e):x.isMiMoProvider(t)?new x(a,e):I.isOpenRouterProvider(t)?new I(a,e):k.isModelScopeProvider(t)?new k(a,e):M.isMiniMaxProvider(t)?new M(a,e):v.isMistralProvider(t)?new v(a,e):new h(a,e)}export{A as a,T as b,I as c,M as d,v as e,x as f,L as g,U as h,w as i,D as j,_n as k,qe as l};
12
+ /**
13
+ * @license
14
+ * Copyright 2026 Matilda
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Matilda
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ /**
23
+ * @license
24
+ * Copyright 2026 Maincode
25
+ * SPDX-License-Identifier: Apache-2.0
26
+ *
27
+ * OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
28
+ *
29
+ * Emulates Grok Build's automatic credential refresh
30
+ * (docs: "Automatic Credential Refresh"):
31
+ * 1. Before each request: ensure a fresh access token (re-read disk; refresh
32
+ * when within the early-invalidation window / already expired).
33
+ * 2. On 401 Unauthorized: force-refresh and retry the request once.
34
+ * 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
35
+ *
36
+ * Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
37
+ * createContentGenerator time, so idle sessions past access-token expiry
38
+ * failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
39
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{y as S}from"./chunk-VWWEEU4V.js";import{g as E,i as O,p as P,q as W}from"./chunk-PIFQEMZZ.js";import{b as C}from"./chunk-EQEQPZLQ.js";import{P as y,aa as I}from"./chunk-VLYRNOD3.js";import"./chunk-FWDMPRKU.js";import{b as x}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";x();import*as h from"fs/promises";import*as U from"fs";import*as u from"path";var R=I("TODO_WRITE"),j={name:"todo_write",description:"Creates and manages a structured task list for your current coding session. This helps track progress, organize complex tasks, and demonstrate thoroughness.",parametersJsonSchema:{type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1},status:{type:"string",enum:["pending","in_progress","completed"]},id:{type:"string"}},required:["content","status","id"],additionalProperties:!1},description:"The updated todo list"}},required:["todos"],$schema:"http://json-schema.org/draft-07/schema#"}},q=`
3
+ import{y as S}from"./chunk-JXUDKX6D.js";import{g as E,i as O,p as P,q as W}from"./chunk-T4P4KEDW.js";import{b as C}from"./chunk-GO2GA2GY.js";import{Q as y,ba as I}from"./chunk-MH2P4YXC.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();import*as h from"fs/promises";import*as U from"fs";import*as u from"path";var R=I("TODO_WRITE"),j={name:"todo_write",description:"Creates and manages a structured task list for your current coding session. This helps track progress, organize complex tasks, and demonstrate thoroughness.",parametersJsonSchema:{type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1},status:{type:"string",enum:["pending","in_progress","completed"]},id:{type:"string"}},required:["content","status","id"],additionalProperties:!1},description:"The updated todo list"}},required:["todos"],$schema:"http://json-schema.org/draft-07/schema#"}},q=`
4
4
  Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
5
5
  It also helps the user understand the progress of the task and overall progress of their requests.
6
6
 
@@ -204,7 +204,7 @@ ${_}. Continue on with the tasks at hand if applicable.
204
204
 
205
205
  <system-reminder>
206
206
  Todo list modification failed with error: ${i}. You may need to retry or handle this error appropriately.
207
- </system-reminder>`,returnDisplay:`Error writing todos: ${i}`}}}};async function X(s){return F(s)}async function Z(){try{let s=u.join(y.getRuntimeBaseDir(),N);return(await h.readdir(s)).filter(e=>e.endsWith(".json")).map(e=>e.replace(".json",""))}catch(s){let n=s;if(!(n instanceof Error)||n.code!=="ENOENT")throw s;return[]}}var D=class s extends O{constructor(e){super(s.Name,W.TODO_WRITE,q,"think",j.parametersJsonSchema);this.config=e}static Name=P.TODO_WRITE;validateToolParams(e){if(!Array.isArray(e.todos))return'Parameter "todos" must be an array.';for(let a of e.todos){if(!a.id||typeof a.id!="string"||a.id.trim()==="")return'Each todo must have a non-empty "id" string.';if(!a.content||typeof a.content!="string"||a.content.trim()==="")return'Each todo must have a non-empty "content" string.';if(!["pending","in_progress","completed"].includes(a.status))return'Each todo must have a valid "status" (pending, in_progress, completed).'}let r=e.todos.map(a=>a.id),l=new Set(r);return r.length!==l.size?"Todo IDs must be unique within the array.":null}createInvocation(e){let r=this.config.getSessionId(),l=T(r),a=U.existsSync(l)?"update":"create";return new k(this.config,e,a)}};export{D as TodoWriteTool,Z as listTodoSessions,X as readTodosForSession};
207
+ </system-reminder>`,returnDisplay:`Error writing todos: ${i}`}}}};async function X(s){return F(s)}async function Z(){try{let s=u.join(y.getRuntimeBaseDir(),N);return(await h.readdir(s)).filter(e=>e.endsWith(".json")).map(e=>e.replace(".json",""))}catch(s){let n=s;if(!(n instanceof Error)||n.code!=="ENOENT")throw s;return[]}}var D=class s extends O{constructor(e){super(s.Name,W.TODO_WRITE,q,"think",j.parametersJsonSchema);this.config=e}static Name=P.TODO_WRITE;validateToolParams(e){if(!Array.isArray(e.todos))return'Parameter "todos" must be an array.';for(let a of e.todos){if(!a.id||typeof a.id!="string"||a.id.trim()==="")return'Each todo must have a non-empty "id" string.';if(!a.content||typeof a.content!="string"||a.content.trim()==="")return'Each todo must have a non-empty "content" string.';if(!["pending","in_progress","completed"].includes(a.status))return'Each todo must have a valid "status" (pending, in_progress, completed).'}let r=e.todos.map(a=>a.id),l=new Set(r);return r.length!==l.size?"Todo IDs must be unique within the array.":null}createInvocation(e){let r=this.config.getSessionId(),l=T(r),a=U.existsSync(l)?"update":"create";return new k(this.config,e,a)}};export{X as a,Z as b,D as c};
208
208
  /**
209
209
  * @license
210
210
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{w as i}from"./chunk-32PTAACU.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();import l from"node:path";function d(t,n){if(t.getApprovalMode()!=="bogan")return null;let r=l.resolve(n),s=t.getProjectRoot?.()??t.getTargetDir();if(i(r,s))return null;let e=t.getWorkspaceContext?.();if(!e||(typeof e.isPathWithinWorkspaceFresh=="function"?e.isPathWithinWorkspaceFresh(r):e.isPathWithinWorkspace(r)))return null;let a=e.getDirectories?.()??[t.getTargetDir()],p=t.getChannel?.()==="desktop"?"Approve the folder from Matilda Desktop, then retry the write.":"Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.";return`Refusing out-of-workspace write in BOGAN mode: ${r}. Workspace root(s): ${a.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+p}export{d as a};
3
+ import{w as i}from"./chunk-ELH4YHJR.js";import{b as o}from"./chunk-GZPNIYVZ.js";o();import l from"node:path";function d(t,n){if(t.getApprovalMode()!=="bogan")return null;let r=l.resolve(n),s=t.getProjectRoot?.()??t.getTargetDir();if(i(r,s))return null;let e=t.getWorkspaceContext?.();if(!e||(typeof e.isPathWithinWorkspaceFresh=="function"?e.isPathWithinWorkspaceFresh(r):e.isPathWithinWorkspace(r)))return null;let a=e.getDirectories?.()??[t.getTargetDir()],p=t.getChannel?.()==="desktop"?"Approve the folder from Matilda Desktop, then retry the write.":"Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.";return`Refusing out-of-workspace write in BOGAN mode: ${r}. Workspace root(s): ${a.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+p}export{d as a};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda Team