@maincode-ai/matilda-code 0.21.11 → 0.21.12

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 (123) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +16 -5
  2. package/bundled/mainy/docs/configuration/trusted-folders.md +12 -6
  3. package/chunks/agent-WM63A6NK.js +3 -0
  4. package/chunks/agent-headless-QIUBDKPW.js +3 -0
  5. package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js} +1 -1
  6. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-2QI4NSFJ.js} +1 -1
  7. package/chunks/{ca-EUJBUYX5.js → ca-I2HEEIL7.js} +1 -1
  8. package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
  9. package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
  10. package/chunks/{chunk-2HQMJ2IU.js → chunk-2MOGYHWM.js} +1 -1
  11. package/chunks/{chunk-WRQLIPXW.js → chunk-3IRGBRSP.js} +10 -10
  12. package/chunks/{chunk-NIQK6NX3.js → chunk-5C2RJ5RR.js} +1 -1
  13. package/chunks/{chunk-T4P4KEDW.js → chunk-6E766NPX.js} +1 -1
  14. package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
  15. package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
  16. package/chunks/{chunk-25NCTG5H.js → chunk-6Z2MV7ZY.js} +55 -53
  17. package/chunks/chunk-BVOCFLC4.js +56 -0
  18. package/chunks/chunk-CSJTA7NE.js +101 -0
  19. package/chunks/{chunk-SNLH42QJ.js → chunk-CZGZ3KK7.js} +1 -1
  20. package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
  21. package/chunks/{chunk-4CSSDBOS.js → chunk-DOOFGSRV.js} +10 -10
  22. package/chunks/{chunk-RK2AKQAX.js → chunk-FPO57O66.js} +6 -6
  23. package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
  24. package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
  25. package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
  26. package/chunks/chunk-JRECUFB3.js +2630 -0
  27. package/chunks/chunk-KHHJYBR5.js +9 -0
  28. package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
  29. package/chunks/{chunk-5427BPR2.js → chunk-MCQUPLRE.js} +1 -1
  30. package/chunks/{chunk-QN6WSWMM.js → chunk-MO2HXJG5.js} +1 -1
  31. package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
  32. package/chunks/{chunk-Q55AVE2N.js → chunk-QVCGLQCI.js} +11 -11
  33. package/chunks/{chunk-W5CGKUM4.js → chunk-S3CWEVTS.js} +1 -1
  34. package/chunks/{chunk-YMIF2DMT.js → chunk-VTGICC67.js} +1 -1
  35. package/chunks/chunk-WC2VTVCE.js +27 -0
  36. package/chunks/{chunk-SPW5DXX4.js → chunk-WV3IUPZS.js} +1 -1
  37. package/chunks/{chunk-4YVN5HXG.js → chunk-YJAKOETP.js} +2 -2
  38. package/chunks/{chunk-WHG6N5X2.js → chunk-YRQP3SLC.js} +1 -1
  39. package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
  40. package/chunks/{computer-use-SXP25RZQ.js → computer-use-WKDNUTLD.js} +1 -1
  41. package/chunks/contextCommand-DAB3HOHY.js +3 -0
  42. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-F2LXM2OA.js} +1 -1
  43. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-DE6Q2S2L.js} +1 -1
  44. package/chunks/{cron-list-YYAXNHB6.js → cron-list-IAQEJVV7.js} +1 -1
  45. package/chunks/{de-DNEPG7S7.js → de-AQXFJYZI.js} +1 -1
  46. package/chunks/edit-QQNJZ55P.js +43 -0
  47. package/chunks/{en-NOD6KQNM.js → en-EJLDYIBM.js} +1 -1
  48. package/chunks/{enter-worktree-X47BSJLE.js → enter-worktree-5X5SAMBJ.js} +1 -1
  49. package/chunks/{enterPlanMode-F22ZNTYJ.js → enterPlanMode-HP35SPLN.js} +1 -1
  50. package/chunks/{exit-worktree-XY5UMDHX.js → exit-worktree-SRKZBEYF.js} +1 -1
  51. package/chunks/exitPlanMode-WSPTGGVN.js +120 -0
  52. package/chunks/{fr-2OE5WLJ4.js → fr-6TDHK7F2.js} +1 -1
  53. package/chunks/{geminiContentGenerator-EQEGOXOV.js → geminiContentGenerator-RJ73DQAP.js} +1 -1
  54. package/chunks/{glob-KSBEWI3E.js → glob-QQ6LGKDX.js} +1 -1
  55. package/chunks/{goal-tools-6QTC3UI7.js → goal-tools-C6BSBHCF.js} +1 -1
  56. package/chunks/{grep-6TTPZ524.js → grep-MVCOBUYW.js} +1 -1
  57. package/chunks/{ja-3B6V5KS7.js → ja-GGNJR7AR.js} +1 -1
  58. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
  59. package/chunks/{ls-YWZU3FYL.js → ls-JYJXFSXN.js} +1 -1
  60. package/chunks/{lsp-4CJDKEEC.js → lsp-DYDK6XCS.js} +1 -1
  61. package/chunks/{matildaAgentContentGenerator-OV4U6DJD.js → matildaAgentContentGenerator-YUYS4336.js} +1 -1
  62. package/chunks/{matildaContentGenerator-ETIAWE22.js → matildaContentGenerator-O4Z2QPCP.js} +1 -1
  63. package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-7COTQQR2.js} +1 -1
  64. package/chunks/mcp-client-RXVQU5VI.js +3 -0
  65. package/chunks/monitor-77KXDXPR.js +32 -0
  66. package/chunks/{notebook-edit-TL7CI5EA.js → notebook-edit-TKJD2EQZ.js} +1 -1
  67. package/chunks/{openaiContentGenerator-MGASUFQL.js → openaiContentGenerator-2EALAM3U.js} +1 -1
  68. package/chunks/{pt-KP2JCPUY.js → pt-D6L2QTDM.js} +1 -1
  69. package/chunks/read-file-3KUAH6ND.js +3 -0
  70. package/chunks/ripGrep-U2PLKXMY.js +3 -0
  71. package/chunks/{ru-K7IQQKHC.js → ru-BNJCHDYO.js} +1 -1
  72. package/chunks/{scheduler-TKWPD4LP.js → scheduler-J7VU2V5Y.js} +1 -1
  73. package/chunks/{send-message-OO2HAKCC.js → send-message-P3SMWNEE.js} +1 -1
  74. package/chunks/{serve-ZQX2WBLF.js → serve-FXH6EBQ6.js} +36 -36
  75. package/chunks/shell-PXR2AXDD.js +3 -0
  76. package/chunks/{skill-KDM3UUML.js → skill-HZPFEAPF.js} +1 -1
  77. package/chunks/src-RFAEPLY7.js +3 -0
  78. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-EAIZPWN7.js} +1 -1
  79. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-432LXITX.js} +1 -1
  80. package/chunks/task-create-Z3QRCMX4.js +3 -0
  81. package/chunks/{task-detach-I67ZE5MX.js → task-detach-XMSJ3HBM.js} +1 -1
  82. package/chunks/{task-list-5BGX4G5N.js → task-list-GXAJW3JP.js} +1 -1
  83. package/chunks/{task-stop-ERI5X4AO.js → task-stop-NTS62FLG.js} +1 -1
  84. package/chunks/{task-update-CD3W556L.js → task-update-AR26UFYZ.js} +1 -1
  85. package/chunks/{team-create-F4KQRGMB.js → team-create-PYXFVIR5.js} +1 -1
  86. package/chunks/{team-delete-5U3GBFKJ.js → team-delete-OMYVUAQU.js} +1 -1
  87. package/chunks/todoWrite-5NZ7CHTC.js +3 -0
  88. package/chunks/{tool-search-JFCD5W5M.js → tool-search-RKZDSRYS.js} +1 -1
  89. package/chunks/tree-sitter-bash-2SWKO5B7.js +3 -0
  90. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-VW3SVDQ6.js} +13 -13
  91. package/chunks/{web-search-OX2DPEVN.js → web-search-XQUIZARL.js} +1 -1
  92. package/chunks/{workflow-SEFYGBED.js → workflow-YXNXDRWZ.js} +2 -2
  93. package/chunks/{write-file-UAGVBZMC.js → write-file-XDDLTGSG.js} +1 -1
  94. package/cli.js +459 -449
  95. package/locales/ca.js +1 -0
  96. package/locales/de.js +1 -0
  97. package/locales/en.js +1 -0
  98. package/locales/fr.js +1 -0
  99. package/locales/ja.js +1 -0
  100. package/locales/pt.js +1 -0
  101. package/locales/ru.js +1 -0
  102. package/package.json +2 -2
  103. package/sandbox-macos-restrictive-closed.sb +3 -0
  104. package/sandbox-macos-restrictive-open.sb +3 -0
  105. package/sandbox-macos-restrictive-proxied.sb +3 -0
  106. package/chunks/agent-ZFZ4HJQC.js +0 -3
  107. package/chunks/agent-headless-KH2BKLP7.js +0 -3
  108. package/chunks/chunk-GHBKFIHC.js +0 -35
  109. package/chunks/chunk-HWOQNYAO.js +0 -27
  110. package/chunks/chunk-NVM7W7TG.js +0 -101
  111. package/chunks/chunk-QFNFLE2I.js +0 -2625
  112. package/chunks/chunk-XCFLI3OC.js +0 -9
  113. package/chunks/contextCommand-3GN5CAOK.js +0 -3
  114. package/chunks/edit-KX6V4PH3.js +0 -39
  115. package/chunks/exitPlanMode-G3QLIWJ4.js +0 -90
  116. package/chunks/monitor-F4K5HOZX.js +0 -32
  117. package/chunks/read-file-6EAPS2KG.js +0 -3
  118. package/chunks/ripGrep-K6SFFUIE.js +0 -3
  119. package/chunks/shell-AZRK5GIO.js +0 -3
  120. package/chunks/src-SGI6VLOS.js +0 -3
  121. package/chunks/task-create-EBJD55TB.js +0 -3
  122. package/chunks/todoWrite-YGG6AZ3A.js +0 -3
  123. package/chunks/tree-sitter-bash-XNCMPQBK.js +0 -3
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as c}from"./chunk-HYVP4472.js";import{p as u}from"./chunk-T4P4KEDW.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{AsyncLocalStorage as h}from"node:async_hooks";var a=new h,r=new WeakMap,p={turns:"max_turn_requests",session_turns:"max_turn_requests",loop_detected:"max_turn_requests",continuations:"max_turn_requests",session_tokens:"max_tokens"},k=class{jobs=new Map;joinsJobs;wake;closed=!1;revision=0;task;lastResponse;stop;ended;finished;constructor(e={}){this.joinsJobs=e.joinsJobs??!0}begin(e,t,s=e){this.task||(this.task={startUuid:e,rootUuid:s,recorder:t},this.ended&&this.finish(this.ended).catch(()=>{}))}get taskStartUuid(){return this.task?.startUuid}get taskRef(){return this.task?{startUuid:this.task.startUuid,rootUuid:this.task.rootUuid}:void 0}noteResponse(e){this.lastResponse=e}noteStop(e){this.stop=e}finish(e){let t=this.task;return t?(this.finished??=this.recordOutcome(t,e),this.finished):(this.ended??=e,Promise.resolve(void 0))}async recordOutcome(e,t){let s=this.stop&&(t.outcome==="completed"||t.outcome==="error")?p[this.stop]:t.outcome,i=s==="completed"&&this.lastResponse?.finalAnswer?this.lastResponse:void 0,n=t.limitKind??(s==="max_tokens"||s==="max_turn_requests"?this.stop:void 0);return await e.recorder.recordTaskOutcome({taskStartUuid:e.startUuid,outcome:s,...n?{limitKind:n}:{},...s==="completed"?{finalAnswerUuid:i?i.recordId??i.id:null}:{}}),{outcome:s,...i&&{finalAnswerId:i.id}}}static get current(){return a.getStore()}run(e){return a.run(this,e)}static detached(e){return a.run(void 0,e)}static register(e,t,s){let i=a.getStore();e.originTask??=s?.originTask??i?.taskRef;let n=s?.status==="running"?r.get(s):void 0,o=n??(i?.joinsJobs?i:void 0);if(o){if(n&&s&&n.consume(s),e.completion==="detached"||!n&&e.status!=="running"){o.changed();return}if(r.set(e,o),o.closed){t();return}o.jobs.set(e,t),o.changed()}}static changed(e){e&&r.get(e)?.changed()}static abandoned(e){return r.get(e)?.closed===!0}static detach(e){let t=r.get(e);return!t||t.closed||!t.owns(e)||e.status!=="running"?!1:(e.completion="detached",t.consume(e),t.changed(),!0)}owns(e){return this.jobs.has(e)}consume(e){r.delete(e),this.jobs.delete(e)}get pending(){return this.jobs.size>0}get position(){return this.revision}get paused(){return[...this.jobs.keys()].some(e=>e.status==="paused")}get running(){return[...this.jobs.keys()].filter(e=>e.status==="running")}changed(){this.revision++,this.wake?.()}async wait(e,t,s){this.closed||t.aborted||e!==this.revision||await new Promise(i=>{let n,o=()=>{clearTimeout(n),t.removeEventListener("abort",o),this.wake=void 0,i()};this.wake=o,t.addEventListener("abort",o,{once:!0}),s!==void 0&&(n=setTimeout(o,s))})}close(){this.closed=!0;for(let[e,t]of this.jobs)e.status==="running"&&t();this.changed()}};function g(d,e){let t=s=>{let i=s.description.replace(/[\p{Cc}\s]+/gu," ").trim(),n=Math.max(1,Math.round((e-s.startTime)/6e4));return`background ${s.kind} "${i.length>80?`${i.slice(0,77)}...`:i}" (running ${n} min)`};return{displayText:`Still waiting on ${d.map(t).join(", ")}.`,modelText:d.map(s=>["<task-notification>",`<task-id>${c(s.id)}</task-id>`,`<kind>${s.kind}</kind>`,"<status>running</status>",`<summary>${c(`The ${t(s)} is still running, and this request cannot finish until it does. If the request needs its result, keep waiting. If it should keep running after the request, such as a server or watcher, call ${u.TASK_DETACH}. If it is no longer needed, call ${u.TASK_STOP}.`)}</summary>`,"</task-notification>"].join(`
3
+ import{a as c}from"./chunk-HYVP4472.js";import{p as u}from"./chunk-6E766NPX.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{AsyncLocalStorage as h}from"node:async_hooks";var a=new h,r=new WeakMap,p={turns:"max_turn_requests",session_turns:"max_turn_requests",loop_detected:"max_turn_requests",continuations:"max_turn_requests",session_tokens:"max_tokens"},k=class{jobs=new Map;joinsJobs;wake;closed=!1;revision=0;task;lastResponse;stop;ended;finished;constructor(e={}){this.joinsJobs=e.joinsJobs??!0}begin(e,t,s=e){this.task||(this.task={startUuid:e,rootUuid:s,recorder:t},this.ended&&this.finish(this.ended).catch(()=>{}))}get taskStartUuid(){return this.task?.startUuid}get taskRef(){return this.task?{startUuid:this.task.startUuid,rootUuid:this.task.rootUuid}:void 0}noteResponse(e){this.lastResponse=e}noteStop(e){this.stop=e}finish(e){let t=this.task;return t?(this.finished??=this.recordOutcome(t,e),this.finished):(this.ended??=e,Promise.resolve(void 0))}async recordOutcome(e,t){let s=this.stop&&(t.outcome==="completed"||t.outcome==="error")?p[this.stop]:t.outcome,i=s==="completed"&&this.lastResponse?.finalAnswer?this.lastResponse:void 0,n=t.limitKind??(s==="max_tokens"||s==="max_turn_requests"?this.stop:void 0);return await e.recorder.recordTaskOutcome({taskStartUuid:e.startUuid,outcome:s,...n?{limitKind:n}:{},...s==="completed"?{finalAnswerUuid:i?i.recordId??i.id:null}:{}}),{outcome:s,...i&&{finalAnswerId:i.id}}}static get current(){return a.getStore()}run(e){return a.run(this,e)}static detached(e){return a.run(void 0,e)}static register(e,t,s){let i=a.getStore();e.originTask??=s?.originTask??i?.taskRef;let n=s?.status==="running"?r.get(s):void 0,o=n??(i?.joinsJobs?i:void 0);if(o){if(n&&s&&n.consume(s),e.completion==="detached"||!n&&e.status!=="running"){o.changed();return}if(r.set(e,o),o.closed){t();return}o.jobs.set(e,t),o.changed()}}static changed(e){e&&r.get(e)?.changed()}static abandoned(e){return r.get(e)?.closed===!0}static detach(e){let t=r.get(e);return!t||t.closed||!t.owns(e)||e.status!=="running"?!1:(e.completion="detached",t.consume(e),t.changed(),!0)}owns(e){return this.jobs.has(e)}consume(e){r.delete(e),this.jobs.delete(e)}get pending(){return this.jobs.size>0}get position(){return this.revision}get paused(){return[...this.jobs.keys()].some(e=>e.status==="paused")}get running(){return[...this.jobs.keys()].filter(e=>e.status==="running")}changed(){this.revision++,this.wake?.()}async wait(e,t,s){this.closed||t.aborted||e!==this.revision||await new Promise(i=>{let n,o=()=>{clearTimeout(n),t.removeEventListener("abort",o),this.wake=void 0,i()};this.wake=o,t.addEventListener("abort",o,{once:!0}),s!==void 0&&(n=setTimeout(o,s))})}close(){this.closed=!0;for(let[e,t]of this.jobs)e.status==="running"&&t();this.changed()}};function g(d,e){let t=s=>{let i=s.description.replace(/[\p{Cc}\s]+/gu," ").trim(),n=Math.max(1,Math.round((e-s.startTime)/6e4));return`background ${s.kind} "${i.length>80?`${i.slice(0,77)}...`:i}" (running ${n} min)`};return{displayText:`Still waiting on ${d.map(t).join(", ")}.`,modelText:d.map(s=>["<task-notification>",`<task-id>${c(s.id)}</task-id>`,`<kind>${s.kind}</kind>`,"<status>running</status>",`<summary>${c(`The ${t(s)} is still running, and this request cannot finish until it does. If the request needs its result, keep waiting. If it should keep running after the request, such as a server or watcher, call ${u.TASK_DETACH}. If it is no longer needed, call ${u.TASK_STOP}.`)}</summary>`,"</task-notification>"].join(`
4
4
  `)).join(`
