@maincode-ai/matilda-code 0.21.10-preview.0 → 0.21.10-preview.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled/mainy/docs/configuration/settings.md +9 -0
- package/chunks/agent-XXSEYARS.js +3 -0
- package/chunks/agent-headless-YBWTAFUH.js +3 -0
- package/chunks/{anthropicContentGenerator-SFJGSZHT.js → anthropicContentGenerator-IYZILRDW.js} +1 -1
- package/chunks/{askUserQuestion-G2H4VCRY.js → askUserQuestion-XWHJY3DM.js} +1 -1
- package/chunks/{chunk-INAZKGGR.js → chunk-2HQMJ2IU.js} +1 -1
- package/chunks/chunk-2W6MZZHZ.js +39 -0
- package/chunks/{todoWrite-3XJNFIBR.js → chunk-4CSSDBOS.js} +2 -2
- package/chunks/{chunk-5PMMY47S.js → chunk-4FVBPNTZ.js} +1 -1
- package/chunks/{chunk-TFWOXSAP.js → chunk-4TQ7ABLG.js} +14 -14
- package/chunks/{chunk-X6BEBYGX.js → chunk-66NIIU2R.js} +9 -9
- package/chunks/{chunk-32PTAACU.js → chunk-ELH4YHJR.js} +1 -1
- package/chunks/{chunk-FWIVFCKF.js → chunk-FFFZ2QMG.js} +1 -1
- package/chunks/{chunk-KSNBNXBC.js → chunk-FRRBNNEB.js} +48 -48
- package/chunks/{chunk-EQEQPZLQ.js → chunk-GO2GA2GY.js} +1 -1
- package/chunks/{chunk-QHA3ZBRO.js → chunk-GUFIMKF5.js} +1 -1
- package/chunks/{chunk-H6WMNUW2.js → chunk-HOCFKXNJ.js} +1 -1
- package/chunks/{chunk-VWWEEU4V.js → chunk-JXUDKX6D.js} +1 -1
- package/chunks/{chunk-VLYRNOD3.js → chunk-MH2P4YXC.js} +10 -10
- package/chunks/{chunk-6Q6PMGBD.js → chunk-MKFQMX37.js} +1 -1
- package/chunks/{chunk-VYTYYCBR.js → chunk-NYEWHSBL.js} +1 -1
- package/chunks/{chunk-LIWYWWOK.js → chunk-ODZOYHIC.js} +1 -1
- package/chunks/{chunk-Q2I3ARPJ.js → chunk-QH7736R5.js} +1 -1
- package/chunks/chunk-QN6WSWMM.js +9 -0
- package/chunks/{chunk-RJX7DK4Y.js → chunk-S4UT3QLV.js} +1 -1
- package/chunks/chunk-SNLH42QJ.js +10 -0
- package/chunks/{chunk-SE3XDSIJ.js → chunk-SPW5DXX4.js} +1 -1
- package/chunks/{chunk-S7G6QPEP.js → chunk-SUH3UUWZ.js} +1 -1
- package/chunks/{chunk-PIFQEMZZ.js → chunk-T4P4KEDW.js} +8 -8
- package/chunks/chunk-TO3ID3JW.js +35 -0
- package/chunks/{chunk-6ZMDAPGZ.js → chunk-VVIJGBQK.js} +566 -545
- package/chunks/{chunk-DCQKJTAX.js → chunk-W5CGKUM4.js} +8 -3
- package/chunks/{chunk-2PPJ3MJT.js → chunk-WHG6N5X2.js} +1 -1
- package/chunks/{chunk-GWGQRU36.js → chunk-WJO3QSBJ.js} +1 -1
- package/chunks/{chunk-XCJYORZX.js → chunk-XCFLI3OC.js} +1 -1
- package/chunks/{chunk-IJUI5A6G.js → chunk-YMIF2DMT.js} +1 -1
- package/chunks/chunk-YSIECQIZ.js +113 -0
- package/chunks/{computer-use-QN46FSNK.js → computer-use-HX2LYMYD.js} +7 -7
- package/chunks/contextCommand-W7DBC37U.js +3 -0
- package/chunks/{cron-create-MILWOYF6.js → cron-create-2UI4AT4Q.js} +1 -1
- package/chunks/{cron-delete-IEOPMRWP.js → cron-delete-ZB6BOTFF.js} +1 -1
- package/chunks/{cron-list-GGBUA7S7.js → cron-list-YYAXNHB6.js} +1 -1
- package/chunks/{edit-7AZARQPL.js → edit-HFUF2RN3.js} +1 -1
- package/chunks/{enter-worktree-GKYG5CD2.js → enter-worktree-LFCL64PJ.js} +1 -1
- package/chunks/{enterPlanMode-ICTG6ULZ.js → enterPlanMode-TREN7ULJ.js} +1 -1
- package/chunks/{exit-worktree-ZWYXIEIC.js → exit-worktree-MH2J4P42.js} +1 -1
- package/chunks/{exitPlanMode-5BQ4MY5I.js → exitPlanMode-PQO3EFFT.js} +1 -1
- package/chunks/{geminiContentGenerator-APSI54U5.js → geminiContentGenerator-FE5UVAOZ.js} +1 -1
- package/chunks/glob-VZAYMEQA.js +22 -0
- package/chunks/goal-tools-JN27F5BA.js +12 -0
- package/chunks/grep-2VT5TSRU.js +22 -0
- package/chunks/{keychain-token-storage-HAFQQIXL.js → keychain-token-storage-54BNK6VH.js} +1 -1
- package/chunks/{ls-FQYKJYAK.js → ls-YWZU3FYL.js} +1 -1
- package/chunks/{lsp-FGMC4KSB.js → lsp-4CJDKEEC.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-HVIGLQJZ.js → matildaAgentContentGenerator-EYETUHCZ.js} +1 -1
- package/chunks/matildaContentGenerator-IWKH3YC4.js +8 -0
- package/chunks/{matildaOAuth2-W2DQO2NK.js → matildaOAuth2-GRS5K3D4.js} +1 -1
- package/chunks/monitor-AMIVJKDL.js +32 -0
- package/chunks/notebook-edit-BQUXXNEO.js +17 -0
- package/chunks/{openaiContentGenerator-X6TFPZGL.js → openaiContentGenerator-4M7WBW3G.js} +1 -1
- package/chunks/read-file-FNJZCMIZ.js +3 -0
- package/chunks/ripGrep-UOEUWYVF.js +3 -0
- package/chunks/scheduler-ASQLD6BW.js +8 -0
- package/chunks/{send-message-5PJPE34J.js → send-message-OO2HAKCC.js} +1 -1
- package/chunks/{serve-24HVCLFM.js → serve-FIDAAJAB.js} +1 -1
- package/chunks/shell-S732E2W4.js +3 -0
- package/chunks/{skill-HWDNN7P7.js → skill-VXNOQCSI.js} +1 -1
- package/chunks/src-QZENX46P.js +3 -0
- package/chunks/{symbol-search-BSE3FWJX.js → symbol-search-ALYOX5JN.js} +1 -1
- package/chunks/{syntheticOutput-DX4NN34N.js → syntheticOutput-UASKABJH.js} +1 -1
- package/chunks/task-create-EBJD55TB.js +3 -0
- package/chunks/{task-detach-TGM25ZIU.js → task-detach-I67ZE5MX.js} +1 -1
- package/chunks/{task-list-AZLBAQVL.js → task-list-5BGX4G5N.js} +1 -1
- package/chunks/{task-stop-B5PTXVMO.js → task-stop-ERI5X4AO.js} +1 -1
- package/chunks/{task-update-ARPBRTC5.js → task-update-CD3W556L.js} +1 -1
- package/chunks/{team-create-D4N2QVBX.js → team-create-CXY3MRCE.js} +1 -1
- package/chunks/{team-delete-AGYMEW6E.js → team-delete-5U3GBFKJ.js} +1 -1
- package/chunks/todoWrite-YGG6AZ3A.js +3 -0
- package/chunks/{tool-search-LRVN3W5W.js → tool-search-AJ57WSJC.js} +1 -1
- package/chunks/{web-fetch-Y64RF72K.js → web-fetch-63M6GZQL.js} +1 -1
- package/chunks/{web-search-I3D4EN5B.js → web-search-OX2DPEVN.js} +1 -1
- package/chunks/{workflow-BSK53DUN.js → workflow-55OAJ6XH.js} +2 -2
- package/chunks/write-file-2TWXQRDB.js +15 -0
- package/cli.js +459 -462
- package/package.json +2 -2
- package/chunks/agent-U43GELHB.js +0 -3
- package/chunks/agent-headless-7STBERN4.js +0 -3
- package/chunks/chunk-2NBII5ND.js +0 -34
- package/chunks/chunk-BN2CPSZ5.js +0 -34
- package/chunks/chunk-HMZOLFRP.js +0 -10
- package/chunks/chunk-ROETRE5J.js +0 -9
- package/chunks/chunk-XJYPRCV7.js +0 -108
- package/chunks/contextCommand-7G5FHBBE.js +0 -3
- package/chunks/glob-NPEYXTA6.js +0 -22
- package/chunks/grep-4NQTKAN6.js +0 -22
- package/chunks/matildaContentGenerator-5VOBYNAJ.js +0 -8
- package/chunks/monitor-RMKMKOUY.js +0 -32
- package/chunks/notebook-edit-H3ZFKBLR.js +0 -17
- package/chunks/read-file-3J3ZMBI2.js +0 -3
- package/chunks/ripGrep-WDYTLRCE.js +0 -3
- package/chunks/scheduler-TKK5QECI.js +0 -8
- package/chunks/shell-YPEMRDRO.js +0 -3
- package/chunks/src-W5VAKS5Y.js +0 -3
- package/chunks/task-create-3PW7T36X.js +0 -3
- package/chunks/update-goal-KLUMJFUA.js +0 -16
- package/chunks/write-file-GDKSQBMU.js +0 -15
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.21.10-preview.
|
|
3
|
+
"version": "0.21.10-preview.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.10-preview.
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.10-preview.1"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|
package/chunks/agent-U43GELHB.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{lg as a,mg as b,ng as c,og as d,pg as e,qg as f}from"./chunk-6ZMDAPGZ.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-TISQNFB5.js";import"./chunk-6Q6PMGBD.js";import"./chunk-MTMU7JYZ.js";import"./chunk-RNKDFE2S.js";import"./chunk-BN2CPSZ5.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-HMZOLFRP.js";import"./chunk-QKYGQLWC.js";import"./chunk-SE3XDSIJ.js";import"./chunk-VWWEEU4V.js";import"./chunk-HYVP4472.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-X6BEBYGX.js";import"./chunk-QHA3ZBRO.js";import"./chunk-XJYPRCV7.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-KSNBNXBC.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-2PPJ3MJT.js";import"./chunk-PIFQEMZZ.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{f as AgentTool,b as TOOL_REGISTRY_REBUILT,e as createApprovalModeOverride,c as hasRebuiltToolRegistry,d as rebuildToolRegistryOnOverride,a as resolveSubagentApprovalMode};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Mf as a,Nf as b,Of as c}from"./chunk-6ZMDAPGZ.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-TISQNFB5.js";import"./chunk-6Q6PMGBD.js";import"./chunk-MTMU7JYZ.js";import"./chunk-RNKDFE2S.js";import"./chunk-BN2CPSZ5.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-HMZOLFRP.js";import"./chunk-QKYGQLWC.js";import"./chunk-SE3XDSIJ.js";import"./chunk-VWWEEU4V.js";import"./chunk-HYVP4472.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-X6BEBYGX.js";import"./chunk-QHA3ZBRO.js";import"./chunk-XJYPRCV7.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-KSNBNXBC.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-2PPJ3MJT.js";import"./chunk-PIFQEMZZ.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{c as AgentHeadless,a as ContextState,b as templateString};
|
package/chunks/chunk-2NBII5ND.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
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-XJYPRCV7.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
|
-
|
|
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
|
-
`,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(`
|
|
7
|
-
`):""}sanitizeMatildaUserContent(e){let n=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(n.length<=Ae)return n;let r=Ae-Pe.length;return`${Pe}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let c=n?.[s],m=l?e.config?.[l]:void 0,d=l?t[l]:void 0;return c!==void 0?c:m!==void 0?m:d},o=(s,l,c)=>{let m=r(l,c);return m!==void 0?{[s]:m}:{}};if(n!==void 0){let s=e.config?.maxOutputTokens;return{...n,...s!==void 0&&n.max_tokens!==void 0?{max_tokens:s}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,n,r){let o=this.createRequestContext(e,n);try{let a=await this.buildRequest(e,t,o,n);return ie.getStore()?.(a),ae.recordOpenAIWireRequest(a),await r(a,o)}catch(a){return await this.handleError(a,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(O(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new V:void 0,a=this.config.provider.getResponseParsingOptions?.(),s=t&&a?.taggedThinkingTags?new re:void 0;return{model:n,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:r.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...a?{responseParsingOptions:a}:{},...s?{taggedThinkingParser:s}:{}}}};p();var De=A("OPENAI_ERROR"),S=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=O(e),o=this.isTimeoutError(r),a=this.buildErrorMessage(r,t,o);throw this.shouldSuppressErrorLogging(r,n)||De.error("OpenAI API Error:",a),o?new Error(`${a}
|
|
8
|
-
|
|
9
|
-
${this.getTimeoutTroubleshootingTips()}`):r}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),n=e?.code,r=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||r==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,n){let r=Math.round((Date.now()-t.startTime)/1e3);return n?`Request timeout after ${r}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
10
|
-
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
11
|
-
`)}`}};var Oe=A("OPENAI"),v=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new S((o,a)=>this.shouldSuppressErrorLogging(o,a))};this.pipeline=new _(r)}shouldSuppressErrorLogging(e,t){return!!(ee(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new be().calculateTokens(e)).totalTokens}}catch(t){Oe.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(n=>typeof n=="string"?n:"parts"in n&&n.parts?n.parts.map(r=>typeof r=="string"?r:"text"in r&&r.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(n=>typeof n=="string"?n:"text"in n?n.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(n){let r=O(n);throw Oe.error("OpenAI API Embedding Error:",r),new Error(`OpenAI API error: ${r instanceof Error?r.message:String(r)}`)}}useSummarizedThinking(){return!1}};p();var L=class extends v{contentGeneratorConfig;cliConfig;channel;constructor(e,t,n){super(e,t,n),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return X(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=()=>super.generateContentStream(e,t),r=await this.withTokenRefresh(n);return this.iterateWithAuthRetry(r,n)}async*iterateWithAuthRetry(e,t){let n=!1;try{for await(let r of e)n||=(r.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield r;return}catch(r){if(!X(r))throw $(r);if(n)throw new J("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw $(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await ge({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(n){throw W(n,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),n}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[he]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!X(t))throw $(t);await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(n){throw $(n)}}}};function $(i){return K(i)?new te:X(i)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):i}function X(i){if(!i||K(i))return!1;let e=i instanceof Error?i.message.toLowerCase():String(i).toLowerCase(),t=i,n=Number(t.status??t.statusCode??t.code);return n>=400&&n<600?n===401:e.includes("unauthorized")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("token")&&e.includes("expired")}function In(i,e){let t=He(i,e);return b.isMatildaCompatibleProvider(i)?new L(i,e,t):new v(i,e,t)}function He(i,e){let t=i||e.getContentGeneratorConfig();return b.isMatildaCompatibleProvider(t)?new b(i,e):R.isDeepSeekProvider(t)?new R(i,e):x.isMiMoProvider(t)?new x(i,e):I.isOpenRouterProvider(t)?new I(i,e):w.isModelScopeProvider(t)?new w(i,e):M.isMiniMaxProvider(t)?new M(i,e):T.isMistralProvider(t)?new T(i,e):new f(i,e)}export{b as a,R as b,I as c,M as d,T as e,x as f,_ as g,S as h,v as i,L as j,In as k,He as l};
|
|
12
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2025 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2026 Maincode
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*
|
|
22
|
-
* OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
|
|
23
|
-
*
|
|
24
|
-
* Emulates Grok Build's automatic credential refresh
|
|
25
|
-
* (docs: "Automatic Credential Refresh"):
|
|
26
|
-
* 1. Before each request: ensure a fresh access token (re-read disk; refresh
|
|
27
|
-
* when within the early-invalidation window / already expired).
|
|
28
|
-
* 2. On 401 Unauthorized: force-refresh and retry the request once.
|
|
29
|
-
* 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
|
|
30
|
-
*
|
|
31
|
-
* Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
|
|
32
|
-
* createContentGenerator time, so idle sessions past access-token expiry
|
|
33
|
-
* failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
|
|
34
|
-
*/
|
package/chunks/chunk-BN2CPSZ5.js
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as j}from"./chunk-4J6DC24J.js";import{k as H}from"./chunk-SDTWBD62.js";import{aa as p}from"./chunk-VLYRNOD3.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();var u=new Map,A=new Map;function bt(t,e){e?A.set(t,e):A.delete(t)}function S(t){try{A.get(t)?.()}catch{}}function At(t,e){return t===e?!0:!t||!e?!1:J(t)===J(e)}function J(t){let e={};for(let n of Object.keys(t).sort()){let o=t[n];o!==void 0&&(e[n]=o)}return JSON.stringify(e)}function E(t){return u.get(t)}function P(t,e){u.set(t,e),S(t)}function _(t){let e=u.get(t);return u.delete(t),e&&S(t),e}function $(t,e){let n=u.get(t);if(!n)return;let o={...n,iterations:n.iterations+1,lastReason:e};return u.set(t,o),S(t),o}function D(t,e,n){let o=u.get(t);if(!o)return;let i={...o,status:e,statusNote:e==="active"?void 0:n?.trim()||o.statusNote};return e==="active"&&delete i.statusNote,u.set(t,i),S(t),i}function U(t){let e=u.get(t);if(!e)return;let{statusNote:n,...o}=e,i={...o,status:"active",iterations:0};return u.set(t,i),S(t),i}function Et(t,e){return t!==void 0&&e!==void 0&&m(t)==="active"&&m(e)==="paused"}function m(t){return t.status??"active"}function Ct(){u.clear(),A.clear(),C.clear(),k.clear()}var C=new Map;function Tt(t,e){C.set(t,e)}function L(t){C.delete(t)}function F(t,e){Z(t,e);let n=C.get(t);if(n)try{n(e)}catch{}}var k=new Map;function Z(t,e){k.set(t,e)}function Rt(t){return k.get(t)}function wt(t,e){if(!e){k.delete(t);return}k.set(t,e)}g();g();var T=p("ERROR_REPORT");async function K(t,e,n,o="general"){let i;t instanceof Error?i={message:t.message,stack:t.stack}:typeof t=="object"&&t!==null&&"message"in t?i={message:String(t.message)}:i={message:String(t)};let s={error:i};n&&(s.context=n);let r=`${e} [${o}]`,a;try{a=JSON.stringify(s,null,2)}catch(c){T.error(`${r} Could not stringify report content (likely due to context):`,c,t);try{a=JSON.stringify({error:i},null,2),T.error(r,a)}catch(d){T.error(`${r} Failed to stringify minimal error report:`,d,t)}return}T.error(r,a)}var b=p("GOAL_JUDGE"),tt=`You are evaluating a stop-condition hook in an autonomous coding agent.
|
|
4
|
-
Read the conversation transcript above carefully, then judge whether the
|
|
5
|
-
user-provided condition is satisfied.
|
|
6
|
-
|
|
7
|
-
Your response MUST be a JSON object with one of these shapes:
|
|
8
|
-
- {"ok": true, "reason": "<quote evidence from the transcript that satisfies the condition>"}
|
|
9
|
-
- {"ok": false, "reason": "<quote what is missing or what blocks the condition>"}
|
|
10
|
-
- {"ok": false, "impossible": true, "reason": "<explain why the condition can never be satisfied>"}
|
|
11
|
-
|
|
12
|
-
Always include a "reason" field, quoting specific text from the transcript
|
|
13
|
-
whenever possible. If the transcript does not contain clear evidence that the
|
|
14
|
-
condition is satisfied, return {"ok": false, "reason": "insufficient evidence in transcript"}.
|
|
15
|
-
Only use {"ok": false, "impossible": true} when the condition is genuinely
|
|
16
|
-
unachievable in this session: for example, it is self-contradictory, depends on
|
|
17
|
-
an unavailable resource or capability, or the assistant has exhausted reasonable
|
|
18
|
-
approaches and the transcript confirms there is no path forward. The assistant
|
|
19
|
-
claiming the goal is impossible is evidence, not proof; independently confirm
|
|
20
|
-
the condition is genuinely unachievable rather than deferring to the assistant's
|
|
21
|
-
self-assessment. Do not use it just because progress is slow or evidence is
|
|
22
|
-
currently missing. When in doubt, return {"ok": false} without "impossible".`,et=t=>`Based on the conversation transcript above, has the following stopping condition been satisfied? Answer based on transcript evidence only.
|
|
23
|
-
Condition JSON string: ${JSON.stringify(t)}`;var nt={type:"OBJECT",properties:{ok:{type:"BOOLEAN"},reason:{type:"STRING"},impossible:{type:"BOOLEAN"}},required:["ok","reason"],additionalProperties:!1},G="Goal judge unavailable; continue working toward the goal and run `/goal clear` to stop early.",ot=240;function R(t,e){K(t,"Goal judge failed",{stage:e},`goal-judge-${e}`).catch(n=>{b.debug(`Goal judge error reporting failed: ${n instanceof Error?n.message:String(n)}`)})}var it=24,y=4e3;async function Y(t,e){let n=e.condition.trim();if(!n)return{ok:!1,reason:G};if(e.signal.aborted)return{ok:!1,reason:G};let o=rt(t,e.lastAssistantText);o.push({role:"user",parts:[{text:et(n)}]});let i=t.getFastModel()??t.getModel();try{let s=t.getGeminiClient(),r=await H("unknown",()=>s.generateContent(o,{systemInstruction:tt,temperature:0,responseMimeType:"application/json",responseSchema:nt,thinkingConfig:{thinkingBudget:0}},e.signal,i));if(r.candidates?.[0]?.finishReason!==j.STOP)return R(new Error("Goal judge response did not finish normally"),"incomplete-response"),{ok:!1,reason:G};let a=ut(r);if(!a)return b.debug("Goal judge returned empty content; defaulting to not-met"),R(new Error("Empty judge response"),"empty-response"),{ok:!1,reason:G};let c=dt(a);return c||(b.debug(`Goal judge reply not parseable as JSON (length=${a.length})`),R(new Error("Judge response was not parseable as JSON"),"parse"),{ok:!1,reason:G})}catch(s){return b.debug(`Goal judge threw: ${s instanceof Error?s.message:String(s)}`),R(s,"generate-content"),{ok:!1,reason:G}}}function rt(t,e){try{let n=t.getGeminiClient();if(!n.isInitialized())return I(e);let i=n.getHistoryTail(it).map(st);return i.length===0?I(e):(!(lt(i).includes(e)||e.trim()==="")&&e.trim()&&i.push({role:"model",parts:[{text:e.slice(0,y)}]}),i)}catch(n){return b.debug(`Goal judge transcript fetch failed: ${n instanceof Error?n.message:String(n)}`),I(e)}}function I(t){return t.trim()?[{role:"model",parts:[{text:t.slice(0,y)}]}]:[]}function st(t){return t.parts?{...t,parts:t.parts.map(at)}:t}function at(t){return typeof t.text=="string"?t.text.length>y?{...t,text:t.text.slice(0,y)+"\u2026[truncated]"}:t:t.functionResponse?{...t,functionResponse:{...t.functionResponse,response:B(t.functionResponse.response)}}:t.functionCall?{...t,functionCall:{...t.functionCall,args:B(t.functionCall.args)}}:t}function B(t){let e=ct(t);return e.length<=y?t:{truncated:!0,originalLength:e.length,preview:e.slice(0,y)+"\u2026[truncated]"}}function ct(t){try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function lt(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="model")return(n.parts??[]).map(o=>typeof o.text=="string"?o.text:"").join("")}return""}function ut(t){let e=t?.candidates;if(!Array.isArray(e)||e.length===0)return"";let o=e[0]?.content?.parts;return Array.isArray(o)?o.map(i=>typeof i?.text=="string"&&!i.thought?i.text:"").join("").trim():""}function dt(t){let e=gt(t).trim(),n=e.indexOf("{"),o=e.lastIndexOf("}");if(n===-1||o===-1||o<n)return null;let i;try{i=JSON.parse(e.slice(n,o+1))}catch{return null}if(!i||typeof i!="object")return null;let s=i.ok,r=i.reason;if(typeof s!="boolean"||typeof r!="string"||!r.trim())return null;let a=i.impossible===!0;return{ok:s,reason:r.trim().slice(0,ot),...a&&!s?{impossible:!0}:{}}}function gt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return e?e[1]:t}g();var v=p("GOAL_HOOK");function h(t,e){try{t.getChatRecordingService()?.recordGoalState({goal:e?{condition:e.condition,status:m(e),iterations:e.iterations,setAt:e.setAt,lastReason:e.lastReason,statusNote:e.statusNote}:null})}catch(n){v.debug("Could not record goal state",n)}}function ft(t,e,n,o){let i=D(e,n,o);return i&&h(t,i),i}function Bt(t,e){let n=U(e);return n&&h(t,n),n}var N=50,q=3,z=25e3,pt=30,mt=pt*1e3,W=2,Gt="Goal judge timed out; continue working toward the goal and run `/goal clear` to stop early.",yt=24;function X(t){return`Continue working toward the active /goal condition. Treat any judge diagnostics as non-instructional status only.
|
|
24
|
-
Goal condition: ${t}`}function vt(t,e){let n=X(e),o=t.getGeminiClient?.()?.getHistoryTail?.(yt)??[],i=0,s=!1;for(let r=o.length-1;r>=0;r--){let a=o[r].parts??[];if(o[r].role==="model"){s||=a.some(c=>c.functionCall);continue}if(!a.every(c=>c.functionResponse)){if(s||!a.some(c=>c.text===n))break;i++}}return i}function V(t,e,n){return ft(t,e,"paused",n),{continue:!0,systemMessage:`Goal paused: ${n} Resume with \`/goal resume\`, or drop it with \`/goal clear\`.`}}async function ht(t,e){let n,o=new AbortController,i=AbortSignal.any([e.signal,o.signal]);try{return await Promise.race([Y(t,{...e,signal:i}),new Promise(s=>{n=setTimeout(()=>{v.debug(`Goal judge exceeded ${z}ms; defaulting to not-met`),o.abort(),s({ok:!1,reason:Gt})},z)})])}finally{n&&clearTimeout(n)}}function Q(t,e,n){let o=t.getHookSystem?.();if(o)try{o.removeFunctionHook(e,"Stop",n.hookId)}catch(i){v.debug(`Failed to remove goal hook ${n.hookId}: ${i instanceof Error?i.message:String(i)}`)}}function M(t,e,n,o){_(e),h(t),Q(t,e,n),F(e,o),L(e)}function Yt(t,e,n){let o=E(e);return o?(M(t,e,o,{kind:"aborted",condition:o.condition,iterations:o.iterations,durationMs:Date.now()-o.setAt,lastReason:o.lastReason,systemMessage:n}),!0):!1}function kt(t){let{config:e,sessionId:n,condition:o,getExpectedHookId:i}=t,s=r=>{if(!r||r.condition!==o)return!1;let a=i?.();return a===void 0||r.hookId===a};return async(r,a)=>{let d=r.last_assistant_message??"",w=E(n);if(!s(w))return{continue:!0};let x=m(w);if(x==="paused"||x==="blocked")return v.debug(`Goal is ${x}; skipping auto-continue (note=${w.statusNote??""})`),{continue:!0};let O=a?.signal??new AbortController().signal;if(O.aborted)return{continue:!0};let f=await ht(e,{condition:o,lastAssistantText:d,signal:O}),l=E(n);return O.aborted||!s(l)||m(l)!=="active"?{continue:!0}:f.ok?(M(e,n,l,{kind:"achieved",condition:l.condition,iterations:l.iterations,durationMs:Date.now()-l.setAt,lastReason:f.reason}),{continue:!0}):f.impossible&&l.iterations>=W?(v.debug("Goal judge ruled impossible; clearing goal.",{reason:f.reason,iterations:l.iterations}),M(e,n,l,{kind:"failed",condition:l.condition,iterations:l.iterations,durationMs:Date.now()-l.setAt,lastReason:f.reason}),{continue:!0}):(f.impossible&&v.debug(`Impossible goal verdict suppressed: iterations=${l.iterations} < MIN_IMPOSSIBLE_GOAL_ITERATIONS=${W}; continuing.`),l.iterations>=N?V(e,n,`the condition is still not met after ${N} continuations. Resuming allows another ${N}.`):vt(e,o)>=q?V(e,n,`the last ${q} continuations made no tool calls, so the goal is not progressing.`):(h(e,$(n,f.reason)),{decision:"block",reason:X(o)}))}}function St(t,e,{persist:n=!0}={}){let o=_(e);if(L(e),!!o)return n&&h(t),Q(t,e,o),o}function qt(t){let{config:e,sessionId:n,condition:o,tokensAtStart:i}=t,s=e.getHookSystem();if(!s)throw new Error("Hook system is not initialized; cannot register /goal");St(e,n,{persist:!1});let r={},a=kt({config:e,sessionId:n,condition:o,getExpectedHookId:()=>r.hookId}),c=s.addFunctionHook(n,"Stop","*",a,"Goal evaluator failed",{name:"goal-stop-hook",description:`Continue until: ${o}`,statusMessage:"Checking goal\u2026",timeout:mt});r.hookId=c;let d={condition:o,status:t.initialStatus??"active",iterations:Math.max(0,t.initialIterations??0),setAt:t.initialSetAt??Date.now(),tokensAtStart:i,hookId:c,lastReason:t.initialLastReason,statusNote:t.initialStatusNote};return P(n,d),h(e,d),d}export{K as a,bt as b,At as c,E as d,P as e,_ as f,$ as g,D as h,Et as i,m as j,Ct as k,Tt as l,L as m,F as n,Rt as o,wt as p,Y as q,ft as r,Bt as s,N as t,q as u,pt as v,mt as w,Yt as x,kt as y,St as z,qt as A};
|
|
25
|
-
/**
|
|
26
|
-
* @license
|
|
27
|
-
* Copyright 2026 Matilda Team
|
|
28
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
29
|
-
*/
|
|
30
|
-
/**
|
|
31
|
-
* @license
|
|
32
|
-
* Copyright 2025 Google LLC
|
|
33
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
34
|
-
*/
|
package/chunks/chunk-HMZOLFRP.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as c}from"./chunk-HYVP4472.js";import{p as u}from"./chunk-PIFQEMZZ.js";import{b as l}from"./chunk-GZPNIYVZ.js";l();import{AsyncLocalStorage as h}from"node:async_hooks";var r=new h,a=new WeakMap,m=class{jobs=new Map;wake;closed=!1;revision=0;static get current(){return r.getStore()}run(e){return r.run(this,e)}static detached(e){return r.run(void 0,e)}static register(e,t,s){let i=s?.status==="running"?a.get(s):void 0,n=i??r.getStore();if(n){if(i&&s&&i.consume(s),e.completion==="detached"||!i&&e.status!=="running"){n.changed();return}if(a.set(e,n),n.closed){t();return}n.jobs.set(e,t),n.changed()}}static changed(e){e&&a.get(e)?.changed()}static abandoned(e){return a.get(e)?.closed===!0}static detach(e){let t=a.get(e);return!t||t.closed||!t.owns(e)||e.status!=="running"?!1:(e.completion="detached",t.consume(e),t.changed(),!0)}owns(e){return this.jobs.has(e)}consume(e){a.delete(e),this.jobs.delete(e)}get pending(){return this.jobs.size>0}get position(){return this.revision}get paused(){return[...this.jobs.keys()].some(e=>e.status==="paused")}get running(){return[...this.jobs.keys()].filter(e=>e.status==="running")}changed(){this.revision++,this.wake?.()}async wait(e,t,s){this.closed||t.aborted||e!==this.revision||await new Promise(i=>{let n,o=()=>{clearTimeout(n),t.removeEventListener("abort",o),this.wake=void 0,i()};this.wake=o,t.addEventListener("abort",o,{once:!0}),s!==void 0&&(n=setTimeout(o,s))})}close(){this.closed=!0;for(let[e,t]of this.jobs)e.status==="running"&&t();this.changed()}};function T(d,e){let t=s=>{let i=s.description.replace(/[\p{Cc}\s]+/gu," ").trim(),n=Math.max(1,Math.round((e-s.startTime)/6e4));return`background ${s.kind} "${i.length>80?`${i.slice(0,77)}...`:i}" (running ${n} min)`};return{displayText:`Still waiting on ${d.map(t).join(", ")}.`,modelText:d.map(s=>["<task-notification>",`<task-id>${c(s.id)}</task-id>`,`<kind>${s.kind}</kind>`,"<status>running</status>",`<summary>${c(`The ${t(s)} is still running, and this request cannot finish until it does. If the request needs its result, keep waiting. If it should keep running after the request, such as a server or watcher, call ${u.TASK_DETACH}. If it is no longer needed, call ${u.TASK_STOP}.`)}</summary>`,"</task-notification>"].join(`
|
|
4
|
-
`)).join(`
|
|
5
|
-
`)}}export{m as a,T as b};
|
|
6
|
-
/**
|
|
7
|
-
* @license
|
|
8
|
-
* Copyright 2026 Matilda
|
|
9
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
10
|
-
*/
|
package/chunks/chunk-ROETRE5J.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as h,f as g}from"./chunk-DCQKJTAX.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-EQEQPZLQ.js";import{aa as b,b as c}from"./chunk-VLYRNOD3.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
|
|
4
|
-
`,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
|
|
5
|
-
/**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2025 Matilda
|
|
8
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
9
|
-
*/
|
package/chunks/chunk-XJYPRCV7.js
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d as on}from"./chunk-DC7LAFZZ.js";import{b as Wt,d as qt,g as yt,j as Yt,k as Jt,s as en,v as ue}from"./chunk-S7G6QPEP.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as Xt,d as Qt}from"./chunk-SDTWBD62.js";import{Bb as de,Jc as ht,Kc as Ct,Mb as ft,Mc as Tt,Pa as Co,Pb as gt,Ra as To,Rb as mt,Sa as X,Wa as xe,Xa as ke,Ya as Ie,a as _,ab as pt,eb as Oe,f as U,fb as V,na as ut,tb as we,ub as Pe}from"./chunk-KSNBNXBC.js";import{b as rn}from"./chunk-3YLXGE6T.js";import{P as ve,T as zt,V as dt,aa as O,d as Vt,e as ae,f as le,k as at}from"./chunk-VLYRNOD3.js";import{b as lt,c as v,f as ct,g as ce,h as M,i as be,k as jt,l as x,n as J}from"./chunk-FWDMPRKU.js";import{b as g}from"./chunk-GZPNIYVZ.js";import{f as ho}from"./chunk-OWGSC52X.js";g();function Q(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function De(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function yo(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+De(t)):(t.prompt||0)+De(t)}function Ao(t){let e=Math.max(0,t.thoughtsTokens||0),n=De({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}g();g();var So=/[A-Za-z\u00C0-\u024F]/g;function Eo(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function St(t){let e=t.codePointAt(0);return e!==void 0&&Eo(e)}function _o(t){let e=t.match(So)?.length??0;if(e<24)return!1;let n=0;for(let o of t)St(o)&&n++;return n===0||e>=n*8}function Le(t){if(!t||!_o(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!St(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&St(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}g();var Z=O("TAGGED_THINKING_PARSER"),fe=["<think>","<thinking>"],ge=["</think>","</thinking>"],Mo=Math.max(...fe.map(t=>t.length),...ge.map(t=>t.length));function pe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Ue(t,e,n){let o=t.length-e;return o<=0||o>Mo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Ne(t,e,n){return n.find(o=>t.startsWith(o,e))}function _t(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function sn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Le(_t(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var Et=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Ne(o,s,fe);if(a){Z.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Ne(o,s,ge);if(l){Z.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),pe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,fe)||Ue(o,s,ge)))break}else{let a=Ne(o,s,ge);if(a){Z.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Ne(o,s,fe);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,fe)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(pe(r,i,this.mode),this.buffer=this.buffer.slice(s),Z.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),sn(r)):(this.buffer="",this.mode==="thought"&&i&&Z.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),pe(r,i,this.mode),Z.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),sn(r))}};function an(t){return new Et().parse(t,!0)}var P=O("CONVERTER"),gn="(attached media from previous tool call)";function mn(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),r>n&&(n>0||o>0||p>0)&&(d=Math.max(d,r-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,f=r;return(f===0&&(m>0||d>0)||f>0&&m>0&&f<m+d)&&(f=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:f,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ro=64,ln=1024;function cn(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=ln&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Ro?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ln&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function hn(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(e)}async function vo(t,e="auto"){let n=[];for(let o of t){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=hn(i.parameters)),s&&(s=qt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function bo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),Io(t.contents,o,e),o=fn(o),n.cleanOrphanToolCalls&&(o=Ko(o),o=fn(o)),o}function xo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let f of o)typeof f=="string"?i.push(f):"text"in f&&f.text?"thought"in f&&f.thought?r.push(f.text):i.push(f.text):"functionCall"in f&&f.functionCall&&(s.push({id:f.functionCall.id||`call_${a}`,type:"function",function:{name:f.functionCall.name||"",arguments:JSON.stringify(f.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=Go(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=t.createTime?Number(t.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Tn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Io(t,e,n){if(Array.isArray(t))for(let o of t)dn(o,e,n);else t&&dn(t,e,n)}function dn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Do(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let h=Cn(d,n);if(h&&r==="user"&&i.push(h),"functionCall"in d&&d.functionCall&&r==="assistant"){let m=d.functionCall.id;if(m){if(c.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let m=d.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let f=wo(d.functionResponse,n);if(f){if(n.splitToolMedia&&Array.isArray(f.content)){let C=[],T=[];for(let y of f.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(S=>S.text).join(`
|
|
4
|
-
`);f.content=y||"[media attached in following user message]",p.push(...C)}}e.push(f)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:gn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(f=>f.type==="text").map(f=>f.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),e.push(h);return}i.length>0&&e.push({role:"user",content:i})}function Oo(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function wo(t,e){let n=Oo(t.response),o=[];n&&o.push({type:"text",text:n});for(let r of t.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=Cn(r,e);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function Cn(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=un(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("image",i,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:z("pdf",i,e);if(r==="audio"){if(!n.audio)return z("audio",i,e);let s=Po(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("video",i,e):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",r=t.fileData.fileUri,i=t.fileData.mimeType,s=un(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:z("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:z("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:z("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function z(t,e,n){P.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
|
|
5
|
-
/extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function un(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Po(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function Do(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Tn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Tn(e)).filter(Boolean).join(`
|
|
6
|
-
`):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
|
|
7
|
-
`)||""}function Fe(t,e,n=!0){if(e.taggedThinkingParser)return e.taggedThinkingParser.parse(t,n);if(e.responseParsingOptions?.taggedThinkingTags)return an(t);if(!t)return[];let o=Le(_t(t));return o?[{text:o}]:[]}function Lo(t,e){let n=t.choices?.[0],o=new B;if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let i=n.message.reasoning_content??n.message.reasoning;i&&r.push({text:i,thought:!0})}if(n.message.content&&r.push(...Fe(n.message.content,e)),n.message.tool_calls){for(let i of n.message.tool_calls)if(i.function){let s=Wt(i.function.arguments);if(s===null)continue;r.push({functionCall:{id:i.id,name:i.function.name,args:s}})}}o.candidates=[{content:{parts:r,role:"model"},finishReason:yn(n.finish_reason),index:0,safetyRatings:[]}]}else o.candidates=[];if(o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage){let r=t.choices?.[0]?.message,i=r?.reasoning_content??r?.reasoning??"",s=typeof r?.content=="string"?r.content:"";o.usageMetadata=mn(t.usage,{estimatedReasoningTokens:Q(i.length),estimatedContentTokens:Q(s.length)})}return o}function Uo(t,e){let n=t.choices?.[0],o=new B,r=e.toolCallParser;if(!r)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let c=n.delta?.reasoning_content??n.delta?.reasoning;if(c){let u=cn(c,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});u&&i.push({text:u,thought:!0})}}if(typeof n.delta?.content=="string"){let c=cn(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(c||n.finish_reason)&&i.push(...Fe(c,e,!!n.finish_reason))}else n.finish_reason&&i.push(...Fe("",e,!0));if(n.delta?.tool_calls)for(let c of n.delta.tool_calls){let u=c.index??0;c.function?.arguments?r.addChunk(u,c.function.arguments,c.id,c.function.name):r.addChunk(u,"",c.id,c.function?.name)}let s=!1;if(n.finish_reason){s=r.hasIncompleteToolCalls();let c=r.getCompletedToolCalls();for(let u of c)u.name&&i.push({functionCall:{id:u.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:u.name,args:u.args}})}let a=s&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:i,role:"model"},index:0,safetyRatings:[]};a&&(l.finishReason=yn(a)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=mn(t.usage,Fo(e))),o}function No(t){let e=t.toolCallParser;if(!e)return null;let n=[],o=e.getStrictCompletedToolCalls(),r=e.hasIncompleteToolCalls();for(let s of o)s.name&&n.push({functionCall:{id:s.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:s.name,args:s.args}});if(n.push(...Fe("",t,!0)),n.length===0&&!r)return null;let i=new B;return i.candidates=[{content:{parts:n,role:"model"},index:0,safetyRatings:[],finishReason:r?A.MAX_TOKENS:A.STOP}],i.responseId=`stream-flush-${Date.now()}`,i.createTime=new Date().getTime().toString(),i.modelVersion=t.model,i.promptFeedback={safetyRatings:[]},i}function Fo(t){return{estimatedReasoningTokens:Q(t.reasoningDeltaState?.emittedLength??0),estimatedContentTokens:Q(t.textDeltaState?.emittedLength??0)}}function yn(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function Go(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Mt(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function pn(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===gn}function Ko(t){let e=[],n=new Map,o=new Map,r=new Map,i=new Set,s=new Set;for(let a=0;a<t.length;a+=1){let l=t[a];if(Mt(l)){let c=[],u=new Set;for(let C of l.tool_calls){let T=C.id;!T||s.has(T)||u.has(T)||(u.add(T),c.push(C))}let p=new Set,d=[],h=[],m=!1;for(let C=a+1;C<t.length;C+=1){let T=t[C];if(T.role==="tool"&&"tool_call_id"in T){if(!T.tool_call_id){m=!1;continue}u.has(T.tool_call_id)&&!p.has(T.tool_call_id)?(p.add(T.tool_call_id),d.push(C),m=!0):m=!1;continue}if(pn(T)){m&&h.push(C);continue}if(!(T.role==="assistant"&&!Mt(T)))break}let f=c.filter(C=>p.has(C.id));for(let C of f)s.add(C.id);n.set(a,f),o.set(a,d),r.set(a,h)}}for(let a=0;a<t.length;a+=1){if(i.has(a))continue;let l=t[a];if(Mt(l)){let c=l.reasoning_content,u=n.get(a)??[];if(u.length>0){let p={...l};p.tool_calls=u,e.push(p);for(let d of o.get(a)??[]){let h=t[d];h&&(e.push(h),i.add(d))}for(let d of r.get(a)??[]){let h=t[d];h&&(e.push(h),i.add(d))}}else if(typeof l.content=="string"&&l.content.trim()||c){let p={...l};delete p.tool_calls,e.push(p)}else P.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?P.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):pn(l)?P.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function fn(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let r="tool_calls"in o?o.tool_calls||[]:[],i="tool_calls"in n?n.tool_calls||[]:[],s=o.content,a=n.content,l=Array.isArray(s)||Array.isArray(a),c;if(l){let p=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[],d=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[];c=[...p,...d]}else c=[typeof s=="string"?s:"",typeof a=="string"?a:""].filter(Boolean).join("")||null;let u=[...r,...i];o.content=c||null,u.length>0&&(o.tool_calls=u);continue}}e.push(n)}return e}var Ge={convertGeminiToolParametersToOpenAI:hn,convertGeminiToolsToOpenAI:vo,convertGeminiRequestToOpenAI:bo,convertGeminiResponseToOpenAI:xo,convertOpenAIResponseToGemini:Lo,convertOpenAIChunkToGemini:Uo,flushOpenAIStreamToGemini:No};g();import*as I from"node:path";import{promises as He}from"node:fs";g();g();import $o from"crypto";var $e=new Uint8Array(256),Ke=$e.length;function Rt(){return Ke>$e.length-16&&($o.randomFillSync($e),Ke=0),$e.slice(Ke,Ke+=16)}g();var E=[];for(let t=0;t<256;++t)E.push((t+256).toString(16).slice(1));function An(t,e=0){return E[t[e+0]]+E[t[e+1]]+E[t[e+2]]+E[t[e+3]]+"-"+E[t[e+4]]+E[t[e+5]]+"-"+E[t[e+6]]+E[t[e+7]]+"-"+E[t[e+8]]+E[t[e+9]]+"-"+E[t[e+10]]+E[t[e+11]]+E[t[e+12]]+E[t[e+13]]+E[t[e+14]]+E[t[e+15]]}g();g();import Ho from"crypto";var vt={randomUUID:Ho.randomUUID};function Bo(t,e,n){if(vt.randomUUID&&!e&&!t)return vt.randomUUID();t=t||{};let o=t.random||(t.rng||Rt)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=o[r];return e}return An(o)}var bt=Bo;import*as N from"os";var Be=O("OPENAI_LOGGER"),Vo="########",jo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function zo(t,e){let n=e||process.cwd();if(!t)return I.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=I.join(N.homedir(),t.slice(1)):I.isAbsolute(t)||(o=I.resolve(n,t)),I.normalize(o)}function Sn(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function Wo(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function qo(t){if(t)return X(t)?Sn(t):Sn(Wo(t))}function Yo(t){if(!t)return;let e=t.indexOf(Vo);if(e>0)return t.slice(0,e);if(jo.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function Jo(t){let e=t?.trim(),n=Yo(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var me=class{logDir;initialized=!1;constructor(e,n){this.logDir=zo(e,n)}async initialize(){if(!this.initialized)try{await He.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw Be.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,r){this.initialized||await this.initialize();let i=new Date().toISOString().replace(/:/g,"-"),s=bt().slice(0,8),a=qo(r),l=a?`openai-${i}-${s}-${a}.json`:`openai-${i}-${s}.json`,c=I.join(this.logDir,l),u={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:Jo(r),system:{hostname:N.hostname(),platform:N.platform(),release:N.release(),nodeVersion:process.version}};try{return await He.writeFile(c,JSON.stringify(u,null,2),"utf-8"),c}catch(p){throw Be.error("Failed to write OpenAI log file:",p),new Error(`Failed to write OpenAI log file: ${p}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await He.readdir(this.logDir)).filter(r=>r.startsWith("openai-")&&r.endsWith(".json")).map(r=>I.join(this.logDir,r)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(Be.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await He.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw Be.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Vs=new me;g();g();J();To();g();J();var En=ho(Co(),1);import{createHash as Xo}from"node:crypto";var ee="matilda.telemetry.traceparent",Ve="matilda.telemetry.tracestate",Qo="matilda-code.daemon.request",_n="matilda-code.daemon.bridge",Zo="matilda-code.daemon.error";function er(t){return t instanceof Error?t.message:String(t)}function tr(t){return t instanceof Error?t.name||"Error":typeof t}var nr="0".repeat(32),or="0".repeat(16);function rr(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t;if(!(ee in e)&&!(Ve in e))return{...e};let n={...e};return delete n[ee],delete n[Ve],n}function ir(t){return Xo("sha256").update(t).digest("hex").slice(0,16)}async function xt(t,e,n,o={}){if(!de())return await n(void 0);let r=o.autoOkOnSuccess??!0;return await x.getTracer(_).startActiveSpan(t,{kind:ct.INTERNAL,attributes:e},async s=>{try{let a=await n(s);return r&&s.setStatus({code:ce.OK}),a}catch(a){throw Rn(s,a),a}finally{s.end()}})}async function sr(t,e){return await xt(Qo,{"http.request.method":t.method,"http.route":t.route,"matilda-code.daemon.operation":"http_request",...t.workspaceHash?{"matilda-code.workspace.hash":t.workspaceHash}:{},...t.sessionId?{"session.id":t.sessionId}:{},...t.clientId?{"matilda-code.client_id":t.clientId}:{},...t.permissionRequestId?{"matilda-code.daemon.permission.request_id":t.permissionRequestId}:{}},e,{autoOkOnSuccess:!1})}async function Mn(t,e,n){return await xt(_n,{"matilda-code.daemon.operation":t,...e},async()=>await n())}function ar(t,e){try{t?.setAttribute("http.response.status_code",e)}catch{}}function lr(t,e){try{x.getSpan(M.active())?.setAttribute(t,e)}catch{}}function Rn(t,e,n={}){let o=t??x.getSpan(M.active());if(o)try{let r=pt(er(e));o.recordException(e instanceof Error?e:new Error(r)),o.setAttributes({"error.type":tr(e),"error.message":r,...n}),o.setStatus({code:ce.ERROR,message:r})}catch{}}function cr(t,e={},n){if(de())try{En.logs.getLogger(_).emit({body:t,timestamp:new Date,attributes:{"event.name":n?.eventName??Zo,...e},...n?.severityNumber!=null?{severityNumber:n.severityNumber}:{}})}catch{}}function vn(){return{context:M.active()}}async function bn(t,e){let n=t&&typeof t=="object"&&"context"in t&&t.context?t.context:void 0;return n?await M.with(n,e):await e()}function xn(t){let e=t._meta,n=rr(e);try{let o=zt();o&&(n[ee]=dt(o))}catch{}return!e&&!n[ee]?t:{...t,_meta:n}}function dr(t){let e=t?._meta;if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,o=n[ee];if(typeof o!="string"||o.length===0)return;let r={traceparent:o},i=n[Ve];typeof i=="string"&&i.length>0&&(r.tracestate=i);let s=jt.extract(lt,r);if(x.getSpanContext(s))return s;let a=o.split("-"),l=a[1],c=a[2],u=a[3];if(!(a[0]!=="00"||!l?.match(/^[0-9a-f]{32}$/)||!c?.match(/^[0-9a-f]{16}$/)||!u?.match(/^[0-9a-f]{2}$/)||l===nr||c===or))return x.setSpan(lt,x.wrapSpanContext({traceId:l,spanId:c,traceFlags:Number.parseInt(u,16),isRemote:!0}))}function ur(){return{captureContext:vn,runWithContext:bn,withSpan:Mn,event(t,e){if(de())try{let n=x.getSpan(M.active());if(n){n.addEvent(t,e);return}let o=x.getTracer(_).startSpan(_n,{kind:ct.INTERNAL,attributes:{"event.name":t,"matilda-code.daemon.operation":`event.${t}`,...e}});o.addEvent(t,e),o.setStatus({code:ce.OK}),o.end()}catch{}},injectPromptContext:xn}}g();J();var pr=`${_}.daemon.http.request.count`,fr=`${_}.daemon.http.request.duration`,gr=`${_}.daemon.session.active`,mr=`${_}.daemon.session.lifecycle`,hr=`${_}.daemon.channel.lifecycle`,Cr=`${_}.daemon.prompt.queue_wait`,Tr=`${_}.daemon.prompt.duration`,yr=`${_}.daemon.bridge.error.count`,Ar=`${_}.daemon.cancel.count`,Sr=`${_}.daemon.sse.active`,Er=`${_}.daemon.process.heap_used`,_r=new Set(["SessionNotFoundError","WorkspaceMismatchError","InvalidClientIdError","SessionLimitExceededError","RestoreInProgressError","InvalidSessionScopeError","TrustGateError","WorkspaceInitConflictError","WorkspaceInitPathEscapeError","WorkspaceInitSymlinkError","WorkspaceInitRaceError","McpServerNotFoundError","McpServerRestartFailedError","PromptDeadlineExceededError","InvalidSessionMetadataError","SubscriberLimitExceededError","BridgeChannelClosedError","BridgeTimeoutError","PermissionForbiddenError"]),D=!1,In,On,wn,Pn,Dn,Ln,Un,Nn;function Mr(t){let e=t instanceof Error?t.name:typeof t;return _r.has(e)?e:"unknown"}function Rr(){if(D)return;let t=ut();t&&(In=t.createCounter(pr,{description:"Daemon HTTP request count by route and status class.",valueType:v.INT}),On=t.createHistogram(fr,{description:"Daemon HTTP request duration in milliseconds.",unit:"ms",valueType:v.DOUBLE,advice:{explicitBucketBoundaries:[1,2,5,10,25,50,100,250,500,1e3,2500,5e3,1e4,3e4]}}),wn=t.createCounter(mr,{description:"Daemon session lifecycle events (spawn, close, die).",valueType:v.INT}),Pn=t.createCounter(hr,{description:"Daemon ACP channel lifecycle events (spawn, exit).",valueType:v.INT}),Dn=t.createHistogram(Cr,{description:"Time a prompt waited in the per-session FIFO queue.",unit:"ms",valueType:v.DOUBLE,advice:{explicitBucketBoundaries:[1,5,10,50,100,500,1e3,5e3,1e4,3e4,6e4]}}),Ln=t.createHistogram(Tr,{description:"End-to-end prompt duration from dispatch to completion.",unit:"ms",valueType:v.DOUBLE,advice:{explicitBucketBoundaries:[100,500,1e3,2500,5e3,1e4,3e4,6e4,12e4,3e5,6e5]}}),Un=t.createCounter(yr,{description:"Daemon bridge error count by normalized error type.",valueType:v.INT}),Nn=t.createCounter(Ar,{description:"Daemon cancel request count.",valueType:v.INT}),D=!0)}var kn=!1;function vr(t){if(kn)return;let e=ut();e&&(e.createObservableGauge(gr,{description:"Current number of active daemon sessions.",valueType:v.INT}).addCallback(n=>{try{n.observe(t.sessionCount())}catch{}}),e.createObservableGauge(Sr,{description:"Current number of active SSE connections.",valueType:v.INT}).addCallback(n=>{try{n.observe(t.sseCount())}catch{}}),e.createObservableGauge(Er,{description:"Daemon process heap memory usage in bytes.",unit:"bytes",valueType:v.INT}).addCallback(n=>{try{n.observe(t.heapUsed())}catch{}}),kn=!0)}function br(t,e,n){if(!D)return;let o=`${Math.floor(n/100)}xx`;In?.add(1,{route:e,status_class:o}),On?.record(t,{route:e})}function xr(t){D&&wn?.add(1,{action:t})}function kr(t,e){D&&Pn?.add(1,{action:t,...e!=null?{expected:e}:{}})}function Ir(t){D&&Dn?.record(t)}function Or(t){D&&Ln?.record(t)}function wr(t){D&&Un?.add(1,{error_type:Mr(t)})}function Pr(){D&&Nn?.add(1)}g();J();import*as K from"node:fs";import*as st from"node:path";g();g();g();g();J();g();import{AsyncLocalStorage as Dr}from"node:async_hooks";var Fn=new Dr;g();function Gn(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Lr)}function Lr(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}function Kn(){let t=Xt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var W=O("LOGGING_CONTENT_GENERATOR"),Ur=4096,$n="...[truncated]",Nr=Ur-$n.length,he=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new me(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let r=JSON.stringify(e);ft(this.config,new ht(n,o,r,U.getStore()))}_logApiResponse(e,n,o,r,i,s){mt(this.config,new Tt(e,o,n,r,this.generatorAuthType,i,s,U.getStore()))}_logApiError(e,n,o,r,i){let s=Vt(o),a=le(o),l=o?.requestID||o?.request_id||e,c=ae(o);gt(this.config,new Ct({responseId:l,model:r,durationMs:n,promptId:i,authType:this.generatorAuthType,errorMessage:s,errorType:a,statusCode:c,subagentName:U.getStore()}))}safelyLogApiError(e,n,o,r,i){try{this._logApiError(e,n,o,r,i)}catch(s){W.warn("Failed to log API error:",s)}}safelyLogApiResponse(e,n,o,r,i,s){try{this._logApiResponse(e,n,o,r,i,s)}catch(a){W.warn("Failed to log API response:",a)}}getClientVisibleModelId(e,n){return("isManagedMatildaModel"in this.config&&typeof this.config.isManagedMatildaModel=="function"?this.config.isManagedMatildaModel(e):!1)&&"getPublicModelId"in this.config&&typeof this.config.getPublicModelId=="function"?this.config.getPublicModelId(e):n||e}async generateContent(e,n){let o=Kn(),r=Oe(e.model,n);try{r.setAttribute("llm_request.stream",!1)}catch{}let i=x.setSpan(M.active(),r),s=Date.now(),a=X(n),l=this.startCaptureSession();try{yt.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),a||(xe(this.config,r,e.config?.systemInstruction),ke(this.config,r,e.config?.tools));let c=await M.with(i,async()=>{a||this.logApiRequest(this.toContents(e.contents),e.model,n);let u=await l.wrap(()=>this.wrapped.generateContent(e,n)),p=Date.now()-s,d=a?void 0:this.extractResponseText(u);a||Ie(this.config,r,d),this.safelyLogApiResponse(u.responseId??"",p,this.getClientVisibleModelId(e.model,u.modelVersion),n,u.usageMetadata,d);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),u,void 0,n)}catch(h){W.warn("Failed to log OpenAI interaction:",h)}return u});return V(r,{success:!0,inputTokens:c.usageMetadata?.promptTokenCount,outputTokens:c.usageMetadata?.candidatesTokenCount,cachedInputTokens:c.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-s,responseId:c.responseId||void 0,finishReason:c.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:c.usageMetadata?.thoughtsTokenCount,subagentName:U.getStore()||void 0,...o}),c}catch(c){let u=Date.now()-s,p=e.config?.abortSignal?.aborted??!1;throw V(r,{success:!1,durationMs:u,error:p?Pe:we,errorType:le(c),errorStatusCode:ae(c),subagentName:U.getStore()||void 0,...o}),await M.with(i,async()=>{this.safelyLogApiError("",u,c,this.getClientVisibleModelId(e.model),n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,c,n)}catch(d){W.warn("Failed to log OpenAI interaction:",d)}}),c}}async generateContentStream(e,n){let o=Kn(),r=Oe(e.model,n);try{r.setAttribute("llm_request.stream",!0)}catch{}let i=x.setSpan(M.active(),r),s=Date.now(),a=X(n),l=this.startCaptureSession(),c;try{yt.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),a||(xe(this.config,r,e.config?.systemInstruction),ke(this.config,r,e.config?.tools)),c=await M.with(i,async()=>(a||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(p){let d=Date.now()-s;M.with(i,()=>this.safelyLogApiError("",d,p,e.model,n));let h=e.config?.abortSignal?.aborted??!1;V(r,{success:!1,durationMs:d,error:h?Pe:we,errorType:le(p),errorStatusCode:ae(p),subagentName:U.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,p,n)}catch(m){W.warn("Failed to log OpenAI interaction:",m)}throw p}let u;if(this.openaiLogger)try{u=await l.resolve(e)}catch(p){W.warn("Failed to resolve OpenAI request:",p)}return M.with(i,()=>this.loggingStreamWrapper(c,s,n,e.model,u,r,i,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():Fn.run(r=>{e=r},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,r,i,s,a,l,c){let u=X(o),p=!u||!!this.openaiLogger,d=[],h="",m="",f,C=!1,T,y=!1,S,R=U.getStore(),$,H=!1,L=b=>a?M.with(a,b):b(),mo=5*6e4,w,$t=s?()=>{H||(w!==void 0&&clearTimeout(w),w=setTimeout(()=>{try{s.setAttribute("stream.timed_out",!0)}catch{}V(s,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:h||void 0,subagentName:R||void 0,...c}),H=!0},mo),w.unref())}:void 0;$t?.();try{for await(let k of e){!h&&k.responseId&&(h=k.responseId),!m&&k.modelVersion&&(m=k.modelVersion),p&&d.push(k),k.usageMetadata&&(f=k.usageMetadata);let Bt=k.candidates?.[0];Bt?.finishReason&&(T=Bt.finishReason),k.functionCalls?.length&&(y=!0),$===void 0&&Gn(k)&&($=Date.now()-n),$t?.(),yield k}w!==void 0&&(clearTimeout(w),w=void 0);let b=Date.now()-n,ie=p?this.consolidateGeminiResponsesForLogging(d):void 0,Ht=u?void 0:this.extractResponseText(ie),se=!T&&!y?new Error("Model stream ended without a finish reason"):void 0;se&&(C=!0,S=se),H||(se?(L(()=>this.safelyLogApiError(h,b,se,this.getClientVisibleModelId(r,m),o)),await L(()=>this.safelyLogOpenAIInteraction(i,ie,se,o))):(L(()=>this.safelyLogApiResponse(h,b,this.getClientVisibleModelId(r,m),o,f,Ht)),!u&&s&&Ie(this.config,s,Ht),await L(()=>this.safelyLogOpenAIInteraction(i,ie,void 0,o))))}catch(b){if(C=!0,S=b,!H){let ie=Date.now()-n;L(()=>this.safelyLogApiError(h,ie,b,this.getClientVisibleModelId(r,m),o)),await L(()=>this.safelyLogOpenAIInteraction(i,void 0,b,o))}throw b}finally{if(w!==void 0&&clearTimeout(w),s&&!H){let b=l?.aborted??!1;V(s,{success:!C,inputTokens:f?.promptTokenCount,outputTokens:f?.candidatesTokenCount,cachedInputTokens:f?.cachedContentTokenCount,ttftMs:$,durationMs:Date.now()-n,error:C?b?Pe:we:void 0,responseId:h||void 0,finishReason:T,thoughtsTokenCount:f?.thoughtsTokenCount,subagentName:R||void 0,errorType:S?le(S):void 0,errorStatusCode:S?ae(S):void 0,...c})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=Ge.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),r={model:e.model,messages:o};return e.config?.tools&&(r.tools=await Ge.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(r.temperature=e.config.temperature),e.config?.topP!==void 0&&(r.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(r.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(r.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(r.frequency_penalty=e.config.frequencyPenalty),r}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,r){if(!this.openaiLogger||!e)return;let i=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,i,o instanceof Error?o:o?new Error(String(o)):void 0,r)}async safelyLogOpenAIInteraction(e,n,o,r){try{await this.logOpenAIInteraction(e,n,o,r)}catch(i){W.warn("Failed to log OpenAI interaction:",i)}}convertGeminiResponseToOpenAIForLogging(e,n){let o=new B;return Object.assign(o,e),o.modelVersion=this.getClientVisibleModelId(n.model,e.modelVersion),Ge.convertGeminiResponseToOpenAI(o,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new B,o=[],r=new Map,i,s;for(let c of e){c.usageMetadata&&(s=c.usageMetadata);let u=c.candidates?.[0];u?.finishReason&&(i=u.finishReason);let p=u?.content?.parts??[];for(let d of p){if(typeof d=="string"){o.push({text:d});continue}if("text"in d){d.text&&o.push({text:d.text,...d.thought?{thought:!0}:{},...d.thoughtSignature?{thoughtSignature:d.thoughtSignature}:{}});continue}if("functionCall"in d&&d.functionCall){let h=d.functionCall.id||d.functionCall.name||"tool_call",m=r.get(h),f={functionCall:d.functionCall};m!==void 0?o[m]=f:(r.set(h,o.length),o.push(f));continue}if("functionResponse"in d&&d.functionResponse){o.push({functionResponse:d.functionResponse});continue}o.push(d)}}let a=e[e.length-1],l=a.candidates?.[0];return n.responseId=a.responseId,n.createTime=a.createTime,n.modelVersion=a.modelVersion,n.promptFeedback=a.promptFeedback,n.usageMetadata=s,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...i?{finishReason:i}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",r=!1,i=!1,s=a=>{if(r=!0,i)return;let l=Nr-o.length;if(a.length<=l){o+=a;return}o+=a.slice(0,Math.max(0,l)),i=!0};for(let a of n){if(typeof a=="string"){s(a);continue}"text"in a&&typeof a.text=="string"&&!("thought"in a&&a.thought)&&s(a.text)}if(r)return i?`${o}${$n}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let i=o.text,s=i?String(i):"",a=s?`${s}
|
|
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
|
-
`,()=>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
|
-
`));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-HVIGLQJZ.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-X6TFPZGL.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-W2DQO2NK.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-5VOBYNAJ.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-APSI54U5.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
|
-
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
|
-
`,"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
|
-
/**
|
|
15
|
-
* @license
|
|
16
|
-
* Copyright 2026 Matilda Team
|
|
17
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
18
|
-
*/
|
|
19
|
-
/**
|
|
20
|
-
* @license
|
|
21
|
-
* Copyright 2025 Matilda
|
|
22
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
23
|
-
*/
|
|
24
|
-
/**
|
|
25
|
-
* @license
|
|
26
|
-
* Copyright 2025 Google LLC
|
|
27
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
28
|
-
*/
|
|
29
|
-
/**
|
|
30
|
-
* @license
|
|
31
|
-
* Copyright 2025 Matilda Team
|
|
32
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
33
|
-
*/
|
|
34
|
-
/**
|
|
35
|
-
* @license
|
|
36
|
-
* Copyright 2026 Maincode
|
|
37
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
38
|
-
*
|
|
39
|
-
* Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
|
|
40
|
-
* (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
|
|
41
|
-
* grant, and refresh. Vendored (as source) from matilda-core's
|
|
42
|
-
* `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
|
|
43
|
-
* (display identity) that the higher-level flows need. Node built-ins only —
|
|
44
|
-
* no third-party runtime dependencies.
|
|
45
|
-
*/
|
|
46
|
-
/**
|
|
47
|
-
* @license
|
|
48
|
-
* Copyright 2026 Maincode
|
|
49
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
50
|
-
*
|
|
51
|
-
* File-backed token store + cross-process lock. The store persists a JSON map
|
|
52
|
-
* (`{ [key]: value }`) at 0600 so callers can key several credentials in one
|
|
53
|
-
* file; the lock is an O_EXCL lockfile that serialises refreshes across
|
|
54
|
-
* processes (the guarantee a plaintext read/modify/write can't give).
|
|
55
|
-
*/
|
|
56
|
-
/**
|
|
57
|
-
* @license
|
|
58
|
-
* Copyright 2026 Maincode
|
|
59
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
60
|
-
*
|
|
61
|
-
* Hardened access-token manager: returns a valid access token, refreshing via
|
|
62
|
-
* core-auth's token endpoint when expired or forced. Single-flight within the
|
|
63
|
-
* process, serialised across processes by the store's lock, carries a prior
|
|
64
|
-
* refresh token forward when the response omits one, and evicts on a terminal
|
|
65
|
-
* `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
|
|
66
|
-
*/
|
|
67
|
-
/**
|
|
68
|
-
* @license
|
|
69
|
-
* Copyright 2026 Maincode
|
|
70
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
71
|
-
*
|
|
72
|
-
* Browser login orchestration: PKCE + a loopback capture server, driven off
|
|
73
|
-
* discovery metadata. Unlike a bare loopback helper, this emits lifecycle
|
|
74
|
-
* events for a UI, honours an AbortSignal, and — instead of serving its own
|
|
75
|
-
* HTML — 302-redirects the browser to an app-owned branded landing
|
|
76
|
-
* (`successRedirect`). Returns a TokenSet including the `id_token`.
|
|
77
|
-
*/
|
|
78
|
-
/**
|
|
79
|
-
* @license
|
|
80
|
-
* Copyright 2026 Maincode
|
|
81
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
82
|
-
*
|
|
83
|
-
* Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
|
|
84
|
-
* Re-exports the OAuth primitives plus the higher-level login flow, file token
|
|
85
|
-
* store, and hardened token manager that the CLI (`packages/core`) and the
|
|
86
|
-
* Electron desktop app consume.
|
|
87
|
-
*/
|
|
88
|
-
/**
|
|
89
|
-
* @license
|
|
90
|
-
* Copyright 2026 Maincode
|
|
91
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
92
|
-
*
|
|
93
|
-
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
94
|
-
*
|
|
95
|
-
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
96
|
-
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
97
|
-
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
98
|
-
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
99
|
-
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
100
|
-
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
101
|
-
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
102
|
-
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
103
|
-
*/
|
|
104
|
-
/**
|
|
105
|
-
* @license
|
|
106
|
-
* Copyright 2026 Matilda
|
|
107
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
108
|
-
*/
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{c as a,d as b,e as c}from"./chunk-H6WMNUW2.js";import"./chunk-GWGQRU36.js";import"./chunk-6ZMDAPGZ.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-TISQNFB5.js";import"./chunk-6Q6PMGBD.js";import"./chunk-MTMU7JYZ.js";import"./chunk-RNKDFE2S.js";import"./chunk-BN2CPSZ5.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-HMZOLFRP.js";import"./chunk-QKYGQLWC.js";import"./chunk-SE3XDSIJ.js";import"./chunk-VWWEEU4V.js";import"./chunk-HYVP4472.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-X6BEBYGX.js";import"./chunk-QHA3ZBRO.js";import"./chunk-XJYPRCV7.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-KSNBNXBC.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-2PPJ3MJT.js";import"./chunk-PIFQEMZZ.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};
|
package/chunks/glob-NPEYXTA6.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{Ue as _,Ve as j}from"./chunk-6ZMDAPGZ.js";import"./chunk-TZIDSCTF.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-TISQNFB5.js";import"./chunk-6Q6PMGBD.js";import"./chunk-MTMU7JYZ.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-BN2CPSZ5.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-HMZOLFRP.js";import"./chunk-QKYGQLWC.js";import"./chunk-SE3XDSIJ.js";import"./chunk-VWWEEU4V.js";import"./chunk-HYVP4472.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-X6BEBYGX.js";import"./chunk-QHA3ZBRO.js";import"./chunk-XJYPRCV7.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-KSNBNXBC.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-32PTAACU.js";import"./chunk-2PPJ3MJT.js";import{g as M,i as C,p as N,q as A}from"./chunk-PIFQEMZZ.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
|
-
|
|
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
|
-
|
|
7
|
-
[Search stopped after scanning ${B} entries. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:"";if(!l||l.length===0)return{llmContent:`No files found matching pattern "${this.params.pattern}" ${r}${p}`,returnDisplay:o?"No files found (search truncated)":"No files found"};let d=24*60*60*1e3,P=new Date().getTime(),m=K(l,P,d),h=m.length,f=Math.min(Y,this.config.getTruncateToolOutputLines()),y=h>f,b=(y?m.slice(0,f):m).map(i=>i.fullpath()),X=b.join(`
|
|
8
|
-
`),w=`Found ${h} file(s) matching "${this.params.pattern}" ${r}`;if(w+=`, sorted by modification time (newest first):
|
|
9
|
-
---
|
|
10
|
-
${X}`,y){let i=h-f;w+=`
|
|
11
|
-
---
|
|
12
|
-
[${i} ${i===1?"file":"files"} truncated] ...`}return w+=p,{llmContent:w,returnDisplay:`Found ${h} matching file(s)${y?" (truncated)":""}`,resultFilePaths:b}}catch(e){let r=e instanceof Error?e.message:String(e);V.error(`GlobLogic execute Error: ${r}`,e);let s=`Error during glob search operation: ${r}`;return{llmContent:s,returnDisplay:`Error: ${r||"An unexpected error occurred."}`,error:{message:s,type:"glob_execution_error"}}}}getFileFilteringOptions(){let t=this.config.getFileFilteringOptions?.();return{respectGitIgnore:t?.respectGitIgnore??D.respectGitIgnore,respectMatildaIgnore:t?.respectMatildaIgnore??D.respectMatildaIgnore}}},U=class u extends C{constructor(t){super(u.Name,A.GLOB,`Fast file pattern matching tool that works with any codebase size
|
|
13
|
-
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
14
|
-
- Returns matching file paths sorted by modification time
|
|
15
|
-
- Use this tool when you need to find files by name patterns
|
|
16
|
-
- When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead
|
|
17
|
-
- You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`,"search",{properties:{pattern:{description:"The glob pattern to match files against",type:"string"},path:{description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',type:"string"}},required:["pattern"],type:"object"});this.config=t}static Name=N.GLOB;validateToolParamValues(t){if(!t.pattern||typeof t.pattern!="string"||t.pattern.trim()==="")return"The 'pattern' parameter cannot be empty.";if(t.path){t.path=$(t.path.trim());try{v(this.config,t.path,{allowExternalPaths:!0})}catch(e){return x(e)}}return null}createInvocation(t){return new S(this.config,t)}};export{U as GlobTool,B as MAX_SCAN_ENTRIES,W as MAX_SCAN_MS,K as sortFileEntries};
|
|
18
|
-
/**
|
|
19
|
-
* @license
|
|
20
|
-
* Copyright 2025 Google LLC
|
|
21
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
22
|
-
*/
|