@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
|
@@ -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,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};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{b as d}from"./chunk-GZPNIYVZ.js";d();import{setMaxListeners as b}from"node:events";var f=50;function c(r=f){let t=new AbortController;return b(r,t.signal),t}function m(r){if(r)return r instanceof AbortController?r.signal:r}function v(r,t){let e=c(t),n=m(r);if(!n)return e;if(n.aborted)return e.abort(n.reason),e;let a=new WeakRef(n),i=()=>{e.abort(a.deref()?.reason)};return n.addEventListener("abort",i,{once:!0}),e.signal.addEventListener("abort",()=>{a.deref()?.removeEventListener("abort",i)},{once:!0}),e}function g(r,t){let e=c(t?.maxListeners),n=r.find(o=>o?.aborted);if(n)return e.abort(n.reason),{signal:e.signal,cleanup:()=>{}};let a=[];for(let o of r){if(!o)continue;if(o.aborted){e.abort(o.reason);break}let u=()=>e.abort(o.reason);o.addEventListener("abort",u,{once:!0}),a.push(()=>o.removeEventListener("abort",u))}let i=t?.timeoutMs;if(i!==void 0&&i>0&&!e.signal.aborted){let o=setTimeout(()=>{e.abort(new DOMException("Operation timed out","TimeoutError"))},i);a.push(()=>clearTimeout(o))}let s=!1,l=()=>{if(!s){s=!0;for(let o of a)o()}};return e.signal.aborted?l():e.signal.addEventListener("abort",l,{once:!0}),{signal:e.signal,cleanup:l}}async function E(r,t){t?.throwIfAborted();let e=r();if(!t)return e;let n=()=>{},a=new Promise((i,s)=>{n=()=>s(t.reason),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,a])}finally{t.removeEventListener("abort",n),e.catch(()=>{})}}export{c as a,v as b,g as c,E as d};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2025 Matilda
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as sn,b as St,c as an,d as ln}from"./chunk-DC7LAFZZ.js";import{a as q,d as on}from"./chunk-4F4DA5UI.js";import{b as Xt,d as Qt,g as Et,j as Zt,k as en,s as rn,v as pe}from"./chunk-SUH3UUWZ.js";import{b as A,e as V}from"./chunk-4J6DC24J.js";import{a as tn,d as nn}from"./chunk-SDTWBD62.js";import{Bb as ue,Jc as Tt,Kc as yt,Mb as mt,Mc as At,Pa as Io,Pb as ht,Ra as Oo,Rb as Ct,Sa as Q,Wa as ke,Xa as Ie,Ya as Oe,a as M,ab as gt,eb as we,f as F,fb as B,na as ft,tb as Pe,ub as De}from"./chunk-FRRBNNEB.js";import{b as dn}from"./chunk-3YLXGE6T.js";import{Q as ve,U as Jt,W as pt,ba as O,c as zt,d as Wt,e as U,f as de,k as dt}from"./chunk-MH2P4YXC.js";import{b as ct,c as b,f as ut,g as ce,h as _,i as xe,k as Yt,l as x,n as X}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as ko}from"./chunk-OWGSC52X.js";f();function Z(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function Le(e){let t=e.candidates||0,n=e.thoughts||0;return n>t?t+n:Math.max(t,n)}function wo(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Le(e)):(e.prompt||0)+Le(e)}function Po(e){let t=Math.max(0,e.thoughtsTokens||0),n=Le({candidates:e.outputTokens||0,thoughts:t}),o=Math.max(e.totalTokens||0,(e.inputTokens||0)+n);return{...e,outputTokens:n,thoughtsTokens:t,totalTokens:o}}f();f();var Do=/[A-Za-z\u00C0-\u024F]/g;function Lo(e){return e>=1024&&e<=1279||e>=1280&&e<=1327||e>=11744&&e<=11775||e>=42560&&e<=42655||e>=12352&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=63744&&e<=64255||e>=44032&&e<=55215}function Mt(e){let t=e.codePointAt(0);return t!==void 0&&Lo(t)}function No(e){let t=e.match(Do)?.length??0;if(t<24)return!1;let n=0;for(let o of e)Mt(o)&&n++;return n===0||t>=n*8}function Ne(e){if(!e||!No(e))return e;let t="",n=0,o=[...e];for(;n<o.length;){if(!Mt(o[n])){t+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&Mt(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(t+=" "),n=i,r<n&&o[r]===" "&&t.endsWith(" ")&&(t=t.slice(0,-1))}return t.replace(/ {2,}/g," ")}f();var ee=O("TAGGED_THINKING_PARSER"),ge=["<think>","<thinking>"],me=["</think>","</thinking>"],Uo=Math.max(...ge.map(e=>e.length),...me.map(e=>e.length));function fe(e,t,n){t&&e.push(n==="thought"?{text:t,thought:!0}:{text:t})}function Ue(e,t,n){let o=e.length-t;return o<=0||o>Uo?!1:n.some(r=>r.startsWith(e.slice(t,t+o)))}function Fe(e,t,n){return n.find(o=>e.startsWith(o,t))}function Rt(e){if(!e)return e;let t=e;return t=t.replace(/<\/?think(?:ing)?>/gi,""),t=t.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),t=t.replace(/\bM?long[_-]?message\b/gi,""),t=t.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),t!==e&&(t=t.replace(/[ \t]{2,}/g," ")),t}function cn(e){let t=[];for(let n of e){if(n.thought===!0||typeof n.text!="string"){t.push(n);continue}let o=Ne(Rt(n.text));(o.length>0||/^\s+$/.test(n.text))&&t.push({text:o.length>0?o:n.text})}return t}var _t=class{mode="text";buffer="";parse(t,n=!1){this.buffer+=t;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Fe(o,s,ge);if(a){ee.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Fe(o,s,me);if(l){ee.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),fe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,me)))break}else{let a=Fe(o,s,me);if(a){ee.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Fe(o,s,ge);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,me)||Ue(o,s,ge)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(fe(r,i,this.mode),this.buffer=this.buffer.slice(s),ee.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),cn(r)):(this.buffer="",this.mode==="thought"&&i&&ee.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),fe(r,i,this.mode),ee.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),cn(r))}};function un(e){return new _t().parse(e,!0)}var P=O("CONVERTER"),Tn="(attached media from previous tool call)";function yn(e,t={}){let n=e.prompt_tokens||0,o=e.completion_tokens||0,r=e.total_tokens||0,i=e.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??e.cached_tokens??e.prompt_cache_hit_tokens??e.cache_read_input_tokens??0,a=e.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??e.reasoning_tokens??0,u=Math.max(0,t.estimatedReasoningTokens??0),d=Math.max(0,t.estimatedContentTokens??0),p=l>0?l:u,c=o;p>0&&(o>=p?c=o:c=o+p),(d>0||u>0)&&(c=Math.max(c,d+(l>0?0:u),d+p)),r>n&&(n>0||o>0||p>0)&&(c=Math.max(c,r-n)),p===0&&u>0&&(p=u),p>c&&(p=c);let h=e.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,g=r;return(g===0&&(m>0||c>0)||g>0&&m>0&&g<m+c)&&(g=m+c),{promptTokenCount:m,candidatesTokenCount:c,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Fo=64,pn=1024;function fn(e,t){if(e.length===0)return"";if(t.emittedText.length===0)return t.emittedText=e,t.emittedLength=e.length,e;if(t.cumulativeMode){if(e.startsWith(t.emittedText)){let n=e.slice(t.emittedText.length);return t.emittedText=e,t.emittedLength=e.length,n}return t.emittedText.startsWith(e)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),t.cumulativeMode=!1,t.emittedText=e,t.emittedLength+=e.length,e)}if(e.length>t.emittedText.length&&e.startsWith(t.emittedText)){let n=t.emittedText.length,r=n>=pn&&t.emittedLength>n?t.emittedLength:n;if(e.length>r){let i=e.slice(r);return t.emittedText=e,t.emittedLength=e.length,t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=Fo?(t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<pn&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function An(e){if(!e||typeof e!="object")return e;let t=JSON.parse(JSON.stringify(e)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(t)}async function Go(e,t="auto"){let n=[];for(let o of e){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=An(i.parameters)),s&&(s=Qt(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Ko(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return jo(e,o),Ho(e.contents,o,t),o=Cn(o),n.cleanOrphanToolCalls&&(o=Zo(o),o=Cn(o)),o}function $o(e,t){let n=e.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let d=Qo(n?.finishReason),p=e.usageMetadata,c={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(c.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=e.createTime?Number(e.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:e.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:e.modelVersion||t.model,choices:[{index:0,message:l,finish_reason:d,logprobs:null}],usage:c}}function jo(e,t){if(!e.config?.systemInstruction)return;let n=Sn(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function Ho(e,t,n){if(Array.isArray(e))for(let o of e)gn(o,t,n);else e&&gn(e,t,n)}function gn(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!zo(e))return;let o=e.parts||[],r=e.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,u=new Set,d=new Set,p=[];for(let c of o){if(typeof c=="string"){i.push({type:"text",text:c});continue}"text"in c&&"thought"in c&&c.thought&&r==="assistant"&&c.text&&s.push(c.text),"text"in c&&c.text&&!("thought"in c&&c.thought)&&i.push({type:"text",text:c.text});let h=En(c,n);if(h&&r==="user"&&i.push(h),"functionCall"in c&&c.functionCall&&r==="assistant"){let m=c.functionCall.id;if(m){if(u.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}u.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:c.functionCall.name||"",arguments:JSON.stringify(c.functionCall.args||{})}}),l+=1}if(c.functionResponse&&r==="user"){let m=c.functionResponse.id;if(m){if(d.has(m))continue;d.add(m)}let g=Bo(c.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let y of g.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(E=>E.text).join(`
|
|
3
|
+
import{a as sn,b as St,c as an,d as ln}from"./chunk-DC7LAFZZ.js";import{a as q,d as on}from"./chunk-4F4DA5UI.js";import{b as Xt,d as Qt,g as Et,j as Zt,k as en,s as rn,v as pe}from"./chunk-SUH3UUWZ.js";import{b as A,e as V}from"./chunk-4J6DC24J.js";import{a as tn,d as nn}from"./chunk-SDTWBD62.js";import{Bb as ue,Mb as mt,Nc as Tt,Oc as yt,Pa as Io,Pb as ht,Qc as At,Ra as Oo,Rb as Ct,Sa as Q,Wa as ke,Xa as Ie,Ya as Oe,a as M,ab as gt,eb as we,f as F,fb as B,na as ft,tb as Pe,ub as De}from"./chunk-25NCTG5H.js";import{b as dn}from"./chunk-3YLXGE6T.js";import{Q as ve,U as Jt,W as pt,ba as O,c as zt,d as Wt,e as U,f as de,k as dt}from"./chunk-MH2P4YXC.js";import{b as ct,c as b,f as ut,g as ce,h as _,i as xe,k as Yt,l as x,n as X}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{f as ko}from"./chunk-OWGSC52X.js";f();function Z(e){return!Number.isFinite(e)||e<=0?0:Math.ceil(e/4)}function Le(e){let t=e.candidates||0,n=e.thoughts||0;return n>t?t+n:Math.max(t,n)}function wo(e){return e.total&&e.total>0?Math.max(e.total,(e.prompt||0)+Le(e)):(e.prompt||0)+Le(e)}function Po(e){let t=Math.max(0,e.thoughtsTokens||0),n=Le({candidates:e.outputTokens||0,thoughts:t}),o=Math.max(e.totalTokens||0,(e.inputTokens||0)+n);return{...e,outputTokens:n,thoughtsTokens:t,totalTokens:o}}f();f();var Do=/[A-Za-z\u00C0-\u024F]/g;function Lo(e){return e>=1024&&e<=1279||e>=1280&&e<=1327||e>=11744&&e<=11775||e>=42560&&e<=42655||e>=12352&&e<=12543||e>=13312&&e<=19903||e>=19968&&e<=40959||e>=63744&&e<=64255||e>=44032&&e<=55215}function Mt(e){let t=e.codePointAt(0);return t!==void 0&&Lo(t)}function No(e){let t=e.match(Do)?.length??0;if(t<24)return!1;let n=0;for(let o of e)Mt(o)&&n++;return n===0||t>=n*8}function Ne(e){if(!e||!No(e))return e;let t="",n=0,o=[...e];for(;n<o.length;){if(!Mt(o[n])){t+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&Mt(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(t+=" "),n=i,r<n&&o[r]===" "&&t.endsWith(" ")&&(t=t.slice(0,-1))}return t.replace(/ {2,}/g," ")}f();var ee=O("TAGGED_THINKING_PARSER"),ge=["<think>","<thinking>"],me=["</think>","</thinking>"],Uo=Math.max(...ge.map(e=>e.length),...me.map(e=>e.length));function fe(e,t,n){t&&e.push(n==="thought"?{text:t,thought:!0}:{text:t})}function Ue(e,t,n){let o=e.length-t;return o<=0||o>Uo?!1:n.some(r=>r.startsWith(e.slice(t,t+o)))}function Fe(e,t,n){return n.find(o=>e.startsWith(o,t))}function Rt(e){if(!e)return e;let t=e;return t=t.replace(/<\/?think(?:ing)?>/gi,""),t=t.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),t=t.replace(/\bM?long[_-]?message\b/gi,""),t=t.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),t!==e&&(t=t.replace(/[ \t]{2,}/g," ")),t}function cn(e){let t=[];for(let n of e){if(n.thought===!0||typeof n.text!="string"){t.push(n);continue}let o=Ne(Rt(n.text));(o.length>0||/^\s+$/.test(n.text))&&t.push({text:o.length>0?o:n.text})}return t}var _t=class{mode="text";buffer="";parse(t,n=!1){this.buffer+=t;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Fe(o,s,ge);if(a){ee.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Fe(o,s,me);if(l){ee.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),fe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,me)))break}else{let a=Fe(o,s,me);if(a){ee.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),fe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Fe(o,s,ge);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,me)||Ue(o,s,ge)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(fe(r,i,this.mode),this.buffer=this.buffer.slice(s),ee.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),cn(r)):(this.buffer="",this.mode==="thought"&&i&&ee.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),fe(r,i,this.mode),ee.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),cn(r))}};function un(e){return new _t().parse(e,!0)}var P=O("CONVERTER"),Tn="(attached media from previous tool call)";function yn(e,t={}){let n=e.prompt_tokens||0,o=e.completion_tokens||0,r=e.total_tokens||0,i=e.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??e.cached_tokens??e.prompt_cache_hit_tokens??e.cache_read_input_tokens??0,a=e.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??e.reasoning_tokens??0,u=Math.max(0,t.estimatedReasoningTokens??0),d=Math.max(0,t.estimatedContentTokens??0),p=l>0?l:u,c=o;p>0&&(o>=p?c=o:c=o+p),(d>0||u>0)&&(c=Math.max(c,d+(l>0?0:u),d+p)),r>n&&(n>0||o>0||p>0)&&(c=Math.max(c,r-n)),p===0&&u>0&&(p=u),p>c&&(p=c);let h=e.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,g=r;return(g===0&&(m>0||c>0)||g>0&&m>0&&g<m+c)&&(g=m+c),{promptTokenCount:m,candidatesTokenCount:c,totalTokenCount:g,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Fo=64,pn=1024;function fn(e,t){if(e.length===0)return"";if(t.emittedText.length===0)return t.emittedText=e,t.emittedLength=e.length,e;if(t.cumulativeMode){if(e.startsWith(t.emittedText)){let n=e.slice(t.emittedText.length);return t.emittedText=e,t.emittedLength=e.length,n}return t.emittedText.startsWith(e)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${t.emittedText.length}b, chunk=${e.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),t.cumulativeMode=!1,t.emittedText=e,t.emittedLength+=e.length,e)}if(e.length>t.emittedText.length&&e.startsWith(t.emittedText)){let n=t.emittedText.length,r=n>=pn&&t.emittedLength>n?t.emittedLength:n;if(e.length>r){let i=e.slice(r);return t.emittedText=e,t.emittedLength=e.length,t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${e.length}b)`),i}}return e===t.emittedText?e.length>=Fo?(t.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${e.length}b)`),""):(t.emittedLength+=e.length,e):(t.emittedText.length<pn&&(t.emittedText+=e),t.emittedLength+=e.length,e)}function An(e){if(!e||typeof e!="object")return e;let t=JSON.parse(JSON.stringify(e)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(t)}async function Go(e,t="auto"){let n=[];for(let o of e){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=An(i.parameters)),s&&(s=Qt(s,t)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function Ko(e,t,n={cleanOrphanToolCalls:!0}){let o=[];return jo(e,o),Ho(e.contents,o,t),o=Cn(o),n.cleanOrphanToolCalls&&(o=Zo(o),o=Cn(o)),o}function $o(e,t){let n=e.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let g of o)typeof g=="string"?i.push(g):"text"in g&&g.text?"thought"in g&&g.thought?r.push(g.text):i.push(g.text):"functionCall"in g&&g.functionCall&&(s.push({id:g.functionCall.id||`call_${a}`,type:"function",function:{name:g.functionCall.name||"",arguments:JSON.stringify(g.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},u=r.join("");u&&(l.reasoning_content=u),s.length>0&&(l.tool_calls=s);let d=Qo(n?.finishReason),p=e.usageMetadata,c={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(c.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=e.createTime?Number(e.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:e.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:e.modelVersion||t.model,choices:[{index:0,message:l,finish_reason:d,logprobs:null}],usage:c}}function jo(e,t){if(!e.config?.systemInstruction)return;let n=Sn(e.config.systemInstruction);n&&t.push({role:"system",content:n})}function Ho(e,t,n){if(Array.isArray(e))for(let o of e)gn(o,t,n);else e&&gn(e,t,n)}function gn(e,t,n){if(typeof e=="string"){t.push({role:"user",content:e});return}if(!zo(e))return;let o=e.parts||[],r=e.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,u=new Set,d=new Set,p=[];for(let c of o){if(typeof c=="string"){i.push({type:"text",text:c});continue}"text"in c&&"thought"in c&&c.thought&&r==="assistant"&&c.text&&s.push(c.text),"text"in c&&c.text&&!("thought"in c&&c.thought)&&i.push({type:"text",text:c.text});let h=En(c,n);if(h&&r==="user"&&i.push(h),"functionCall"in c&&c.functionCall&&r==="assistant"){let m=c.functionCall.id;if(m){if(u.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}u.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:c.functionCall.name||"",arguments:JSON.stringify(c.functionCall.args||{})}}),l+=1}if(c.functionResponse&&r==="user"){let m=c.functionResponse.id;if(m){if(d.has(m))continue;d.add(m)}let g=Bo(c.functionResponse,n);if(g){if(n.splitToolMedia&&Array.isArray(g.content)){let C=[],T=[];for(let y of g.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(E=>E.text).join(`
|
|
4
4
|
`);g.content=y||"[media attached in following user message]",p.push(...C)}}t.push(g)}}}if(p.length>0&&t.push({role:"user",content:[{type:"text",text:Tn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(g=>g.type==="text").map(g=>g.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),t.push(h);return}i.length>0&&t.push({role:"user",content:i})}function Vo(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let o=t.error;if(typeof o=="string")return o}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Bo(e,t){let n=Vo(e.response),o=[];n&&o.push({type:"text",text:n});for(let r of e.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=En(r,t);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:e.id||"",content:""}:{role:"tool",tool_call_id:e.id||"",content:o}}function En(e,t){let{modalities:n}=t;if(e.inlineData?.mimeType&&e.inlineData?.data){let o=e.inlineData.mimeType,r=mn(o),i=e.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${e.inlineData.data}`}}:z("image",i,t);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:e.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${e.inlineData.data}`}}:z("pdf",i,t);if(r==="audio"){if(!n.audio)return z("audio",i,t);let s=qo(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${e.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${e.inlineData.data}`}}:z("video",i,t):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let o=e.fileData.displayName||"file",r=e.fileData.fileUri,i=e.fileData.mimeType,s=mn(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:z("image",o,t);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:z("pdf",o,t);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:z("video",o,t);let a=e.fileData.displayName?` (${e.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function z(e,t,n){P.warn(`Model '${n.model}' does not support ${e} input. Replacing with text placeholder: ${t}`);let o;return e==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
|
|
5
5
|
/extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${e} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${e} file: "${t}". ${o}]`}}function mn(e){return e.startsWith("image/")?"image":e.startsWith("audio/")?"audio":e.startsWith("video/")?"video":"file"}function qo(e){return e.includes("wav")?"wav":e.includes("mp3")||e.includes("mpeg")?"mp3":null}function zo(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}function Sn(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>Sn(t)).filter(Boolean).join(`
|
|
6
6
|
`):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
@@ -8,9 +8,9 @@ import{a as sn,b as St,c as an,d as ln}from"./chunk-DC7LAFZZ.js";import{a as q,d
|
|
|
8
8
|
${n}`:n;return{...o,text:a}}return t}};f();function qn(e){switch(e){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function zn(e){switch(e){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var K=class extends Error{constructor(t){super(t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},qe=class extends K{code="STRICT_MISSING_CREDENTIALS";constructor(t,n,o){let r=t||"(unknown)",i=n||"(unknown)";super(`Missing credentials for modelProviders model '${i}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${r}[].envKey.`:`Configure modelProviders.${r}[].envKey and set that environment variable.`))}},ze=class extends K{code="STRICT_MISSING_MODEL_ID";constructor(t){super(`Missing model id for strict modelProviders resolution (authType: ${t}).`)}},We=class extends K{code="MISSING_API_KEY";constructor(t){super(`Missing API key for ${t.authType} auth. Current model: '${t.model||"(unknown)"}', baseUrl: '${t.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${t.envKey}'.`)}},Ye=class extends K{code="MISSING_MODEL";constructor(t){super(`Missing model for ${t.authType} auth. Set the environment variable '${t.envKey}'.`)}},Je=class extends K{code="MISSING_BASE_URL";constructor(t){super(`Missing baseUrl for modelProviders model '${t.model||"(unknown)"}'. Configure modelProviders.${t.authType||"(unknown)"}[].baseUrl.`)}},Xe=class extends K{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import Zr from"node:process";f();var Wn={image:!0,pdf:!0,audio:!0,video:!0},Xr=[[/^gemini-3/,Wn],[/^gemini-/,Wn],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Te(e){let t=rn(e);for(let[n,o]of Xr)if(n.test(t))return{...o};return{}}f();var Qe="$runtime|";function fl(e){let t=e;for(;t.startsWith(Qe);){let n=t.split("|").slice(2).join("|");if(!n)break;t=n}return t}f();f();f();var Ze=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],Yn=["model","apiKey","apiKeyEnvKey","baseUrl"],et=[...Yn,...Ze],Tl={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},yl={openai:on,"matilda-oauth":q},tt=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Al=tt.map(e=>e.id);var Ot=O("MODEL_REGISTRY");function Jn(e){if(Object.values(L).includes(e))return e}function Qr(e){return/^minimax-m3/i.test(e.trim().toLowerCase())}function Xn(e,t){return t?`${e}\0${t}`:e}var nt=class{modelsByAuthType;getDefaultBaseUrl(t){switch(t){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return Zt;default:return""}}constructor(t){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",tt),t)for(let[n,o]of Object.entries(t)){let r=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(t,n){let o=new Map;for(let r of n){let i=Xn(r.id,r.baseUrl);if(o.has(i)){Ot.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${t}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,t);o.set(i,s)}this.modelsByAuthType.set(t,o)}getModelsForAuthType(t){let n=this.modelsByAuthType.get(t);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??pe(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(t,n,o){let r=this.modelsByAuthType.get(t);if(!r)return;if(o)return r.get(Xn(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(t,n,o){return this.getModel(t,n,o)!==void 0}getDefaultModelForAuthType(t){if(t==="matilda-oauth")return this.getModel(t,q);let n=this.modelsByAuthType.get(t);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(t,n){this.validateModelConfig(t,n);let o={...t.generationConfig??{}};return(o.modalities===void 0||Qr(t.id))&&(o.modalities=Te(t.id)),{...t,authType:n,name:t.name||t.id,baseUrl:t.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:t.capabilities||{}}}validateModelConfig(t,n){if(!t.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(t){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(t)for(let[n,o]of Object.entries(t)){let r=Jn(n);if(!r){Ot.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(L).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var Qn=class e{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(o=>e.deepClone(o));let n={};for(let o of Object.keys(t))n[o]=e.deepClone(t[o]);return n}constructor(t={}){this.modelRegistry=new nt(t.modelProvidersConfig),this.onModelChange=t.onModelChange,this._generationConfig={...t.generationConfig||{}},this.generationConfigSources=t.generationConfigSources||{},this.authTypeWasExplicitlyProvided=t.initialAuthType!==void 0,this.currentAuthType=t.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:e.deepClone(this._generationConfig),generationConfigSources:e.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(t){this.currentAuthType=t.currentAuthType,this._generationConfig=t.generationConfig,this.generationConfigSources=t.generationConfigSources,this.strictModelProviderSelection=t.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=t.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=t.hasManualCredentials,this.activeRuntimeModelSnapshotId=t.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||q}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(t){return this.modelRegistry.getModelsForAuthType(t)}getAllConfiguredModels(t){let n=t&&t.length>0?t:Object.values(L),o=new Set,r=[];for(let l of n)o.has(l)||(o.add(l),r.push(l));let i=[];r.includes("matilda-oauth")&&i.push("matilda-oauth");for(let l of r)l!=="matilda-oauth"&&i.push(l);let s=this.getRuntimeModelOption(),a=[];for(let l of i)s&&s.authType===l&&a.push(s),a.push(...this.modelRegistry.getModelsForAuthType(l));return a}hasModel(t,n){return this.modelRegistry.hasModel(t,n)}getResolvedModel(t,n){return this.modelRegistry.getModel(t,n)}isManagedMatildaResolvedModel(t){return t?.id===St&&t?.envKey===sn&&t?.baseUrl===ln&&t?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(t){let n=t.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(t){return this.isManagedMatildaModel(t)?St:t}getModelDisplayName(t){return this.isManagedMatildaModel(t)?an:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,t)?.name??t:t}async setModel(t,n){if(this.currentAuthType==="matilda-oauth"&&t===q){this.strictModelProviderSelection=!1,this._generationConfig.model=t,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,t)){await this.switchModel(this.currentAuthType,t);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=t,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(t),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(t){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Te(t),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=pe(t,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(t){let n=this.generationConfigSources[t];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(t,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();t==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let s=t!==this.currentAuthType;this.currentAuthType=t;let a=this.modelRegistry.getModel(t,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${t}'`);let l=i.generationConfig.model||"",u=!s&&l?this.modelRegistry.getModel(t,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(t,l):void 0,d=t!=="matilda-oauth"&&!s&&!!i.generationConfig.apiKey&&!!a.envKey&&u?.envKey===a.envKey&&u.baseUrl===a.baseUrl,p=d?i.generationConfig.apiKey:void 0,c=d?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,c&&(this.generationConfigSources.apiKey=e.deepClone(c))),this.activeRuntimeModelSnapshotId=void 0;let h=s?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(t,h)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(t,n){return`${Qe}${t}|${n}`}extractRuntimeModelSnapshotId(t){if(t.startsWith(Qe))return this.runtimeModelSnapshots.has(t)?t:void 0;if(this.runtimeModelSnapshots.has(t))return t}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(t){if(t)for(let n of Ze)!(n in this._generationConfig)&&n in t&&(this._generationConfig[n]=t[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(t,n){(t.apiKey||t.baseUrl||t.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),t.apiKey&&(this._generationConfig.apiKey=t.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),t.baseUrl&&(this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),t.model&&(this._generationConfig.model=t.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let t=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!t||!o||!r)&&!this.modelRegistry.hasModel(t,n,r))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let i=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);i.apiKey=o,i.baseUrl=r,i.modelId=n;let s=this.buildRuntimeModelSnapshotId(i.authType,i.modelId);s!==i.id&&(this.runtimeModelSnapshots.delete(i.id),i.id=s,this.runtimeModelSnapshots.set(s,i),this.activeRuntimeModelSnapshotId=s),i.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let t of et)this.generationConfigSources[t]?.kind==="modelProviders"&&(delete this._generationConfig[t],delete this.generationConfigSources[t])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let t=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,t}applyResolvedModelDefaults(t){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=t.id,this.generationConfigSources.model={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),t.envKey!==void 0){let o=Zr.env[t.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:t.envKey,via:{kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=t.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"envKey"}}this._generationConfig.baseUrl=t.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:"baseUrl"};let n=t.generationConfig;for(let o of Ze)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:t.authType,modelId:t.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=pe(t.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Te(t.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(t){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),r=this.modelRegistry.getModel(n,t);return!r||!o||r.envKey!==o.envKey||r.baseUrl!==o.baseUrl}syncAfterAuthRefresh(t,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=t;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(t,n,r)??this.modelRegistry.getModel(t,n):void 0;if(i){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),m=o===t&&this._generationConfig.model===n&&!h,g=m?this._generationConfig.apiKey:void 0,C=m&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,y=m&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),E=y?this._generationConfig.baseUrl:void 0,R=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,C&&(this.generationConfigSources.apiKey=C)),E&&(this._generationConfig.baseUrl=E,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let s=this.generationConfigSources.apiKey,a=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&s?.kind!=="modelProviders"||this._generationConfig.baseUrl&&a?.kind!=="modelProviders";if(!(o!==t)&&(n===void 0||!this.modelRegistry.hasModel(t,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(t);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(t){this.onModelChange=t}detectAndCaptureRuntimeModel(){let{model:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!t||!s)return;if(this.modelRegistry.hasModel(s,t,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,t),u={id:l,authType:s,modelId:t,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,u),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(t){let n=this.runtimeModelSnapshots.get(t);if(!n)throw new Error(`Runtime model snapshot '${t}' not found`);let o=this.createStateSnapshotForRollback();try{let r=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=t,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let i=r;this.onModelChange&&await this.onModelChange(n.authType,i)}catch(r){throw this.rollbackToStateSnapshot(o),r}}getRuntimeModelOption(){let t=this.getActiveRuntimeModelSnapshot();if(t)return{id:t.modelId,label:t.modelId,authType:t.authType,isVision:!1,contextWindowSize:t.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:t.id}}clearRuntimeModelSnapshotForAuthType(t){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===t&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let t=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=t.get(n.authType);(!o||n.createdAt>o.createdAt)&&t.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of t.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(t){this.modelRegistry.reloadModels(t)}};f();import{readFileSync as Ti}from"node:fs";import{join as yi}from"node:path";f();f();import{randomBytes as ei,createHash as ti}from"node:crypto";function Zn(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e==="[::1]"}function wt(){let e=ei(32).toString("base64url"),t=ti("sha256").update(e).digest("base64url");return{codeVerifier:e,codeChallenge:t}}function ye(e,t){return{accessToken:e.access_token,refreshToken:e.refresh_token??t?.refreshToken,expiresAt:Date.now()+(e.expires_in??3600)*1e3,idToken:e.id_token??t?.idToken}}var ni=15e3;async function Pt(e){let t=e.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",t);if(n.protocol!=="https:"&&!Zn(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(ni)});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let r=await o.json();if(!r.issuer||!r.authorization_endpoint||!r.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:r.issuer,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint,device_authorization_endpoint:r.device_authorization_endpoint}}f();import{promises as ot,openSync as oi,closeSync as ri,unlinkSync as eo,statSync as ii}from"node:fs";import{dirname as si}from"node:path";var ai=2e4,li=3e4,di=50;function Dt(e,t={}){let n=async()=>{try{let i=await ot.readFile(e,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"?s:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},o=async i=>{await ot.mkdir(si(e),{recursive:!0}),await ot.writeFile(e,JSON.stringify(i,null,2),{mode:384}),await ot.chmod(e,384).catch(()=>{})};return{store:{async get(i){return(await n())[i]??null},async set(i,s){let a=await n();a[i]=s,await o(a)},async remove(i){let s=await n();i in s&&(delete s[i],await o(s))}},lock:ci(`${e}.lock`,t.lockTimeoutMs??ai)}}function ci(e,t){let n=Promise.resolve();return o=>{let r=n.then(async()=>{await ui(e,t);try{return await o()}finally{pi(e)}});return n=r.then(()=>{},()=>{}),r}}async function ui(e,t){let n=Date.now()+t;for(;;)try{ri(oi(e,"wx"));return}catch(o){if(o.code!=="EEXIST")throw o;try{if(Date.now()-ii(e).mtimeMs>li){eo(e);continue}}catch{continue}if(Date.now()>n)throw Object.assign(new Error(`Timed out acquiring credential lock at ${e}`),{code:"ETIMEDOUT"});await fi(di)}}function pi(e){try{eo(e)}catch{}}function fi(e){return new Promise(t=>setTimeout(t,e))}f();var ne=class extends Error{code="invalid_grant";constructor(t="Refresh token is no longer valid \u2014 sign in again."){super(t),this.name="InvalidGrantError"}};function Lt(e){let t=e.storageKey??"default",n=e.fetchImpl??fetch,o=e.expirySkewMs??6e4,r=e.refreshTimeoutMs??15e3,i=null,s=async()=>{let u=await e.store.get(t);if(!u)return null;try{let d=JSON.parse(u);return d.accessToken?d:null}catch{return null}},a=u=>u.expiresAt-Date.now()>o,l=u=>e.lock(async()=>{let d=await s()??u;if(d.accessToken!==u.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new ne("No refresh token available \u2014 sign in again.");let p;try{let h=await n(e.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:d.refreshToken}),signal:AbortSignal.timeout(r)});if(!h.ok){let m=await h.text().catch(()=>"");throw h.status>=400&&h.status<500&&gi(m)==="invalid_grant"?(await e.store.remove(t),new ne):Object.assign(new Error(`Token refresh failed (${h.status})`),{status:h.status})}p=await h.json()}catch(h){throw h?.name==="TimeoutError"?Object.assign(new Error(`Token refresh timed out after ${r} ms`),{code:"ETIMEDOUT",cause:h}):h}let c=ye(p,d);return await e.store.set(t,JSON.stringify(c)),c.accessToken});return{async getAccessToken(u){let d=await s();if(!d)throw new ne("Not signed in.");return!u?.forceRefresh&&a(d)?d.accessToken:(i||(i=l(d).finally(()=>{i=null})),i)}}}function gi(e){try{return JSON.parse(e).error}catch{return}}f();import{createServer as mi}from"node:http";import{randomBytes as hi}from"node:crypto";async function Nt(e){if(e.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${e.transport.kind}`);if(e.signal?.aborted)throw new Error("Login aborted");let t=m=>e.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=wt(),r=hi(16).toString("hex"),i=e.timeoutMs??5*60*1e3,s=e.transport.successRedirect;t({type:"state",status:"idle"});let a,l,u=new Promise((m,g)=>{a=m,l=g});u.catch(()=>{});let d=mi((m,g)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){g.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),E=C.searchParams.get("code");if(T){let R=C.searchParams.get("error_description"),j=R?`OAuth error: ${T} (${R})`:`OAuth error: ${T}`;g.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${T}
|
|
9
9
|
`,()=>l(new Error(j)));return}if(y!==r){g.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!E){g.writeHead(400).end("Missing authorization code");return}Ci(g,s,()=>a(E))}),p=await new Promise((m,g)=>{d.once("error",g),d.listen(e.transport.port??0,"127.0.0.1",()=>{m(d.address().port)})}),c=setTimeout(()=>l(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>l(new Error("Login aborted"));e.signal?.addEventListener("abort",h,{once:!0}),e.signal?.aborted&&h();try{e.signal?.throwIfAborted();let m=`http://127.0.0.1:${p}/callback`,g=new URL(e.metadata.authorization_endpoint);g.searchParams.set("client_id",e.clientId),g.searchParams.set("response_type","code"),g.searchParams.set("redirect_uri",m),g.searchParams.set("code_challenge",o),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("state",r),g.searchParams.set("prompt","select_account"),g.searchParams.set("scope",e.scope??"openid offline_access");let C=g.toString();t({type:"authorize_url",url:C}),t({type:"state",status:"awaiting_user"}),e.openBrowser&&await e.openBrowser(C);let T=await u;await to(d),t({type:"state",status:"exchanging"});let y=await fetch(e.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:T,code_verifier:n,redirect_uri:m}),signal:e.signal});if(!y.ok){let R=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${R}`)}let E=ye(await y.json());return t({type:"state",status:"authenticated"}),E}catch(m){throw t({type:"state",status:"error"}),e.signal?.aborted?new Error("Login aborted"):m}finally{clearTimeout(c),e.signal?.removeEventListener("abort",h),await to(d)}}function to(e){return e.listening?new Promise(t=>{e.close(()=>t()),e.closeAllConnections()}):Promise.resolve()}function Ci(e,t,n){e.writeHead(302,{location:t}).end(n)}var Ae="matilda-code",oo="matilda-desktop",Ai="openid profile email offline_access",Ee="MATILDA_API_KEY",Ei="matilda";function Se(e){return e.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function ro(){return yi(ve.getGlobalMatildaDir(),"matilda-auth.json")}function rt(){return Dt(ro())}function Si(e){return e==="desktop"}function Me(e){return e?.clientId?e.clientId:Si(e?.channel)?oo:Ae}function re(e){return`matilda:${e}`}function it(e){return`${re(e)}:refresh-rejected`}function _e(e){return e===Ae?[re(e),Ei]:[re(e)]}function Mi(){try{let e=Ti(ro(),"utf8");return JSON.parse(e)}catch{return{}}}function Ut(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.accessToken=="string"&&typeof t?.baseUrl=="string"?t:null}catch{return null}}function _i(e,t){return Se(e)===Se(t)}function Ri(e){if(!e)return{};try{let t=e.split(".")[1],n=Buffer.from(t.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function bi(e,t){let n=Ri(e.idToken);return{accessToken:e.accessToken,accessTokenExpiresAt:e.expiresAt,refreshToken:e.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:t}}var no=new Map;async function io(e){let t=no.get(e);if(t)return t;try{let n=await Pt(e);return no.set(e,n),n}catch{return{issuer:e,authorization_endpoint:`${e}/api/auth/oauth/authorize`,token_endpoint:`${e}/api/auth/oauth/token`,device_authorization_endpoint:`${e}/api/auth/oauth/device/code`}}}function Y(e){try{let t=Mi(),n=Me(e);for(let o of _e(n)){let r=Ut(t[o]);if(r)return r}return null}catch{return null}}function so(e){let t=Y(e);return!t||e?.baseUrl&&!_i(t.baseUrl,e.baseUrl)?null:t}function Sd(e){return so(e)!==null}async function vi(e){let t=Me(e),n=rt().store;for(let o of _e(t))await n.remove(o);await n.set(it(t),"1"),delete process.env[Ee]}function xi(e){return e instanceof Error?e.code==="invalid_grant"||e.name==="InvalidGrantError"?!0:e.message==="Token refresh failed (401)":!1}function oe(e){Ft({authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:e.occurrenceCount},{baseUrl:e.baseUrl,token:e.token}).catch(()=>{})}async function ki(e,t){let n=Me(t),o=rt().store;await o.set(re(n),JSON.stringify(e)),await o.remove(it(n));for(let r of _e(n))r!==re(n)&&await o.remove(r);process.env[Ee]=e.accessToken}async function Ii(e){let t=Me(e),n=rt().store;for(let o of _e(t))await n.remove(o);await n.remove(it(t)),delete process.env[Ee]}function Md(e){let t=Y(e);return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function _d(e){let t={channel:e?.channel,clientId:e?.clientId},n=Y(t);if(n?.accessToken){let o=Se(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:e?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await Ii(t)}async function Gt(e){let t=Me(e),n=re(t),o=so({baseUrl:e?.baseUrl,channel:e?.channel,clientId:t});if(!o)return e?.fallbackAccessToken??process.env[Ee]??"";let r=Se(o.baseUrl),i=await io(r),{store:s,lock:a}=rt(),l=Oi(s,a,i.token_endpoint,o.baseUrl,t,n,e?.signal),u=t===Ae&&(!!e?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),d;try{d=await l.getAccessToken({forceRefresh:e?.forceRefresh})}catch(p){throw u&&oe({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),t===oo&&xi(p)&&await vi({channel:e?.channel,clientId:t}),p}return u&&oe({baseUrl:o.baseUrl,token:d,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ee]=d,d}async function Rd(e){await Gt(e);let t=Y(e);if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function Oi(e,t,n,o,r,i,s){let a=_e(r);return Lt({tokenEndpoint:n,clientId:r,store:{get:async d=>{let p=d===i?a:[d],c=null;for(let m of p)if(c=Ut(await e.get(m)),c)break;if(!c?.accessToken)return null;let h={accessToken:c.accessToken,refreshToken:c.refreshToken,expiresAt:c.accessTokenExpiresAt};return JSON.stringify(h)},set:async(d,p)=>{let c=JSON.parse(p),h=d===i?a:[d],m={};for(let C of h){let T=Ut(await e.get(C));if(T){m=T;break}}let g={...m,accessToken:c.accessToken,accessTokenExpiresAt:c.expiresAt,refreshToken:c.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await e.set(i,JSON.stringify(g)),await e.remove(it(r));for(let C of a)C!==i&&await e.remove(C)},remove:async d=>{let p=d===i?a:[d];for(let c of p)await e.remove(c)}},storageKey:i,lock:t,fetchImpl:(d,p)=>{let c=[p?.signal,s].filter(h=>h instanceof AbortSignal);return fetch(d,{...p,signal:c.length>1?AbortSignal.any(c):c[0]})},expirySkewMs:3e5})}function wi(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&dn()}async function bd(e){let t=Se(e.baseUrl),n=await io(t),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},u=await(p=>(r+=1,Nt({metadata:n,clientId:Ae,scope:p,transport:{kind:"loopback",successRedirect:`${t}/api/auth/oauth/success?client_id=${encodeURIComponent(Ae)}`},signal:e.signal,onEvent:c=>{c.type==="authorize_url"&&(o=c.url,e.onAuthorizeUrl?.(c.url)),c.type==="state"&&c.status==="exchanging"&&(i+=1)},openBrowser:async c=>{if(e.openBrowser===!1||!wi()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(c)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(Ai),d=bi(u,e.baseUrl);await ki(d),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,c]of Object.entries(s))oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:c});return i>0&&oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),oe({baseUrl:e.baseUrl,token:d.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...d,authorizeUrl:o}}f();f();function ie(e){return typeof e=="object"&&e!==null&&"error"in e&&typeof e.error=="object"&&"message"in e.error}function st(e){return typeof e=="object"&&e!==null&&"message"in e&&typeof e.message=="string"}function kd(e){let t=n=>n.includes("Quota exceeded for quota metric 'Gemini")&&n.includes("Pro Requests'");if(typeof e=="string")return t(e);if(st(e))return t(e.message);if(ie(e))return t(e.error.message);if(e&&typeof e=="object"&&"response"in e){let n=e;if(n.response&&n.response.data){if(typeof n.response.data=="string")return t(n.response.data);if(typeof n.response.data=="object"&&n.response.data!==null&&"error"in n.response.data){let o=n.response.data;return t(o.error?.message||"")}}}return!1}function Id(e){return typeof e=="string"?e.includes("Quota exceeded for quota metric"):st(e)?e.message.includes("Quota exceeded for quota metric"):ie(e)?e.error.message.includes("Quota exceeded for quota metric"):!1}function ao(e){if(typeof e!="object"||e===null)return!1;let{status:t,code:n,message:o}=e;return t===429&&n==="insufficient_quota"&&typeof o=="string"&&o.toLowerCase().includes("free allocated quota exceeded")}f();f();function lo(e){let t=Math.max(1,e.attempt),n=Math.min(e.maxDelayMs,2147483647),o=Math.min(t-1,31),r=Math.min(e.initialDelayMs*Math.pow(2,o),n),s=(e.retryAfterMode??"ignore")==="ignore"?null:Pi(e.error);if(s!==null&&s>0){let d=Math.min(e.retryAfterMaxDelayMs??e.maxDelayMs,2147483647),p=Math.min(s,d);return Math.max(r,p)}let a=e.jitterRatio??0;if(a<=0)return r;let l=e.random??Math.random,u=r*a*(l()*2-1);return Math.min(Math.max(0,r+u),n)}function Pi(e){let t=co(e,"retry-after")??Di(e,"retry-after");if(t===null)return null;let n=t.trim();if(/^\d+(\.\d+)?$/.test(n)){let i=Number(n);if(Number.isFinite(i)&&i>=0)return Math.min(i*1e3,2147483647)}let o=Date.parse(n);if(!Number.isFinite(o))return null;let r=o-Date.now();return r>0?Math.min(r,2147483647):0}function co(e,t){if(!Li(e))return null;let{headers:n}=e;if(typeof n.get=="function"){let r=n.get(t);return typeof r=="string"?r:null}if(typeof n!="object"||n===null)return null;let o=t.toLowerCase();for(let[r,i]of Object.entries(n))if(r.toLowerCase()===o)return typeof i=="string"?i:null;return null}function Di(e,t){return Ni(e)?co(e.response,t):null}function Li(e){return typeof e=="object"&&e!==null&&"headers"in e&&e.headers!=null}function Ni(e){return typeof e=="object"&&e!==null&&"response"in e&&typeof e.response=="object"&&e.response!==null&&"headers"in e.response&&e.response.headers!=null}var Ui=new Set([429,503,1302,1305]);function Kt(e,t){let n=Fi(e);return n===null?!1:!!(Ui.has(n)||t&&t.includes(n))}function uo(e){let t=U(e),n=Gi(e),o=po(e),r=o?.includes("event:error")||o?.includes("HTTP_STATUS/")?"sse":t!==void 0?"http":"unknown";return{...t!==void 0?{statusCode:t}:{},...n?.code!==void 0?{providerCode:String(n.code)}:{},...n?.message!==void 0?{providerMessage:n.message}:{},...n?.requestId!==void 0?{requestId:n.requestId}:{},transport:r}}function Fd(e,t){return lo({attempt:e,initialDelayMs:t.initialDelayMs,maxDelayMs:t.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:t.maxDelayMs,error:t.error})}function Fi(e){if(ie(e)){let n=Number(e.error.code);if(Number.isFinite(n)&&n>0)return n}let t=e instanceof Error?e.message:typeof e=="string"?e:null;if(t){let n=t.indexOf("{");if(n!==-1)try{let o=JSON.parse(t.substring(n));if(ie(o)){let r=Number(o.error.code);if(Number.isFinite(r)&&r>0)return r}}catch{}}if(st(e)&&typeof e.status=="number")return e.status;if(e instanceof Error&&"status"in e){let n=e.status;if(typeof n=="number")return n}return U(e)??null}function Gi(e){for(let t of Ki(e)){if(typeof t!="object"||t===null)continue;let n=t,o=t.error,i=(typeof o=="object"&&o!==null?o:void 0)??n,s=typeof i.code=="string"||typeof i.code=="number"?i.code:void 0,a=typeof i.message=="string"?i.message:void 0,l=typeof i.request_id=="string"?i.request_id:typeof i.requestId=="string"?i.requestId:typeof n.request_id=="string"?n.request_id:typeof n.requestId=="string"?n.requestId:void 0;if(s!==void 0||a!==void 0||l!==void 0)return{code:s,message:a,requestId:l}}return ie(e)?{code:e.error.code,message:e.error.message}:null}function Ki(e){let t=po(e);if(!t)return[];let n=[];for(let i of t.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{n.push(JSON.parse(s))}catch{}}if(n.length>0)return n;let o=t.indexOf("{"),r=t.lastIndexOf("}");if(o!==-1&&r>o)try{n.push(JSON.parse(t.slice(o,r+1)))}catch{}return n}function po(e){return e instanceof Error?e.message:typeof e=="string"?e:null}function $i(e,t={}){if(ji(e))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let n=uo(e),o=n.statusCode,r=Wi(e),i=n.providerCode??r.providerCode,s=n.providerMessage??r.providerMessage,a=n.requestId??r.requestId,l={...o!==void 0?{statusCode:o}:{},...i!==void 0?{providerCode:i}:{},...s!==void 0?{providerMessage:s}:{},...a!==void 0?{requestId:a}:{}};if(t.authType==="matilda-oauth"&&ao(e))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...l};if(zi(i))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...l};if(Kt(e,t.extraRetryErrorCodes))return{kind:n.transport==="sse"?"sse-provider":o!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...l};let u=Vi(e);if(u!==void 0&&(o===void 0||o>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...o!==void 0?{statusCode:o}:{}};if(o!==void 0){let d=n.transport==="sse"?"sse-provider":"http";return o===529?{kind:d,diagnosis:"retryable",reason:"capacity-overload",...l}:o===401||o===403?{kind:d,diagnosis:"fail-fast",reason:"auth-error",...l}:o>=400&&o<500?{kind:d,diagnosis:"fail-fast",reason:"client-error",...l}:o>=500&&o<600?{kind:d,diagnosis:"retryable",reason:"server-error",...l}:{kind:d,diagnosis:"unknown",reason:"http-status",...l}}return{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...l}}function fo(e,t){return Kt(e,t)||$i(e,{extraRetryErrorCodes:t}).diagnosis==="retryable"}function ji(e){return zt(e)?!0:e instanceof Error&&e.name==="CanceledError"}var Hi=5;function Vi(e){let t=e;for(let n=0;n<=Hi;n++){if(typeof t!="object"||t===null)return;let o=t.code;if(typeof o=="string"&&Bi(o))return o;t=t instanceof Error?t.cause:void 0}}function Bi(e){return qi.has(e)}var qi=new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","ConnectionClosed","ConnectionRefused","ConnectionReset","ConnectionTimedOut","FailedToOpenSocket","HostUnreachable","NetworkUnreachable"]);function zi(e){return e==="Throttling.AllocationQuota"}function Wi(e){if(typeof e!="object"||e===null)return{};let t=e,n=typeof t.code=="string"||typeof t.code=="number"?String(t.code):void 0,o=typeof t.code=="number"&&t.code>=100&&t.code<600,r=e instanceof Error&&n?.startsWith("ERR_")||o?void 0:n,i=typeof t.request_id=="string"?t.request_id:typeof t.requestId=="string"?t.requestId:void 0,s=typeof t.message=="string"&&(!(e instanceof Error)||r!==void 0||i!==void 0)?t.message:void 0;return{...r!==void 0?{providerCode:r}:{},...s!==void 0?{providerMessage:s}:{},...i!==void 0?{requestId:i}:{}}}var L=(i=>(i.USE_OPENAI="openai",i.MATILDA_OAUTH="matilda-oauth",i.USE_GEMINI="gemini",i.USE_VERTEX_AI="vertex-ai",i.USE_ANTHROPIC="anthropic",i))(L||{}),Yi="MATILDA_AGENT_SDK",at="MATILDA_API_KEY";function Ji(e,t){if(e.apiKey||e.apiKeyEnvKey!==at)return;let n=Y({channel:t});n?.accessToken&&(e.apiKey=n.accessToken,process.env[at]=n.accessToken)}async function Xi(e,t){if(e.apiKeyEnvKey!==at)return;let n=Y({channel:t});if(!n?.accessToken)return;let o;try{o=await Gt({baseUrl:e.baseUrl,fallbackAccessToken:n.accessToken,channel:t})}catch(r){if(!fo(r))throw r;o=n.accessToken}o&&(e.apiKey=o,process.env[at]=o)}function Qi(e){return e.matildaAgentSdk===!0||process.env[Yi]==="1"}function $t(e,t,n){e[t]=n}function Zi(e,t){return e?.[t]}function es(e,t,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:t,proxy:e?.getProxy()};$t(i,"authType",{kind:"computed",detail:"provided by caller"}),e?.getProxy()&&$t(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=d=>Zi(o,d)??{kind:"unknown"};for(let d of et)n&&d in n&&!i[d]&&$t(i,d,l(d));Ji(a,e.getChannel());let u=mo(a,s);if(!u.valid)throw new Error(u.errors.map(d=>d.message).join(`
|
|
10
10
|
`));return{config:a,sources:i}}function mo(e,t=!1){let n=[];if(e.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!e.apiKey)if(t)n.push(new qe(e.authType,e.model,e.apiKeyEnvKey));else{let o=e.apiKeyEnvKey||qn(e.authType);n.push(new We({authType:e.authType,model:e.model,baseUrl:e.baseUrl,envKey:o}))}if(!e.model)if(t)n.push(new ze(e.authType));else{let o=zn(e.authType);n.push(new Ye({authType:e.authType,envKey:o}))}return e.authType==="anthropic"&&!e.baseUrl&&(t?n.push(new Je({authType:e.authType,model:e.model})):e.authType==="anthropic"&&n.push(new Xe)),{valid:n.length===0,errors:n}}function Qd(e,t,n){return es(e,t,n).config}function go(e){let t=e;for(;t instanceof Error;){if("code"in t&&t.code==="ERR_MODULE_NOT_FOUND")return t;t=t.cause}}async function Zd(e,t,n){await Xi(e,t.getChannel());let o=mo(e,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
|
|
11
|
-
`));let r=e.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Qi(e)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-
|
|
11
|
+
`));let r=e.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Qi(e)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-OV4U6DJD.js");i=s(e,t)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-MGASUFQL.js");i=s(e,t)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-WOY7ZS43.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-ETIAWE22.js");try{let l=await s(t,n?{requireCachedCredentials:!0}:void 0);i=new a(l,e,t)}catch(l){throw go(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-IYZILRDW.js");i=s(e,t)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-EQEGOXOV.js");i=s(e,t)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=go(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
|
|
12
12
|
Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new Ce(i,t,e)}var ts=["x-matilda-client-name","x-matilda-client-version","x-matilda-client-operating-system","x-matilda-client-architecture","x-matilda-client-distribution-channel","x-matilda-client-release-channel"],ns=new Set([...ts,...nn]),os=new Set(["VSCode","ACP","SDK","CI"]),se="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",rs="[A-Za-z][0-9A-Za-z-]{0,23}",ho="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",is=new RegExp(`^${se}(?:-${rs}(?:\\.${ho})+)?$`),ss=63,as=new RegExp(`^${se}$`),ls=new RegExp(`^${se}-preview\\.(?:0|[1-9]\\d{0,11})$`),ds=new RegExp(`^${se}-canary\\.(?:0|[1-9]\\d{0,11})$`),cs=new RegExp(`^${se}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),us=new RegExp(`^${se}-(preview|canary|nightly|development|internal)(?:\\.${ho})+$`);function ps(e){return e==="desktop"?"desktop":e===void 0||os.has(e)?"code_cli":"unknown"}function fs(e){if(e==="android")return"android";if(e==="darwin")return"macos";if(e==="win32")return"windows";if(e==="linux")return"linux"}function gs(e){if(e==="x64")return"x64";if(e==="arm64")return"arm64"}function ms(e){if(e===void 0)return"npm";if(e==="desktop")return"direct-download";if(e==="VSCode")return"vscode-marketplace"}function hs(e,t){if(t==="desktop")return"matilda-desktop";if(e==="VSCode")return"matilda-vscode";if(t==="code_cli")return"matilda-code"}function Cs(e){if(typeof e=="string"&&!(e.length>ss||!is.test(e)))return e}function Ts(e){if(e!==void 0)return as.test(e)?"stable":ls.test(e)?"preview":ds.test(e)?"canary":cs.test(e)?"nightly":us.exec(e)?.[1]}function Co(e,t=process.platform,n=process.arch){let o=e.getChannel?.(),r=ps(o),i=Cs(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:e.getCliVersion?.()),s=Ts(i),a=fs(t),l=gs(n),u=ms(o),d=hs(o,r);return{...d?{"x-matilda-client-name":d}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...u?{"x-matilda-client-distribution-channel":u}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function ic(e){let t=e.toLowerCase();return ns.has(t)||t.startsWith("x-matilda-reported-")}function ys(e){let t=e??en;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="core-api.matilda"}catch{return!1}}function sc(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&ys(e.baseUrl)}var As=3e3,Re=1,Es=24*60*60*1e3,To=20,yo=999,Ss=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID"]),Ms=new Set(["ENOTFOUND","EAI_AGAIN"]),_s=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Rs=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),bs=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function vs(e){return`${new URL(e).origin}/api/client-events`}function xs(e){let t={eventType:e.eventType,platform:"cli"};return e.eventType==="network_error"&&(t.transportReason=e.transportReason,t.transportStage=e.transportStage,t.responseReceived=e.responseReceived,t.occurrenceCount=e.occurrenceCount),e.eventType==="auth_funnel"&&(t.authStage=e.authStage,t.authOutcome=e.authOutcome,t.occurrenceCount=e.occurrenceCount),e.eventType==="network_error"&&(t.reportedSurface=e.reportedSurface,t.reportedOs=e.reportedOs,t.reportedArchitecture=e.reportedArchitecture,t.reportedProcess=e.reportedProcess,t.reportedReleaseChannel=e.reportedReleaseChannel,e.reportedVersion&&(t.reportedVersion=e.reportedVersion)),t}async function jt(e,t){let{baseUrl:n,token:o}=t;if(!n||!o)return!1;let r=t.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),t.timeoutMs??As);try{let a=await r(vs(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(xs(e)),signal:i.signal});return a.ok?!0:(xe.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Ft(e,t){let n=typeof e.occurrenceCount=="number"&&Number.isFinite(e.occurrenceCount)?Math.max(1,Math.min(Math.floor(e.occurrenceCount),yo)):1;return jt({eventType:"auth_funnel",authStage:e.authStage,authOutcome:e.authOutcome,occurrenceCount:n},t)}function Ao(){try{let e=$.readFileSync(Mo(),"utf8"),t=JSON.parse(e);return t.schemaVersion!==Re||!Array.isArray(t.failures)?void 0:{schemaVersion:Re,failures:t.failures.filter(ks)}}catch{return}}function ks(e){if(!e||typeof e!="object")return!1;let t=e;return t.eventType==="network_error"&&typeof t.transportReason=="string"&&typeof t.transportStage=="string"&&typeof t.responseReceived=="boolean"&&typeof t.occurrenceCount=="number"&&typeof t.reportedSurface=="string"&&typeof t.reportedOs=="string"&&typeof t.reportedArchitecture=="string"&&typeof t.reportedProcess=="string"&&typeof t.reportedReleaseChannel=="string"&&typeof t.firstObservedAtMs=="number"&&typeof t.lastObservedAtMs=="number"}function Eo(e){let t=Mo();if(e.failures.length===0){try{$.rmSync(t,{force:!0})}catch{}return}try{$.mkdirSync(lt.dirname(t),{recursive:!0}),$.writeFileSync(t,`${JSON.stringify(e)}
|
|
13
|
-
`,"utf8")}catch{}}function So(e,t){return e.filter(n=>t-n.lastObservedAtMs<=Es).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-To)}function Is(e){let t=Co(e);return{reportedSurface:t["x-matilda-client-name"]==="matilda-desktop"?"desktop":t["x-matilda-client-name"]==="matilda-code"||t["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:t["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:t["x-matilda-client-architecture"]??"unknown",reportedProcess:t["x-matilda-client-name"]??"unknown",reportedVersion:t["x-matilda-client-version"],reportedReleaseChannel:t["x-matilda-client-release-channel"]??"unknown"}}function Os(e){if(!e||typeof e!="object")return;let t=e.code;if(typeof t=="string")return t;if(!(e instanceof Error)||!e.cause||typeof e.cause!="object")return;let n=e.cause.code;return typeof n=="string"?n:void 0}function ws(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Ps(e,t){let n=Os(e);if(n&&Ss.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Ms.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&_s.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Rs.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&bs.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ws(e),r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(t&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function Ds(e,t){return e.findIndex(n=>n.transportReason===t.transportReason&&n.transportStage===t.transportStage&&n.responseReceived===t.responseReceived&&n.reportedSurface===t.reportedSurface&&n.reportedOs===t.reportedOs&&n.reportedArchitecture===t.reportedArchitecture&&n.reportedProcess===t.reportedProcess&&n.reportedVersion===t.reportedVersion&&n.reportedReleaseChannel===t.reportedReleaseChannel)}function pc(e,t){let n=Is(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Ps(e,t.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=Ao()??{schemaVersion:Re,failures:[]},a=So(s.failures,r),l=Ds(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,yo),lastObservedAtMs:r}}else a.push(i);return Eo({schemaVersion:Re,failures:a.slice(-To)}),!0}async function fc(e){let t=Ao();if(!t)return;let n=So(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await jt({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},e)){o.push(...n.slice(r));break}}Eo({schemaVersion:Re,failures:o})}function Mo(){return lt.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Ro=(n=>(n.GCP="gcp",n.LOCAL="local",n))(Ro||{}),
|
|
13
|
+
`,"utf8")}catch{}}function So(e,t){return e.filter(n=>t-n.lastObservedAtMs<=Es).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-To)}function Is(e){let t=Co(e);return{reportedSurface:t["x-matilda-client-name"]==="matilda-desktop"?"desktop":t["x-matilda-client-name"]==="matilda-code"||t["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:t["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:t["x-matilda-client-architecture"]??"unknown",reportedProcess:t["x-matilda-client-name"]??"unknown",reportedVersion:t["x-matilda-client-version"],reportedReleaseChannel:t["x-matilda-client-release-channel"]??"unknown"}}function Os(e){if(!e||typeof e!="object")return;let t=e.code;if(typeof t=="string")return t;if(!(e instanceof Error)||!e.cause||typeof e.cause!="object")return;let n=e.cause.code;return typeof n=="string"?n:void 0}function ws(e){if(!(!e||typeof e!="object"))for(let t of["status","statusCode"]){let n=e[t];if(typeof n=="number")return n}}function Ps(e,t){let n=Os(e);if(n&&Ss.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Ms.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&_s.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Rs.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&bs.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ws(e),r=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(t&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function Ds(e,t){return e.findIndex(n=>n.transportReason===t.transportReason&&n.transportStage===t.transportStage&&n.responseReceived===t.responseReceived&&n.reportedSurface===t.reportedSurface&&n.reportedOs===t.reportedOs&&n.reportedArchitecture===t.reportedArchitecture&&n.reportedProcess===t.reportedProcess&&n.reportedVersion===t.reportedVersion&&n.reportedReleaseChannel===t.reportedReleaseChannel)}function pc(e,t){let n=Is(t.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=Ps(e,t.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=Ao()??{schemaVersion:Re,failures:[]},a=So(s.failures,r),l=Ds(a,i);if(l>=0){let u=a[l];a[l]={...u,occurrenceCount:Math.min(u.occurrenceCount+1,yo),lastObservedAtMs:r}}else a.push(i);return Eo({schemaVersion:Re,failures:a.slice(-To)}),!0}async function fc(e){let t=Ao();if(!t)return;let n=So(t.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await jt({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},e)){o.push(...n.slice(r));break}}Eo({schemaVersion:Re,failures:o})}function Mo(){return lt.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var Ro=(n=>(n.GCP="gcp",n.LOCAL="local",n))(Ro||{}),Ap="local",Ep="http://localhost:4317";f();X();var Ns=new Set(["service.version","service.instance.id","session.id"]);function J(e,t){xe.warn(e),t?.push(e)}function bo(e,t){if(!e)return{};let n={};for(let o of e.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){J(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,t);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,t),l=s}let u;try{u=decodeURIComponent(a)}catch{J(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,t),u=a}n[l]=u}return n}function Ht(e,t,n){for(let o of Ns)o in e&&(J(`${t} cannot override reserved key "${o}"; ignoring`,n),delete e[o]);return e}function vo(e,t){if(e==null)return{};if(typeof e!="object"||Array.isArray(e))return J("settings.telemetry.resourceAttributes must be an object; ignoring",t),{};let n={};for(let[o,r]of Object.entries(e)){let i=o.trim();if(!i){J("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",t);continue}typeof r=="string"?n[i]=r:J(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,t)}return n}function be(e){if(e!==void 0)return e==="true"||e==="1"}function _o(e){if(e!==void 0){if(e==="local"||e==="local")return"local";if(e==="gcp"||e==="gcp")return"gcp"}}async function Ls(e){let t=e.argv??{},n=e.env??{},o=e.settings??{},r=t.telemetry??be(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=t.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=_o(i);if(i!==void 0&&s===void 0)throw new dt(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=t.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=t.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,u=["grpc","http"].find(N=>N===l);if(l!==void 0&&u===void 0)throw new dt(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let d=t.telemetryLogPrompts??be(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=be(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,c=t.telemetryOutfile??n.MATILDA_TELEMETRY_OUTFILE??o.outfile,h=n.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??n.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??o.otlpTracesEndpoint,m=n.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??n.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??o.otlpLogsEndpoint,g=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=Ht(bo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Ht(vo(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),E={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(E["service.name"]=R);let j=Object.keys(E).length?E:void 0,H=be(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:u,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:g,logPrompts:d,includeSensitiveSpanAttributes:p,outfile:c,resourceAttributes:j,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{_t as a,Z as b,Le as c,wo as d,Po as e,yn as f,Ke as g,jn as h,ir as i,he as j,Aa as k,be as l,_o as m,Ls as n,te as o,Be as p,Tr as q,It as r,yr as s,xn as t,Ar as u,Er as v,kn as w,Sr as x,In as y,On as z,wn as A,Mr as B,_r as C,Fr as D,Gr as E,Kr as F,$r as G,jr as H,Hr as I,Vr as J,Br as K,qr as L,Co as M,ic as N,sc as O,jt as P,Ft as Q,pc as R,fc as S,Ro as T,Ap as U,Ep as V,Te as W,Qe as X,fl as Y,Ze as Z,Tl as _,yl as $,tt as aa,Al as ba,Xn as ca,nt as da,Qn as ea,ro as fa,Y as ga,Sd as ha,xi as ia,ki as ja,Ii as ka,Md as la,_d as ma,Gt as na,Rd as oa,wi as pa,bd as qa,ie as ra,st as sa,kd as ta,Id as ua,ao as va,lo as wa,Pi as xa,Kt as ya,uo as za,Fd as Aa,$i as Ba,fo as Ca,L as Da,es as Ea,mo as Fa,Qd as Ga,Zd as Ha};
|
|
14
14
|
/**
|
|
15
15
|
* @license
|
|
16
16
|
* Copyright 2026 Matilda Team
|