@maincode-ai/matilda-code 0.21.10 → 0.21.11

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 (138) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +10 -1
  2. package/bundled/mainy/docs/matilda-serve.md +6 -6
  3. package/chunks/agent-ZFZ4HJQC.js +3 -0
  4. package/chunks/agent-headless-KH2BKLP7.js +3 -0
  5. package/chunks/{anthropicContentGenerator-SFJGSZHT.js → anthropicContentGenerator-IYZILRDW.js} +1 -1
  6. package/chunks/{askUserQuestion-MJ4FTAOQ.js → askUserQuestion-XWHJY3DM.js} +1 -1
  7. package/chunks/{ca-H4HPSGTI.js → ca-EUJBUYX5.js} +1 -1
  8. package/chunks/{chunk-B3NVKOSU.js → chunk-25NCTG5H.js} +63 -54
  9. package/chunks/{chunk-INAZKGGR.js → chunk-2HQMJ2IU.js} +1 -1
  10. package/chunks/{todoWrite-7BZMVNBC.js → chunk-4CSSDBOS.js} +2 -2
  11. package/chunks/{chunk-5PMMY47S.js → chunk-4FVBPNTZ.js} +1 -1
  12. package/chunks/{chunk-C62LTEOV.js → chunk-4YVN5HXG.js} +2 -2
  13. package/chunks/{chunk-LSDMWVW6.js → chunk-5427BPR2.js} +2 -2
  14. package/chunks/{chunk-GC2F575A.js → chunk-6GBNB5Z2.js} +1 -1
  15. package/chunks/{chunk-32PTAACU.js → chunk-ELH4YHJR.js} +1 -1
  16. package/chunks/{chunk-3HUM74NZ.js → chunk-EQGA7LH7.js} +2 -2
  17. package/chunks/{chunk-FWIVFCKF.js → chunk-FFFZ2QMG.js} +1 -1
  18. package/chunks/chunk-GHBKFIHC.js +35 -0
  19. package/chunks/{chunk-EQEQPZLQ.js → chunk-GO2GA2GY.js} +1 -1
  20. package/chunks/{chunk-QHA3ZBRO.js → chunk-GUFIMKF5.js} +1 -1
  21. package/chunks/{chunk-RJX7DK4Y.js → chunk-HWOQNYAO.js} +1 -1
  22. package/chunks/chunk-HYVP4472.js +8 -0
  23. package/chunks/{chunk-VWWEEU4V.js → chunk-JXUDKX6D.js} +1 -1
  24. package/chunks/chunk-M53RP3YP.js +31 -0
  25. package/chunks/{chunk-VLYRNOD3.js → chunk-MH2P4YXC.js} +10 -10
  26. package/chunks/{chunk-DJSOHDUB.js → chunk-NIQK6NX3.js} +1 -1
  27. package/chunks/{chunk-K3ELACN2.js → chunk-NVM7W7TG.js} +17 -17
  28. package/chunks/{chunk-VYTYYCBR.js → chunk-NYEWHSBL.js} +1 -1
  29. package/chunks/{chunk-LIWYWWOK.js → chunk-ODZOYHIC.js} +1 -1
  30. package/chunks/{chunk-EXIO3QHE.js → chunk-Q55AVE2N.js} +9 -9
  31. package/chunks/chunk-QFNFLE2I.js +2625 -0
  32. package/chunks/{chunk-Q2I3ARPJ.js → chunk-QH7736R5.js} +1 -1
  33. package/chunks/chunk-QN6WSWMM.js +9 -0
  34. package/chunks/chunk-RK2AKQAX.js +39 -0
  35. package/chunks/chunk-SNLH42QJ.js +10 -0
  36. package/chunks/chunk-SPW5DXX4.js +35 -0
  37. package/chunks/{chunk-S7G6QPEP.js → chunk-SUH3UUWZ.js} +1 -1
  38. package/chunks/chunk-T2T2UEPY.js +4 -0
  39. package/chunks/{chunk-6B5BDE7S.js → chunk-T4P4KEDW.js} +8 -8
  40. package/chunks/chunk-VI74YQQO.js +8 -0
  41. package/chunks/{chunk-DCQKJTAX.js → chunk-W5CGKUM4.js} +8 -3
  42. package/chunks/{chunk-32T6RWWT.js → chunk-WHG6N5X2.js} +1 -1
  43. package/chunks/chunk-WRQLIPXW.js +113 -0
  44. package/chunks/{chunk-XCJYORZX.js → chunk-XCFLI3OC.js} +1 -1
  45. package/chunks/{chunk-3ZAMYREW.js → chunk-YMIF2DMT.js} +1 -1
  46. package/chunks/{computer-use-DJV6HTND.js → computer-use-SXP25RZQ.js} +7 -7
  47. package/chunks/contextCommand-3GN5CAOK.js +3 -0
  48. package/chunks/{cron-create-BTTPO3JC.js → cron-create-2UI4AT4Q.js} +1 -1
  49. package/chunks/{cron-delete-U55RHRID.js → cron-delete-ZB6BOTFF.js} +1 -1
  50. package/chunks/{cron-list-J4HRR46K.js → cron-list-YYAXNHB6.js} +1 -1
  51. package/chunks/{de-S7F37S4F.js → de-DNEPG7S7.js} +1 -1
  52. package/chunks/{dist-SVKXQXJX.js → dist-ME6647DQ.js} +1 -1
  53. package/chunks/{dist-SCXU6QWY.js → dist-P6SLWL5V.js} +1 -1
  54. package/chunks/{dist-PVENOVGI.js → dist-VG3ZDJ2A.js} +1 -1
  55. package/chunks/{dist-N66KF4KX.js → dist-YTCHM57U.js} +1 -1
  56. package/chunks/{edit-7XEZHXE4.js → edit-KX6V4PH3.js} +1 -1
  57. package/chunks/{en-S6DMCJQZ.js → en-NOD6KQNM.js} +1 -1
  58. package/chunks/{enter-worktree-MR64QLS4.js → enter-worktree-X47BSJLE.js} +1 -1
  59. package/chunks/{enterPlanMode-UNWCEVYY.js → enterPlanMode-F22ZNTYJ.js} +1 -1
  60. package/chunks/{exit-worktree-D4BMN6LH.js → exit-worktree-XY5UMDHX.js} +1 -1
  61. package/chunks/{exitPlanMode-AKLFFYT2.js → exitPlanMode-G3QLIWJ4.js} +1 -1
  62. package/chunks/{fr-RFJP3KVL.js → fr-2OE5WLJ4.js} +1 -1
  63. package/chunks/{geminiContentGenerator-JBASUS2T.js → geminiContentGenerator-EQEGOXOV.js} +1 -1
  64. package/chunks/glob-KSBEWI3E.js +22 -0
  65. package/chunks/goal-tools-6QTC3UI7.js +12 -0
  66. package/chunks/grep-6TTPZ524.js +22 -0
  67. package/chunks/{ja-UTJHPL3M.js → ja-3B6V5KS7.js} +1 -1
  68. package/chunks/{keychain-token-storage-HAFQQIXL.js → keychain-token-storage-54BNK6VH.js} +1 -1
  69. package/chunks/{ls-CLDNF3YS.js → ls-YWZU3FYL.js} +1 -1
  70. package/chunks/{lsp-7SKRKR5Q.js → lsp-4CJDKEEC.js} +1 -1
  71. package/chunks/{matildaAgentContentGenerator-GMDJPWES.js → matildaAgentContentGenerator-OV4U6DJD.js} +1 -1
  72. package/chunks/matildaContentGenerator-ETIAWE22.js +8 -0
  73. package/chunks/{matildaOAuth2-W2DQO2NK.js → matildaOAuth2-WOY7ZS43.js} +1 -1
  74. package/chunks/monitor-F4K5HOZX.js +32 -0
  75. package/chunks/notebook-edit-TL7CI5EA.js +17 -0
  76. package/chunks/{openaiContentGenerator-XDOQRO4G.js → openaiContentGenerator-MGASUFQL.js} +1 -1
  77. package/chunks/{pt-KXMOTADP.js → pt-KP2JCPUY.js} +1 -1
  78. package/chunks/read-file-6EAPS2KG.js +3 -0
  79. package/chunks/ripGrep-K6SFFUIE.js +3 -0
  80. package/chunks/{ru-EWGWZPQH.js → ru-K7IQQKHC.js} +1 -1
  81. package/chunks/scheduler-TKWPD4LP.js +8 -0
  82. package/chunks/{send-message-XXRROIL7.js → send-message-OO2HAKCC.js} +1 -1
  83. package/chunks/{serve-4MDSDWP7.js → serve-ZQX2WBLF.js} +31 -31
  84. package/chunks/shell-AZRK5GIO.js +3 -0
  85. package/chunks/{skill-JIISRKQN.js → skill-KDM3UUML.js} +1 -1
  86. package/chunks/src-SGI6VLOS.js +3 -0
  87. package/chunks/{symbol-search-3MVTK4KV.js → symbol-search-ALYOX5JN.js} +1 -1
  88. package/chunks/{syntheticOutput-QEUQIVQJ.js → syntheticOutput-UASKABJH.js} +1 -1
  89. package/chunks/task-create-EBJD55TB.js +3 -0
  90. package/chunks/task-detach-I67ZE5MX.js +9 -0
  91. package/chunks/{task-list-ZEJTNZ2O.js → task-list-5BGX4G5N.js} +1 -1
  92. package/chunks/{task-stop-JO3CXG2K.js → task-stop-ERI5X4AO.js} +1 -1
  93. package/chunks/{task-update-3YY37VFN.js → task-update-CD3W556L.js} +1 -1
  94. package/chunks/{team-create-GMI5DIH7.js → team-create-F4KQRGMB.js} +1 -1
  95. package/chunks/{team-delete-4YYLUV23.js → team-delete-5U3GBFKJ.js} +1 -1
  96. package/chunks/todoWrite-YGG6AZ3A.js +3 -0
  97. package/chunks/{tool-search-OWJC3UTX.js → tool-search-JFCD5W5M.js} +1 -1
  98. package/chunks/{web-fetch-K575OWZ7.js → web-fetch-REWGIRWQ.js} +1 -1
  99. package/chunks/{web-search-F6JRBXFV.js → web-search-OX2DPEVN.js} +1 -1
  100. package/chunks/{workflow-H5DWTI5W.js → workflow-SEFYGBED.js} +2 -2
  101. package/chunks/write-file-UAGVBZMC.js +15 -0
  102. package/cli.js +480 -475
  103. package/locales/ca.js +8 -2
  104. package/locales/de.js +9 -2
  105. package/locales/en.js +15 -8
  106. package/locales/fr.js +9 -2
  107. package/locales/ja.js +8 -2
  108. package/locales/pt.js +8 -2
  109. package/locales/ru.js +9 -2
  110. package/package.json +2 -2
  111. package/sandbox-macos-restrictive-closed.sb +4 -0
  112. package/sandbox-macos-restrictive-open.sb +4 -0
  113. package/sandbox-macos-restrictive-proxied.sb +4 -0
  114. package/chunks/agent-2ZM5WMHY.js +0 -3
  115. package/chunks/agent-headless-PX4INULZ.js +0 -3
  116. package/chunks/chunk-2UDXLDSZ.js +0 -34
  117. package/chunks/chunk-34DXSYJZ.js +0 -34
  118. package/chunks/chunk-ESSYHTAZ.js +0 -8
  119. package/chunks/chunk-FRL6KOLY.js +0 -35
  120. package/chunks/chunk-I7TAYS6D.js +0 -108
  121. package/chunks/chunk-JSFA3NEP.js +0 -5
  122. package/chunks/chunk-ROETRE5J.js +0 -9
  123. package/chunks/chunk-RYLWDCCN.js +0 -2594
  124. package/chunks/chunk-TZIDSCTF.js +0 -31
  125. package/chunks/contextCommand-TAFFF6V7.js +0 -3
  126. package/chunks/glob-3QKPKP7Z.js +0 -22
  127. package/chunks/grep-6CL6HJ5Y.js +0 -22
  128. package/chunks/matildaContentGenerator-EFK4QDRS.js +0 -8
  129. package/chunks/monitor-6W2R25LH.js +0 -32
  130. package/chunks/notebook-edit-WL6MZ6AW.js +0 -17
  131. package/chunks/read-file-J5UBJYDO.js +0 -3
  132. package/chunks/ripGrep-2AMYRBCZ.js +0 -3
  133. package/chunks/scheduler-LFSCKDU6.js +0 -8
  134. package/chunks/shell-SMTFAOAE.js +0 -3
  135. package/chunks/src-OF7NIVIL.js +0 -3
  136. package/chunks/task-create-AEJQ73GE.js +0 -3
  137. package/chunks/update-goal-CF6G57J7.js +0 -16
  138. package/chunks/write-file-RUHYPLKF.js +0 -15
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{e as l}from"./chunk-EQEQPZLQ.js";import{P as a,aa as e}from"./chunk-VLYRNOD3.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as i from"node:fs";import{randomUUID as d}from"node:crypto";import*as s from"node:path";var m=e("INSTALLATION"),o=class{getInstallationIdPath(){return a.getInstallationIdPath()}readInstallationIdFromFile(){let t=this.getInstallationIdPath();return i.existsSync(t)&&i.readFileSync(t,"utf-8").trim()||null}writeInstallationIdToFile(t){let r=this.getInstallationIdPath(),I=s.dirname(r);i.mkdirSync(I,{recursive:!0}),l(r,t,{encoding:"utf-8"})}getInstallationId(){try{let t=this.readInstallationIdFromFile();return t||(t=d(),this.writeInstallationIdToFile(t)),t}catch(t){return m.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}};export{o as a};
3
+ import{e as l}from"./chunk-GO2GA2GY.js";import{Q as a,ba as e}from"./chunk-MH2P4YXC.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as i from"node:fs";import{randomUUID as d}from"node:crypto";import*as s from"node:path";var m=e("INSTALLATION"),o=class{getInstallationIdPath(){return a.getInstallationIdPath()}readInstallationIdFromFile(){let t=this.getInstallationIdPath();return i.existsSync(t)&&i.readFileSync(t,"utf-8").trim()||null}writeInstallationIdToFile(t){let r=this.getInstallationIdPath(),I=s.dirname(r);i.mkdirSync(I,{recursive:!0}),l(r,t,{encoding:"utf-8"})}getInstallationId(){try{let t=this.readInstallationIdFromFile();return t||(t=d(),this.writeInstallationIdToFile(t)),t}catch(t){return m.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}};export{o as a};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as h,g}from"./chunk-W5CGKUM4.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-GO2GA2GY.js";import{b as c,ba as b}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
+ `,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Matilda
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
@@ -0,0 +1,39 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as ye}from"./chunk-ODZOYHIC.js";import{c as V,f as 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(`
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}
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:
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};
12
+ /**
13
+ * @license
14
+ * Copyright 2026 Matilda
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+ /**
18
+ * @license
19
+ * Copyright 2025 Matilda
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ */
22
+ /**
23
+ * @license
24
+ * Copyright 2026 Maincode
25
+ * SPDX-License-Identifier: Apache-2.0
26
+ *
27
+ * OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
28
+ *
29
+ * Emulates Grok Build's automatic credential refresh
30
+ * (docs: "Automatic Credential Refresh"):
31
+ * 1. Before each request: ensure a fresh access token (re-read disk; refresh
32
+ * when within the early-invalidation window / already expired).
33
+ * 2. On 401 Unauthorized: force-refresh and retry the request once.
34
+ * 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
35
+ *
36
+ * Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
37
+ * createContentGenerator time, so idle sessions past access-token expiry
38
+ * failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
39
+ */
@@ -0,0 +1,10 @@
1
+ // Force strict mode and setup for ESM
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(`
4
+ `)).join(`
5
+ `)}}export{k as a,g as b};
6
+ /**
7
+ * @license
8
+ * Copyright 2026 Matilda
9
+ * SPDX-License-Identifier: Apache-2.0
10
+ */
@@ -0,0 +1,35 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as r}from"./chunk-HYVP4472.js";import{ba as g}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();function h(n,o){return`Base directory for this skill: ${n}
4
+ Important: ALWAYS resolve absolute paths from this base directory when working with skills.
5
+
6
+ ${o}
7
+ `}async function C(n,o){let i=await n.listSkills(),l=o.getDisabledSkillNames(),t=e=>l.has(e.toLowerCase()),s=i.filter(e=>!e.disableModelInvocation&&n.isSkillActive(e)&&!t(e.name)),m=new Set(i.filter(e=>!e.disableModelInvocation&&e.paths&&e.paths.length>0&&!n.isSkillActive(e)&&!t(e.name)).map(e=>e.name)),a=o.getModelInvocableCommandsProvider(),c=a?a():[],k=new Set(i.filter(e=>!e.disableModelInvocation&&!t(e.name)).map(e=>e.name)),d=c.filter(e=>!k.has(e.name)),S=[...s.map(e=>({name:e.name,description:e.description,whenToUse:e.whenToUse,level:e.level})),...d.map(e=>({name:e.name,description:e.description}))];return{availableSkills:s,pendingConditionalSkillNames:m,modelInvocableCommands:d,entries:S}}function u(n,o){let i=n.level!==void 0?0:1,l=o.level!==void 0?0:1;return i!==l?i-l:n.name.localeCompare(o.name)}function H(n){return[...n].sort(u).map(o=>{if(o.level!==void 0){let i=`${r(o.description)}${o.whenToUse?` \u2014 ${r(o.whenToUse)}`:""} (${o.level})`;return`<skill>
8
+ <name>
9
+ ${r(o.name)}
10
+ </name>
11
+ <description>
12
+ ${i}
13
+ </description>
14
+ <location>
15
+ ${o.level}
16
+ </location>
17
+ </skill>`}return`<skill>
18
+ <name>
19
+ ${r(o.name)}
20
+ </name>
21
+ <description>
22
+ ${r(o.description)}
23
+ </description>
24
+ </skill>`}).join(`
25
+ `)}function y(n,o){if(!(!n||!o?.length))for(let i of o)n.addSessionAllowRule(i)}f();var p=g("SKILL_HOOKS");function M(n,o,i){if(!i.hooks)return p.debug(`Skill '${i.name}' has no hooks to register`),0;let l=i.hooks,t=0;for(let s of Object.keys(l)){let m=l[s];if(m)for(let a of m){let c=a.matcher||"";for(let k of a.hooks){if(k.type==="function"){p.debug("Skipping function hook from skill (not supported in frontmatter)");continue}let d=v(k,i.skillRoot);n.addSessionHook(o,s,c,d,{skillRoot:i.skillRoot}),t++,p.debug(`Registered hook for ${s} with matcher '${c}' from skill '${i.name}'`)}}}return t>0&&p.info(`Registered ${t} hooks from skill '${i.name}'`),t}function v(n,o){return n.type==="command"&&o?{...n,env:{...n.env,MATILDA_SKILL_ROOT:o}}:n}export{h as a,C as b,H as c,y as d,M as e};
26
+ /**
27
+ * @license
28
+ * Copyright 2025 Matilda
29
+ * SPDX-License-Identifier: Apache-2.0
30
+ */
31
+ /**
32
+ * @license
33
+ * Copyright 2026 Matilda Team
34
+ * SPDX-License-Identifier: Apache-2.0
35
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{aa as te}from"./chunk-VLYRNOD3.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-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`,:[]/{}()
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:`
@@ -0,0 +1,4 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{d as n,e as et,f as E,g as C,h as y,i as he,k as r,l as g,m as i,n as nt,o as h,q as H,r as a,t as l,z as A}from"./chunk-M53RP3YP.js";import{b as R}from"./chunk-GZPNIYVZ.js";R();var u={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},p={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_message:"mcp/message",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},ke={cancel_request:"$/cancel_request"},Vt=1;R();R();R();R();var tt=Symbol("skippedItem");function s(o,e){return o.catch(e)}function q(o,e){let t=o.catch(e);return A.unknown().transform((c,d)=>c!==void 0?t.parse(c):(d.addIssue({code:"custom",message:"Required value is missing"}),A.NEVER))}function st(o,e){if(o===null||typeof o!="object"||Array.isArray(o))return;let t=o[e];return typeof t=="string"?t:void 0}function B(o,e,t){return o.superRefine((c,d)=>{let z=st(c,e);z!==void 0&&t.includes(z)&&d.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(z)} is reserved by a known variant, but the value does not match that variant's schema`})})}function W(o,e,t){return A.unknown().transform((c,d)=>{let z=o.safeParse(c);if(!z.success){for(let _ of z.error.issues)d.addIssue({..._,input:c});return A.NEVER}let f=z.data,m=st(c,e);if(m!==void 0&&!t.includes(m)){let _=c;for(let[j,S]of Object.entries(_))j!=="__proto__"&&(Object.hasOwn(f,j)||(f[j]=S))}return f})}function it(o,e){return A.preprocess(t=>{if(t===null||typeof t!="object"||Array.isArray(t))return t;let c=t,d=c[e];if(d==null||typeof d=="string")return t;let z={...c};return delete z[e],z},o)}function T(o){return A.array(o.catch(tt)).transform(e=>e.filter(t=>t!==tt))}var G=h([E(),n()]).nullable(),b=n(),qe=i({sessionId:b,path:n(),content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Oe=i({sessionId:b,path:n(),line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),limit:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ie=n(),ot=h([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),rt=h([l("pending"),l("in_progress"),l("completed"),l("failed")]),Xt=h([l("assistant"),l("user")]),ae=i({audience:s(T(Xt).nullish(),()=>{}),lastModified:s(n().nullish(),()=>{}),priority:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Yt=i({annotations:s(ae.nullish(),()=>{}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zt=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),uri:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),es=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ns=i({annotations:s(ae.nullish(),()=>{}),description:s(n().nullish(),()=>{}),mimeType:s(n().nullish(),()=>{}),name:n(),size:s(E().nullish(),()=>{}),title:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ts=i({mimeType:s(n().nullish(),()=>{}),text:n(),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ss=i({blob:n(),mimeType:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),is=h([ts,ss]),os=i({annotations:s(ae.nullish(),()=>{}),resource:is,_meta:s(a(n(),r()).nullish(),()=>{})}),$=h([Yt.and(i({type:l("text")})),Zt.and(i({type:l("image")})),es.and(i({type:l("audio")})),ns.and(i({type:l("resource_link")})),os.and(i({type:l("resource")}))]),rs=i({content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),as=i({path:n(),oldText:s(n().nullish(),()=>{}),newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),V=n(),cs=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),at=h([rs.and(i({type:l("content")})),as.and(i({type:l("diff")})),cs.and(i({type:l("terminal")}))]),ct=i({path:n(),line:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),lt=i({toolCallId:Ie,kind:s(ot.nullish(),()=>{}),status:s(rt.nullish(),()=>{}),title:s(n().nullish(),()=>{}),name:s(n().nullish(),()=>{}),content:s(T(at).nullish(),()=>{}),locations:s(T(ct).nullish(),()=>{}),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),dt=n(),ls=h([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),ds=i({optionId:dt,name:n(),kind:ls,_meta:s(a(n(),r()).nullish(),()=>{})}),He=i({sessionId:b,toolCall:lt,options:g(ds),_meta:s(a(n(),r()).nullish(),()=>{})}),ut=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ve=i({sessionId:b,command:n(),args:g(n()).optional(),env:g(ut).optional(),cwd:n().nullish(),outputByteLimit:E().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ae=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ge=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Pe=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Le=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),ce=i({sessionId:b,toolCallId:s(Ie.nullish(),()=>{})}),le=i({requestId:G}),us=l("object"),zs=h([l("email"),l("uri"),l("date"),l("date-time")]),zt=i({const:n(),title:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ue=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:n().nullish(),format:zs.nullish(),default:s(n().nullish(),()=>{}),enum:g(n()).nullish(),oneOf:g(zt).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fe=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Be=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),We=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),default:s(y().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),$e=i({enum:g(n()),_meta:s(a(n(),r()).nullish(),()=>{})}),pt=i({anyOf:g(zt),_meta:s(a(n(),r()).nullish(),()=>{})}),ps=W(h([$e.and(i({type:l("string")})),B(i({type:n()}),"type",["string"]),pt]),"type",["string"]),Je=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minItems:E().nullish(),maxItems:E().nullish(),items:ps,default:s(T(n()).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hs=W(h([Ue.and(i({type:l("string")})),Fe.and(i({type:l("number")})),Be.and(i({type:l("integer")})),We.and(i({type:l("boolean")})),Je.and(i({type:l("array")})),B(i({type:n()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),fs=i({type:s(us.optional().default("object"),()=>"object"),title:s(n().nullish(),()=>{}),properties:a(n(),hs).optional().default({}),required:g(n()).nullish(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ve=H(h([ce,le]),i({requestedSchema:fs})),ht=n(),Ke=H(h([ce,le]),i({elicitationId:ht,url:et()})),Qe=W(H(h([Ve.and(i({mode:l("form")})),Ke.and(i({mode:l("url")})),B(H(h([ce,le]),i({mode:n()})),"mode",["form","url"])]),i({message:n(),_meta:s(a(n(),r()).nullish(),()=>{})})),"mode",["form","url"]),Xe=n(),ft=n(),ms=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),mt=r(),Fr=i({id:G,method:n(),params:h([qe,Oe,He,ve,Ae,Ge,Pe,Le,Qe,ms,mt]).nullish()}),gt=C().gte(0).lte(65535),gs=i({image:s(y().optional().default(!1),()=>!1),audio:s(y().optional().default(!1),()=>!1),embeddedContext:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),_s=i({http:s(y().optional().default(!1),()=>!1),sse:s(y().optional().default(!1),()=>!1),acp:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Es=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ss=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ts=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ws=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Rs=i({list:s(bs.nullish(),()=>{}),delete:s(Es.nullish(),()=>{}),additionalDirectories:s(xs.nullish(),()=>{}),fork:s(Ss.nullish(),()=>{}),resume:s(Ts.nullish(),()=>{}),close:s(ws.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ns=i({_meta:s(a(n(),r()).nullish(),()=>{})}),js=i({logout:s(Ns.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ys=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Cs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ms=h([l("full"),l("incremental")]),ks=i({syncKind:Ms,_meta:s(a(n(),r()).nullish(),()=>{})}),Ds=i({_meta:s(a(n(),r()).nullish(),()=>{})}),qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Os=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Is=i({didOpen:s(Cs.nullish(),()=>{}),didChange:s(ks.nullish(),()=>{}),didClose:s(Ds.nullish(),()=>{}),didSave:s(qs.nullish(),()=>{}),didFocus:s(Os.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Hs=i({document:s(Is.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),vs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),As=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Gs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ps=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ls=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Us=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Fs=i({recentFiles:s(vs.nullish(),()=>{}),relatedSnippets:s(As.nullish(),()=>{}),editHistory:s(Gs.nullish(),()=>{}),userActions:s(Ps.nullish(),()=>{}),openFiles:s(Ls.nullish(),()=>{}),diagnostics:s(Us.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Bs=i({events:s(Hs.nullish(),()=>{}),context:s(Fs.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),_t=h([l("utf-16"),l("utf-32"),l("utf-8")]),Ws=i({loadSession:s(y().optional().default(!1),()=>!1),promptCapabilities:s(gs.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:s(_s.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:s(Rs.optional().default({}),()=>({})),auth:s(js.optional().default({}),()=>({})),providers:s(ys.nullish(),()=>{}),nes:s(Bs.nullish(),()=>{}),positionEncoding:s(_t.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ye=n(),$s=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),args:g(n()).optional(),env:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Js=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Vs=h([$s.and(i({type:l("terminal")})),Js]),bt=i({name:n(),title:s(n().nullish(),()=>{}),version:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ks=i({protocolVersion:gt,agentCapabilities:s(Ws.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:s(T(Vs).optional().default([]),()=>[]),agentInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ze=n(),en=h([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),n()]),Xs=i({apiType:en,baseUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ys=i({providerId:Ze,supported:q(T(en),()=>[]),required:y(),current:Xs.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zs=i({providers:g(Ys),_meta:s(a(n(),r()).nullish(),()=>{})}),ei=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ni=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ti=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fe=n(),si=i({id:fe,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),me=i({currentModeId:fe,availableModes:q(T(si),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Et=n(),ii=h([l("mode"),l("model"),l("model_config"),l("thought_level"),n()]),nn=n(),xt=i({value:nn,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),oi=n(),ri=i({group:oi,name:n(),options:q(T(xt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),ai=h([g(xt),g(ri)]),ci=i({currentValue:nn,options:ai}),li=i({currentValue:y()}),K=H(h([ci.and(i({type:l("select")})),li.and(i({type:l("boolean")}))]),i({id:Et,name:n(),description:s(n().nullish(),()=>{}),category:s(ii.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})})),di=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ui=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),zi=i({sessionId:b,cwd:n(),additionalDirectories:s(T(n()).optional(),()=>[]),title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),pi=i({sessions:q(T(zi),()=>[]),nextCursor:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fi=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mi=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),gi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_i=i({_meta:s(a(n(),r()).nullish(),()=>{})}),bi=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Ei=h([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),ge=i({totalTokens:E(),inputTokens:E(),outputTokens:E(),thoughtTokens:s(E().nullish(),()=>{}),cachedReadTokens:s(E().nullish(),()=>{}),cachedWriteTokens:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),xi=i({stopReason:Ei,usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Si=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Q=n(),P=i({line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:s(a(n(),r()).nullish(),()=>{})}),X=i({start:P,end:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ti=i({range:X,newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),wi=i({id:Q,uri:n(),edits:g(Ti),cursorPosition:s(P.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ri=i({id:Q,uri:n(),position:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ni=i({id:Q,uri:n(),position:P,newName:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ji=i({id:Q,uri:n(),search:n(),replace:n(),isRegex:y().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yi=h([wi.and(i({kind:l("edit")})),Ri.and(i({kind:l("jump")})),Ni.and(i({kind:l("rename")})),ji.and(i({kind:l("searchAndReplace")}))]),Ci=i({suggestions:g(yi),_meta:s(a(n(),r()).nullish(),()=>{})}),Mi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),St=r(),ki=h([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),de=i({code:ki,message:n(),data:s(r().optional(),()=>{})}),Br=h([i({id:G,result:h([Ks,Qs,Zs,ei,ni,ti,di,ui,pi,hi,fi,mi,gi,_i,bi,xi,Si,Ci,Mi,St])}),i({id:G,error:de})]),tn=n(),De=i({content:$,messageId:s(tn.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Di=i({toolCallId:Ie,title:n(),name:s(n().nullish(),()=>{}),kind:s(ot.optional(),()=>{}),status:s(rt.optional(),()=>{}),content:s(T(at).optional(),()=>[]),locations:s(T(ct).optional(),()=>[]),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qi=h([l("high"),l("medium"),l("low")]),Oi=h([l("pending"),l("in_progress"),l("completed")]),Tt=i({content:n(),priority:qi,status:Oi,_meta:s(a(n(),r()).nullish(),()=>{})}),Ii=i({entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),_e=n(),Hi=i({planId:_e,entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),vi=i({planId:_e,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ai=i({planId:_e,content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Gi=h([Hi.and(i({type:l("items")})),vi.and(i({type:l("file")})),Ai.and(i({type:l("markdown")}))]),Pi=i({plan:Gi,_meta:s(a(n(),r()).nullish(),()=>{})}),Li=i({planId:_e,_meta:s(a(n(),r()).nullish(),()=>{})}),Ui=i({hint:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fi=Ui,Bi=i({name:n(),description:n(),input:s(Fi.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Wi=i({availableCommands:q(T(Bi),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),$i=i({currentModeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),Ji=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Vi=i({title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ki=i({amount:E(),currency:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Qi=i({used:E(),size:E(),cost:s(Ki.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xi=h([l("info"),l("warning"),l("error"),n()]),Yi=i({severity:Xi,title:n().min(1),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),wt=n(),Zi=h([l("in_progress"),l("completed"),l("failed"),l("cancelled"),n()]),eo=i({compactionId:wt,status:Zi,summary:s(T($).nullish(),()=>{}),error:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),no=i({compactionId:wt,content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),to=i({_meta:s(a(n(),r()).nullish(),()=>{})}),so=i({cancel:s(to.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),sn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),on=i({error:s(de.nullish(),()=>{})}),rn=it(W(H(h([i({stopReason:l("end_turn")}),i({stopReason:l("max_tokens")}),i({stopReason:l("max_turn_requests")}),i({stopReason:l("refusal")}),i({stopReason:l("cancelled")}),on.and(i({stopReason:l("error")})),B(i({stopReason:n()}),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),i({stopReason:he().optional()})]),i({usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{}),stopReason:s(n().nullish(),()=>{})})),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),"stopReason"),an=i({_meta:s(a(n(),r()).nullish(),()=>{})}),cn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),io=W(h([sn.and(i({state:l("running")})),rn.and(i({state:l("idle")})),an.and(i({state:l("requires_action")})),cn.and(i({state:l("unknown")})),B(i({state:n()}),"state",["idle","requires_action","running","unknown"])]),"state",["idle","requires_action","running","unknown"]),oo=i({sessionId:b,title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),capabilities:s(so.nullish(),()=>{}),state:s(io.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ro=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:s(T($).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ao=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),co=h([De.and(i({sessionUpdate:l("user_message_chunk")})),De.and(i({sessionUpdate:l("agent_message_chunk")})),De.and(i({sessionUpdate:l("agent_thought_chunk")})),Di.and(i({sessionUpdate:l("tool_call")})),lt.and(i({sessionUpdate:l("tool_call_update")})),Ii.and(i({sessionUpdate:l("plan")})),Pi.and(i({sessionUpdate:l("plan_update")})),Li.and(i({sessionUpdate:l("plan_removed")})),Wi.and(i({sessionUpdate:l("available_commands_update")})),$i.and(i({sessionUpdate:l("current_mode_update")})),Ji.and(i({sessionUpdate:l("config_option_update")})),Vi.and(i({sessionUpdate:l("session_info_update")})),Qi.and(i({sessionUpdate:l("usage_update")})),Yi.and(i({sessionUpdate:l("notice")})),eo.and(i({sessionUpdate:l("compaction_update")})),no.and(i({sessionUpdate:l("compaction_summary_chunk")})),oo.and(i({sessionUpdate:l("subagent_update")})),ro.and(i({sessionUpdate:l("session_message")})),ao.and(i({sessionUpdate:l("session_message_chunk")}))]),be=i({sessionId:b,update:co,_meta:s(a(n(),r()).nullish(),()=>{})}),ln=i({elicitationId:ht,_meta:s(a(n(),r()).nullish(),()=>{})}),Rt=r(),Wr=i({method:n(),params:h([be,ln,Rt]).nullish()}),lo=i({readTextFile:s(y().optional().default(!1),()=>!1),writeTextFile:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),uo=a(n(),r()),zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),po=i({boolean:s(zo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ho=a(n(),r()),fo=i({compaction:s(uo.nullish(),()=>{}),configOptions:s(po.nullish(),()=>{}),notices:s(ho.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),go=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_o=i({terminal:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Eo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xo=i({form:s(bo.nullish(),()=>{}),url:s(Eo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),So=i({_meta:s(a(n(),r()).nullish(),()=>{})}),To=i({_meta:s(a(n(),r()).nullish(),()=>{})}),wo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ro=i({jump:s(So.nullish(),()=>{}),rename:s(To.nullish(),()=>{}),searchAndReplace:s(wo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),No=i({fs:s(lo.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:s(y().optional().default(!1),()=>!1),session:s(fo.nullish(),()=>{}),subagents:s(mo.nullish(),()=>{}),plan:s(go.nullish(),()=>{}),auth:s(_o.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:s(xo.nullish(),()=>{}),nes:s(Ro.nullish(),()=>{}),positionEncodings:s(T(_t).optional(),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),dn=i({protocolVersion:gt,clientCapabilities:s(No.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),un=i({methodId:Ye,_meta:s(a(n(),r()).nullish(),()=>{})}),zn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),pn=i({providerId:Ze,apiType:en,baseUrl:n(),headers:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),hn=i({providerId:Ze,_meta:s(a(n(),r()).nullish(),()=>{})}),fn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Nt=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),jo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),yo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),Co=i({name:n(),serverId:Xe,_meta:s(a(n(),r()).nullish(),()=>{})}),Mo=i({name:n(),command:n(),args:g(n()),env:g(ut),_meta:s(a(n(),r()).nullish(),()=>{})}),Ee=h([jo.and(i({type:l("http")})),yo.and(i({type:l("sse")})),Co.and(i({type:l("acp")})),Mo]),mn=i({cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee),_meta:s(a(n(),r()).nullish(),()=>{})}),gn=i({mcpServers:g(Ee),cwd:n(),additionalDirectories:g(n()).optional(),sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),_n=i({cwd:n().nullish(),cursor:n().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),bn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),En=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),xn=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Sn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Tn=i({sessionId:b,modeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),wn=H(h([i({value:y(),type:l("boolean")}),i({value:nn})]),i({sessionId:b,configId:Et,_meta:s(a(n(),r()).nullish(),()=>{})})),Rn=i({sessionId:b,prompt:g($),_meta:s(a(n(),r()).nullish(),()=>{})}),ko=i({uri:n(),name:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Do=i({name:n(),owner:n(),remoteUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Nn=i({workspaceUri:s(n().nullish(),()=>{}),workspaceFolders:g(ko).nullish(),repository:s(Do.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qo=h([l("automatic"),l("diagnostic"),l("manual")]),Oo=i({uri:n(),languageId:n(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Io=i({startLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ho=i({uri:n(),excerpts:g(Io),_meta:s(a(n(),r()).nullish(),()=>{})}),vo=i({uri:n(),diff:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ao=i({action:n(),uri:n(),position:P,timestampMs:E(),_meta:s(a(n(),r()).nullish(),()=>{})}),Go=i({uri:n(),languageId:n(),visibleRange:s(X.nullish(),()=>{}),lastFocusedMs:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Po=h([l("error"),l("warning"),l("information"),l("hint")]),Lo=i({uri:n(),range:X,severity:Po,message:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Uo=i({recentFiles:g(Oo).nullish(),relatedSnippets:g(Ho).nullish(),editHistory:g(vo).nullish(),userActions:g(Ao).nullish(),openFiles:g(Go).nullish(),diagnostics:g(Lo).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),jn=i({sessionId:b,uri:n(),version:E(),position:P,selection:X.nullish(),triggerKind:qo,context:Uo.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),$r=i({id:G,method:n(),params:h([dn,un,zn,pn,hn,fn,mn,gn,_n,bn,En,xn,Sn,Tn,wn,Rn,Nn,jn,yn,mt]).nullish()}),Fo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Bo=i({content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Wo=i({optionId:dt,_meta:s(a(n(),r()).nullish(),()=>{})}),$o=h([i({outcome:l("cancelled")}),Wo.and(i({outcome:l("selected")}))]),Jo=i({outcome:$o,_meta:s(a(n(),r()).nullish(),()=>{})}),Vo=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ko=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qo=i({output:n(),truncated:y(),exitStatus:s(Ko.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Yo=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),er=h([n(),E(),E(),y(),g(n())]),Cn=i({content:a(n(),er).nullish()}),nr=W(H(h([Cn.and(i({action:l("accept")})),i({action:l("decline")}),i({action:l("cancel")}),B(i({action:n()}),"action",["accept","cancel","decline"])]),i({_meta:s(a(n(),r()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),tr=nt({code:C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"}),message:n(),data:r().optional()}),sr=h([i({result:r(),_meta:s(a(n(),r()).nullish(),()=>{})}),i({error:tr,_meta:s(a(n(),r()).nullish(),()=>{})})]),Jr=h([i({id:G,result:h([Fo,Bo,Jo,Vo,Qo,Xo,Yo,Zo,nr,sr,St])}),i({id:G,error:de})]),Mn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),kn=i({sessionId:b,uri:n(),languageId:n(),version:E(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ir=i({range:X.nullish(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Dn=i({sessionId:b,uri:n(),version:E(),contentChanges:g(ir),_meta:s(a(n(),r()).nullish(),()=>{})}),qn=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),On=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),In=i({sessionId:b,uri:n(),version:E(),position:P,visibleRange:X,_meta:s(a(n(),r()).nullish(),()=>{})}),Hn=i({sessionId:b,id:Q,_meta:s(a(n(),r()).nullish(),()=>{})}),or=h([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),vn=i({sessionId:b,id:Q,reason:s(or.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),rr=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Vr=i({method:n(),params:h([Mn,kn,Dn,qn,On,In,Hn,vn,rr,Rt]).nullish()}),Kr=i({requestId:G,_meta:s(a(n(),r()).nullish(),()=>{})});R();R();var yt="$/cancel_request";function xe(o){return Ln(o)&&"id"in o&&typeof o.method=="string"&&Un(o.id)}function Mt(o){if(!Ln(o)||"method"in o||!("id"in o)||!Un(o.id))return!1;let e=Object.hasOwn(o,"result"),t=Object.hasOwn(o,"error");return e===t?!1:!t||lr(o.error)}function Y(o){return Ln(o)&&!("id"in o)&&typeof o.method=="string"}function L(o){return typeof o=="object"&&o!==null}function Ln(o){return L(o)&&o.jsonrpc==="2.0"}function Un(o){return o===null||typeof o=="string"||typeof o=="number"&&Number.isFinite(o)}function Ct(o){return L(o)&&!("method"in o)&&("id"in o||"result"in o||"error"in o)}function ar(o){let e=!1,t=!1,c=!1,d=!1;for(let z of o)e||=xe(z)||Y(z),t||=Mt(z),L(z)&&(c||="method"in z,d||="result"in z||"error"in z);return e?!1:t?!0:d&&!c}function cr(o){if(!(!L(o)||!Un(o.requestId)))return o.requestId}function lr(o){return L(o)&&typeof o.code=="number"&&Number.isInteger(o.code)&&typeof o.message=="string"}var M={yes(){return{handled:!0}},no(o,e=!1){return{handled:!1,message:o,retry:e}}};function J(o){let e=Promise.reject(o);return e.catch(()=>{}),e}function dr(o){if(o instanceof Error||typeof o=="object"&&o!=null&&"message"in o&&typeof o.message=="string")return o.message}function ur(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="ZodError"&&"issues"in o&&Array.isArray(o.issues)&&"format"in o&&typeof o.format=="function"}function kt(o){if(o instanceof N)return o.toResult();if(ur(o))return N.invalidParams(o.format()).toResult();let e=dr(o);try{return N.internalError(e?JSON.parse(e):{}).toResult()}catch{return N.internalError({details:e}).toResult()}}function zr(o){return o instanceof N&&o.code===-32800?o:N.requestCancelled(o)}function pr(o,e){let t=hr(o,e);return t?t.toResult():kt(o)}function hr(o,e){if(!(!e.aborted||!fr(o)))return zr(e.reason)}function fr(o){if(typeof o!="object"||o===null)return!1;let e=o;return e.name==="AbortError"||e.code==="ABORT_ERR"}var An=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,c=new AbortController().signal,d){this.id=e,this.sendResult=t,this.signal=c,this.finishRequest=d}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof N?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?J(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},mr=new WeakMap;var ee=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Gn=class{connection;constructor(e){this.connection=e}sendRequest(e,t,c,d){return this.connection.sendRequest(e,t,c,d)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ne=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Gn(this);receiveReader;allowBatches=!0;constructor(e,t,c,d){if(typeof e=="function"){let _=e,j=t,S=c;this.initialize(S,[...d?.handlers??[],this.legacyHandler(_,j)],d);return}let z=e,f=t,m=c;this.initialize(z,[...m?.handlers??[],...f],m)}static builder(){return new Pn}runUntil(e){let t=!1,c=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),d=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([c,d]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch(c=>this.close(c));return new ee(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,c,d={}){if(this.abortController.signal.aborted)return J(this.closedReason());let z=this.prepareRequest(e,t,c,d);return this.sendWireMessage(z.message).catch(()=>{}),d.cancellationSignal?.aborted&&z.cancel(),z.response}sendBatch(e){if(this.abortController.signal.aborted)return J(this.closedReason());if(!this.allowBatches)return J(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return J(new TypeError("JSON-RPC batch must contain at least one entry"));let t=[],c=[],d=[];for(let _ of e){if(_.kind==="notification"){t.push({jsonrpc:"2.0",method:_.method,params:_.params}),d.push(Promise.resolve(void 0));continue}let j=this.prepareRequest(_.method,_.params,_.mapResponse,_.options);t.push(j.message),d.push(j.response),c.push({signal:_.options?.cancellationSignal,cancel:j.cancel})}let z=t,f=this.sendWireMessage(z);for(let _ of c)_.signal?.aborted&&_.cancel();let m=Promise.all([f,...d]).then(([,..._])=>_);return m.catch(()=>{}),m}sendCancelRequest(e){return this.sendNotification(yt,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?J(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,c,d={}){let z=this.nextRequestId++,f=()=>{},m=new Promise((_,j)=>{let S={resolve:D=>{try{_(c?c(D):D)}catch(k){j(k)}},reject:j};f=()=>{S.cancellationSent||(S.cancellationSent=!0,S.cleanup?.(),this.sendCancelRequest(z).catch(()=>{}))},d.cancellationSignal?.addEventListener("abort",f,{once:!0}),S.cleanup=()=>{d.cancellationSignal?.removeEventListener("abort",f)},this.pendingResponses.set(z,S)});return m.catch(()=>{}),{message:{jsonrpc:"2.0",id:z,method:e,params:t},response:m,cancel:()=>f()}}close(e){if(this.abortController.signal.aborted)return;let t=e??new Error("ACP connection closed");this.abortController.abort(t);for(let c of this.pendingResponses.values())c.cleanup?.(),c.reject(t);this.pendingResponses.clear();for(let c of this.incomingRequests.values())c.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,c){this.stream=e,this.staticHandlers=t,this.allowBatches=c?.allowBatches??!0,this.closedPromise=new Promise(d=>{this.abortController.signal.addEventListener("abort",()=>d())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(c,d)=>{if(c.kind==="request"){let z=await e(c.method,c.params,d);await c.responder.respond(z)}else await t(c.method,c.params,d);return M.yes()}}}async receive(){let e;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{for(;!this.abortController.signal.aborted;){let{value:c,done:d}=await t.read();if(this.abortController.signal.aborted||d)break;this.receiveWireMessage(c)}}finally{this.receiveReader===t&&(this.receiveReader=void 0),t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(e);return}if(!xe(e)&&!Y(e)&&!Ct(e)){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}let t=ar(e),d=t?0:e.reduce((S,D)=>S+(Y(D)?0:1),0),z=e.reduce((S,D)=>S+(Y(D)?1:0),0),f=!1,m=[],_=async()=>{f||d!==0||z!==0||m.length===0||(f=!0,await this.sendWireMessage(m))},j=async S=>{m.push(S),d-=1,await _()};for(let S of e){if(t){Ct(S)&&this.receiveMessage(S);continue}if(!xe(S)&&!Y(S)){j(Z(N.invalidRequest(S))).catch(()=>{});continue}let D=this.receiveMessage(S,xe(S)?j:void 0,e.length);Y(S)&&D.finally(()=>{z-=1,_().catch(k=>this.close(k))})}}receiveMessage(e,t,c){return this.abortController.signal.aborted?Promise.resolve():L(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,t,c)).catch(d=>this.close(d))):("id"in e?this.handleResponse(e):console.error("Invalid message",{message:e}),Promise.resolve()):(console.error("Invalid message",{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,c=!1;try{for(let d of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let z=await d.handleMessage(t,this.context)??{handled:!0};if(z.handled)return;t=z.message??t,c=c||!!z.retry}c?this.retryQueue.push(t):t.kind==="request"&&await t.responder.respondWithError(N.methodNotFound(t.method))}catch(d){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(pr(d,t.responder.signal));else{let z=kt(d);"error"in z&&console.error("Error handling notification",e.raw,z.error)}}}toIncomingMessage(e,t,c){if("id"in e){let d=new AbortController;this.incomingRequests.set(e.id,d);let z=()=>{this.incomingRequests.get(e.id)===d&&this.incomingRequests.delete(e.id)},f=new An(e.id,m=>{let _={jsonrpc:"2.0",id:e.id,...m};return t?t(_):this.sendWireMessage(_)},d.signal,z);return c!==void 0&&mr.set(f,c),{kind:"request",method:e.method,params:e.params,raw:e,signal:d.signal,responder:f}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),!Mt(e))t.reject(N.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:c,message:d,data:z}=e.error;t.reject(new N(c,d,z))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==yt)return;let t=cr(e.params);if(t===void 0)return;let c=this.incomingRequests.get(t);!c||c.signal.aborted||c.abort(N.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?J(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(t=>{throw this.close(t),t}),this.writeQueue)}},Pn=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,c)=>await e(t,c)??M.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="request"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,d.responder,z)??M.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="notification"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,z)??M.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new ne(e,this.handlers,t)}connectWith(e,t,c){return this.connect(e,c).runUntil(t)}},N=class o extends Error{code;data;constructor(e,t,c){super(t),this.code=e,this.name="RequestError",this.data=c}static parseError(e,t){return new o(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new o(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new o(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new o(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new o(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new o(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new o(-32e3,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new o(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function Z(o){return{jsonrpc:"2.0",id:null,error:o.toErrorResponse()}}R();R();var te=class extends Error{maxMessageBytes;constructor(e){super(`Incoming ACP data exceeds the configured ${e} byte limit`),this.maxMessageBytes=e,this.name="MessageTooLargeError"}};function ue(o){let e=o??33554432;if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("maxMessageBytes must be a positive safe integer");return e}var Se=class{#e=new Uint8Array(0);#n=0;#t;constructor(e){this.#t=ue(e)}get byteLength(){return this.#n}get lastByte(){return this.#e[this.#n-1]}#s(e){if(e>this.#t-this.#n)throw this.clear(),new te(this.#t)}append(e){this.#s(e.byteLength);let t=this.#n+e.byteLength;if(t>this.#e.byteLength){let c=Math.min(this.#t,Math.max(t,this.#e.byteLength*2,1024)),d=new Uint8Array(c);d.set(this.#e.subarray(0,this.#n)),this.#e=d}this.#e.set(e,this.#n),this.#n=t}take(){let e=this.#e.subarray(0,this.#n);return this.clear(),e}clear(){this.#e=new Uint8Array(0),this.#n=0}};var Dt=10,Te=class{#e;#n;constructor(e){this.#n=ue(e),this.#e=new Se(Math.min(Number.MAX_SAFE_INTEGER,this.#n+1))}*push(e){let t=0,c=e.indexOf(Dt,t);for(;c!==-1;)yield this.#t(e.subarray(t,c)),t=c+1,c=e.indexOf(Dt,t);if(t<e.byteLength){let d=e.subarray(t);this.#s(d),this.#e.append(d)}}flush(){if(this.#e.byteLength!==0)return Fn(this.#e.take())}clear(){this.#e.clear()}#t(e){return this.#s(e),this.#e.byteLength===0?Fn(e):(this.#e.append(e),Fn(this.#e.take()))}#s(e){let t=e.byteLength>0?e[e.byteLength-1]:this.#e.lastByte;if(this.#e.byteLength+e.byteLength-(t===13?1:0)>this.#n)throw this.clear(),new te(this.#n)}};function Fn(o){return o[o.byteLength-1]===13?o.subarray(0,-1):o}function qt(o,e,t={}){let c=ue(t.maxMessageBytes),d=new TextEncoder,z=new TextDecoder,f=!1,m,_=Promise.resolve(),j=k=>{let ie=JSON.stringify(k)+`
4
+ `,oe=_.then(async()=>{let v=o.getWriter();try{await v.write(d.encode(ie))}finally{v.releaseLock()}});return _=oe.catch(()=>{}),oe},S=new ReadableStream({async start(k){let ie=new Te(c),oe=async U=>{let re=z.decode(U).trim();if(!re)return;let F;try{F=JSON.parse(re)}catch{await j(Z(N.parseError()));return}L(F)||Array.isArray(F)?k.enqueue(F):await j(Z(N.invalidRequest(F)))},v=e.getReader();m=v;try{for(;;){let{value:re,done:F}=await v.read();if(f)return;if(F)break;if(re){for(let Jt of ie.push(re))if(await oe(Jt),f)return}}if(f)return;let U=ie.flush();U&&await oe(U)}catch(U){if(f)return;k.error(U),v.cancel(U).catch(()=>{});return}finally{ie.clear(),m===v&&(m=void 0),v.releaseLock()}f||k.close()},cancel(k){return f=!0,m?.cancel(k)}}),D=new WritableStream({write(k){return j(k)}});return{readable:S,writable:D}}R();var la=Ve.and(i({mode:l("form")})).and(i({message:n()})),da=Ke.and(i({mode:l("url")})).and(i({message:n()})),ua=h([ce,le]).and(i({message:n()})),za=Ue.and(i({type:l("string")})),pa=Fe.and(i({type:l("number")})),ha=Be.and(i({type:l("integer")})),fa=We.and(i({type:l("boolean")})),ma=Je.and(i({type:l("array")})),ga=$e.and(i({type:l("string")}));var _a=sn.and(i({state:l("running")})),ba=rn.and(i({usage:ge.nullish()})).and(i({state:l("idle")})),Ea=an.and(i({state:l("requires_action")})),xa=cn.and(i({state:l("unknown")})),Sa=i({stopReason:l("end_turn")}),Ta=i({stopReason:l("max_tokens")}),wa=i({stopReason:l("max_turn_requests")}),Ra=i({stopReason:l("refusal")}),Na=i({stopReason:l("cancelled")}),ja=on.and(i({error:de.nullish()})).and(i({stopReason:l("error")})),ya=i({stopReason:he().optional()}),Ca=Cn.and(i({action:l("accept")})),Ma=i({action:l("decline")}),ka=i({action:l("cancel")});function Ua(o,e,t){return qt(o,e,t)}function w(o){return o??{}}function At(o){return typeof o=="object"&&o!==null&&"readable"in o&&"writable"in o}function Gt(){let o=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:o.writable},{readable:o.readable,writable:e.writable}]}var Ba={agent:{initialize:u.initialize,authenticate:u.authenticate,logout:u.logout,providers:{list:u.providers_list,set:u.providers_set,disable:u.providers_disable},session:{new:u.session_new,load:u.session_load,list:u.session_list,delete:u.session_delete,fork:u.session_fork,resume:u.session_resume,close:u.session_close,setMode:u.session_set_mode,setConfigOption:u.session_set_config_option,prompt:u.session_prompt,cancel:u.session_cancel},nes:{start:u.nes_start,suggest:u.nes_suggest,accept:u.nes_accept,reject:u.nes_reject,close:u.nes_close},document:{didOpen:u.document_did_open,didChange:u.document_did_change,didClose:u.document_did_close,didSave:u.document_did_save,didFocus:u.document_did_focus}},client:{session:{requestPermission:p.session_request_permission,update:p.session_update},fs:{writeTextFile:p.fs_write_text_file,readTextFile:p.fs_read_text_file},terminal:{create:p.terminal_create,output:p.terminal_output,release:p.terminal_release,waitForExit:p.terminal_wait_for_exit,kill:p.terminal_kill},elicitation:{create:p.elicitation_create,complete:p.elicitation_complete}},protocol:{cancelRequest:ke.cancel_request}},Pt=Symbol("startActiveSession"),Ne=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,c,d){return this.cx.sendRequest(e,t,c,d)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},ze=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}request(e,t,c){let d=Zn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},pe=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}[Pt](e,t){return this.sendRequest(u.session_new,e,c=>this.attachSession(c),t)}buildSession(e){return typeof e=="string"?ye.create(this,{cwd:e,mcpServers:[]}):ye.create(this,e)}attachSession(e){let t=new $n,c=this.connectionContext.signal,d=()=>{t.fail(c.reason??new Error("ACP connection closed"))};c.aborted?d():c.addEventListener("abort",d);let z=$t(this.connectionContext).attach(e,t),f=new ee(()=>{c.removeEventListener("abort",d)});return Jn.create(this,e,t,[z,f])}request(e,t,c){let d=Yn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},je=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},Bn=class extends je{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=ze.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}},Wn=class extends je{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=pe.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}};function Lt(o,e=[]){return new Bn(o,e)}function Ut(o,e=[]){return new Wn(o,e)}var $n=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function Ot(o){return{...o,additionalDirectories:o.additionalDirectories?[...o.additionalDirectories]:void 0,mcpServers:[...o.mcpServers]}}var ye=class o{cx;request;constructor(e,t){this.cx=e,this.request=Ot(t)}static create(e,t){return new o(e,t)}toRequest(){return Ot(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Pt](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},Jn=class o{cx;sessionResponse;updates;registrations;constructor(e,t,c,d){this.cx=e,this.sessionResponse=t,this.updates=c,this.registrations=d}static create(e,t,c,d){return new o(e,t,c,d)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let c=this.cx.request(u.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return c.then(d=>{this.updates.enqueue({kind:"stop",response:d,stopReason:d.stopReason})},d=>{this.updates.reject(d)}),c}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:c}=t;c.sessionUpdate==="agent_message_chunk"&&c.content.type==="text"&&(e+=c.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}};function Ft(o,e){return o?typeof o=="function"?o(e):o.parse(e):e}function x(o,e,t){return{method:o,params:e,mapResponse:t}}function O(o,e){return{method:o,params:e}}function Bt(o,e,t,c){o.onReceiveRequest(e.method,d=>Ft(e.params,d),async(d,z,f)=>{let m=await c(t(d,f,z.signal,z.id));await z.respond(e.mapResponse?e.mapResponse(m):m)})}function Wt(o,e,t,c){o.onReceiveNotification(e.method,d=>Ft(e.params,d),(d,z)=>c(t(d,z,z.signal)))}function Ce(o){let e={};for(let t of Object.values(o))e[t.method]=t;return e}var gr={initialize:x(u.initialize,dn),newSession:x(u.session_new,mn),loadSession:x(u.session_load,gn,w),unstable_forkSession:x(u.session_fork,En),listSessions:x(u.session_list,_n),deleteSession:x(u.session_delete,bn,w),resumeSession:x(u.session_resume,xn),closeSession:x(u.session_close,Sn,w),setSessionMode:x(u.session_set_mode,Tn,w),setSessionConfigOption:x(u.session_set_config_option,wn),authenticate:x(u.authenticate,un,w),unstable_listProviders:x(u.providers_list,zn),unstable_setProvider:x(u.providers_set,pn,w),unstable_disableProvider:x(u.providers_disable,hn,w),logout:x(u.logout,fn,w),prompt:x(u.session_prompt,Rn),unstable_startNes:x(u.nes_start,Nn),unstable_suggestNes:x(u.nes_suggest,jn),unstable_closeNes:x(u.nes_close,yn,w)},_r={cancel:O(u.session_cancel,Mn),unstable_didOpenDocument:O(u.document_did_open,kn),unstable_didChangeDocument:O(u.document_did_change,Dn),unstable_didCloseDocument:O(u.document_did_close,qn),unstable_didSaveDocument:O(u.document_did_save,On),unstable_didFocusDocument:O(u.document_did_focus,In),unstable_acceptNes:O(u.nes_accept,Hn),unstable_rejectNes:O(u.nes_reject,vn)},br={requestPermission:x(p.session_request_permission,He),writeTextFile:x(p.fs_write_text_file,qe,w),readTextFile:x(p.fs_read_text_file,Oe),createTerminal:x(p.terminal_create,ve),terminalOutput:x(p.terminal_output,Ae),releaseTerminal:x(p.terminal_release,Ge,w),waitForTerminalExit:x(p.terminal_wait_for_exit,Pe),killTerminal:x(p.terminal_kill,Le,w),createElicitation:x(p.elicitation_create,Qe)},Er={sessionUpdate:O(p.session_update,be),completeElicitation:O(p.elicitation_complete,ln)},Yn=Ce(gr),xr=Ce(_r),Zn=Ce(br),Sr=Ce(Er);function Tr(o,e,t,c){return{params:o,requestId:c,signal:t,client:e}}function wr(o,e,t){return{params:o,signal:t,client:e}}function Rr(o,e,t,c){return{params:o,requestId:c,signal:t,agent:e}}function Nr(o,e,t){return{params:o,signal:t,agent:e}}var Vn=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==p.session_update)return M.no(e);let t=be.parse(e.params),c={kind:"session_update",notification:t,update:t.update},d=this.activeSessions.get(t.sessionId);if(d&&d.size>0)for(let z of d)z.enqueue(c);return M.no(e)}attach(e,t){let c=this.activeSessions.get(e.sessionId)??new Set;return c.add(t),this.activeSessions.set(e.sessionId,c),new ee(()=>{c.delete(t),c.size===0&&this.activeSessions.delete(e.sessionId)})}},It=new WeakMap;function $t(o){let e=It.get(o);return e||(e=new Vn,It.set(o,e)),e}function Me(o,e){for(let t of e){let c;try{c=t(o)}catch(d){throw o.close(d),d}Promise.resolve(c).catch(d=>{o.close(d)})}}var I=Symbol("appBuilder"),we=Symbol("runAgentConnectHandlers"),Re=Symbol("runClientConnectHandlers"),se={allowBatches:!1};function jr(o){return new Kn(o)}var Kn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[I](){return this.builder}[we](e){Me(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Yn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=xr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Tr(c,ze.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>wr(c,ze.create(d),z),t),this}connectConnection(e,t={}){if(At(e)){let _=this.openStreamConnection(e);return t.deferConnectHandlers||this[we](_.connection),_}let[c,d]=Gt(),z=e[I]().connect(d,se),f=Ut(z),m=this.openStreamConnection(c);m.rawConnection.closed.then(()=>f.close()),z.closed.then(()=>m.connection.close());try{e[Re](f),this[we](m.connection)}catch(_){throw f.close(_),m.connection.close(_),_}return m}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Lt(t,this.connectHandlers)}}};function yr(o){return new Qn(o)}var Qn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(t,c)=>$t(c).handleMessage(t),describe:()=>"client-session-update-router"})}[I](){return this.builder}[Re](e){Me(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Zn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=Sr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Rr(c,pe.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>Nr(c,pe.create(d),z),t),this}connectConnection(e){if(At(e)){let m=this.openStreamConnection(e);return this[Re](m.connection),m}let[t,c]=Gt(),d=e[I]().connect(c,se),z=Lt(d),f=this.openStreamConnection(t);f.rawConnection.closed.then(()=>z.close()),d.closed.then(()=>f.connection.close());try{e[we](z),this[Re](f.connection)}catch(m){throw z.close(m),f.connection.close(m),m}return f}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Ut(t,this.connectHandlers)}}},Cr=new Set([u.initialize,u.authenticate,u.providers_list,u.providers_set,u.providers_disable,u.session_new,u.session_load,u.session_set_mode,u.session_set_config_option,u.session_prompt,u.session_list,u.session_delete,u.session_fork,u.session_resume,u.session_close,u.logout,u.nes_start,u.nes_suggest,u.nes_close]),Mr=new Set([u.session_cancel,u.nes_accept,u.nes_reject,u.document_did_open,u.document_did_change,u.document_did_close,u.document_did_save,u.document_did_focus]),kr=new Set([p.session_request_permission,p.fs_write_text_file,p.fs_read_text_file,p.terminal_create,p.terminal_output,p.terminal_release,p.terminal_wait_for_exit,p.terminal_kill,p.elicitation_create]),Dr=new Set([p.session_update,p.elicitation_complete]);function qr(o){let e=jr().onRequest(u.initialize,t=>o.initialize(t.params)).onRequest(u.session_new,t=>o.newSession(t.params)).onRequest(u.authenticate,async t=>await o.authenticate(t.params)??{}).onRequest(u.session_prompt,t=>o.prompt(t.params)).onNotification(u.session_cancel,t=>o.cancel(t.params));return o.loadSession&&e.onRequest(u.session_load,t=>o.loadSession(t.params)),o.listSessions&&e.onRequest(u.session_list,t=>o.listSessions(t.params)),o.deleteSession&&e.onRequest(u.session_delete,async t=>await o.deleteSession(t.params)??{}),o.unstable_forkSession&&e.onRequest(u.session_fork,t=>o.unstable_forkSession(t.params)),o.resumeSession&&e.onRequest(u.session_resume,t=>o.resumeSession(t.params)),o.closeSession&&e.onRequest(u.session_close,async t=>await o.closeSession(t.params)??{}),o.setSessionMode&&e.onRequest(u.session_set_mode,async t=>await o.setSessionMode(t.params)??{}),o.setSessionConfigOption&&e.onRequest(u.session_set_config_option,t=>o.setSessionConfigOption(t.params)),o.unstable_listProviders&&e.onRequest(u.providers_list,t=>o.unstable_listProviders(t.params)),o.unstable_setProvider&&e.onRequest(u.providers_set,async t=>await o.unstable_setProvider(t.params)??{}),o.unstable_disableProvider&&e.onRequest(u.providers_disable,async t=>await o.unstable_disableProvider(t.params)??{}),o.logout&&e.onRequest(u.logout,async t=>await o.logout(t.params)??{}),o.unstable_startNes&&e.onRequest(u.nes_start,t=>o.unstable_startNes(t.params)),o.unstable_suggestNes&&e.onRequest(u.nes_suggest,t=>o.unstable_suggestNes(t.params)),o.unstable_closeNes&&e.onRequest(u.nes_close,async t=>await o.unstable_closeNes(t.params)??{}),o.unstable_didOpenDocument&&e.onNotification(u.document_did_open,t=>o.unstable_didOpenDocument(t.params)),o.unstable_didChangeDocument&&e.onNotification(u.document_did_change,t=>o.unstable_didChangeDocument(t.params)),o.unstable_didCloseDocument&&e.onNotification(u.document_did_close,t=>o.unstable_didCloseDocument(t.params)),o.unstable_didSaveDocument&&e.onNotification(u.document_did_save,t=>o.unstable_didSaveDocument(t.params)),o.unstable_didFocusDocument&&e.onNotification(u.document_did_focus,t=>o.unstable_didFocusDocument(t.params)),o.unstable_acceptNes&&e.onNotification(u.nes_accept,t=>o.unstable_acceptNes(t.params)),o.unstable_rejectNes&&e.onNotification(u.nes_reject,t=>o.unstable_rejectNes(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||Cr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-agent-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Mr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-agent-extension-notification"}),e}function Or(o){let e=yr().onRequest(p.session_request_permission,t=>o.requestPermission(t.params)).onNotification(p.session_update,t=>o.sessionUpdate(t.params)).onRequest(p.fs_write_text_file,async t=>await o.writeTextFile?.(t.params)??{}).onRequest(p.fs_read_text_file,async t=>await o.readTextFile?.(t.params)).onRequest(p.terminal_create,async t=>await o.createTerminal?.(t.params)).onRequest(p.terminal_output,async t=>await o.terminalOutput?.(t.params)).onRequest(p.terminal_release,async t=>await o.releaseTerminal?.(t.params)??{}).onRequest(p.terminal_wait_for_exit,async t=>await o.waitForTerminalExit?.(t.params)).onRequest(p.terminal_kill,async t=>await o.killTerminal?.(t.params)??{});return o.createElicitation&&e.onRequest(p.elicitation_create,t=>o.createElicitation(t.params)),o.completeElicitation&&e.onNotification(p.elicitation_complete,t=>o.completeElicitation(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||kr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-client-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Dr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-client-extension-notification"}),e}var Ht=class{connection;constructor(e,t){this.connection=qr(e(this))[I]().connect(t,se)}sessionUpdate(e){return this.connection.sendNotification(p.session_update,e)}requestPermission(e){return this.connection.sendRequest(p.session_request_permission,e)}readTextFile(e){return this.connection.sendRequest(p.fs_read_text_file,e)}writeTextFile(e){return this.connection.sendRequest(p.fs_write_text_file,e,w)}createTerminal(e){return this.connection.sendRequest(p.terminal_create,e,t=>Xn.create(t.terminalId,e.sessionId,this.connection))}createElicitation(e){return this.connection.sendRequest(p.elicitation_create,e)}completeElicitation(e){return this.connection.sendNotification(p.elicitation_complete,e)}request(e,t,c){let d=Zn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Xn=class o{id;sessionId;connection;constructor(e,t,c){this.id=e,this.sessionId=t,this.connection=c}static create(e,t,c){return new o(e,t,c)}currentOutput(){return this.connection.sendRequest(p.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(p.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(p.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},w)}release(){return this.connection.sendRequest(p.terminal_release,{sessionId:this.sessionId,terminalId:this.id},w)}async[Symbol.asyncDispose](){await this.release()}},vt=class{connection;constructor(e,t){this.connection=Or(e(this))[I]().connect(t,se)}initialize(e){return this.connection.sendRequest(u.initialize,e)}newSession(e){return this.connection.sendRequest(u.session_new,e)}loadSession(e){return this.connection.sendRequest(u.session_load,e,w)}unstable_forkSession(e){return this.connection.sendRequest(u.session_fork,e)}listSessions(e){return this.connection.sendRequest(u.session_list,e)}deleteSession(e){return this.connection.sendRequest(u.session_delete,e,w)}resumeSession(e){return this.connection.sendRequest(u.session_resume,e)}closeSession(e){return this.connection.sendRequest(u.session_close,e,w)}setSessionMode(e){return this.connection.sendRequest(u.session_set_mode,e,w)}setSessionConfigOption(e){return this.connection.sendRequest(u.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(u.authenticate,e,w)}unstable_listProviders(e){return this.connection.sendRequest(u.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(u.providers_set,e,w)}unstable_disableProvider(e){return this.connection.sendRequest(u.providers_disable,e,w)}logout(e){return this.connection.sendRequest(u.logout,e,w)}prompt(e){return this.connection.sendRequest(u.session_prompt,e)}cancel(e){return this.connection.sendNotification(u.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(u.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(u.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(u.nes_close,e,w)}unstable_didOpenDocument(e){return this.connection.sendNotification(u.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(u.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(u.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(u.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(u.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(u.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(u.nes_reject,e)}request(e,t,c){let d=Yn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}};export{Vt as a,N as b,Ua as c,Ht as d,vt as e};