@maincode-ai/matilda-code 0.21.6-nightly.20260915.32b7498ab → 0.21.6-preview.0
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/chunks/{agent-XFV5U5UR.js → agent-KYTWNT5B.js} +1 -1
- package/chunks/{agent-headless-AP2RDJE7.js → agent-headless-O2QFYUGL.js} +1 -1
- package/chunks/{chunk-CNXLNKTK.js → chunk-2SD4SGKF.js} +2 -2
- package/chunks/{chunk-26Q3OMYG.js → chunk-AC7V5HGT.js} +2 -2
- package/chunks/{chunk-PWZKNP2M.js → chunk-BQFYMLHH.js} +1 -1
- package/chunks/{chunk-TUABRSEC.js → chunk-ERD4AVF5.js} +1 -1
- package/chunks/{chunk-S2IFSFLW.js → chunk-LB2LZKIS.js} +1 -1
- package/chunks/{chunk-XYKLTBHX.js → chunk-N5UZND2H.js} +1 -1
- package/chunks/{chunk-VGSOK3HR.js → chunk-OCYTOKZC.js} +1 -1
- package/chunks/{computer-use-X62MY7W4.js → computer-use-PHYIWQFA.js} +1 -1
- package/chunks/{contextCommand-62LGMPFL.js → contextCommand-URYU4N6P.js} +1 -1
- package/chunks/{edit-YUZWNCNB.js → edit-ZLVT3HLS.js} +1 -1
- package/chunks/{enter-worktree-BJ45V6XF.js → enter-worktree-TZ4BHFV3.js} +1 -1
- package/chunks/{enterPlanMode-OSVM33TI.js → enterPlanMode-H6P74G54.js} +1 -1
- package/chunks/{exit-worktree-PSI5SWCR.js → exit-worktree-TRFH3EKK.js} +1 -1
- package/chunks/{exitPlanMode-XBWMG32V.js → exitPlanMode-3DSR3TTH.js} +1 -1
- package/chunks/{geminiContentGenerator-2UGEUYW4.js → geminiContentGenerator-PULU6AOZ.js} +1 -1
- package/chunks/{glob-MTVHO6XB.js → glob-JGVGPH7O.js} +1 -1
- package/chunks/{grep-4AXAQC27.js → grep-YXF7LG25.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-3W4VL63J.js → matildaAgentContentGenerator-MYD7CTHU.js} +1 -1
- package/chunks/{matildaContentGenerator-KJ6JE3H2.js → matildaContentGenerator-NTMW3R45.js} +1 -1
- package/chunks/{monitor-BQOJUBTQ.js → monitor-DBD44UCH.js} +1 -1
- package/chunks/{notebook-edit-IUCNPGSN.js → notebook-edit-UBSCMF55.js} +1 -1
- package/chunks/{openaiContentGenerator-4GWCJXZX.js → openaiContentGenerator-SDDETC25.js} +1 -1
- package/chunks/{ripGrep-AH56VENM.js → ripGrep-RTSNQ27E.js} +1 -1
- package/chunks/{scheduler-4BIJYMM7.js → scheduler-APKZPCNX.js} +1 -1
- package/chunks/{serve-XCD6MHBP.js → serve-GCZSYJ4D.js} +1 -1
- package/chunks/{shell-ZKQKZK5C.js → shell-JDSST5O4.js} +1 -1
- package/chunks/{skill-RWZZJLZ7.js → skill-GLBTH3Q4.js} +1 -1
- package/chunks/{src-VJNJL3IU.js → src-FSJDBAGQ.js} +1 -1
- package/chunks/{team-create-M7I2DBCX.js → team-create-TQHT5HCX.js} +1 -1
- package/chunks/{workflow-CNJV7VEY.js → workflow-WMRTYTZE.js} +2 -2
- package/chunks/{write-file-JR276HM4.js → write-file-FMBJAKLZ.js} +1 -1
- package/cli.js +6 -6
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as be}from"./chunk-LIWYWWOK.js";import{c as q,f as O}from"./chunk-QHA3ZBRO.js";import{M as pe,N as ce,O as k,Q as me,R as W,S as de,a as re,g as P,h as ie,la as ge}from"./chunk-
|
|
3
|
+
import{a as be}from"./chunk-LIWYWWOK.js";import{c as q,f as O}from"./chunk-QHA3ZBRO.js";import{M as pe,N as ce,O as k,Q as me,R as W,S as de,a as re,g as P,h as ie,la as ge}from"./chunk-ERD4AVF5.js";import{a as he}from"./chunk-DC7LAFZZ.js";import{a as oe,g as ae,k as se,l as D,o as ue,t as fe,v as Ce}from"./chunk-S7G6QPEP.js";import{e as ne}from"./chunk-4J6DC24J.js";import{b as H,c as N,f as le,n as j}from"./chunk-SDTWBD62.js";import{b as z}from"./chunk-ESSYHTAZ.js";import{a as U,aa as A,c as ee,q as J,s as te,t as K}from"./chunk-VLYRNOD3.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Re(i){return i.toLowerCase().includes("matilda3")}function Ie(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 f=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=q("openai",this.cliConfig.getProxy());return new U({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=Re(e.model)?r.messages.map(Ie):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=Ce(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 w=class extends f{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();var Me=A("MatildaOpenAICompatibleProvider"),b=class i extends f{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=D?.endsWith("/")?D.slice(0,-1):D,l=!!(s&&r.toLowerCase()===s.toLowerCase());return s&&!a&&!l&&Me.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 k(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=q("openai",this.cliConfig.getProxy()),s=a?.fetch??globalThis.fetch,l=k(this.contentGeneratorConfig)?async(c,m)=>{let d=new Headers(c instanceof Request?c.headers:void 0);new Headers(m?.headers).forEach((C,u)=>{d.set(u,C)});let g=d.has(H)||d.has(N),h=j(),y=g||Object.keys(h).length>0;if(y){d.delete(H),d.delete(N);for(let[u,G]of Object.entries(h))d.set(u,G);let C=d.get("x-stainless-retry-count");d.has(H)&&C!==null&&/^[1-9][0-9]*$/.test(C)&&d.set(N,"retry")}this.cliConfig.getChannel()===void 0&&me({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let C=await s(c,y?{...m,headers:d}:m);return de({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),C}catch(C){throw W(C,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),C}}:void 0;return new U({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{},...l?{fetch:l}:{}})}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 F(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content=="string"?i:{...e,reasoning_content:""}}function E(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 Te(i){return E(i)?!0:(i.model??"").toLowerCase().includes("deepseek")}var R=class extends f{constructor(e,t){super(e,t)}static isDeepSeekProvider=Te;static isDeepSeekHostname=E;buildRequest(e,t){let n=super.buildRequest(e,t),r=E(this.contentGeneratorConfig)?ve(n):n;if(!r.messages?.length)return r;let o=r.messages.map(a=>{let s=xe(a);return F(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function xe(i){if(!("content"in i))return i;let{content:e}=i;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return i;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
|
|
4
4
|
|
|
5
5
|
`);return{...i,content:t}}function ve(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 I=class extends f{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 we=["api.minimaxi.com","api.minimax.io"],Ge=[".minimaxi.com",".minimax.io"],M=class extends f{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return we.includes(t)?!0:Ge.some(n=>t.endsWith(n))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};p();var ye="api.mistral.ai",ke=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ee(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===ye||t.endsWith(`.${ye}`)}catch{return!1}}function _e(i){if(Ee(i))return!0;let e=i.model?.toLowerCase()??"";return ke.some(t=>e.includes(t))}var T=class extends f{static isMistralProvider=_e;buildRequest(e,t){let n=super.buildRequest(e,t);return{...n,messages:n.messages.map(Se)}}};function Se(i){if(!("reasoning_content"in i))return i;let e={...i};return delete e.reasoning_content,e}p();function Le(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 f{constructor(e,t){super(e,t)}static isMiMoProvider=Le;buildRequest(e,t){let n=super.buildRequest(e,t);return n.messages?.length?{...n,messages:n.messages.map(F)}:n}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};p();p();var Ue=A("STREAMING_TOOL_CALL_PARSER"),V=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 u=this.buffers.get(e),G=this.depths.get(e),Z=this.toolCallMeta.get(e);if(u.trim()&&G===0&&Z?.id&&Z.id!==n)try{JSON.parse(u),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(n,o)}else if(this.buffers.has(e)){let u=this.buffers.get(e);if(this.depths.get(e)>0||!u.trim())o=e;else try{JSON.parse(u),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),Ue.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 m=this.inStrings.get(o),d=this.escapes.get(o),g=s+t;this.buffers.set(o,g);let h=l,y=m,C=d;for(let u of t)y||(u==="{"||u==="["?h++:(u==="}"||u==="]")&&h--),u==='"'&&!C&&(y=!y),C=u==="\\"&&!C;if(this.depths.set(o,h),this.inStrings.set(o,y),this.escapes.set(o,C),h===0&&g.trim().length>0)try{return{complete:!0,value:JSON.parse(g)}}catch(u){if(y)try{return{complete:!0,value:JSON.parse(g+'"'),repaired:!0}}catch{}return{complete:!1,error:u instanceof Error?u:new Error(String(u))}}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 m=oe(o,null);if(!m||typeof m!="object")continue;c=m}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 Ae=16e3,Pe=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
6
6
|
`,B=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},_=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?z(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}});return P.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?z(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}})}catch(g){throw a?.abort(),g}if(!a)return this.processStreamWithLogging(l,r,e);let c=a,m=this.processStreamWithLogging(l,r,e);async function*d(){try{yield*m}finally{c.abort()}}return d()})}reportedOperationHeaders(){if(!k(this.contentGeneratorConfig))return;let e=j();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null,a=!1;try{for await(let s of e){if(s.choices?.[0]?.finish_reason==="error_finish"){let m=s.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new B(m)}let l=P.convertOpenAIChunkToGemini(s,t);if(l.candidates?.[0]?.content?.parts?.length===0&&!l.candidates?.[0]?.finishReason&&!l.usageMetadata)continue;if(a){if(l.usageMetadata){let m=o;m&&(m.usageMetadata=l.usageMetadata)}r.push(l);continue}this.handleChunkMerging(l,r,m=>{o=m})&&(o?(yield o,a=!0):yield l)}if(!o&&!a){let s=P.flushOpenAIStreamToGemini(t);s&&(yield s,a=!0)}o&&!a&&(yield o)}catch(s){if(s instanceof B)throw O(s);await this.handleError(s,t,n)}}handleChunkMerging(e,t,n){let r=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(r){if(o){let 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 ne;return s.candidates=a.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=a.usageMetadata,s.responseId=e.responseId,s.createTime=e.createTime,s.modelVersion=e.modelVersion,s.promptFeedback=e.promptFeedback,t[t.length-1]=s,n(s),!0}return t.push(e),!0}async buildRequest(e,t,n,r){let o=P.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 P.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 d=c,g=(n.model??"").toLowerCase();if(b.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(g.startsWith("matilda")||g==="coder-model")){d.enable_thinking=!1;let h=d.chat_template_kwargs;typeof h=="object"&&h!==null&&"enable_thinking"in h&&(d.chat_template_kwargs={...h,enable_thinking:!1})}"reasoning"in d&&delete d.reasoning,"reasoning_effort"in d&&delete d.reasoning_effort,E(this.contentGeneratorConfig)&&(d.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(`
|
|
@@ -8,7 +8,7 @@ import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d
|
|
|
8
8
|
${n}`:n;return{...o,text:a}}return e}};g();function Hn(t){switch(t){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 Bn(t){switch(t){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 F=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},je=class extends F{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let r=e||"(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 F{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},We=class extends F{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},qe=class extends F{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},Ye=class extends F{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},Je=class extends F{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};g();import Kr from"node:process";g();var Vn={image:!0,pdf:!0,audio:!0,video:!0},Fr=[[/^gemini-3/,Vn],[/^gemini-/,Vn],[/^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 Ce(t){let e=en(t);for(let[n,o]of Fr)if(n.test(e))return{...o};return{}}g();var Xe="$runtime|";function Na(t){let e=t;for(;e.startsWith(Xe);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}g();g();g();var Qe=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],jn=["model","apiKey","apiKeyEnvKey","baseUrl"],Ze=[...jn,...Qe],Ha={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:[]}},Ba={openai:Zt,"matilda-oauth":j},et=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Va=et.map(t=>t.id);var kt=O("MODEL_REGISTRY");function zn(t){if(Object.values(G).includes(t))return t}function Gr(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function Wn(t,e){return e?`${t}\0${e}`:t}var tt=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return Yt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",et),e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=Wn(r.id,r.baseUrl);if(o.has(i)){kt.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,e);o.set(i,s)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);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??ue(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let r=this.modelsByAuthType.get(e);if(!r)return;if(o)return r.get(Wn(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,j);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||Gr(e.id))&&(o.modalities=Ce(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var qn=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new tt(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||j}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),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(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===At&&e?.envKey===tn&&e?.baseUrl===on&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?At:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?nn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===j){this.strictModelProviderSelection=!1,this._generationConfig.model=e,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,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Ce(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=ue(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let s=e!==this.currentAuthType;this.currentAuthType=e;let a=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=i.generationConfig.model||"",c=!s&&l?this.modelRegistry.getModel(e,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,u=e!=="matilda-oauth"&&!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,p=u?i.generationConfig.apiKey:void 0,d=u?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0;let h=s?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,h)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(e,n){return`${Xe}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Xe))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of Qe)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!e||!o||!r)&&!this.modelRegistry.hasModel(e,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 e of Ze)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.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),e.envKey!==void 0){let o=Kr.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of Qe)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=ue(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Ce(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){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,e);return!r||!o||r.envKey!==o.envKey||r.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(e,n,r)??this.modelRegistry.getModel(e,n):void 0;if(i){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),m=o===e&&this._generationConfig.model===n&&!h,f=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"),S=y?this._generationConfig.baseUrl:void 0,R=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&f&&(this._generationConfig.apiKey=f,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,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!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,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(e);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(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!e||!s)return;if(this.modelRegistry.hasModel(s,e,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,e),c={id:l,authType:s,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,c),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let r=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,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 e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};g();import{readFileSync as ri}from"node:fs";import{join as ii}from"node:path";g();g();import{randomBytes as $r,createHash as Hr}from"node:crypto";function Yn(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function It(){let t=$r(32).toString("base64url"),e=Hr("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Te(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function Ot(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Yn(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});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}}g();import{promises as nt,openSync as Br,closeSync as Vr,unlinkSync as Jn,statSync as jr}from"node:fs";import{dirname as zr}from"node:path";var Wr=1e4,qr=3e4,Yr=50;function wt(t){let e=async()=>{try{let r=await nt.readFile(t,"utf8"),i=JSON.parse(r);return i&&typeof i=="object"?i:{}}catch(r){if(r.code==="ENOENT")return{};throw r}},n=async r=>{await nt.mkdir(zr(t),{recursive:!0}),await nt.writeFile(t,JSON.stringify(r,null,2),{mode:384}),await nt.chmod(t,384).catch(()=>{})};return{store:{async get(r){return(await e())[r]??null},async set(r,i){let s=await e();s[r]=i,await n(s)},async remove(r){let i=await e();r in i&&(delete i[r],await n(i))}},lock:Jr(`${t}.lock`)}}function Jr(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Xr(t);try{return await n()}finally{Qr(t)}});return e=o.then(()=>{},()=>{}),o}}async function Xr(t){let e=Date.now()+Wr;for(;;)try{Vr(Br(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-jr(t).mtimeMs>qr){Jn(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Zr(Yr)}}function Qr(t){try{Jn(t)}catch{}}function Zr(t){return new Promise(e=>setTimeout(e,t))}g();var te=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Pt(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=null,i=async()=>{let l=await t.store.get(e);if(!l)return null;try{let c=JSON.parse(l);return c.accessToken?c:null}catch{return null}},s=l=>l.expiresAt-Date.now()>o,a=l=>t.lock(async()=>{let c=await i()??l;if(c.accessToken!==l.accessToken&&s(c))return c.accessToken;if(!c.refreshToken)throw new te("No refresh token available \u2014 sign in again.");let u=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:c.refreshToken})});if(!u.ok){let h=await u.text().catch(()=>"");throw u.status>=400&&u.status<500&&ei(h)==="invalid_grant"?(await t.store.remove(e),new te):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),d=Te(p,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(l){let c=await i();if(!c)throw new te("Not signed in.");return!l?.forceRefresh&&s(c)?c.accessToken:(r||(r=a(c).finally(()=>{r=null})),r)}}}function ei(t){try{return JSON.parse(t).error}catch{return}}g();import{createServer as ti}from"node:http";import{randomBytes as ni}from"node:crypto";async function Dt(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=m=>t.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=It(),r=ni(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect;e({type:"state",status:"idle"});let a,l,c=new Promise((m,f)=>{a=m,l=f});c.catch(()=>{});let u=ti((m,f)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){f.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),S=C.searchParams.get("code");if(T){let R=C.searchParams.get("error_description"),$=R?`OAuth error: ${T} (${R})`:`OAuth error: ${T}`;f.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${T}
|
|
9
9
|
`,()=>l(new Error($)));return}if(y!==r){f.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){f.writeHead(400).end("Missing authorization code");return}oi(f,s,()=>a(S))}),p=await new Promise((m,f)=>{u.once("error",f),u.listen(t.transport.port??0,"127.0.0.1",()=>{m(u.address().port)})}),d=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"));t.signal?.addEventListener("abort",h,{once:!0});try{let m=`http://127.0.0.1:${p}/callback`,f=new URL(t.metadata.authorization_endpoint);f.searchParams.set("client_id",t.clientId),f.searchParams.set("response_type","code"),f.searchParams.set("redirect_uri",m),f.searchParams.set("code_challenge",o),f.searchParams.set("code_challenge_method","S256"),f.searchParams.set("state",r),f.searchParams.set("prompt","select_account"),f.searchParams.set("scope",t.scope??"openid offline_access");let C=f.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let T=await c;e({type:"state",status:"exchanging"});let y=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:T,code_verifier:n,redirect_uri:m})});if(!y.ok){let R=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${R}`)}let S=Te(await y.json());return e({type:"state",status:"authenticated"}),S}catch(m){throw e({type:"state",status:"error"}),m}finally{clearTimeout(d),t.signal?.removeEventListener("abort",h),u.close()}}function oi(t,e,n){t.writeHead(302,{location:e}).end(n)}var ye="matilda-code",Xn="matilda-desktop",si="openid profile email offline_access",Ae="MATILDA_API_KEY",ai="matilda";function Se(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qn(){return ii(ve.getGlobalMatildaDir(),"matilda-auth.json")}function ot(){return wt(Qn())}function li(t){return t==="desktop"}function Ee(t){return t?.clientId?t.clientId:li(t?.channel)?Xn:ye}function oe(t){return`matilda:${t}`}function rt(t){return`${oe(t)}:refresh-rejected`}function _e(t){return t===ye?[oe(t),ai]:[oe(t)]}function ci(){try{let t=ri(Qn(),"utf8");return JSON.parse(t)}catch{return{}}}function Lt(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function di(t,e){return Se(t)===Se(e)}function ui(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function pi(t,e){let n=ui(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Zn(t){try{return await Ot(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function q(t){try{let e=ci(),n=Ee(t);for(let o of _e(n)){let r=Lt(e[o]);if(r)return r}return null}catch{return null}}async function fi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.set(rt(e),"1"),delete process.env[Ae]}function gi(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function ne(t){Ut({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function mi(t,e){let n=Ee(e),o=ot().store;await o.set(oe(n),JSON.stringify(t)),await o.remove(rt(n));for(let r of _e(n))r!==oe(n)&&await o.remove(r);process.env[Ae]=t.accessToken}async function hi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.remove(rt(e)),delete process.env[Ae]}function zl(t){let e=q(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Wl(t){let e={channel:t?.channel,clientId:t?.clientId},n=q(e);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:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await hi(e)}async function Nt(t){let e=Ee(t),n=oe(e),o=q({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!di(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[Ae]??"";let r=Se(o.baseUrl),i=await Zn(r),{store:s,lock:a}=ot(),l=Ci(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),c=e===ye&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),u;try{u=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(p){throw c&&ne({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),e===Xn&&gi(p)&&await fi({channel:t?.channel,clientId:e}),p}return c&&ne({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ae]=u,u}async function ql(t){await Nt(t);let e=q(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function Ci(t,e,n,o,r,i,s){let a=_e(r);return Pt({tokenEndpoint:n,clientId:r,store:{get:async u=>{let p=u===i?a:[u],d=null;for(let m of p)if(d=Lt(await t.get(m)),d)break;if(!d?.accessToken)return null;let h={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresAt:d.accessTokenExpiresAt};return JSON.stringify(h)},set:async(u,p)=>{let d=JSON.parse(p),h=u===i?a:[u],m={};for(let C of h){let T=Lt(await t.get(C));if(T){m=T;break}}let f={...m,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await t.set(i,JSON.stringify(f)),await t.remove(rt(r));for(let C of a)C!==i&&await t.remove(C)},remove:async u=>{let p=u===i?a:[u];for(let d of p)await t.remove(d)}},storageKey:i,lock:e,fetchImpl:(u,p)=>fetch(u,{...p,signal:s}),expirySkewMs:3e5})}function Ti(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&rn()}async function Yl(t){let e=Se(t.baseUrl),n=await Zn(e),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},c=await(p=>(r+=1,Dt({metadata:n,clientId:ye,scope:p,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(ye)}`},signal:t.signal,onEvent:d=>{d.type==="authorize_url"&&(o=d.url,t.onAuthorizeUrl?.(d.url)),d.type==="state"&&d.status==="exchanging"&&(i+=1)},openBrowser:async d=>{if(t.openBrowser===!1||!Ti()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(si),u=pi(c,t.baseUrl);await mi(u),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,d]of Object.entries(s))ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:d});return i>0&&ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}var G=(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))(G||{}),yi="MATILDA_AGENT_SDK",it="MATILDA_API_KEY";function Ai(t,e){if(t.apiKey||t.apiKeyEnvKey!==it)return;let n=q({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[it]=n.accessToken)}async function Si(t,e){if(t.apiKeyEnvKey!==it)return;let n=q({channel:e});if(!n?.accessToken)return;let o=await Nt({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[it]=o)}function Ei(t){return t.matildaAgentSdk===!0||process.env[yi]==="1"}function Ft(t,e,n){t[e]=n}function _i(t,e){return t?.[e]}function Mi(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};Ft(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Ft(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>_i(o,u)??{kind:"unknown"};for(let u of Ze)n&&u in n&&!i[u]&&Ft(i,u,l(u));Ai(a,t.getChannel());let c=to(a,s);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
|
|
10
10
|
`));return{config:a,sources:i}}function to(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new je(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Hn(t.authType);n.push(new We({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new ze(t.authType));else{let o=Bn(t.authType);n.push(new qe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new Ye({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new Je)),{valid:n.length===0,errors:n}}function nc(t,e,n){return Mi(t,e,n).config}function eo(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function oc(t,e,n){await Si(t,e.getChannel());let o=to(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
|
|
11
|
-
`));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-
|
|
11
|
+
`));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-MYD7CTHU.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-SDDETC25.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-W2DQO2NK.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-NTMW3R45.js");try{let l=await s(e,n?{requireCachedCredentials:!0}:void 0);i=new a(l,t,e)}catch(l){throw eo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-SFJGSZHT.js");i=s(t,e)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-PULU6AOZ.js");i=s(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=eo(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 he(i,e,t)}var Ri=["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"],vi=new Set([...Ri,...Qt]),bi=new Set(["VSCode","ACP","SDK","CI"]),re="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",xi="[A-Za-z][0-9A-Za-z-]{0,23}",no="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ki=new RegExp(`^${re}(?:-${xi}(?:\\.${no})+)?$`),Ii=63,Oi=new RegExp(`^${re}$`),wi=new RegExp(`^${re}-preview\\.(?:0|[1-9]\\d{0,11})$`),Pi=new RegExp(`^${re}-canary\\.(?:0|[1-9]\\d{0,11})$`),Di=new RegExp(`^${re}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Li=new RegExp(`^${re}-(preview|canary|nightly|development|internal)(?:\\.${no})+$`);function Ui(t){return t==="desktop"?"desktop":t===void 0||bi.has(t)?"code_cli":"unknown"}function Ni(t){if(t==="android")return"android";if(t==="darwin")return"macos";if(t==="win32")return"windows";if(t==="linux")return"linux"}function Fi(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64"}function Gi(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Ki(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function $i(t){if(typeof t=="string"&&!(t.length>Ii||!ki.test(t)))return t}function Hi(t){if(t!==void 0)return Oi.test(t)?"stable":wi.test(t)?"preview":Pi.test(t)?"canary":Di.test(t)?"nightly":Li.exec(t)?.[1]}function oo(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=Ui(o),i=$i(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Hi(i),a=Ni(e),l=Fi(n),c=Gi(o),u=Ki(o,r);return{...u?{"x-matilda-client-name":u}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function cc(t){let e=t.toLowerCase();return vi.has(e)||e.startsWith("x-matilda-reported-")}function Bi(t){let e=t??Jt;try{let n=new URL(e);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 dc(t,e=t.apiKey){return t.authType==="matilda-oauth"?!0:t.authType==="openai"&&!!e&&Bi(t.baseUrl)}var Vi=3e3,Me=1,ji=24*60*60*1e3,ro=20,io=999,zi=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"]),Wi=new Set(["ENOTFOUND","EAI_AGAIN"]),qi=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Yi=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),Ji=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Xi(t){return`${new URL(t).origin}/api/client-events`}function Qi(t){let e={eventType:t.eventType,platform:"cli"};return t.eventType==="network_error"&&(e.transportReason=t.transportReason,e.transportStage=t.transportStage,e.responseReceived=t.responseReceived,e.occurrenceCount=t.occurrenceCount),t.eventType==="auth_funnel"&&(e.authStage=t.authStage,e.authOutcome=t.authOutcome,e.occurrenceCount=t.occurrenceCount),t.eventType==="network_error"&&(e.reportedSurface=t.reportedSurface,e.reportedOs=t.reportedOs,e.reportedArchitecture=t.reportedArchitecture,e.reportedProcess=t.reportedProcess,e.reportedReleaseChannel=t.reportedReleaseChannel,t.reportedVersion&&(e.reportedVersion=t.reportedVersion)),e}async function Gt(t,e){let{baseUrl:n,token:o}=e;if(!n||!o)return!1;let r=e.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),e.timeoutMs??Vi);try{let a=await r(Xi(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Qi(t)),signal:i.signal});return a.ok?!0:(be.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Ut(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),io)):1;return Gt({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function so(){try{let t=K.readFileSync(co(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Me||!Array.isArray(e.failures)?void 0:{schemaVersion:Me,failures:e.failures.filter(Zi)}}catch{return}}function Zi(t){if(!t||typeof t!="object")return!1;let e=t;return e.eventType==="network_error"&&typeof e.transportReason=="string"&&typeof e.transportStage=="string"&&typeof e.responseReceived=="boolean"&&typeof e.occurrenceCount=="number"&&typeof e.reportedSurface=="string"&&typeof e.reportedOs=="string"&&typeof e.reportedArchitecture=="string"&&typeof e.reportedProcess=="string"&&typeof e.reportedReleaseChannel=="string"&&typeof e.firstObservedAtMs=="number"&&typeof e.lastObservedAtMs=="number"}function ao(t){let e=co();if(t.failures.length===0){try{K.rmSync(e,{force:!0})}catch{}return}try{K.mkdirSync(st.dirname(e),{recursive:!0}),K.writeFileSync(e,`${JSON.stringify(t)}
|
|
13
13
|
`,"utf8")}catch{}}function lo(t,e){return t.filter(n=>e-n.lastObservedAtMs<=ji).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-ro)}function es(t){let e=oo(t);return{reportedSurface:e["x-matilda-client-name"]==="matilda-desktop"?"desktop":e["x-matilda-client-name"]==="matilda-code"||e["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:e["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:e["x-matilda-client-architecture"]??"unknown",reportedProcess:e["x-matilda-client-name"]??"unknown",reportedVersion:e["x-matilda-client-version"],reportedReleaseChannel:e["x-matilda-client-release-channel"]??"unknown"}}function ts(t){if(!t||typeof t!="object")return;let e=t.code;if(typeof e=="string")return e;if(!(t instanceof Error)||!t.cause||typeof t.cause!="object")return;let n=t.cause.code;return typeof n=="string"?n:void 0}function ns(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function os(t,e){let n=ts(t);if(n&&zi.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Wi.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&qi.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Yi.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&Ji.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ns(t),r=t instanceof Error?t.message.toLowerCase():String(t).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(e&&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 rs(t,e){return t.findIndex(n=>n.transportReason===e.transportReason&&n.transportStage===e.transportStage&&n.responseReceived===e.responseReceived&&n.reportedSurface===e.reportedSurface&&n.reportedOs===e.reportedOs&&n.reportedArchitecture===e.reportedArchitecture&&n.reportedProcess===e.reportedProcess&&n.reportedVersion===e.reportedVersion&&n.reportedReleaseChannel===e.reportedReleaseChannel)}function hc(t,e){let n=es(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=os(t,e.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=so()??{schemaVersion:Me,failures:[]},a=lo(s.failures,r),l=rs(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,io),lastObservedAtMs:r}}else a.push(i);return ao({schemaVersion:Me,failures:a.slice(-ro)}),!0}async function Cc(t){let e=so();if(!e)return;let n=lo(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Gt({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},t)){o.push(...n.slice(r));break}}ao({schemaVersion:Me,failures:o})}function co(){return st.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var po=(n=>(n.GCP="gcp",n.LOCAL="local",n))(po||{}),bu="local",xu="http://localhost:4317";g();J();var ss=new Set(["service.version","service.instance.id","session.id"]);function Y(t,e){be.warn(t),e?.push(t)}function fo(t,e){if(!t)return{};let n={};for(let o of t.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){Y(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,e);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let c;try{c=decodeURIComponent(a)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),c=a}n[l]=c}return n}function Kt(t,e,n){for(let o of ss)o in t&&(Y(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function go(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return Y("settings.telemetry.resourceAttributes must be an object; ignoring",e),{};let n={};for(let[o,r]of Object.entries(t)){let i=o.trim();if(!i){Y("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:Y(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Re(t){if(t!==void 0)return t==="true"||t==="1"}function uo(t){if(t!==void 0){if(t==="local"||t==="local")return"local";if(t==="gcp"||t==="gcp")return"gcp"}}async function is(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Re(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=uo(i);if(i!==void 0&&s===void 0)throw new at(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=e.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=e.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,c=["grpc","http"].find(L=>L===l);if(l!==void 0&&c===void 0)throw new at(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let u=e.telemetryLogPrompts??Re(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=Re(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,d=e.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,f=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=Kt(fo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Kt(go(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),S={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(S["service.name"]=R);let $=Object.keys(S).length?S:void 0,H=Re(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:f,logPrompts:u,includeSensitiveSpanAttributes:p,outfile:d,resourceAttributes:$,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{Et as a,Q as b,De as c,yo as d,Ao as e,mn as f,Ge as g,Fn as h,zo as i,me as j,Vs as k,Re as l,uo as m,is as n,ee as o,Ve as p,ir as q,xt as r,sr as s,Mn as t,ar as u,lr as v,Rn as w,cr as x,vn as y,bn as z,xn as A,dr as B,ur as C,Rr as D,vr as E,br as F,xr as G,kr as H,Ir as I,Or as J,wr as K,Pr as L,oo as M,cc as N,dc as O,Gt as P,Ut as Q,hc as R,Cc as S,po as T,bu as U,xu as V,Ce as W,Xe as X,Na as Y,Qe as Z,Ha as _,Ba as $,et as aa,Va as ba,Wn as ca,tt as da,qn as ea,Qn as fa,q as ga,mi as ha,hi as ia,zl as ja,Wl as ka,Nt as la,ql as ma,Ti as na,Yl as oa,G as pa,Mi as qa,to as ra,nc as sa,oc as ta};
|
|
14
14
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{l as k}from"./chunk-
|
|
3
|
+
import{l as k}from"./chunk-N5UZND2H.js";import{Kb as It,Qb as St}from"./chunk-AC7V5HGT.js";import{c as Tt}from"./chunk-FRL6KOLY.js";import{m as Ct}from"./chunk-S7G6QPEP.js";import{Cc as ht,h as nt}from"./chunk-B3NVKOSU.js";import{p as st}from"./chunk-6B5BDE7S.js";import{b as C}from"./chunk-GZPNIYVZ.js";import{d as gt,f as Bt}from"./chunk-OWGSC52X.js";var Mt=gt(i=>{"use strict";C();var at=Symbol.for("react.transitional.element"),$t=Symbol.for("react.portal"),Gt=Symbol.for("react.fragment"),jt=Symbol.for("react.strict_mode"),Wt=Symbol.for("react.profiler"),qt=Symbol.for("react.consumer"),Ft=Symbol.for("react.context"),Yt=Symbol.for("react.forward_ref"),Kt=Symbol.for("react.suspense"),Jt=Symbol.for("react.memo"),kt=Symbol.for("react.lazy"),zt=Symbol.for("react.activity"),xt=Symbol.iterator;function Qt(t){return t===null||typeof t!="object"?null:(t=xt&&t[xt]||t["@@iterator"],typeof t=="function"?t:null)}var Rt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},vt=Object.assign,Et={};function v(t,e,s){this.props=t,this.context=e,this.refs=Et,this.updater=s||Rt}v.prototype.isReactComponent={};v.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};v.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function At(){}At.prototype=v.prototype;function ut(t,e,s){this.props=t,this.context=e,this.refs=Et,this.updater=s||Rt}var mt=ut.prototype=new At;mt.constructor=ut;vt(mt,v.prototype);mt.isPureReactComponent=!0;var bt=Array.isArray;function it(){}var p={H:null,A:null,T:null,S:null},wt=Object.prototype.hasOwnProperty;function lt(t,e,s){var o=s.ref;return{$$typeof:at,type:t,key:e,ref:o!==void 0?o:null,props:s}}function Vt(t,e){return lt(t.type,e,t.props)}function pt(t){return typeof t=="object"&&t!==null&&t.$$typeof===at}function Xt(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(s){return e[s]})}var _t=/\/+/g;function rt(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Xt(""+t.key):e.toString(36)}function Zt(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(it,it):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function R(t,e,s,o,n){var a=typeof t;(a==="undefined"||a==="boolean")&&(t=null);var m=!1;if(t===null)m=!0;else switch(a){case"bigint":case"string":case"number":m=!0;break;case"object":switch(t.$$typeof){case at:case $t:m=!0;break;case kt:return m=t._init,R(m(t._payload),e,s,o,n)}}if(m)return n=n(t),m=o===""?"."+rt(t,0):o,bt(n)?(s="",m!=null&&(s=m.replace(_t,"$&/")+"/"),R(n,e,s,"",function(g){return g})):n!=null&&(pt(n)&&(n=Vt(n,s+(n.key==null||t&&t.key===n.key?"":(""+n.key).replace(_t,"$&/")+"/")+m)),e.push(n)),1;m=0;var d=o===""?".":o+":";if(bt(t))for(var c=0;c<t.length;c++)o=t[c],a=d+rt(o,c),m+=R(o,e,s,a,n);else if(c=Qt(t),typeof c=="function")for(t=c.call(t),c=0;!(o=t.next()).done;)o=o.value,a=d+rt(o,c++),m+=R(o,e,s,a,n);else if(a==="object"){if(typeof t.then=="function")return R(Zt(t),e,s,o,n);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return m}function B(t,e,s){if(t==null)return t;var o=[],n=0;return R(t,o,"","",function(a){return e.call(s,a,n++)}),o}function te(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(s){(t._status===0||t._status===-1)&&(t._status=1,t._result=s)},function(s){(t._status===0||t._status===-1)&&(t._status=2,t._result=s)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ht=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},ee={map:B,forEach:function(t,e,s){B(t,function(){e.apply(this,arguments)},s)},count:function(t){var e=0;return B(t,function(){e++}),e},toArray:function(t){return B(t,function(e){return e})||[]},only:function(t){if(!pt(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};i.Activity=zt;i.Children=ee;i.Component=v;i.Fragment=Gt;i.Profiler=Wt;i.PureComponent=ut;i.StrictMode=jt;i.Suspense=Kt;i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=p;i.__COMPILER_RUNTIME={__proto__:null,c:function(t){return p.H.useMemoCache(t)}};i.cache=function(t){return function(){return t.apply(null,arguments)}};i.cacheSignal=function(){return null};i.cloneElement=function(t,e,s){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var o=vt({},t.props),n=t.key;if(e!=null)for(a in e.key!==void 0&&(n=""+e.key),e)!wt.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(o[a]=e[a]);var a=arguments.length-2;if(a===1)o.children=s;else if(1<a){for(var m=Array(a),d=0;d<a;d++)m[d]=arguments[d+2];o.children=m}return lt(t.type,n,o)};i.createContext=function(t){return t={$$typeof:Ft,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:qt,_context:t},t};i.createElement=function(t,e,s){var o,n={},a=null;if(e!=null)for(o in e.key!==void 0&&(a=""+e.key),e)wt.call(e,o)&&o!=="key"&&o!=="__self"&&o!=="__source"&&(n[o]=e[o]);var m=arguments.length-2;if(m===1)n.children=s;else if(1<m){for(var d=Array(m),c=0;c<m;c++)d[c]=arguments[c+2];n.children=d}if(t&&t.defaultProps)for(o in m=t.defaultProps,m)n[o]===void 0&&(n[o]=m[o]);return lt(t,a,n)};i.createRef=function(){return{current:null}};i.forwardRef=function(t){return{$$typeof:Yt,render:t}};i.isValidElement=pt;i.lazy=function(t){return{$$typeof:kt,_payload:{_status:-1,_result:t},_init:te}};i.memo=function(t,e){return{$$typeof:Jt,type:t,compare:e===void 0?null:e}};i.startTransition=function(t){var e=p.T,s={};p.T=s;try{var o=t(),n=p.S;n!==null&&n(s,o),typeof o=="object"&&o!==null&&typeof o.then=="function"&&o.then(it,Ht)}catch(a){Ht(a)}finally{e!==null&&s.types!==null&&(e.types=s.types),p.T=e}};i.unstable_useCacheRefresh=function(){return p.H.useCacheRefresh()};i.use=function(t){return p.H.use(t)};i.useActionState=function(t,e,s){return p.H.useActionState(t,e,s)};i.useCallback=function(t,e){return p.H.useCallback(t,e)};i.useContext=function(t){return p.H.useContext(t)};i.useDebugValue=function(){};i.useDeferredValue=function(t,e){return p.H.useDeferredValue(t,e)};i.useEffect=function(t,e){return p.H.useEffect(t,e)};i.useEffectEvent=function(t){return p.H.useEffectEvent(t)};i.useId=function(){return p.H.useId()};i.useImperativeHandle=function(t,e,s){return p.H.useImperativeHandle(t,e,s)};i.useInsertionEffect=function(t,e){return p.H.useInsertionEffect(t,e)};i.useLayoutEffect=function(t,e){return p.H.useLayoutEffect(t,e)};i.useMemo=function(t,e){return p.H.useMemo(t,e)};i.useOptimistic=function(t,e){return p.H.useOptimistic(t,e)};i.useReducer=function(t,e,s){return p.H.useReducer(t,e,s)};i.useRef=function(t){return p.H.useRef(t)};i.useState=function(t){return p.H.useState(t)};i.useSyncExternalStore=function(t,e,s){return p.H.useSyncExternalStore(t,e,s)};i.useTransition=function(){return p.H.useTransition()};i.version="19.2.4"});var Dt=gt((de,Pt)=>{"use strict";C();Pt.exports=Mt()});C();C();C();var fe=Bt(Dt(),1);var oe=["achieved","aborted","failed"];function ge(t){return oe.includes(t)}function ne(t,e){return t>=e.hard?"hard":t>=e.auto?"auto":t>=e.warn?"warn":"safe"}function T(t){if(!t||t.length===0)return 0;let e=0,s=0;for(let o=0;o<t.length;o++)t.charCodeAt(o)<128?e++:s++;return Math.ceil(e/4+s*1.5)}function se(t){if(!t||t.trim().length===0)return[];let e=[],s=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g,o;for(;(o=s.exec(t))!==null;){let n=o[1],a=o[2];e.push({path:n,tokens:T(a)})}return e.length===0&&t.trim().length>0&&e.push({path:k("memory"),tokens:T(t)}),e}async function re(t,e){let s=t.getModelDisplayName()||"unknown",o=t.getContentGeneratorConfig(),n=o.contextWindowSize??131072,a=nt.getLastPromptTokenCount(),m=nt.getLastCachedContentTokenCount(),d=It(void 0,s),c=T(d),g=t.getToolRegistry(),M=g?g.getAllTools():[],r=g?g.getFunctionDeclarations():[],P=JSON.stringify(r),_=T(P),H=[],x=[];for(let u of M){if(u.shouldDefer&&!u.alwaysLoad&&!g?.isDeferredToolRevealed(u.name))continue;let h=JSON.stringify(u.schema),S=T(h);u instanceof ht?x.push({name:`${u.serverName}__${u.serverToolName||u.name}`,tokens:S}):u.name!==st.SKILL&&H.push({name:u.name,tokens:S})}let l=t.getUserMemory(),y=se(l),$=y.reduce((u,h)=>u+h.tokens,0),E=M.find(u=>u.name===st.SKILL),G=E?T(JSON.stringify(E.schema)):0,Nt=E&&"getLoadedSkillNames"in E?E.getLoadedSkillNames():new Set,dt=t.getSkillManager(),Ut=dt?await dt.listSkills():[],D=0,j=Ut.map(u=>{let h=T(`<skill>
|
|
4
4
|
<name>
|
|
5
5
|
${u.name}
|
|
6
6
|
</name>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Oh as T}from"./chunk-
|
|
3
|
+
import{Oh as T}from"./chunk-AC7V5HGT.js";import{P as b}from"./chunk-VLYRNOD3.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
|
|
4
4
|
`)?e:`${e}
|
|
5
5
|
`)},m=e=>{process.stderr.write(e.endsWith(`
|
|
6
6
|
`)?e:`${e}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{M as D,N as L,O as j,g as I,la as _}from"./chunk-
|
|
3
|
+
import{M as D,N as L,O as j,g as I,la as _}from"./chunk-ERD4AVF5.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as F,n as U}from"./chunk-SDTWBD62.js";import{q as b,s as $,t as x,u as O}from"./chunk-VLYRNOD3.js";import{b as G}from"./chunk-GZPNIYVZ.js";G();var V="2026-06-23",X="auto",K="instant",z=12e4,h=18e4,Y=5e4,R=16e3,S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},Q=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),Z=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function q(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var ee="Your message was blocked by our content safety system.";function te(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:ee;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function W(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
|
|
4
4
|
`):""}function f(n,e){if(n.length<=e)return n;let t=`
|
|
5
5
|
[...omitted to fit Matilda native agent context...]
|
|
6
6
|
`,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function ne(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function se(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function oe(n){if(C(n)<=h)return n;let e=`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Ji as K,xf as X,zf as H}from"./chunk-
|
|
3
|
+
import{Ji as K,xf as X,zf as H}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{i as S}from"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as B,i as G}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as ye}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",ue="https://matilda.maincode.com/assets/computer-use",me="https://github.com/trycua/cua/releases/download";function E(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function U(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ge(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${ue}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs-v${o}/${e}`),r}function J(e=process.env,t=l){return U("checksums.txt",e,t)}var he="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function V(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Y(e,t=process.env){let o=V(t[he]);return o!==void 0?o:V(e)}function fe(e=R()){return I(e,".matilda","computer-use")}function N(e=R(),t=l){return I(fe(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=E(t,o,r);return I(N(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ge(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(ye())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new H({command:this.binary,args:["mcp"],env:{...process.env}}),i=new X({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Q(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Q(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Q(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var M=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
|
|
4
4
|
|
|
5
5
|
Two addressing modes:
|
|
6
6
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{c as a,d as b,e as c}from"./chunk-
|
|
3
|
+
import{c as a,d as b,e as c}from"./chunk-LB2LZKIS.js";import"./chunk-N5UZND2H.js";import"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as y}from"./chunk-5PMMY47S.js";import{$e as Y,Ae as K,Ne as R,Oe as x,Ue as X,Ve as V,Ye as Q,ka as I,se as A,te as G,vc as q}from"./chunk-
|
|
3
|
+
import{a as y}from"./chunk-5PMMY47S.js";import{$e as Y,Ae as K,Ne as R,Oe as x,Ue as X,Ve as V,Ye as Q,ka as I,se as A,te as G,vc as q}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{Lb as z,Oa as j,_c as H,ca as U,ha as N,wc as D}from"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as B}from"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{i as k,p as P,q as W}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{D as w,E as S,G as M,aa as $,b as C}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as T}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";T();import*as m from"node:fs";import*as u from"node:path";T();var se={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "};function L(n){if(n==="")return n;let t="";for(let i of n)t+=se[i]??i;return t}var ae=[n=>n,n=>n.trimEnd()];function ce(n){return L(n).trimEnd()}function J(n,t,i){if(t.length===0)return 0;if(t.length>n.length)return null;e:for(let e=0;e<=n.length-t.length;e++){for(let r=0;r<t.length;r++)if(i(n[e+r])!==i(t[r]))continue e;return e}return null}function fe(n){let t=n.split(`
|
|
4
4
|
`),i=new Array(t.length+1),e=0;for(let r=0;r<t.length;r++)i[r]=e,e+=t[r].length,r<t.length-1&&(e+=1);return i[t.length]=n.length,{lines:t,offsets:i}}function Z(n,t,i,e,r,o){if(r===0)return o?`
|
|
5
5
|
`:"";let f=t[e]??0,l=e+r-1,c=(t[l]??0)+(i[l]?.length??0);if(o){let g=t[e+r];g!==void 0?c=g:n.endsWith(`
|
|
6
6
|
`)&&(c=n.length)}return n.slice(f,c)}function de(n,t){let{lines:i,offsets:e}=fe(n),r=t.split(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Qj as T,Vf as W,bg as s}from"./chunk-
|
|
3
|
+
import{Qj as T,Vf as W,bg as s}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as $,i as E,p as m,q as R}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{aa as b}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
|
|
4
4
|
|
|
5
5
|
## When to Use
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{I as r}from"./chunk-
|
|
3
|
+
import{I as r}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as m,i as u,p as d,q as c}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{aa as p}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as l}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";l();var y=p("ENTER_PLAN_MODE"),g=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
|
|
4
4
|
|
|
5
5
|
## When to Use This Tool
|
|
6
6
|
Use this tool when the task is not yet clear enough to safely execute, for example when it requires multi-file changes, design choices, investigation before a plan can be summarized, or when requirements are ambiguous. While investigating, if complexity rises or you find yourself repeatedly needing to ask the user, enter plan mode and consolidate a plan.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Pj as C,Rj as x,Tf as k,Wf as W,bg as l}from"./chunk-
|
|
3
|
+
import{Pj as C,Rj as x,Tf as k,Wf as W,bg as l}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as E,i as R,p as c,q as T}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{aa as b,b as $}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
|
|
4
4
|
|
|
5
5
|
## Behavior
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as k}from"./chunk-ILBTI4K5.js";import{I as w,Jf as M,mg as $}from"./chunk-
|
|
3
|
+
import{a as k}from"./chunk-ILBTI4K5.js";import{I as w,Jf as M,mg as $}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as G,i as R,p as T,q as _}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{aa as f}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as h}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";h();h();h();var E=f("GATE_REVIEW_AGENTS");function L(n){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
|
|
4
4
|
|
|
5
5
|
1. **Request Fit** \u2014 Does the plan fulfill every part of the user's original request and respect all explicit constraints? Does it do anything the user explicitly asked NOT to do?
|
|
6
6
|
2. **System Fit** \u2014 Does the plan align with the codebase structure, file paths, function names, permission model, and integration boundaries found during investigation?
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as g}from"./chunk-Q2I3ARPJ.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as d}from"./chunk-SDTWBD62.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.21.6-
|
|
3
|
+
import{a as g}from"./chunk-Q2I3ARPJ.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as d}from"./chunk-SDTWBD62.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.21.6-preview.0 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let f=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${f}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new p({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{p as GeminiContentGenerator,T as createGeminiContentGenerator};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Re as _,Se as j}from"./chunk-
|
|
3
|
+
import{Re as _,Se as j}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as M,i as C,p as N,q as A}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{G as $,J as O,N as v,aa as R,d as x}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
|
|
4
4
|
|
|
5
5
|
[Search stopped after ${W/1e3}s before scanning the whole tree. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:o==="count"?`
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{Lj as K,Mj as Y,S as q,Se as z,gd as F}from"./chunk-
|
|
3
|
+
import{Lj as K,Mj as Y,S as q,Se as z,gd as F}from"./chunk-AC7V5HGT.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-OCYTOKZC.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as _}from"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as U,i as V,p as H,q as J}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{G as O,J as W,N as S,aa as j,b as I,d as P}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as B}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";B();import tt from"node:fs/promises";import y from"node:path";import{EOL as et}from"node:os";import{spawn as X}from"node:child_process";var k=j("GREP"),M=class extends U{constructor(e,s){super(s);this.config=e;this.fileExclusions=e.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let e=this.config.getWorkspaceContext(),s=y.resolve(this.config.getTargetDir(),this.params.path);return e.isPathWithinWorkspace(s)||W(_(),s)?"allow":"ask"}async execute(e){try{let s=[],i;if(this.params.path){let t=S(this.config,this.params.path,{allowExternalPaths:!0});s.push(t),i=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();s.push(...t),i=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let l=[];for(let t of s){let o=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:e});if(s.length>1)for(let a of o)y.isAbsolute(a.filePath)||(a.filePath=y.resolve(t,a.filePath));l.push(...o)}if(s.length>1){let t=new Set;l=l.filter(o=>{let a=`${o.filePath}:${o.lineNumber}`;return t.has(a)?!1:(t.add(a),!0)})}let f=this.params.glob?` (filter: "${this.params.glob}")`:"";if(l.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${i}${f}.`,returnDisplay:"No matches found"};let h=this.config.getTruncateToolOutputThreshold(),w=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),$=!1,C=l;l.length>w&&(C=l.slice(0,w),$=!0);let E=l.length,x=E===1?"match":"matches",G=`Found ${E} ${x} for pattern "${this.params.pattern}" ${i}${f}:
|
|
4
4
|
---
|
|
5
5
|
`,v=C.reduce((t,o)=>{let a=o.filePath;return t[a]||(t[a]=[]),t[a].push(o),t[a].sort((L,D)=>L.lineNumber-D.lineNumber),t},{}),n="",g=[],m=!1,c=(t,o)=>Number.isFinite(h)&&n.length+t.length>h?(n+=t.slice(0,Math.max(h-n.length,0)),n+="...",o&&g.push(o),m=!0,!1):(n+=t,o&&g.push(o),!0);for(let t in v){if(!c(`File: ${t}
|
|
6
6
|
`))break;let o=!1;for(let a of v[t]){let L=a.line.trim();if(!c(`L${a.lineNumber}: ${L}
|
package/chunks/{matildaAgentContentGenerator-3W4VL63J.js → matildaAgentContentGenerator-MYD7CTHU.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{b as t}from"./chunk-
|
|
3
|
+
import{b as t}from"./chunk-OCYTOKZC.js";import"./chunk-ERD4AVF5.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import"./chunk-6B5BDE7S.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as n}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";n();function a(e,o){return new t(e,o)}export{t as MatildaAgentContentGenerator,a as createMatildaAgentContentGenerator};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2026 Matilda Team
|