5
5
  `)}}export{k as a,g as b};
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ba as f}from"./chunk-MH2P4YXC.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
3
+ import{ba as f}from"./chunk-27Q5KW3A.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
4
4
  ${this.stopReason}`}},m=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"decision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.decision;if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}}isPermissionDenied(){return this.getPermissionDecision()?.behavior==="deny"}getDenyMessage(){return this.getPermissionDecision()?.message}shouldInterrupt(){return this.getPermissionDecision()?.interrupt===!0}getUpdatedToolInput(){return this.getPermissionDecision()?.updatedInput}getUpdatedPermissions(){return this.getPermissionDecision()?.updatedPermissions}},b=(n=>(n.PermissionPrompt="permission_prompt",n.IdlePrompt="idle_prompt",n.AuthSuccess="auth_success",n.ElicitationDialog="elicitation_dialog",n))(b||{}),H=(t=>(t.Startup="startup",t.Resume="resume",t.Clear="clear",t.Compact="compact",t.Branch="branch",t))(H||{}),I=(t=>(t.Default="default",t.Plan="plan",t.AutoEdit="auto_edit",t.Auto="auto",t.Bogan="bogan",t))(I||{}),T=(t=>(t.Clear="clear",t.Logout="logout",t.PromptInputExit="prompt_input_exit",t.Bypass_permissions_disabled="bypass_permissions_disabled",t.Other="other",t))(T||{}),y=(s=>(s.Manual="manual",s.Auto="auto",s))(y||{}),R=(s=>(s.Manual="manual",s.Auto="auto",s))(R||{}),w=(n=>(n.Bash="Bash",n.Explorer="Explorer",n.Plan="Plan",n.Custom="Custom",n))(w||{});function A(o,e){let s=new Map(o.map(n=>[n.id,n])),u={created:[],completed:[]};for(let n of e){let t=s.get(n.id);t?t.status!=="completed"&&n.status==="completed"&&u.completed.push(n):u.created.push(n)}return u}export{h as a,_ as b,P as c,E as d,S as e,v as f,O as g,C as h,U as i,r as j,p as k,a as l,c as m,d as n,l as o,g as p,m as q,b as r,H as s,I as t,T as u,y as v,R as w,w as x,A as y};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
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=`
3
+ import{y as A}from"./chunk-DE3HKC2W.js";import{b as C}from"./chunk-LUNDTQ3G.js";import{g as O,i as S,p as W,q as P}from"./chunk-6E766NPX.js";import{Q as T,ba as I}from"./chunk-27Q5KW3A.js";import{b as E}from"./chunk-GZPNIYVZ.js";E();import*as h from"fs/promises";import*as f from"fs";import*as u from"path";var R=I("TODO_WRITE"),z={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#"}},j=`
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
 
