@maincode-ai/matilda-code 0.21.10-preview.1 → 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.
- package/bundled/mainy/docs/configuration/settings.md +1 -1
- package/bundled/mainy/docs/matilda-serve.md +6 -6
- package/chunks/{agent-XXSEYARS.js → agent-ZFZ4HJQC.js} +1 -1
- package/chunks/{agent-headless-YBWTAFUH.js → agent-headless-KH2BKLP7.js} +1 -1
- package/chunks/{ca-H4HPSGTI.js → ca-EUJBUYX5.js} +1 -1
- package/chunks/{chunk-FRRBNNEB.js → chunk-25NCTG5H.js} +63 -54
- package/chunks/{chunk-WJO3QSBJ.js → chunk-4YVN5HXG.js} +2 -2
- package/chunks/{chunk-MKFQMX37.js → chunk-5427BPR2.js} +2 -2
- package/chunks/{chunk-GC2F575A.js → chunk-6GBNB5Z2.js} +1 -1
- package/chunks/{chunk-3HUM74NZ.js → chunk-EQGA7LH7.js} +2 -2
- package/chunks/{chunk-TO3ID3JW.js → chunk-GHBKFIHC.js} +2 -2
- package/chunks/{chunk-S4UT3QLV.js → chunk-HWOQNYAO.js} +1 -1
- package/chunks/chunk-M53RP3YP.js +31 -0
- package/chunks/{chunk-HOCFKXNJ.js → chunk-NIQK6NX3.js} +1 -1
- package/chunks/{chunk-4TQ7ABLG.js → chunk-NVM7W7TG.js} +17 -17
- package/chunks/{chunk-66NIIU2R.js → chunk-Q55AVE2N.js} +1 -1
- package/chunks/chunk-QFNFLE2I.js +2625 -0
- package/chunks/chunk-RK2AKQAX.js +39 -0
- package/chunks/chunk-T2T2UEPY.js +4 -0
- package/chunks/chunk-VI74YQQO.js +8 -0
- package/chunks/{chunk-YSIECQIZ.js → chunk-WRQLIPXW.js} +3 -3
- package/chunks/{computer-use-HX2LYMYD.js → computer-use-SXP25RZQ.js} +1 -1
- package/chunks/{contextCommand-W7DBC37U.js → contextCommand-3GN5CAOK.js} +1 -1
- package/chunks/{de-S7F37S4F.js → de-DNEPG7S7.js} +1 -1
- package/chunks/{dist-ZOFMYY3D.js → dist-ME6647DQ.js} +1 -1
- package/chunks/{dist-SCXU6QWY.js → dist-P6SLWL5V.js} +1 -1
- package/chunks/{dist-PVENOVGI.js → dist-VG3ZDJ2A.js} +1 -1
- package/chunks/{dist-N66KF4KX.js → dist-YTCHM57U.js} +1 -1
- package/chunks/{edit-HFUF2RN3.js → edit-KX6V4PH3.js} +1 -1
- package/chunks/{en-S6DMCJQZ.js → en-NOD6KQNM.js} +1 -1
- package/chunks/{enter-worktree-LFCL64PJ.js → enter-worktree-X47BSJLE.js} +1 -1
- package/chunks/{enterPlanMode-TREN7ULJ.js → enterPlanMode-F22ZNTYJ.js} +1 -1
- package/chunks/{exit-worktree-MH2J4P42.js → exit-worktree-XY5UMDHX.js} +1 -1
- package/chunks/{exitPlanMode-PQO3EFFT.js → exitPlanMode-G3QLIWJ4.js} +1 -1
- package/chunks/{fr-RFJP3KVL.js → fr-2OE5WLJ4.js} +1 -1
- package/chunks/{geminiContentGenerator-FE5UVAOZ.js → geminiContentGenerator-EQEGOXOV.js} +1 -1
- package/chunks/{glob-VZAYMEQA.js → glob-KSBEWI3E.js} +1 -1
- package/chunks/{goal-tools-JN27F5BA.js → goal-tools-6QTC3UI7.js} +1 -1
- package/chunks/{grep-2VT5TSRU.js → grep-6TTPZ524.js} +1 -1
- package/chunks/{ja-UTJHPL3M.js → ja-3B6V5KS7.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-EYETUHCZ.js → matildaAgentContentGenerator-OV4U6DJD.js} +1 -1
- package/chunks/{matildaContentGenerator-IWKH3YC4.js → matildaContentGenerator-ETIAWE22.js} +1 -1
- package/chunks/{matildaOAuth2-GRS5K3D4.js → matildaOAuth2-WOY7ZS43.js} +1 -1
- package/chunks/{monitor-AMIVJKDL.js → monitor-F4K5HOZX.js} +1 -1
- package/chunks/{notebook-edit-BQUXXNEO.js → notebook-edit-TL7CI5EA.js} +1 -1
- package/chunks/{openaiContentGenerator-4M7WBW3G.js → openaiContentGenerator-MGASUFQL.js} +1 -1
- package/chunks/{pt-KXMOTADP.js → pt-KP2JCPUY.js} +1 -1
- package/chunks/{read-file-FNJZCMIZ.js → read-file-6EAPS2KG.js} +1 -1
- package/chunks/{ripGrep-UOEUWYVF.js → ripGrep-K6SFFUIE.js} +1 -1
- package/chunks/{ru-EWGWZPQH.js → ru-K7IQQKHC.js} +1 -1
- package/chunks/{scheduler-ASQLD6BW.js → scheduler-TKWPD4LP.js} +1 -1
- package/chunks/{serve-FIDAAJAB.js → serve-ZQX2WBLF.js} +31 -31
- package/chunks/{shell-S732E2W4.js → shell-AZRK5GIO.js} +1 -1
- package/chunks/{skill-VXNOQCSI.js → skill-KDM3UUML.js} +1 -1
- package/chunks/src-SGI6VLOS.js +3 -0
- package/chunks/{team-create-CXY3MRCE.js → team-create-F4KQRGMB.js} +1 -1
- package/chunks/{tool-search-AJ57WSJC.js → tool-search-JFCD5W5M.js} +1 -1
- package/chunks/{web-fetch-63M6GZQL.js → web-fetch-REWGIRWQ.js} +1 -1
- package/chunks/{workflow-55OAJ6XH.js → workflow-SEFYGBED.js} +2 -2
- package/chunks/{write-file-2TWXQRDB.js → write-file-UAGVBZMC.js} +1 -1
- package/cli.js +494 -489
- package/locales/ca.js +8 -2
- package/locales/de.js +9 -2
- package/locales/en.js +15 -8
- package/locales/fr.js +9 -2
- package/locales/ja.js +8 -2
- package/locales/pt.js +8 -2
- package/locales/ru.js +9 -2
- package/package.json +2 -2
- package/chunks/chunk-2W6MZZHZ.js +0 -39
- package/chunks/chunk-ESSYHTAZ.js +0 -8
- package/chunks/chunk-JSFA3NEP.js +0 -5
- package/chunks/chunk-TZIDSCTF.js +0 -31
- package/chunks/chunk-VVIJGBQK.js +0 -2615
- package/chunks/src-QZENX46P.js +0 -3
package/locales/ca.js
CHANGED
|
@@ -449,8 +449,14 @@ export default {
|
|
|
449
449
|
'Custom Witty Phrases': 'Frases enginyoses personalitzades',
|
|
450
450
|
'Show Welcome Back Dialog': 'Mostrar el diàleg de benvinguda',
|
|
451
451
|
'Enable User Feedback': 'Activar les valoracions dels usuaris',
|
|
452
|
-
'How is Matilda
|
|
453
|
-
|
|
452
|
+
'How well is Matilda working for you?': 'Com et funciona Matilda?',
|
|
453
|
+
'Give a rating from 1 to 5:': 'Dona una puntuació de l’1 al 5:',
|
|
454
|
+
'Tell us more and/or give suggestions!':
|
|
455
|
+
'Explica’ns més coses i/o fes suggeriments!',
|
|
456
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
457
|
+
'1–5 puntuar · ←→ ajustar · retorn següent · esc tancar',
|
|
458
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
459
|
+
'retorn enviar · maj+retorn línia nova · tab enrere · esc tancar',
|
|
454
460
|
Bad: 'Malament',
|
|
455
461
|
Fine: 'Bé',
|
|
456
462
|
Good: 'Molt bé',
|
package/locales/de.js
CHANGED
|
@@ -379,8 +379,15 @@ export default {
|
|
|
379
379
|
'Custom Witty Phrases': 'Benutzerdefinierte Witzige Sprüche',
|
|
380
380
|
'Show Welcome Back Dialog': 'Willkommen-zurück-Dialog anzeigen',
|
|
381
381
|
'Enable User Feedback': 'Benutzerfeedback aktivieren',
|
|
382
|
-
'How is Matilda
|
|
383
|
-
'Wie
|
|
382
|
+
'How well is Matilda working for you?':
|
|
383
|
+
'Wie gut funktioniert Matilda für dich?',
|
|
384
|
+
'Give a rating from 1 to 5:': 'Gib eine Bewertung von 1 bis 5 ab:',
|
|
385
|
+
'Tell us more and/or give suggestions!':
|
|
386
|
+
'Erzähl uns mehr und/oder mach Vorschläge!',
|
|
387
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
388
|
+
'1–5 bewerten · ←→ anpassen · Eingabe weiter · Esc schließen',
|
|
389
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
390
|
+
'Eingabe senden · Umschalt+Eingabe neue Zeile · Tab zurück · Esc schließen',
|
|
384
391
|
Bad: 'Schlecht',
|
|
385
392
|
Fine: 'In Ordnung',
|
|
386
393
|
Good: 'Gut',
|
package/locales/en.js
CHANGED
|
@@ -480,8 +480,15 @@ export default {
|
|
|
480
480
|
'Custom Witty Phrases': 'Custom Witty Phrases',
|
|
481
481
|
'Show Welcome Back Dialog': 'Show Welcome Back Dialog',
|
|
482
482
|
'Enable User Feedback': 'Enable User Feedback',
|
|
483
|
-
'How is Matilda
|
|
484
|
-
'How is Matilda
|
|
483
|
+
'How well is Matilda working for you?':
|
|
484
|
+
'How well is Matilda working for you?',
|
|
485
|
+
'Give a rating from 1 to 5:': 'Give a rating from 1 to 5:',
|
|
486
|
+
'Tell us more and/or give suggestions!':
|
|
487
|
+
'Tell us more and/or give suggestions!',
|
|
488
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
489
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss',
|
|
490
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
491
|
+
'enter submit · shift+enter newline · tab back · esc dismiss',
|
|
485
492
|
Bad: 'Bad',
|
|
486
493
|
Fine: 'Fine',
|
|
487
494
|
Good: 'Good',
|
|
@@ -1154,12 +1161,12 @@ export default {
|
|
|
1154
1161
|
'Chat history compression did not reduce size. This may indicate issues with the compression prompt.',
|
|
1155
1162
|
'Could not compress chat history due to a token counting error.':
|
|
1156
1163
|
'Could not compress chat history due to a token counting error.',
|
|
1157
|
-
'Could not compress chat history
|
|
1158
|
-
'Could not compress chat history
|
|
1159
|
-
'Could not compress chat history
|
|
1160
|
-
'Could not compress chat history
|
|
1161
|
-
'Could not compress chat history
|
|
1162
|
-
'Could not compress chat history
|
|
1164
|
+
'Could not compress chat history: the summarizer timed out or failed. Try again, or continue chatting (auto-compact will retry).':
|
|
1165
|
+
'Could not compress chat history: the summarizer timed out or failed. Try again, or continue chatting (auto-compact will retry).',
|
|
1166
|
+
'Could not compress chat history: the summarizer returned an empty summary. Try again.':
|
|
1167
|
+
'Could not compress chat history: the summarizer returned an empty summary. Try again.',
|
|
1168
|
+
'Could not compress chat history: the summary hit the output length cap. Try again later or start a new session.':
|
|
1169
|
+
'Could not compress chat history: the summary hit the output length cap. Try again later or start a new session.',
|
|
1163
1170
|
// ============================================================================
|
|
1164
1171
|
// Commands - Directory
|
|
1165
1172
|
// ============================================================================
|
package/locales/fr.js
CHANGED
|
@@ -454,8 +454,15 @@ export default {
|
|
|
454
454
|
'Custom Witty Phrases': 'Phrases personnalisées spirituelles',
|
|
455
455
|
'Show Welcome Back Dialog': 'Afficher le dialogue de bienvenue',
|
|
456
456
|
'Enable User Feedback': 'Activer les retours utilisateur',
|
|
457
|
-
'How is Matilda
|
|
458
|
-
'
|
|
457
|
+
'How well is Matilda working for you?':
|
|
458
|
+
'Matilda répond-elle bien à vos besoins ?',
|
|
459
|
+
'Give a rating from 1 to 5:': 'Donnez une note de 1 à 5 :',
|
|
460
|
+
'Tell us more and/or give suggestions!':
|
|
461
|
+
'Dites-nous-en plus et/ou faites des suggestions !',
|
|
462
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
463
|
+
'1–5 noter · ←→ ajuster · entrée suivant · échap fermer',
|
|
464
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
465
|
+
'entrée envoyer · maj+entrée nouvelle ligne · tab retour · échap fermer',
|
|
459
466
|
Bad: 'Mauvais',
|
|
460
467
|
Fine: 'Correct',
|
|
461
468
|
Good: 'Bien',
|
package/locales/ja.js
CHANGED
|
@@ -1403,8 +1403,14 @@ export default {
|
|
|
1403
1403
|
'Show Line Numbers in Code': 'コードの行番号を表示',
|
|
1404
1404
|
'Show Welcome Back Dialog': 'おかえりダイアログを表示',
|
|
1405
1405
|
'Enable User Feedback': 'ユーザーフィードバックを有効化',
|
|
1406
|
-
'How is Matilda
|
|
1407
|
-
|
|
1406
|
+
'How well is Matilda working for you?': 'Matilda の使い心地はいかがですか?',
|
|
1407
|
+
'Give a rating from 1 to 5:': '1〜5で評価してください:',
|
|
1408
|
+
'Tell us more and/or give suggestions!':
|
|
1409
|
+
'詳しい感想やご提案をお聞かせください!',
|
|
1410
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
1411
|
+
'1–5 評価 · ←→ 調整 · enter 次へ · esc 閉じる',
|
|
1412
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
1413
|
+
'enter 送信 · shift+enter 改行 · tab 戻る · esc 閉じる',
|
|
1408
1414
|
'Interactive Shell (PTY)': '対話型シェル (PTY)',
|
|
1409
1415
|
'Select Editor': 'エディタを選択',
|
|
1410
1416
|
'Editor Preference': 'エディタ設定',
|
package/locales/pt.js
CHANGED
|
@@ -401,8 +401,14 @@ export default {
|
|
|
401
401
|
'Custom Witty Phrases': 'Frases de Efeito Personalizadas',
|
|
402
402
|
'Show Welcome Back Dialog': 'Mostrar Diálogo de Bem-vindo de Volta',
|
|
403
403
|
'Enable User Feedback': 'Ativar Feedback do Usuário',
|
|
404
|
-
'How is Matilda
|
|
405
|
-
'Como
|
|
404
|
+
'How well is Matilda working for you?':
|
|
405
|
+
'Como está sendo sua experiência com a Matilda?',
|
|
406
|
+
'Give a rating from 1 to 5:': 'Dê uma nota de 1 a 5:',
|
|
407
|
+
'Tell us more and/or give suggestions!': 'Conte-nos mais e/ou dê sugestões!',
|
|
408
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
409
|
+
'1–5 avaliar · ←→ ajustar · enter avançar · esc fechar',
|
|
410
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
411
|
+
'enter enviar · shift+enter nova linha · tab voltar · esc fechar',
|
|
406
412
|
Bad: 'Ruim',
|
|
407
413
|
Fine: 'Bom',
|
|
408
414
|
Good: 'Ótimo',
|
package/locales/ru.js
CHANGED
|
@@ -399,8 +399,15 @@ export default {
|
|
|
399
399
|
'Custom Witty Phrases': 'Пользовательские остроумные фразы',
|
|
400
400
|
'Show Welcome Back Dialog': 'Показывать диалог приветствия',
|
|
401
401
|
'Enable User Feedback': 'Включить отзывы пользователей',
|
|
402
|
-
'How is Matilda
|
|
403
|
-
'
|
|
402
|
+
'How well is Matilda working for you?':
|
|
403
|
+
'Насколько хорошо Matilda справляется с вашими задачами?',
|
|
404
|
+
'Give a rating from 1 to 5:': 'Поставьте оценку от 1 до 5:',
|
|
405
|
+
'Tell us more and/or give suggestions!':
|
|
406
|
+
'Расскажите подробнее и/или поделитесь предложениями!',
|
|
407
|
+
'1–5 rate · ←→ adjust · enter next · esc dismiss':
|
|
408
|
+
'1–5 оценка · ←→ изменить · enter далее · esc закрыть',
|
|
409
|
+
'enter submit · shift+enter newline · tab back · esc dismiss':
|
|
410
|
+
'enter отправить · shift+enter новая строка · tab назад · esc закрыть',
|
|
404
411
|
Bad: 'Плохо',
|
|
405
412
|
Fine: 'Нормально',
|
|
406
413
|
Good: 'Хорошо',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.21.
|
|
3
|
+
"version": "0.21.11",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.11"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|
package/chunks/chunk-2W6MZZHZ.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as ye}from"./chunk-ODZOYHIC.js";import{c as V,f as O}from"./chunk-GUFIMKF5.js";import{M as pe,N as ce,O as _,Q as de,R as F,S as me,a as re,g as R,h as ae,ha as ge,na as be}from"./chunk-YSIECQIZ.js";import{a as Ce}from"./chunk-DC7LAFZZ.js";import{a as oe,g as ie,k as se,l as N,o as ue,t as fe,v as he}from"./chunk-SUH3UUWZ.js";import{e as ne}from"./chunk-4J6DC24J.js";import{b as j,c as W,f as le,n as q}from"./chunk-SDTWBD62.js";import{b as z}from"./chunk-ESSYHTAZ.js";import{a as H,ba as P,c as Z,e as ee,q as J,s as te,t as K}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Me(a){return a.toLowerCase().includes("matilda3")}function ve(a){if(a.role!=="assistant")return a;let e=a;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?a:{...e,reasoning:e.reasoning_content}}var h=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,i]of Object.entries(n??{}))le(o)||(r[o]=i);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=V("openai",this.cliConfig.getProxy());return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...i||{}})}buildRequest(e,t){let n=this.contentGeneratorConfig.extra_body,r=this.applyOutputTokenLimit(e),o=Me(e.model)?r.messages.map(ve):r.messages;return{...r,messages:o,...n||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,n=he(e.model,"output"),r=fe(e.model),o;if(t!=null)r?o=Math.min(t,n):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=i?parseInt(i,10):NaN;!isNaN(s)&&s>0?o=r?Math.min(s,n):s:o=Math.min(n,8e3)}return{...e,max_tokens:o}}};var k=class extends h{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let n=super.buildRequest(e,t);return n.stream||delete n.stream_options,n}};p();p();var G=class extends Error{constructor(t,n){super(`No stream activity for ${t}ms after ${n} chunks.`);this.idleMs=t;this.chunksReceived=n;this.name="StreamInactivityTimeoutError"}code="ETIMEDOUT"};function Ae(a,e){return async(t,n)=>{let r=new AbortController,o=n?.signal??void 0,i=()=>r.abort(o?.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",i,{once:!0});let s=()=>o?.removeEventListener("abort",i),l;try{l=await a(t,{...n,signal:r.signal})}catch(C){throw s(),C}let m=l.headers.get("content-type")??"";if(!l.body||!m.includes("text/event-stream"))return l;let c=l.body.getReader(),f=0,u,b=new ReadableStream({async pull(C){let d=new Promise((g,E)=>{u=setTimeout(()=>E(new G(e,f)),e)});try{let g=await Promise.race([c.read(),d]);if(g.done){s(),C.close();return}f+=1,C.enqueue(g.value)}catch(g){s(),C.error(g),g instanceof G&&r.abort(g)}finally{clearTimeout(u)}},cancel(C){return clearTimeout(u),s(),c.cancel(C)}}),y=new Response(b,{status:l.status,statusText:l.statusText,headers:l.headers});return Object.defineProperty(y,"url",{value:l.url}),y}}var we=P("MatildaOpenAICompatibleProvider"),A=class a extends h{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:n}=e;if(t==="matilda-oauth"||!n)return!0;let r=n.endsWith("/")?n.slice(0,-1):n,o=null;try{o=new URL(r).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),s=N?.endsWith("/")?N.slice(0,-1):N,l=!!(s&&r.toLowerCase()===s.toLowerCase());return s&&!i&&!l&&we.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,i]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=i);return _(this.contentGeneratorConfig)&&Object.assign(r,pe(this.cliConfig)),r}buildClient(){let{apiKey:e,baseUrl:t=se,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=V("openai",this.cliConfig.getProxy()),s=i?.fetch??globalThis.fetch,l=Ae(s,24e4),m=_(this.contentGeneratorConfig)?async(c,f)=>{let u=new Headers(c instanceof Request?c.headers:void 0);new Headers(f?.headers).forEach((d,g)=>{u.set(g,d)});let b=u.has(j)||u.has(W),y=q(),C=b||Object.keys(y).length>0;if(C){u.delete(j),u.delete(W);for(let[g,E]of Object.entries(y))u.set(g,E);let d=u.get("x-stainless-retry-count");u.has(j)&&d!==null&&/^[1-9][0-9]*$/.test(d)&&u.set(W,"retry")}this.cliConfig.getChannel()===void 0&&de({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let d=await l(c,C?{...f,headers:u}:f);return me({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),d}catch(d){throw F(d,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),d}}:void 0;return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...i||{},...m?{fetch:m}:{}})}buildRequest(e,t){let n=e.messages,r=e.tools;if(this.shouldEnableCacheControl()){let{messages:s,tools:l}=this.addCacheControl(e,e.stream?"all":"system_only");n=s,r=l}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let n=e.messages,r=n.findIndex(l=>l.role==="system"),o=n.length-1,i=n.length===0?n:n.map((l,m)=>!(m===r&&r!==-1||m===o&&t==="all")||!("content"in l)||l.content===null||l.content===void 0?l:{...l,content:this.addCacheControlToContent(l.content)}),s=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:s}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],n=e.length-1;return t[n]={...t[n],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(a.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of a.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function B(a){if(a.role!=="assistant")return a;let e=a;return typeof e.reasoning_content=="string"?a:{...e,reasoning_content:""}}function S(a){let e=a.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Ee(a){return S(a)?!0:(a.model??"").toLowerCase().includes("deepseek")}var T=class extends h{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ee;static isDeepSeekHostname=S;buildRequest(e,t){let n=super.buildRequest(e,t),r=S(this.contentGeneratorConfig)?Ge(n):n;if(!r.messages?.length)return r;let o=r.messages.map(i=>{let s=ke(i);return B(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ke(a){if(!("content"in a))return a;let{content:e}=a;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return a;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
|
|
4
|
-
|
|
5
|
-
`);return{...a,content:t}}function Ge(a){let e=a,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return a;let r={...e};if(typeof r.reasoning_effort!="string"||!r.reasoning_effort){let o=n;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),r.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete r.reasoning;else if(t){let{effort:o,...i}=t;r.reasoning=i}return r}p();var I=class extends h{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};p();var _e=["api.minimaxi.com","api.minimax.io"],Se=[".minimaxi.com",".minimax.io"],M=class extends h{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return _e.includes(t)?!0:Se.some(n=>t.endsWith(n))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};p();var Pe="api.mistral.ai",Le=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ue(a){let e=a.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Pe||t.endsWith(`.${Pe}`)}catch{return!1}}function De(a){if(Ue(a))return!0;let e=a.model?.toLowerCase()??"";return Le.some(t=>e.includes(t))}var v=class extends h{static isMistralProvider=De;buildRequest(e,t){let n=super.buildRequest(e,t);return{...n,messages:n.messages.map(He)}}};function He(a){if(!("reasoning_content"in a))return a;let e={...a};return delete e.reasoning_content,e}p();function Ne(a){let e=a.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(a.model??"").toLowerCase().startsWith("mimo-")}var x=class extends h{constructor(e,t){super(e,t)}static isMiMoProvider=Ne;buildRequest(e,t){let n=super.buildRequest(e,t);return n.messages?.length?{...n,messages:n.messages.map(B)}:n}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};p();p();var je=P("STREAMING_TOOL_CALL_PARSER"),$=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,n,r){let o=e,i=!!(n&&this.idToIndexMap.has(n));if(n)if(this.idToIndexMap.has(n))o=this.idToIndexMap.get(n);else{if(this.buffers.has(e)){let d=this.buffers.get(e),g=this.depths.get(e),E=this.toolCallMeta.get(e);if(d.trim()&&g===0&&E?.id&&E.id!==n)try{JSON.parse(d),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(n,o)}else if(this.buffers.has(e)){let d=this.buffers.get(e);if(this.depths.get(e)>0||!d.trim())o=e;else try{JSON.parse(d),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let s=this.buffers.get(o),l=this.depths.get(o);if(i&&s.trim()&&l===0)try{return JSON.parse(s),je.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let m=this.toolCallMeta.get(o);n&&(m.id=n),r&&(m.name=r);let c=this.inStrings.get(o),f=this.escapes.get(o),u=s+t;this.buffers.set(o,u);let b=l,y=c,C=f;for(let d of t)y||(d==="{"||d==="["?b++:(d==="}"||d==="]")&&b--),d==='"'&&!C&&(y=!y),C=d==="\\"&&!C;if(this.depths.set(o,b),this.inStrings.set(o,y),this.escapes.set(o,C),b===0&&u.trim().length>0)try{return{complete:!0,value:JSON.parse(u)}}catch(d){if(y)try{return{complete:!0,value:JSON.parse(u+'"'),repaired:!0}}catch{}return{complete:!1,error:d instanceof Error?d:new Error(String(d))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!0})}getStrictCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!1})}collectCompletedToolCalls({allowJsonRepair:e}){let t=[],n=new Set;for(let[r,o]of this.buffers.entries()){let i=this.toolCallMeta.get(r);if(i?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(i.id){if(n.has(i.id))continue;n.add(i.id)}let m;if(!o.trim())m={};else try{m=JSON.parse(o)}catch{if(!e)continue;let c=oe(o,null);if(!c||typeof c!="object")continue;m=c}t.push({id:i.id,name:i.name,args:m,index:r})}}return t}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),n=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!n?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,n]of this.buffers.entries()){let r=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(r>0||!n.trim()))e=Math.max(e,t);else if(n.trim())try{JSON.parse(n)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e,t]of this.buffers.entries()){let n=this.toolCallMeta.get(e),r=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(r>0||o)return!0;if(!n?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var Re=16e3,Oe=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
6
|
-
`,X=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},L=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(n,r)=>{let o=e.config?.abortSignal,i=o?z(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:i?.signal,...s?{headers:s}:{}});return R.convertOpenAIResponseToGemini(l,r)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,i=o?z(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:i?.signal,...s?{headers:s}:{}})}catch(u){throw i?.abort(),u}if(!i)return this.processStreamWithLogging(l,r,e);let m=i,c=this.processStreamWithLogging(l,r,e);async function*f(){try{yield*c}finally{m.abort()}}return f()})}reportedOperationHeaders(){if(!_(this.contentGeneratorConfig))return;let e=q();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null,i=!1;try{for await(let s of e){if(s.choices?.[0]?.finish_reason==="error_finish"){let c=s.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new X(c)}let l=R.convertOpenAIChunkToGemini(s,t);if(l.candidates?.[0]?.content?.parts?.length===0&&!l.candidates?.[0]?.finishReason&&!l.usageMetadata)continue;if(i){if(l.usageMetadata){let c=o;c&&(c.usageMetadata=l.usageMetadata)}r.push(l);continue}this.handleChunkMerging(l,r,c=>{o=c})&&(o?(yield o,i=!0):yield l)}if(!o&&!i){let s=R.flushOpenAIStreamToGemini(t);s&&(yield s,i=!0)}o&&!i&&(yield o)}catch(s){if(s instanceof X)throw O(s);await this.handleError(s,t,n)}}handleChunkMerging(e,t,n){let r=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(r){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),n(i)}else t.push(e),n(e);return!1}else if(o){let i=t[t.length-1],s=new ne;return s.candidates=i.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=i.usageMetadata,s.responseId=e.responseId,s.createTime=e.createTime,s.modelVersion=e.modelVersion,s.promptFeedback=e.promptFeedback,t[t.length-1]=s,n(s),!0}return t.push(e),!0}async buildRequest(e,t,n,r){let o=R.convertGeminiRequestToOpenAI(e,n),i=this.shouldUseMatildaCoreRequestProfile(),s=i?this.toMatildaCoreUserMessages(o):o,l={model:n.model,messages:s,...this.buildGenerateContentConfig(e)};r?(l.stream=!0,l.stream_options={include_usage:!0}):l.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await R.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let m=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let f=m,u=(n.model??"").toLowerCase();if(A.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(u.startsWith("matilda")||u==="coder-model")){f.enable_thinking=!1;let b=f.chat_template_kwargs;typeof b=="object"&&b!==null&&"enable_thinking"in b&&(f.chat_template_kwargs={...b,enable_thinking:!1})}"reasoning"in f&&delete f.reasoning,"reasoning_effort"in f&&delete f.reasoning_effort,S(this.contentGeneratorConfig)&&(f.thinking={type:"disabled"})}return m}toMatildaCoreUserMessages(e){let t=e.filter(n=>n.role==="user").map(n=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(n.content))})).filter(n=>n.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;let n=this.contentGeneratorConfig.customHeaders??{};return Object.entries(n).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
|
|
7
|
-
`):""}sanitizeMatildaUserContent(e){let n=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(n.length<=Re)return n;let r=Re-Oe.length;return`${Oe}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let m=n?.[s],c=l?e.config?.[l]:void 0,f=l?t[l]:void 0;return m!==void 0?m:c!==void 0?c:f},o=(s,l,m)=>{let c=r(l,m);return c!==void 0?{[s]:c}:{}};if(n!==void 0){let s=e.config?.maxOutputTokens;return{...n,...s!==void 0&&n.max_tokens!==void 0?{max_tokens:s}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,n,r){let o=this.createRequestContext(e,n);try{let i=await this.buildRequest(e,t,o,n);return ae.getStore()?.(i),ie.recordOpenAIWireRequest(i),await r(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(O(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new $:void 0,i=this.config.provider.getResponseParsingOptions?.(),s=t&&i?.taggedThinkingTags?new re:void 0;return{model:n,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:r.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...s?{taggedThinkingParser:s}:{}}}};p();var We=P("OPENAI_ERROR"),U=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=O(e),o=!(r instanceof G)&&this.isTimeoutError(r),i=this.buildErrorMessage(r,t,o);if(this.shouldSuppressErrorLogging(r,n)||We.error("OpenAI API Error:",i),o){let s=new Error(`${i}
|
|
8
|
-
|
|
9
|
-
${this.getTimeoutTroubleshootingTips()}`,{cause:r}),l=ee(r);throw l!==void 0?Object.assign(s,{status:l}):s}throw r}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),n=e?.code,r=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||r==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,n){let r=Math.round((Date.now()-t.startTime)/1e3);return n?`Request timeout after ${r}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
10
|
-
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
11
|
-
`)}`}};var Te=P("OPENAI"),w=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new U((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new L(r)}shouldSuppressErrorLogging(e,t){return!!(Z(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new ye().calculateTokens(e)).totalTokens}}catch(t){Te.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(n=>typeof n=="string"?n:"parts"in n&&n.parts?n.parts.map(r=>typeof r=="string"?r:"text"in r&&r.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(n=>typeof n=="string"?n:"text"in n?n.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(n){let r=O(n);throw Te.error("OpenAI API Embedding Error:",r),new Error(`OpenAI API error: ${r instanceof Error?r.message:String(r)}`)}}useSummarizedThinking(){return!1}};p();var D=class extends w{contentGeneratorConfig;cliConfig;channel;constructor(e,t,n){super(e,t,n),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return Ie(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=()=>super.generateContentStream(e,t),r=await this.withTokenRefresh(n);return this.iterateWithAuthRetry(r,n)}async*iterateWithAuthRetry(e,t){let n=!1;try{for await(let r of e)n||=(r.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield r;return}catch(r){if(!this.isSessionAuthError(r))throw this.toAuthRecoveryError(r);if(n)throw new J("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw this.toAuthRecoveryError(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await be({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(n){throw F(n,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),n}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[Ce]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!this.isSessionAuthError(t))throw this.toAuthRecoveryError(t);await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(n){throw this.toAuthRecoveryError(n)}}}isSessionAuthError(e){return Ie(e)&&ge({baseUrl:this.contentGeneratorConfig.baseUrl,channel:this.channel})}toAuthRecoveryError(e){return K(e)?new te:this.isSessionAuthError(e)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):e}};function Ie(a){if(!a||K(a))return!1;let e=a instanceof Error?a.message.toLowerCase():String(a).toLowerCase(),t=a,n=Number(t.status??t.statusCode??t.code);return n>=400&&n<600?n===401:e.includes("unauthorized")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("token")&&e.includes("expired")}function _n(a,e){let t=qe(a,e);return A.isMatildaCompatibleProvider(a)?new D(a,e,t):new w(a,e,t)}function qe(a,e){let t=a||e.getContentGeneratorConfig();return A.isMatildaCompatibleProvider(t)?new A(a,e):T.isDeepSeekProvider(t)?new T(a,e):x.isMiMoProvider(t)?new x(a,e):I.isOpenRouterProvider(t)?new I(a,e):k.isModelScopeProvider(t)?new k(a,e):M.isMiniMaxProvider(t)?new M(a,e):v.isMistralProvider(t)?new v(a,e):new h(a,e)}export{A as a,T as b,I as c,M as d,v as e,x as f,L as g,U as h,w as i,D as j,_n as k,qe as l};
|
|
12
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2026 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2025 Matilda
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* @license
|
|
24
|
-
* Copyright 2026 Maincode
|
|
25
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
26
|
-
*
|
|
27
|
-
* OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
|
|
28
|
-
*
|
|
29
|
-
* Emulates Grok Build's automatic credential refresh
|
|
30
|
-
* (docs: "Automatic Credential Refresh"):
|
|
31
|
-
* 1. Before each request: ensure a fresh access token (re-read disk; refresh
|
|
32
|
-
* when within the early-invalidation window / already expired).
|
|
33
|
-
* 2. On 401 Unauthorized: force-refresh and retry the request once.
|
|
34
|
-
* 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
|
|
35
|
-
*
|
|
36
|
-
* Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
|
|
37
|
-
* createContentGenerator time, so idle sessions past access-token expiry
|
|
38
|
-
* failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
|
|
39
|
-
*/
|
package/chunks/chunk-ESSYHTAZ.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as d}from"./chunk-GZPNIYVZ.js";d();import{setMaxListeners as c}from"node:events";var f=50;function b(r=f){let o=new AbortController;return c(r,o.signal),o}function g(r){if(r)return r instanceof AbortController?r.signal:r}function A(r,o){let e=b(o),t=g(r);if(!t)return e;if(t.aborted)return e.abort(t.reason),e;let a=new WeakRef(t),i=()=>{e.abort(a.deref()?.reason)};return t.addEventListener("abort",i,{once:!0}),e.signal.addEventListener("abort",()=>{a.deref()?.removeEventListener("abort",i)},{once:!0}),e}function v(r,o){let e=b(o?.maxListeners),t=r.find(n=>n?.aborted);if(t)return e.abort(t.reason),{signal:e.signal,cleanup:()=>{}};let a=[];for(let n of r){if(!n)continue;if(n.aborted){e.abort(n.reason);break}let u=()=>e.abort(n.reason);n.addEventListener("abort",u,{once:!0}),a.push(()=>n.removeEventListener("abort",u))}let i=o?.timeoutMs;if(i!==void 0&&i>0&&!e.signal.aborted){let n=setTimeout(()=>{e.abort(new DOMException("Operation timed out","TimeoutError"))},i);a.push(()=>clearTimeout(n))}let l=!1,s=()=>{if(!l){l=!0;for(let n of a)n()}};return e.signal.aborted?s():e.signal.addEventListener("abort",s,{once:!0}),{signal:e.signal,cleanup:s}}export{b as a,A as b,v as c};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Matilda
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-JSFA3NEP.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as R,z as n}from"./chunk-TZIDSCTF.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();var a={authenticate:"authenticate",initialize:"initialize",session_cancel:"session/cancel",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode",session_set_model:"session/set_model"},d={fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"},We=1;m();function Je(p,e){let o=new TextEncoder,t=new TextDecoder,l=new ReadableStream({async start(r){let s="",i=e.getReader();try{for(;;){let{value:_,done:fn}=await i.read();if(fn)break;if(!_)continue;s+=t.decode(_,{stream:!0});let Y=s.split(`
|
|
4
|
-
`);s=Y.pop()||"";for(let zn of Y){let k=zn.trim();if(k)try{let j=JSON.parse(k);r.enqueue(j)}catch(j){console.error("Failed to parse JSON message:",k,j)}}}}finally{i.releaseLock(),r.close()}}}),g=new WritableStream({async write(r){let s=JSON.stringify(r)+`
|
|
5
|
-
`,i=p.getWriter();try{await i.write(o.encode(s))}finally{i.releaseLock()}}});return{readable:l,writable:g}}m();m();m();var Tn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),id:n.string(),name:n.string()}),y=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),methodId:n.string()}),kn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),jn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),blob:n.string(),mimeType:n.union([n.string(),n.null()]).optional(),uri:n.string()}),Rn=n.object({amount:n.number(),currency:n.string()}),En=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),terminalId:n.string()}),yn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),newText:n.string(),oldText:n.union([n.string(),n.null()]).optional(),path:n.string()}),nn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),name:n.string(),value:n.string()}),In=n.union([n.literal(-32700),n.literal(-32600),n.literal(-32601),n.literal(-32602),n.literal(-32603),n.literal(-32800),n.literal(-32e3),n.literal(-32002),n.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),en=n.object({code:In,data:n.unknown().optional(),message:n.string()}),tn=n.unknown(),on=n.unknown(),sn=n.unknown(),Cn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),readTextFile:n.boolean().optional().default(!1),writeTextFile:n.boolean().optional().default(!1)}),vn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),fs:Cn.optional().default({readTextFile:!1,writeTextFile:!1}),terminal:n.boolean().optional().default(!1)}),rn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),name:n.string(),value:n.string()}),an=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),name:n.string(),title:n.union([n.string(),n.null()]).optional(),version:n.string()}),qn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),I=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cursor:n.union([n.string(),n.null()]).optional(),cwd:n.union([n.string(),n.null()]).optional()}),Nn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),http:n.boolean().optional().default(!1),sse:n.boolean().optional().default(!1)}),On=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),headers:n.array(rn),name:n.string(),url:n.string()}),Mn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),headers:n.array(rn),name:n.string(),url:n.string()}),Hn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),args:n.array(n.string()),command:n.string(),env:n.array(nn),name:n.string()}),h=n.union([On.and(n.object({type:n.literal("http")})),Mn.and(n.object({type:n.literal("sse")})),Hn]),C=n.string(),Pn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),modelId:C,name:n.string()}),v=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cwd:n.string(),mcpServers:n.array(h)}),ln=n.string(),Dn=n.union([n.literal("allow_once"),n.literal("allow_always"),n.literal("reject_once"),n.literal("reject_always")]),An=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),kind:Dn,name:n.string(),optionId:ln}),Fn=n.union([n.literal("high"),n.literal("medium"),n.literal("low")]),Ln=n.union([n.literal("pending"),n.literal("in_progress"),n.literal("completed")]),Gn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:n.string(),priority:Fn,status:Ln}),Un=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),entries:n.array(Gn)}),$n=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),audio:n.boolean().optional().default(!1),embeddedContext:n.boolean().optional().default(!1),image:n.boolean().optional().default(!1)}),un=n.number().int().gte(0).lte(65535),q=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),clientCapabilities:vn.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:n.union([an,n.null()]).optional(),protocolVersion:un}),Wn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:n.string()}),Vn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),x=n.union([n.null(),n.number(),n.string()]),nt=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),requestId:x}),Jn=n.enum(["assistant","user"]),b=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),audience:n.union([n.array(Jn),n.null()]).optional(),lastModified:n.union([n.string(),n.null()]).optional(),priority:n.union([n.number(),n.null()]).optional()}),Kn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),annotations:n.union([b,n.null()]).optional(),data:n.string(),mimeType:n.string()}),Bn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),annotations:n.union([b,n.null()]).optional(),data:n.string(),mimeType:n.string(),uri:n.union([n.string(),n.null()]).optional()}),Zn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),annotations:n.union([b,n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),mimeType:n.union([n.string(),n.null()]).optional(),name:n.string(),size:n.union([n.number(),n.null()]).optional(),title:n.union([n.string(),n.null()]).optional(),uri:n.string()}),Qn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),optionId:ln}),Xn=n.union([n.object({outcome:n.literal("cancelled")}),Qn.and(n.object({outcome:n.literal("selected")}))]),Yn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),outcome:Xn}),ne=n.string(),cn=n.string(),ee=n.union([n.literal("mode"),n.literal("model"),n.literal("thought_level"),n.string()]),N=n.string(),dn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),name:n.string(),value:N}),te=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),group:ne,name:n.string(),options:n.array(dn)}),oe=n.union([n.array(dn),n.array(te)]),ie=n.object({currentValue:N,options:oe}),w=ie.and(n.object({type:n.literal("select")})).and(n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),category:n.union([ee,n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),id:cn,name:n.string()})),se=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.array(w)}),re=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),c=n.string(),O=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c}),et=n.object({method:n.string(),params:n.union([n.union([O,tn]),n.null()]).optional()}),M=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),args:n.array(n.string()).optional(),command:n.string(),cwd:n.union([n.string(),n.null()]).optional(),env:n.array(nn).optional(),outputByteLimit:n.union([n.number(),n.null()]).optional(),sessionId:c}),H=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cwd:n.string(),mcpServers:n.array(h).optional(),sessionId:c}),P=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c,terminalId:n.string()}),D=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cwd:n.string(),mcpServers:n.array(h),sessionId:c}),A=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),limit:n.union([n.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),n.null()]).optional(),line:n.union([n.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),n.null()]).optional(),path:n.string(),sessionId:c}),F=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c,terminalId:n.string()}),L=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cwd:n.string(),mcpServers:n.array(h).optional(),sessionId:c}),ae=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cwd:n.string(),sessionId:c,title:n.union([n.string(),n.null()]).optional(),updatedAt:n.union([n.string(),n.null()]).optional()}),le=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),nextCursor:n.union([n.string(),n.null()]).optional(),sessions:n.array(ae)}),ue=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),title:n.union([n.string(),n.null()]).optional(),updatedAt:n.union([n.string(),n.null()]).optional()}),ce=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),f=n.string(),de=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),currentModeId:f}),pe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),description:n.union([n.string(),n.null()]).optional(),id:f,name:n.string()}),z=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),availableModes:n.array(pe),currentModeId:f}),S=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),availableModels:n.array(Pn),currentModelId:C}),me=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.union([n.array(w),n.null()]).optional(),models:n.union([S,n.null()]).optional(),modes:n.union([z,n.null()]).optional(),sessionId:c}),ge=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.union([n.array(w),n.null()]).optional(),models:n.union([S,n.null()]).optional(),modes:n.union([z,n.null()]).optional()}),_e=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.union([n.array(w),n.null()]).optional(),models:n.union([S,n.null()]).optional(),modes:n.union([z,n.null()]).optional(),sessionId:c}),xe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.union([n.array(w),n.null()]).optional(),models:n.union([S,n.null()]).optional(),modes:n.union([z,n.null()]).optional()}),we=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),be=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),fork:n.union([re,n.null()]).optional(),list:n.union([ce,n.null()]).optional(),resume:n.union([we,n.null()]).optional()}),he=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),loadSession:n.boolean().optional().default(!1),mcpCapabilities:Nn.optional().default({http:!1,sse:!1}),promptCapabilities:$n.optional().default({audio:!1,embeddedContext:!1,image:!1}),sessionCapabilities:be.optional().default({})}),fe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),agentCapabilities:he.optional().default({loadSession:!1,mcpCapabilities:{http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:n.union([an,n.null()]).optional(),authMethods:n.array(Tn).optional().default([]),protocolVersion:un}),G=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configId:cn,sessionId:c,value:N}),ze=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),configOptions:n.array(w)}),U=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),modeId:f,sessionId:c}),Se=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),$=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),modelId:C,sessionId:c}),Te=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),ke=n.union([n.literal("end_turn"),n.literal("max_tokens"),n.literal("max_turn_requests"),n.literal("refusal"),n.literal("cancelled")]),je=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),terminalId:n.string()}),Re=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),exitCode:n.union([n.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),n.null()]).optional(),signal:n.union([n.string(),n.null()]).optional()}),W=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c,terminalId:n.string()}),Ee=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),exitStatus:n.union([Re,n.null()]).optional(),output:n.string(),truncated:n.boolean()}),ye=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),annotations:n.union([b,n.null()]).optional(),text:n.string()}),Ie=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),mimeType:n.union([n.string(),n.null()]).optional(),text:n.string(),uri:n.string()}),Ce=n.union([Ie,jn]),ve=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),annotations:n.union([b,n.null()]).optional(),resource:Ce}),V=n.union([ye.and(n.object({type:n.literal("text")})),Bn.and(n.object({type:n.literal("image")})),Kn.and(n.object({type:n.literal("audio")})),Zn.and(n.object({type:n.literal("resource_link")})),ve.and(n.object({type:n.literal("resource")}))]),qe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:V}),E=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:V}),J=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),prompt:n.array(V),sessionId:c}),tt=n.object({id:x,method:n.string(),params:n.union([n.union([q,y,v,D,I,H,L,U,G,J,$,on]),n.null()]).optional()}),pn=n.union([qe.and(n.object({type:n.literal("content")})),yn.and(n.object({type:n.literal("diff")})),je.and(n.object({type:n.literal("terminal")}))]),mn=n.string(),gn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),line:n.union([n.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),n.null()]).optional(),path:n.string()}),_n=n.union([n.literal("pending"),n.literal("in_progress"),n.literal("completed"),n.literal("failed")]),xn=n.union([n.literal("read"),n.literal("edit"),n.literal("delete"),n.literal("move"),n.literal("search"),n.literal("execute"),n.literal("think"),n.literal("fetch"),n.literal("switch_mode"),n.literal("other")]),Ne=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:n.array(pn).optional(),kind:xn.optional(),locations:n.array(gn).optional(),rawInput:n.unknown().optional(),rawOutput:n.unknown().optional(),status:_n.optional(),title:n.string(),toolCallId:mn}),wn=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:n.union([n.array(pn),n.null()]).optional(),kind:n.union([xn,n.null()]).optional(),locations:n.union([n.array(gn),n.null()]).optional(),rawInput:n.unknown().optional(),rawOutput:n.unknown().optional(),status:n.union([_n,n.null()]).optional(),title:n.union([n.string(),n.null()]).optional(),toolCallId:mn}),K=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),options:n.array(An),sessionId:c,toolCall:wn}),Oe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),hint:n.string()}),Me=Oe,He=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),description:n.string(),input:n.union([Me,n.null()]).optional(),name:n.string()}),Pe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),availableCommands:n.array(He)}),De=n.object({cachedReadTokens:n.union([n.number(),n.null()]).optional(),cachedWriteTokens:n.union([n.number(),n.null()]).optional(),inputTokens:n.number(),outputTokens:n.number(),thoughtTokens:n.union([n.number(),n.null()]).optional(),totalTokens:n.number()}),Ae=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),stopReason:ke,usage:n.union([De,n.null()]).optional()}),ot=n.union([n.object({id:x,result:n.union([fe,kn,_e,ge,le,me,xe,Se,ze,Ae,Te,sn])}),n.object({error:en,id:x})]),Fe=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),cost:n.union([Rn,n.null()]).optional(),size:n.number(),used:n.number()}),Le=n.union([E.and(n.object({sessionUpdate:n.literal("user_message_chunk")})),E.and(n.object({sessionUpdate:n.literal("agent_message_chunk")})),E.and(n.object({sessionUpdate:n.literal("agent_thought_chunk")})),Ne.and(n.object({sessionUpdate:n.literal("tool_call")})),wn.and(n.object({sessionUpdate:n.literal("tool_call_update")})),Un.and(n.object({sessionUpdate:n.literal("plan")})),Pe.and(n.object({sessionUpdate:n.literal("available_commands_update")})),de.and(n.object({sessionUpdate:n.literal("current_mode_update")})),se.and(n.object({sessionUpdate:n.literal("config_option_update")})),ue.and(n.object({sessionUpdate:n.literal("session_info_update")})),Fe.and(n.object({sessionUpdate:n.literal("usage_update")}))]),B=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c,update:Le}),it=n.object({method:n.string(),params:n.union([n.union([B,tn]),n.null()]).optional()}),Z=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),sessionId:c,terminalId:n.string()}),Ge=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),exitCode:n.union([n.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),n.null()]).optional(),signal:n.union([n.string(),n.null()]).optional()}),Q=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional(),content:n.string(),path:n.string(),sessionId:c}),st=n.object({id:x,method:n.string(),params:n.union([n.union([Q,A,K,M,W,F,Z,P,on]),n.null()]).optional()}),Ue=n.object({_meta:n.union([n.record(n.string(),n.unknown()),n.null()]).optional()}),rt=n.union([n.object({id:x,result:n.union([Ue,Wn,Yn,En,Ee,Vn,Ge,qn,sn])}),n.object({error:en,id:x})]);var bn=class{#n;constructor(e,o){let t=e(this),l=async(r,s)=>{switch(r){case a.initialize:{let i=q.parse(s);return t.initialize(i)}case a.session_new:{let i=v.parse(s);return t.newSession(i)}case a.session_load:{if(!t.loadSession)throw u.methodNotFound(r);let i=D.parse(s);return t.loadSession(i)}case a.session_list:{if(!t.unstable_listSessions)throw u.methodNotFound(r);let i=I.parse(s);return t.unstable_listSessions(i)}case a.session_fork:{if(!t.unstable_forkSession)throw u.methodNotFound(r);let i=H.parse(s);return t.unstable_forkSession(i)}case a.session_resume:{if(!t.unstable_resumeSession)throw u.methodNotFound(r);let i=L.parse(s);return t.unstable_resumeSession(i)}case a.session_set_mode:{if(!t.setSessionMode)throw u.methodNotFound(r);let i=U.parse(s);return await t.setSessionMode(i)??{}}case a.authenticate:{let i=y.parse(s);return await t.authenticate(i)??{}}case a.session_prompt:{let i=J.parse(s);return t.prompt(i)}case a.session_set_model:{if(!t.unstable_setSessionModel)throw u.methodNotFound(r);let i=$.parse(s);return await t.unstable_setSessionModel(i)??{}}case a.session_set_config_option:{if(!t.setSessionConfigOption)throw u.methodNotFound(r);let i=G.parse(s);return t.setSessionConfigOption(i)}default:if(t.extMethod)return t.extMethod(r,s);throw u.methodNotFound(r)}},g=async(r,s)=>{switch(r){case a.session_cancel:{let i=O.parse(s);return t.cancel(i)}default:if(t.extNotification)return t.extNotification(r,s);throw u.methodNotFound(r)}};this.#n=new T(l,g,o)}async sessionUpdate(e){return await this.#n.sendNotification(d.session_update,e)}async requestPermission(e){return await this.#n.sendRequest(d.session_request_permission,e)}async readTextFile(e){return await this.#n.sendRequest(d.fs_read_text_file,e)}async writeTextFile(e){return await this.#n.sendRequest(d.fs_write_text_file,e)??{}}async createTerminal(e){let o=await this.#n.sendRequest(d.terminal_create,e);return new X(o.terminalId,e.sessionId,this.#n)}async extMethod(e,o){return await this.#n.sendRequest(e,o)}async extNotification(e,o){return await this.#n.sendNotification(e,o)}get signal(){return this.#n.signal}get closed(){return this.#n.closed}},X=class{id;#n;#e;constructor(e,o,t){this.id=e,this.#n=o,this.#e=t}async currentOutput(){return await this.#e.sendRequest(d.terminal_output,{sessionId:this.#n,terminalId:this.id})}async waitForExit(){return await this.#e.sendRequest(d.terminal_wait_for_exit,{sessionId:this.#n,terminalId:this.id})}async kill(){return await this.#e.sendRequest(d.terminal_kill,{sessionId:this.#n,terminalId:this.id})??{}}async release(){return await this.#e.sendRequest(d.terminal_release,{sessionId:this.#n,terminalId:this.id})??{}}async[Symbol.asyncDispose](){await this.release()}},hn=class{#n;constructor(e,o){let t=e(this),l=async(r,s)=>{switch(r){case d.fs_write_text_file:{let i=Q.parse(s);return t.writeTextFile?.(i)}case d.fs_read_text_file:{let i=A.parse(s);return t.readTextFile?.(i)}case d.session_request_permission:{let i=K.parse(s);return t.requestPermission(i)}case d.terminal_create:{let i=M.parse(s);return t.createTerminal?.(i)}case d.terminal_output:{let i=W.parse(s);return t.terminalOutput?.(i)}case d.terminal_release:{let i=F.parse(s);return await t.releaseTerminal?.(i)??{}}case d.terminal_wait_for_exit:{let i=Z.parse(s);return t.waitForTerminalExit?.(i)}case d.terminal_kill:{let i=P.parse(s);return await t.killTerminal?.(i)??{}}default:if(t.extMethod)return t.extMethod(r,s);throw u.methodNotFound(r)}},g=async(r,s)=>{switch(r){case d.session_update:{let i=B.parse(s);return t.sessionUpdate(i)}default:if(t.extNotification)return t.extNotification(r,s);throw u.methodNotFound(r)}};this.#n=new T(l,g,o)}async initialize(e){return await this.#n.sendRequest(a.initialize,e)}async newSession(e){return await this.#n.sendRequest(a.session_new,e)}async loadSession(e){return await this.#n.sendRequest(a.session_load,e)??{}}async unstable_forkSession(e){return await this.#n.sendRequest(a.session_fork,e)}async unstable_listSessions(e){return await this.#n.sendRequest(a.session_list,e)}async unstable_resumeSession(e){return await this.#n.sendRequest(a.session_resume,e)}async setSessionMode(e){return await this.#n.sendRequest(a.session_set_mode,e)??{}}async unstable_setSessionModel(e){return await this.#n.sendRequest(a.session_set_model,e)??{}}async setSessionConfigOption(e){return await this.#n.sendRequest(a.session_set_config_option,e)}async authenticate(e){return await this.#n.sendRequest(a.authenticate,e)??{}}async prompt(e){return await this.#n.sendRequest(a.session_prompt,e)}async cancel(e){return await this.#n.sendNotification(a.session_cancel,e)}async extMethod(e,o){return await this.#n.sendRequest(e,o)}async extNotification(e,o){return await this.#n.sendNotification(e,o)}get signal(){return this.#n.signal}get closed(){return this.#n.closed}},T=class{#n=new Map;#e=0;#r;#a;#o;#i=Promise.resolve();#s=new AbortController;#l;constructor(e,o,t){this.#r=e,this.#a=o,this.#o=t,this.#l=new Promise(l=>{this.#s.signal.addEventListener("abort",()=>l())}),this.#u()}get signal(){return this.#s.signal}get closed(){return this.#l}async#u(){let e=this.#o.readable.getReader();try{for(;;){let{value:o,done:t}=await e.read();if(t)break;if(o)try{this.#c(o)}catch(l){console.error("Unexpected error during message processing:",o,l),"id"in o&&o.id!==void 0&&this.#t({jsonrpc:"2.0",id:o.id,error:{code:-32700,message:"Parse error"}})}}}finally{e.releaseLock(),this.#s.abort()}}async#c(e){if("method"in e&&"id"in e){let o=await this.#d(e.method,e.params);"error"in o&&console.error("Error handling request",e,o.error),await this.#t({jsonrpc:"2.0",id:e.id,...o})}else if("method"in e){let o=await this.#p(e.method,e.params);"error"in o&&console.error("Error handling notification",e,o.error)}else"id"in e?this.#m(e):console.error("Invalid message",{message:e})}async#d(e,o){try{return{result:await this.#r(e,o)??null}}catch(t){if(t instanceof u)return t.toResult();if(t instanceof R.ZodError)return u.invalidParams(t.format()).toResult();let l;(t instanceof Error||typeof t=="object"&&t!=null&&"message"in t&&typeof t.message=="string")&&(l=t.message);try{return u.internalError(l?JSON.parse(l):{}).toResult()}catch{return u.internalError({details:l}).toResult()}}}async#p(e,o){try{return await this.#a(e,o),{result:null}}catch(t){if(t instanceof u)return t.toResult();if(t instanceof R.ZodError)return u.invalidParams(t.format()).toResult();let l;(t instanceof Error||typeof t=="object"&&t!=null&&"message"in t&&typeof t.message=="string")&&(l=t.message);try{return u.internalError(l?JSON.parse(l):{}).toResult()}catch{return u.internalError({details:l}).toResult()}}}#m(e){let o=this.#n.get(e.id);o?("result"in e?o.resolve(e.result):"error"in e&&o.reject(e.error),this.#n.delete(e.id)):console.error("Got response to unknown request",e.id)}async sendRequest(e,o){let t=this.#e++,l=new Promise((g,r)=>{this.#n.set(t,{resolve:g,reject:r})});return await this.#t({jsonrpc:"2.0",id:t,method:e,params:o}),l}async sendNotification(e,o){await this.#t({jsonrpc:"2.0",method:e,params:o})}async#t(e){return this.#i=this.#i.then(async()=>{let o=this.#o.writable.getWriter();try{await o.write(e)}finally{o.releaseLock()}}).catch(o=>{console.error("ACP write error:",o)}),this.#i}},u=class p extends Error{code;data;constructor(e,o,t){super(o),this.code=e,this.name="RequestError",this.data=t}static parseError(e,o){return new p(-32700,`Parse error${o?`: ${o}`:""}`,e)}static invalidRequest(e,o){return new p(-32600,`Invalid request${o?`: ${o}`:""}`,e)}static methodNotFound(e){return new p(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,o){return new p(-32602,`Invalid params${o?`: ${o}`:""}`,e)}static internalError(e,o){return new p(-32603,`Internal error${o?`: ${o}`:""}`,e)}static authRequired(e,o){return new p(-32e3,`Authentication required${o?`: ${o}`:""}`,e)}static resourceNotFound(e){return new p(-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}}};export{We as a,Je as b,bn as c,hn as d,u as e};
|