@@ -182,29 +182,29 @@ When new information changes your understanding of the task, update the todo str
182
182
  - Use clear, descriptive task names
183
183
 
184
184
  When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
185
- `,N="todos";function T(s){let n=u.join(y.getRuntimeBaseDir(),N),e=`${s||"default"}.json`;return u.join(n,e)}async function F(s){try{let n=T(s),e=await h.readFile(n,"utf-8"),r=JSON.parse(e);return Array.isArray(r.todos)?r.todos:[]}catch(n){let e=n;if(!(e instanceof Error)||e.code!=="ENOENT")throw n;return[]}}async function $(s,n){let e=T(n),r=u.dirname(e);await h.mkdir(r,{recursive:!0}),await C(e,JSON.stringify({todos:s,sessionId:n||"default"},null,2),{encoding:"utf-8"})}function A(s,n){return{llmContent:`${s}
185
+ `,N="todos";function y(n){let t=u.join(T.getRuntimeBaseDir(),N),e=`${n||"default"}.json`;return u.join(t,e)}async function q(n){try{let t=y(n),e=await h.readFile(t,"utf-8"),r=JSON.parse(e);return Array.isArray(r.todos)?r.todos:[]}catch(t){let e=t;if(!(e instanceof Error)||e.code!=="ENOENT")throw t;return[]}}async function $(n,t){let e=y(t),r=u.dirname(e);await h.mkdir(r,{recursive:!0}),await C(e,JSON.stringify({todos:n,sessionId:t||"default"},null,2),{encoding:"utf-8"})}function D(n,t){return{llmContent:`${n}
186
186
 
187
187
  <system-reminder>
188
- ${n}
189
- </system-reminder>`,returnDisplay:s}}var k=class extends E{constructor(e,r,l="update"){super(r);this.config=e;this.operationType=l}operationType;getDescription(){return this.operationType==="create"?"Create todos":"Update todos"}async execute(e){let{todos:r,modified_by_user:l,modified_content:a}=this.params,w=this.config.getSessionId();try{let m=await F(w),i;if(l&&a!==void 0){let t=JSON.parse(a);i=Array.isArray(t.todos)?t.todos:[]}else i=r;let d=S(m,i),b=new Map(m.map(t=>[t.id,t])),c=this.config.getHookSystem();if(c&&d.created.length>0){let p=(await Promise.all(d.created.map(o=>c.fireTodoCreatedEvent(o.id,o.content,o.status,i,"validation",e)))).find(o=>o.finalOutput?.decision==="block");if(p?.finalOutput){let o=p.finalOutput.reason||"Hook blocked todo creation";return A(`Todo creation blocked: ${o}`,`Todo list was not modified because a TodoCreated hook blocked the operation: ${o}`)}}if(c&&d.completed.length>0){let p=(await Promise.all(d.completed.map(o=>{let z=b.get(o.id)?.status??"pending";return c.fireTodoCompletedEvent(o.id,o.content,z,i,"validation",e)}))).find(o=>o.finalOutput?.decision==="block");if(p?.finalOutput){let o=p.finalOutput.reason||"Hook blocked todo completion";return A(`Todo completion blocked: ${o}`,`Todo list was not modified because a TodoCompleted hook blocked the operation: ${o}`)}}await $(i,w);let g;try{c&&d.created.length>0&&await Promise.all(d.created.map(t=>c.fireTodoCreatedEvent(t.id,t.content,t.status,i,"postWrite",e))),c&&d.completed.length>0&&await Promise.all(d.completed.map(t=>{let o=b.get(t.id)?.status??"pending";return c.fireTodoCompletedEvent(t.id,t.content,o,i,"postWrite",e)}))}catch(t){g=t instanceof Error?t:new Error(String(t)),R.error(`[TodoWriteTool] Post-write hooks failed after todos were persisted: ${g.message}`)}let L={type:"todo_list",todos:i,changes:d},_=JSON.stringify(i),f,v=g?`
188
+ ${t}
189
+ </system-reminder>`,returnDisplay:n}}var w=class extends O{constructor(e,r,l="update"){super(r);this.config=e;this.operationType=l}operationType;getDescription(){return this.operationType==="create"?"Create todos":"Update todos"}async execute(e){let{todos:r,modified_by_user:l,modified_content:i}=this.params,b=this.config.getSessionId();try{let m=await q(b),a;if(l&&i!==void 0){let o=JSON.parse(i);a=Array.isArray(o.todos)?o.todos:[]}else a=r;let d=A(m,a),v=new Map(m.map(o=>[o.id,o])),c=this.config.getHookSystem();if(c&&d.created.length>0){let p=(await Promise.all(d.created.map(s=>c.fireTodoCreatedEvent(s.id,s.content,s.status,a,"validation",e)))).find(s=>s.finalOutput?.decision==="block");if(p?.finalOutput){let s=p.finalOutput.reason||"Hook blocked todo creation";return D(`Todo creation blocked: ${s}`,`Todo list was not modified because a TodoCreated hook blocked the operation: ${s}`)}}if(c&&d.completed.length>0){let p=(await Promise.all(d.completed.map(s=>{let _=v.get(s.id)?.status??"pending";return c.fireTodoCompletedEvent(s.id,s.content,_,a,"validation",e)}))).find(s=>s.finalOutput?.decision==="block");if(p?.finalOutput){let s=p.finalOutput.reason||"Hook blocked todo completion";return D(`Todo completion blocked: ${s}`,`Todo list was not modified because a TodoCompleted hook blocked the operation: ${s}`)}}await $(a,b);let g;try{c&&d.created.length>0&&await Promise.all(d.created.map(o=>c.fireTodoCreatedEvent(o.id,o.content,o.status,a,"postWrite",e))),c&&d.completed.length>0&&await Promise.all(d.completed.map(o=>{let s=v.get(o.id)?.status??"pending";return c.fireTodoCompletedEvent(o.id,o.content,s,a,"postWrite",e)}))}catch(o){g=o instanceof Error?o:new Error(String(o)),R.error(`[TodoWriteTool] Post-write hooks failed after todos were persisted: ${g.message}`)}let F={type:"todo_list",todos:a,changes:d},L=JSON.stringify(a),k,x=g?`
190
190
 
191
191
  <system-reminder>
192
192
  Todos were persisted successfully, but post-write hooks failed with error: ${g.message}. Do not tell the user the write failed; only handle any follow-up hook issues if needed.
193
- </system-reminder>`:"";return i.length===0?f=`Todo list has been cleared.
193
+ </system-reminder>`:"";return a.length===0?k=`Todo list has been cleared.
194
194
 
195
195
  <system-reminder>
196
196
  Your todo list is now empty. DO NOT mention this explicitly to the user. You have no pending tasks in your todo list.
197
- </system-reminder>${v}`:f=`Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable
197
+ </system-reminder>${x}`:k=`Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable
198
198
 
199
199
  <system-reminder>
200
200
  Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:
201
201
 
202
- ${_}. Continue on with the tasks at hand if applicable.
203
- </system-reminder>${v}`,{llmContent:f,returnDisplay:L}}catch(m){let i=m instanceof Error?m.message:String(m);return R.error(`[TodoWriteTool] Error executing todo_write: ${i}`),{llmContent:`Failed to modify todos. An error occurred during the operation.
202
+ ${L}. Continue on with the tasks at hand if applicable.
203
+ </system-reminder>${x}`,{llmContent:k,returnDisplay:F}}catch(m){let a=m instanceof Error?m.message:String(m);return R.error(`[TodoWriteTool] Error executing todo_write: ${a}`),{llmContent:`Failed to modify todos. An error occurred during the operation.
204
204
 
205
205
  <system-reminder>
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{X as a,Z as b,D as c};
206
+ Todo list modification failed with error: ${a}. You may need to retry or handle this error appropriately.
207
+ </system-reminder>`,returnDisplay:`Error writing todos: ${a}`}}}};function X(n){try{let t=JSON.parse(f.readFileSync(y(n),"utf-8"));return Array.isArray(t.todos)?t.todos:[]}catch(t){let e=t;if(!(e instanceof Error)||e.code!=="ENOENT")throw t;return[]}}async function Z(){try{let n=u.join(T.getRuntimeBaseDir(),N);return(await h.readdir(n)).filter(e=>e.endsWith(".json")).map(e=>e.replace(".json",""))}catch(n){let t=n;if(!(t instanceof Error)||t.code!=="ENOENT")throw n;return[]}}var U=class n extends S{constructor(e){super(n.Name,P.TODO_WRITE,j,"think",z.parametersJsonSchema);this.config=e}static Name=W.TODO_WRITE;validateToolParams(e){if(!Array.isArray(e.todos))return'Parameter "todos" must be an array.';for(let i of e.todos){if(!i.id||typeof i.id!="string"||i.id.trim()==="")return'Each todo must have a non-empty "id" string.';if(!i.content||typeof i.content!="string"||i.content.trim()==="")return'Each todo must have a non-empty "content" string.';if(!["pending","in_progress","completed"].includes(i.status))return'Each todo must have a valid "status" (pending, in_progress, completed).'}let r=e.todos.map(i=>i.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=y(r),i=f.existsSync(l)?"update":"create";return new w(this.config,e,i)}};export{X as a,Z as b,U as c};
208
208
  /**
209
209
  * @license
210
210
  * Copyright 2025 Google LLC
@@ -1,14 +1,14 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as ye}from"./chunk-ODZOYHIC.js";import{c as V,f as I}from"./chunk-GUFIMKF5.js";import{M as pe,N as ce,O as _,Q as de,R as q,S as me,a as re,g as R,h as ae,ha as ge,na as be}from"./chunk-WRQLIPXW.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 z}from"./chunk-4J6DC24J.js";import{b as j,c as W,f as le,n as F}from"./chunk-SDTWBD62.js";import{b as Y}from"./chunk-VI74YQQO.js";import{a as H,ba as P,c as ee,e as te,q as J,s as ne,t as K}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Me(i){return i.toLowerCase().includes("matilda3")}function ve(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?i:{...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,a]of Object.entries(n??{}))le(o)||(r[o]=a);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=V("openai",this.cliConfig.getProxy());return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{}})}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 a=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=a?parseInt(a,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(i,e){return async(t,n)=>{let r=new AbortController,o=n?.signal??void 0,a=()=>r.abort(o?.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",a,{once:!0});let s=()=>o?.removeEventListener("abort",a),l;try{l=await i(t,{...n,signal:r.signal})}catch(C){throw s(),C}let c=l.headers.get("content-type")??"";if(!l.body||!c.includes("text/event-stream"))return l;let u=l.body.getReader(),f=0,m,b=new ReadableStream({async pull(C){let d=new Promise((g,E)=>{m=setTimeout(()=>E(new G(e,f)),e)});try{let g=await Promise.race([u.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(m)}},cancel(C){return clearTimeout(m),s(),u.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 i 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 a=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&&!a&&!l&&we.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),a||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=a);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(),a=V("openai",this.cliConfig.getProxy()),s=a?.fetch??globalThis.fetch,l=Ae(s,24e4),c=_(this.contentGeneratorConfig)?async(u,f)=>{let m=new Headers(u instanceof Request?u.headers:void 0);new Headers(f?.headers).forEach((d,g)=>{m.set(g,d)});let b=m.has(j)||m.has(W),y=F(),C=b||Object.keys(y).length>0;if(C){m.delete(j),m.delete(W);for(let[g,E]of Object.entries(y))m.set(g,E);let d=m.get("x-stainless-retry-count");m.has(j)&&d!==null&&/^[1-9][0-9]*$/.test(d)&&m.set(W,"retry")}this.cliConfig.getChannel()===void 0&&de({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let d=await l(u,C?{...f,headers:m}:f);return me({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),d}catch(d){throw q(d,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),d}}:void 0;return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{},...c?{fetch:c}:{}})}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),a=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...a||{}}:{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},...a||{}}}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,a=n.length===0?n:n.map((l,c)=>!(c===r&&r!==-1||c===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:a,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(i.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of i.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function B(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content=="string"?i:{...e,reasoning_content:""}}function S(i){let e=i.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(i){return S(i)?!0:(i.model??"").toLowerCase().includes("deepseek")}var O=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(a=>{let s=ke(a);return B(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ke(i){if(!("content"in i))return i;let{content:e}=i;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return i;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
3
+ import{a as ye}from"./chunk-GOJCMVJJ.js";import{b as Y}from"./chunk-VI74YQQO.js";import{c as V,f as O}from"./chunk-YV3PUOBU.js";import{M as pe,N as ce,O as _,Q as de,R as q,S as me,a as re,g as R,h as ae,ha as ge,na as be}from"./chunk-3IRGBRSP.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-JCE3JAVC.js";import{e as z}from"./chunk-4J6DC24J.js";import{b as j,c as W,f as le,n as F}from"./chunk-SDTWBD62.js";import{a as H,ba as P,c as ee,e as te,q as J,s as ne,t as K}from"./chunk-27Q5KW3A.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Me(i){return i.toLowerCase().includes("matilda3")}function ve(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?i:{...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,a]of Object.entries(n??{}))le(o)||(r[o]=a);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=V("openai",this.cliConfig.getProxy());return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{}})}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 a=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=a?parseInt(a,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(i,e){return async(t,n)=>{let r=new AbortController,o=n?.signal??void 0,a=()=>r.abort(o?.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",a,{once:!0});let s=()=>o?.removeEventListener("abort",a),l;try{l=await i(t,{...n,signal:r.signal})}catch(C){throw s(),C}let c=l.headers.get("content-type")??"";if(!l.body||!c.includes("text/event-stream"))return l;let u=l.body.getReader(),f=0,m,b=new ReadableStream({async pull(C){let d=new Promise((g,E)=>{m=setTimeout(()=>E(new G(e,f)),e)});try{let g=await Promise.race([u.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(m)}},cancel(C){return clearTimeout(m),s(),u.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 i 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 a=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&&!a&&!l&&we.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),a||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=a);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(),a=V("openai",this.cliConfig.getProxy()),s=a?.fetch??globalThis.fetch,l=Ae(s,24e4),c=_(this.contentGeneratorConfig)?async(u,f)=>{let m=new Headers(u instanceof Request?u.headers:void 0);new Headers(f?.headers).forEach((d,g)=>{m.set(g,d)});let b=m.has(j)||m.has(W),y=F(),C=b||Object.keys(y).length>0;if(C){m.delete(j),m.delete(W);for(let[g,E]of Object.entries(y))m.set(g,E);let d=m.get("x-stainless-retry-count");m.has(j)&&d!==null&&/^[1-9][0-9]*$/.test(d)&&m.set(W,"retry")}this.cliConfig.getChannel()===void 0&&de({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let d=await l(u,C?{...f,headers:m}:f);return me({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),d}catch(d){throw q(d,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),d}}:void 0;return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{},...c?{fetch:c}:{}})}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),a=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...a||{}}:{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},...a||{}}}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,a=n.length===0?n:n.map((l,c)=>!(c===r&&r!==-1||c===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:a,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(i.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of i.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function B(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content=="string"?i:{...e,reasoning_content:""}}function S(i){let e=i.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(i){return S(i)?!0:(i.model??"").toLowerCase().includes("deepseek")}var I=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(a=>{let s=ke(a);return B(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ke(i){if(!("content"in i))return i;let{content:e}=i;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return i;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
4
4
 
5
- `);return{...i,content:t}}function Ge(i){let e=i,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return i;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,...a}=t;r.reasoning=a}return r}p();var T=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(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Pe||t.endsWith(`.${Pe}`)}catch{return!1}}function De(i){if(Ue(i))return!0;let e=i.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(i){if(!("reasoning_content"in i))return i;let e={...i};return delete e.reasoning_content,e}p();function Ne(i){let e=i.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(i.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,a=!!(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(a&&s.trim()&&l===0)try{return JSON.parse(s),je.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let c=this.toolCallMeta.get(o);n&&(c.id=n),r&&(c.name=r);let u=this.inStrings.get(o),f=this.escapes.get(o),m=s+t;this.buffers.set(o,m);let b=l,y=u,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&&m.trim().length>0)try{return{complete:!0,value:JSON.parse(m)}}catch(d){if(y)try{return{complete:!0,value:JSON.parse(m+'"'),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 a=this.toolCallMeta.get(r);if(a?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(a.id){if(n.has(a.id))continue;n.add(a.id)}let c;if(!o.trim())c={};else try{c=JSON.parse(o)}catch{if(!e)continue;let u=oe(o,null);if(!u||typeof u!="object")continue;c=u}t.push({id:a.id,name:a.name,args:c,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,Ie=`[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,a=o?Y(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}});return R.convertOpenAIResponseToGemini(l,r)}finally{a?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,a=o?Y(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}})}catch(m){throw a?.abort(),m}if(!a)return this.processStreamWithLogging(l,r,e);let c=a,u=this.processStreamWithLogging(l,r,e);async function*f(){try{yield*u}finally{c.abort()}}return f()})}reportedOperationHeaders(){if(!_(this.contentGeneratorConfig))return;let e=F();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null;try{for await(let a of e){if(a.choices?.[0]?.finish_reason==="error_finish"){let c=a.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new X(c)}let s=R.convertOpenAIChunkToGemini(a,t);if(s.candidates?.[0]?.content?.parts?.length===0&&!s.candidates?.[0]?.finishReason&&!s.usageMetadata)continue;this.handleChunkMerging(s,r,c=>{o=c})&&(yield s)}if(!o){let a=R.flushOpenAIStreamToGemini(t);a&&(yield a)}o&&(yield o)}catch(a){let s=o;if(s?.usageMetadata){let l=new z;l.candidates=[],l.usageMetadata=s.usageMetadata,l.responseId=s.responseId,l.modelVersion=s.modelVersion,yield l}if(a instanceof X)throw I(a);await this.handleError(a,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 a=t[t.length-1];e.usageMetadata&&(a.usageMetadata=e.usageMetadata),n(a)}else t.push(e),n(e);return!1}else if(o){let a=t[t.length-1],s=new z;return s.candidates=a.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=a.usageMetadata,s.responseId=e.responseId??a.responseId,s.createTime=e.createTime??a.createTime,s.modelVersion=e.modelVersion??a.modelVersion,s.promptFeedback=e.promptFeedback??a.promptFeedback,t[t.length-1]=s,n(s),!1}return t.push(e),!0}async buildRequest(e,t,n,r){let o=R.convertGeminiRequestToOpenAI(e,n),a=this.shouldUseMatildaCoreRequestProfile(),s=a?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,!a&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await R.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let c=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let f=c,m=(n.model??"").toLowerCase();if(A.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(m.startsWith("matilda")||m==="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 c}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,a])=>o.toLowerCase()==="x-matilda-client"&&a.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-Ie.length;return`${Ie}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let c=n?.[s],u=l?e.config?.[l]:void 0,f=l?t[l]:void 0;return c!==void 0?c:u!==void 0?u:f},o=(s,l,c)=>{let u=r(l,c);return u!==void 0?{[s]:u}:{}};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 a=await this.buildRequest(e,t,o,n);return ae.getStore()?.(a),ie.recordOpenAIWireRequest(a),await r(a,o)}catch(a){return await this.handleError(a,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(I(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new $:void 0,a=this.config.provider.getResponseParsingOptions?.(),s=t&&a?.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}:{},...a?{responseParsingOptions:a}:{},...s?{taggedThinkingParser:s}:{}}}};p();var We=P("OPENAI_ERROR"),U=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=I(e),o=!(r instanceof G)&&this.isTimeoutError(r),a=this.buildErrorMessage(r,t,o);if(this.shouldSuppressErrorLogging(r,n)||We.error("OpenAI API Error:",a),o){let s=new Error(`${a}
5
+ `);return{...i,content:t}}function Ge(i){let e=i,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return i;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,...a}=t;r.reasoning=a}return r}p();var T=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(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Pe||t.endsWith(`.${Pe}`)}catch{return!1}}function De(i){if(Ue(i))return!0;let e=i.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(i){if(!("reasoning_content"in i))return i;let e={...i};return delete e.reasoning_content,e}p();function Ne(i){let e=i.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(i.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,a=!!(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(a&&s.trim()&&l===0)try{return JSON.parse(s),je.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let c=this.toolCallMeta.get(o);n&&(c.id=n),r&&(c.name=r);let u=this.inStrings.get(o),f=this.escapes.get(o),m=s+t;this.buffers.set(o,m);let b=l,y=u,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&&m.trim().length>0)try{return{complete:!0,value:JSON.parse(m)}}catch(d){if(y)try{return{complete:!0,value:JSON.parse(m+'"'),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 a=this.toolCallMeta.get(r);if(a?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(a.id){if(n.has(a.id))continue;n.add(a.id)}let c;if(!o.trim())c={};else try{c=JSON.parse(o)}catch{if(!e)continue;let u=oe(o,null);if(!u||typeof u!="object")continue;c=u}t.push({id:a.id,name:a.name,args:c,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,a=o?Y(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}});return R.convertOpenAIResponseToGemini(l,r)}finally{a?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,a=o?Y(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}})}catch(m){throw a?.abort(),m}if(!a)return this.processStreamWithLogging(l,r,e);let c=a,u=this.processStreamWithLogging(l,r,e);async function*f(){try{yield*u}finally{c.abort()}}return f()})}reportedOperationHeaders(){if(!_(this.contentGeneratorConfig))return;let e=F();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null;try{for await(let a of e){if(a.choices?.[0]?.finish_reason==="error_finish"){let c=a.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new X(c)}let s=R.convertOpenAIChunkToGemini(a,t);if(s.candidates?.[0]?.content?.parts?.length===0&&!s.candidates?.[0]?.finishReason&&!s.usageMetadata)continue;this.handleChunkMerging(s,r,c=>{o=c})&&(yield s)}if(!o){let a=R.flushOpenAIStreamToGemini(t);a&&(yield a)}o&&(yield o)}catch(a){let s=o;if(s?.usageMetadata){let l=new z;l.candidates=[],l.usageMetadata=s.usageMetadata,l.responseId=s.responseId,l.modelVersion=s.modelVersion,yield l}if(a instanceof X)throw O(a);await this.handleError(a,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 a=t[t.length-1];e.usageMetadata&&(a.usageMetadata=e.usageMetadata),n(a)}else t.push(e),n(e);return!1}else if(o){let a=t[t.length-1],s=new z;return s.candidates=a.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=a.usageMetadata,s.responseId=e.responseId??a.responseId,s.createTime=e.createTime??a.createTime,s.modelVersion=e.modelVersion??a.modelVersion,s.promptFeedback=e.promptFeedback??a.promptFeedback,t[t.length-1]=s,n(s),!1}return t.push(e),!0}async buildRequest(e,t,n,r){let o=R.convertGeminiRequestToOpenAI(e,n),a=this.shouldUseMatildaCoreRequestProfile(),s=a?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,!a&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await R.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let c=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let f=c,m=(n.model??"").toLowerCase();if(A.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(m.startsWith("matilda")||m==="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 c}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,a])=>o.toLowerCase()==="x-matilda-client"&&a.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 c=n?.[s],u=l?e.config?.[l]:void 0,f=l?t[l]:void 0;return c!==void 0?c:u!==void 0?u:f},o=(s,l,c)=>{let u=r(l,c);return u!==void 0?{[s]:u}:{}};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 a=await this.buildRequest(e,t,o,n);return ae.getStore()?.(a),ie.recordOpenAIWireRequest(a),await r(a,o)}catch(a){return await this.handleError(a,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,a=this.config.provider.getResponseParsingOptions?.(),s=t&&a?.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}:{},...a?{responseParsingOptions:a}:{},...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),a=this.buildErrorMessage(r,t,o);if(this.shouldSuppressErrorLogging(r,n)||We.error("OpenAI API Error:",a),o){let s=new Error(`${a}
8
8
 
9
- ${this.getTimeoutTroubleshootingTips()}`,{cause:r}),l=te(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:
9
+ ${this.getTimeoutTroubleshootingTips()}`,{cause:r});typeof r=="object"&&r!==null&&"code"in r&&Object.assign(s,{code:r.code});let l=te(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
10
  ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
11
- `)}`}};var Oe=P("OPENAI"),w=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new U((o,a)=>this.shouldSuppressErrorLogging(o,a))};this.pipeline=new L(r)}shouldSuppressErrorLogging(e,t){return!!(ee(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){Oe.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=I(n);throw Oe.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 Te(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 q(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 Te(e)&&ge({baseUrl:this.contentGeneratorConfig.baseUrl,channel:this.channel})}toAuthRecoveryError(e){return K(e)?new ne:this.isSessionAuthError(e)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):e}};function Te(i){if(!i||K(i))return!1;let e=i instanceof Error?i.message.toLowerCase():String(i).toLowerCase(),t=i,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(i,e){let t=Fe(i,e);return A.isMatildaCompatibleProvider(i)?new D(i,e,t):new w(i,e,t)}function Fe(i,e){let t=i||e.getContentGeneratorConfig();return A.isMatildaCompatibleProvider(t)?new A(i,e):O.isDeepSeekProvider(t)?new O(i,e):x.isMiMoProvider(t)?new x(i,e):T.isOpenRouterProvider(t)?new T(i,e):k.isModelScopeProvider(t)?new k(i,e):M.isMiniMaxProvider(t)?new M(i,e):v.isMistralProvider(t)?new v(i,e):new h(i,e)}export{A as a,O as b,T 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,Fe as l};
11
+ `)}`}};var Ie=P("OPENAI"),w=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new U((o,a)=>this.shouldSuppressErrorLogging(o,a))};this.pipeline=new L(r)}shouldSuppressErrorLogging(e,t){return!!(ee(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){Ie.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 Ie.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 Te(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 q(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 Te(e)&&ge({baseUrl:this.contentGeneratorConfig.baseUrl,channel:this.channel})}toAuthRecoveryError(e){return K(e)?new ne:this.isSessionAuthError(e)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):e}};function Te(i){if(!i||K(i))return!1;let e=i instanceof Error?i.message.toLowerCase():String(i).toLowerCase(),t=i,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(i,e){let t=Fe(i,e);return A.isMatildaCompatibleProvider(i)?new D(i,e,t):new w(i,e,t)}function Fe(i,e){let t=i||e.getContentGeneratorConfig();return A.isMatildaCompatibleProvider(t)?new A(i,e):I.isDeepSeekProvider(t)?new I(i,e):x.isMiMoProvider(t)?new x(i,e):T.isOpenRouterProvider(t)?new T(i,e):k.isModelScopeProvider(t)?new k(i,e):M.isMiniMaxProvider(t)?new M(i,e):v.isMistralProvider(t)?new v(i,e):new h(i,e)}export{A as a,I as b,T 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,Fe as l};
12
12
  /**
13
13
  * @license
14
14
  * Copyright 2026 Matilda
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{g as w,i as x}from"./chunk-GUFIMKF5.js";import{ba as I}from"./chunk-MH2P4YXC.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();m();var p=I("IMAGE_TOKENIZER"),E=class l{static PIXELS_PER_TOKEN=28*28;static MIN_TOKENS_PER_IMAGE=4;static MAX_TOKENS_PER_IMAGE=16384;static VISION_SPECIAL_TOKENS=2;async extractImageMetadata(t,e){try{if(!x(e))return p.warn(`Unsupported image format: ${e}`),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)};let n=t.replace(/^data:[^;]+;base64,/,""),r=Buffer.from(n,"base64"),i=await this.extractDimensions(r,e);return{width:i.width,height:i.height,mimeType:e,dataSize:r.length}}catch(n){return p.warn("Failed to extract image metadata:",n),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)}}}async extractDimensions(t,e){return e.includes("png")?this.extractPngDimensions(t):e.includes("jpeg")||e.includes("jpg")?this.extractJpegDimensions(t):e.includes("webp")?this.extractWebpDimensions(t):e.includes("gif")?this.extractGifDimensions(t):e.includes("bmp")?this.extractBmpDimensions(t):e.includes("tiff")?this.extractTiffDimensions(t):e.includes("heic")?this.extractHeicDimensions(t):{width:512,height:512}}extractPngDimensions(t){if(t.length<24)throw new Error("Invalid PNG: buffer too short");let e=t.subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!e.equals(n))throw new Error("Invalid PNG signature");let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}extractJpegDimensions(t){if(t.length<4||t[0]!==255||t[1]!==216)throw new Error("Invalid JPEG signature");let e=2;for(;e<t.length-8;){if(t[e]!==255){e++;continue}let n=t[e+1];if(n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207){let i=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:i}}let r=t.readUInt16BE(e+2);e+=2+r}throw new Error("Could not find JPEG dimensions")}extractWebpDimensions(t){if(t.length<30)throw new Error("Invalid WebP: too short");let e=t.subarray(0,4).toString("ascii"),n=t.subarray(8,12).toString("ascii");if(e!=="RIFF"||n!=="WEBP")throw new Error("Invalid WebP signature");let r=t.subarray(12,16).toString("ascii");if(r==="VP8 "){let i=t.readUInt16LE(26)&16383,a=t.readUInt16LE(28)&16383;return{width:i,height:a}}else if(r==="VP8L"){let i=t.readUInt32LE(21),a=(i&16383)+1,s=(i>>14&16383)+1;return{width:a,height:s}}else if(r==="VP8X"){let i=(t.readUInt32LE(24)&16777215)+1,a=(t.readUInt32LE(26)&16777215)+1;return{width:i,height:a}}throw new Error("Unsupported WebP format")}extractGifDimensions(t){if(t.length<10)throw new Error("Invalid GIF: too short");let e=t.subarray(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")throw new Error("Invalid GIF signature");let n=t.readUInt16LE(6),r=t.readUInt16LE(8);return{width:n,height:r}}calculateTokens(t){return this.calculateTokensWithScaling(t.width,t.height)}calculateTokensWithScaling(t,e){let n=Math.round(e/28)*28,r=Math.round(t/28)*28,i=l.MIN_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN,a=l.MAX_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN;if(n*r>a){let o=Math.sqrt(e*t/a);n=Math.floor(e/o/28)*28,r=Math.floor(t/o/28)*28}else if(n*r<i){let o=Math.sqrt(i/(e*t));n=Math.ceil(e*o/28)*28,r=Math.ceil(t*o/28)*28}return Math.floor(n*r/l.PIXELS_PER_TOKEN)+l.VISION_SPECIAL_TOKENS}async calculateTokensBatch(t){let e=[];for(let{data:n,mimeType:r}of t)try{let i=await this.extractImageMetadata(n,r);e.push(this.calculateTokens(i))}catch(i){p.warn("Error calculating tokens for image:",i),e.push(l.MIN_TOKENS_PER_IMAGE+l.VISION_SPECIAL_TOKENS)}return e}extractBmpDimensions(t){if(t.length<26)throw new Error("Invalid BMP: buffer too short");if(t[0]!==66||t[1]!==77)throw new Error("Invalid BMP signature");let e=t.readUInt32LE(18),n=t.readUInt32LE(22);return{width:e,height:Math.abs(n)}}extractTiffDimensions(t){if(t.length<8)throw new Error("Invalid TIFF: buffer too short");let e=t.subarray(0,2).toString("ascii"),n=e==="II";if(!n&&!(e==="MM"))throw new Error("Invalid TIFF byte order");if((n?t.readUInt16LE(2):t.readUInt16BE(2))!==42)throw new Error("Invalid TIFF magic number");let a=n?t.readUInt32LE(4):t.readUInt32BE(4);if(a>=t.length)throw new Error("Invalid TIFF IFD offset");let s=n?t.readUInt16LE(a):t.readUInt16BE(a),o=0,h=0;for(let g=0;g<s;g++){let c=a+2+g*12;if(c+12>t.length)break;let u=n?t.readUInt16LE(c):t.readUInt16BE(c),f=(n?t.readUInt16LE(c+2):t.readUInt16BE(c+2))===3?n?t.readUInt16LE(c+8):t.readUInt16BE(c+8):n?t.readUInt32LE(c+8):t.readUInt32BE(c+8);if(u===256?o=f:u===257&&(h=f),o>0&&h>0)break}if(o===0||h===0)throw new Error("Could not find TIFF dimensions");return{width:o,height:h}}extractHeicDimensions(t){if(t.length<12)throw new Error("Invalid HEIC: buffer too short");if(t.subarray(4,8).toString("ascii")!=="ftyp")throw new Error("Invalid HEIC: missing ftyp box");let n=t.subarray(8,12).toString("ascii");if(!["heic","heix","hevc","hevx"].includes(n))throw new Error("Invalid HEIC brand");let r=0;for(;r<t.length-8;){let i=t.readUInt32BE(r);if(t.subarray(r+4,r+8).toString("ascii")==="meta"){let o=r+8+4;for(;o<r+i-8;){let h=t.readUInt32BE(o);if(t.subarray(o+4,o+8).toString("ascii")==="ispe"&&o+20<=t.length){let c=t.readUInt32BE(o+12),u=t.readUInt32BE(o+16);return{width:c,height:u}}if(h===0)break;o+=h}}if(i===0)break;r+=i}return p.warn("Could not extract HEIC dimensions, using default"),{width:512,height:512}}};var d=I("TOKENIZER"),T=class{textTokenizer;imageTokenizer;constructor(){this.textTokenizer=new w,this.imageTokenizer=new E}async calculateTokens(t){let e=performance.now();try{let{textContents:n,imageContents:r,audioContents:i,otherContents:a}=this.processAndGroupContents(t);if(n.length===0&&r.length===0&&i.length===0&&a.length===0)return{totalTokens:0,breakdown:{textTokens:0,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e};let s=await this.calculateTextTokens(n),o=await this.calculateImageTokens(r),h=await this.calculateAudioTokens(i),g=await this.calculateOtherTokens(a),c=s+o+h+g,u=performance.now()-e;return{totalTokens:c,breakdown:{textTokens:s,imageTokens:o,audioTokens:h,otherTokens:g},processingTime:u}}catch(n){d.error("Error calculating tokens:",n);let r=this.calculateFallbackTokens(t);return{totalTokens:r,breakdown:{textTokens:r,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e}}}async calculateTextTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating text tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}async calculateImageTokens(t){if(t.length===0)return 0;try{return(await this.imageTokenizer.calculateTokensBatch(t)).reduce((n,r)=>n+r,0)}catch(e){return d.warn("Error calculating image tokens:",e),t.length*6}}async calculateAudioTokens(t){if(t.length===0)return 0;let e=0;for(let n of t)try{let r=Math.floor(n.data.length*.75);e+=Math.max(Math.ceil(r/100),10)}catch(r){d.warn("Error calculating audio tokens:",r),e+=10}return e}async calculateOtherTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating other content tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}calculateFallbackTokens(t){try{let e=JSON.stringify(t.contents);return Math.ceil(e.length/4)}catch(e){return d.warn("Error in fallback token calculation:",e),100}}processAndGroupContents(t){let e=[],n=[],r=[],i=[];if(!t.contents)return{textContents:e,imageContents:n,audioContents:r,otherContents:i};let a=Array.isArray(t.contents)?t.contents:[t.contents];for(let s of a)this.processContent(s,e,n,r,i);return{textContents:e,imageContents:n,audioContents:r,otherContents:i}}processContent(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("parts"in t&&t.parts){for(let a of t.parts)this.processPart(a,e,n,r,i);return}this.processPart(t,e,n,r,i)}processPart(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("text"in t&&t.text){e.push(t.text);return}if("inlineData"in t&&t.inlineData){let{data:a,mimeType:s}=t.inlineData;if(s&&s.startsWith("image/")){n.push({data:a||"",mimeType:s});return}if(s&&s.startsWith("audio/")){r.push({data:a||"",mimeType:s});return}}if("fileData"in t&&t.fileData){i.push(JSON.stringify(t.fileData));return}if("functionCall"in t&&t.functionCall){i.push(JSON.stringify(t.functionCall));return}if("functionResponse"in t&&t.functionResponse){i.push(JSON.stringify(t.functionResponse));return}try{let a=JSON.stringify(t);a&&a!=="{}"&&i.push(a)}catch(a){d.warn("Failed to serialize unknown part type:",a)}}};m();export{T as a};
3
+ import{g as w,i as x}from"./chunk-YV3PUOBU.js";import{ba as I}from"./chunk-27Q5KW3A.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();m();var p=I("IMAGE_TOKENIZER"),E=class l{static PIXELS_PER_TOKEN=28*28;static MIN_TOKENS_PER_IMAGE=4;static MAX_TOKENS_PER_IMAGE=16384;static VISION_SPECIAL_TOKENS=2;async extractImageMetadata(t,e){try{if(!x(e))return p.warn(`Unsupported image format: ${e}`),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)};let n=t.replace(/^data:[^;]+;base64,/,""),r=Buffer.from(n,"base64"),i=await this.extractDimensions(r,e);return{width:i.width,height:i.height,mimeType:e,dataSize:r.length}}catch(n){return p.warn("Failed to extract image metadata:",n),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)}}}async extractDimensions(t,e){return e.includes("png")?this.extractPngDimensions(t):e.includes("jpeg")||e.includes("jpg")?this.extractJpegDimensions(t):e.includes("webp")?this.extractWebpDimensions(t):e.includes("gif")?this.extractGifDimensions(t):e.includes("bmp")?this.extractBmpDimensions(t):e.includes("tiff")?this.extractTiffDimensions(t):e.includes("heic")?this.extractHeicDimensions(t):{width:512,height:512}}extractPngDimensions(t){if(t.length<24)throw new Error("Invalid PNG: buffer too short");let e=t.subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!e.equals(n))throw new Error("Invalid PNG signature");let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}extractJpegDimensions(t){if(t.length<4||t[0]!==255||t[1]!==216)throw new Error("Invalid JPEG signature");let e=2;for(;e<t.length-8;){if(t[e]!==255){e++;continue}let n=t[e+1];if(n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207){let i=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:i}}let r=t.readUInt16BE(e+2);e+=2+r}throw new Error("Could not find JPEG dimensions")}extractWebpDimensions(t){if(t.length<30)throw new Error("Invalid WebP: too short");let e=t.subarray(0,4).toString("ascii"),n=t.subarray(8,12).toString("ascii");if(e!=="RIFF"||n!=="WEBP")throw new Error("Invalid WebP signature");let r=t.subarray(12,16).toString("ascii");if(r==="VP8 "){let i=t.readUInt16LE(26)&16383,a=t.readUInt16LE(28)&16383;return{width:i,height:a}}else if(r==="VP8L"){let i=t.readUInt32LE(21),a=(i&16383)+1,s=(i>>14&16383)+1;return{width:a,height:s}}else if(r==="VP8X"){let i=(t.readUInt32LE(24)&16777215)+1,a=(t.readUInt32LE(26)&16777215)+1;return{width:i,height:a}}throw new Error("Unsupported WebP format")}extractGifDimensions(t){if(t.length<10)throw new Error("Invalid GIF: too short");let e=t.subarray(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")throw new Error("Invalid GIF signature");let n=t.readUInt16LE(6),r=t.readUInt16LE(8);return{width:n,height:r}}calculateTokens(t){return this.calculateTokensWithScaling(t.width,t.height)}calculateTokensWithScaling(t,e){let n=Math.round(e/28)*28,r=Math.round(t/28)*28,i=l.MIN_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN,a=l.MAX_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN;if(n*r>a){let o=Math.sqrt(e*t/a);n=Math.floor(e/o/28)*28,r=Math.floor(t/o/28)*28}else if(n*r<i){let o=Math.sqrt(i/(e*t));n=Math.ceil(e*o/28)*28,r=Math.ceil(t*o/28)*28}return Math.floor(n*r/l.PIXELS_PER_TOKEN)+l.VISION_SPECIAL_TOKENS}async calculateTokensBatch(t){let e=[];for(let{data:n,mimeType:r}of t)try{let i=await this.extractImageMetadata(n,r);e.push(this.calculateTokens(i))}catch(i){p.warn("Error calculating tokens for image:",i),e.push(l.MIN_TOKENS_PER_IMAGE+l.VISION_SPECIAL_TOKENS)}return e}extractBmpDimensions(t){if(t.length<26)throw new Error("Invalid BMP: buffer too short");if(t[0]!==66||t[1]!==77)throw new Error("Invalid BMP signature");let e=t.readUInt32LE(18),n=t.readUInt32LE(22);return{width:e,height:Math.abs(n)}}extractTiffDimensions(t){if(t.length<8)throw new Error("Invalid TIFF: buffer too short");let e=t.subarray(0,2).toString("ascii"),n=e==="II";if(!n&&!(e==="MM"))throw new Error("Invalid TIFF byte order");if((n?t.readUInt16LE(2):t.readUInt16BE(2))!==42)throw new Error("Invalid TIFF magic number");let a=n?t.readUInt32LE(4):t.readUInt32BE(4);if(a>=t.length)throw new Error("Invalid TIFF IFD offset");let s=n?t.readUInt16LE(a):t.readUInt16BE(a),o=0,h=0;for(let g=0;g<s;g++){let c=a+2+g*12;if(c+12>t.length)break;let u=n?t.readUInt16LE(c):t.readUInt16BE(c),f=(n?t.readUInt16LE(c+2):t.readUInt16BE(c+2))===3?n?t.readUInt16LE(c+8):t.readUInt16BE(c+8):n?t.readUInt32LE(c+8):t.readUInt32BE(c+8);if(u===256?o=f:u===257&&(h=f),o>0&&h>0)break}if(o===0||h===0)throw new Error("Could not find TIFF dimensions");return{width:o,height:h}}extractHeicDimensions(t){if(t.length<12)throw new Error("Invalid HEIC: buffer too short");if(t.subarray(4,8).toString("ascii")!=="ftyp")throw new Error("Invalid HEIC: missing ftyp box");let n=t.subarray(8,12).toString("ascii");if(!["heic","heix","hevc","hevx"].includes(n))throw new Error("Invalid HEIC brand");let r=0;for(;r<t.length-8;){let i=t.readUInt32BE(r);if(t.subarray(r+4,r+8).toString("ascii")==="meta"){let o=r+8+4;for(;o<r+i-8;){let h=t.readUInt32BE(o);if(t.subarray(o+4,o+8).toString("ascii")==="ispe"&&o+20<=t.length){let c=t.readUInt32BE(o+12),u=t.readUInt32BE(o+16);return{width:c,height:u}}if(h===0)break;o+=h}}if(i===0)break;r+=i}return p.warn("Could not extract HEIC dimensions, using default"),{width:512,height:512}}};var d=I("TOKENIZER"),T=class{textTokenizer;imageTokenizer;constructor(){this.textTokenizer=new w,this.imageTokenizer=new E}async calculateTokens(t){let e=performance.now();try{let{textContents:n,imageContents:r,audioContents:i,otherContents:a}=this.processAndGroupContents(t);if(n.length===0&&r.length===0&&i.length===0&&a.length===0)return{totalTokens:0,breakdown:{textTokens:0,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e};let s=await this.calculateTextTokens(n),o=await this.calculateImageTokens(r),h=await this.calculateAudioTokens(i),g=await this.calculateOtherTokens(a),c=s+o+h+g,u=performance.now()-e;return{totalTokens:c,breakdown:{textTokens:s,imageTokens:o,audioTokens:h,otherTokens:g},processingTime:u}}catch(n){d.error("Error calculating tokens:",n);let r=this.calculateFallbackTokens(t);return{totalTokens:r,breakdown:{textTokens:r,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e}}}async calculateTextTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating text tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}async calculateImageTokens(t){if(t.length===0)return 0;try{return(await this.imageTokenizer.calculateTokensBatch(t)).reduce((n,r)=>n+r,0)}catch(e){return d.warn("Error calculating image tokens:",e),t.length*6}}async calculateAudioTokens(t){if(t.length===0)return 0;let e=0;for(let n of t)try{let r=Math.floor(n.data.length*.75);e+=Math.max(Math.ceil(r/100),10)}catch(r){d.warn("Error calculating audio tokens:",r),e+=10}return e}async calculateOtherTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating other content tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}calculateFallbackTokens(t){try{let e=JSON.stringify(t.contents);return Math.ceil(e.length/4)}catch(e){return d.warn("Error in fallback token calculation:",e),100}}processAndGroupContents(t){let e=[],n=[],r=[],i=[];if(!t.contents)return{textContents:e,imageContents:n,audioContents:r,otherContents:i};let a=Array.isArray(t.contents)?t.contents:[t.contents];for(let s of a)this.processContent(s,e,n,r,i);return{textContents:e,imageContents:n,audioContents:r,otherContents:i}}processContent(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("parts"in t&&t.parts){for(let a of t.parts)this.processPart(a,e,n,r,i);return}this.processPart(t,e,n,r,i)}processPart(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("text"in t&&t.text){e.push(t.text);return}if("inlineData"in t&&t.inlineData){let{data:a,mimeType:s}=t.inlineData;if(s&&s.startsWith("image/")){n.push({data:a||"",mimeType:s});return}if(s&&s.startsWith("audio/")){r.push({data:a||"",mimeType:s});return}}if("fileData"in t&&t.fileData){i.push(JSON.stringify(t.fileData));return}if("functionCall"in t&&t.functionCall){i.push(JSON.stringify(t.functionCall));return}if("functionResponse"in t&&t.functionResponse){i.push(JSON.stringify(t.functionResponse));return}try{let a=JSON.stringify(t);a&&a!=="{}"&&i.push(a)}catch(a){d.warn("Failed to serialize unknown part type:",a)}}};m();export{T as a};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ba as d}from"./chunk-MH2P4YXC.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
3
+ import{ba as d}from"./chunk-27Q5KW3A.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ba as te}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
3
+ import{ba as te}from"./chunk-27Q5KW3A.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
4
4
  +`.includes(t)}function P(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function q(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var $=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,F=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function K(t){return`,[]/{}
5
5
  +`.includes(t)}function J(t){return E(t)||Ke.test(t)}var Ke=/^[[{\w-]$/;function le(t){return t===`
6
6
  `||t==="\r"||t===" "||t==="\b"||t==="\f"}function C(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function me(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function fe(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function E(t){return Q(t)||L(t)}function Q(t){return t==='"'||t==="\u201C"||t==="\u201D"}function z(t){return t==='"'}function L(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function G(t){return t==="'"}function B(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function h(t,e){let n=t.length;if(!C(t,n-1))return t+e;for(;C(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function pe(t,e,n){return t.substring(0,e)+t.substring(e+n)}function de(t){return/[,\n][ \t\r]*$/.test(t)}var Je={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Qe={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`