@maincode-ai/matilda-code 0.19.6 → 0.19.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/chunks/{agent-NN3YCAQH.js → agent-JAZ2R5P5.js} +1 -1
  2. package/chunks/{agent-headless-GCUE63J5.js → agent-headless-HUDZQCLT.js} +1 -1
  3. package/chunks/{anthropicContentGenerator-CZLOMDXF.js → anthropicContentGenerator-DKMAJXYA.js} +1 -1
  4. package/chunks/{chunk-RAHHGBHX.js → chunk-4EZRS6DY.js} +1 -1
  5. package/chunks/{chunk-TZIIADJW.js → chunk-4ROBKRWY.js} +2 -2
  6. package/chunks/{chunk-NRPYZBZX.js → chunk-DF4ZZ3BH.js} +1 -1
  7. package/chunks/chunk-GTR4V2PV.js +8 -0
  8. package/chunks/{chunk-ETVBCNID.js → chunk-MHGRKMUG.js} +1 -1
  9. package/chunks/{chunk-OREAJC5D.js → chunk-UOF5DCHP.js} +10 -3
  10. package/chunks/{chunk-OGLMWPGR.js → chunk-YCINFF22.js} +2 -2
  11. package/chunks/{computer-use-AM62LD63.js → computer-use-BCNVOJO6.js} +1 -1
  12. package/chunks/{contextCommand-CWNMYXES.js → contextCommand-7XW5T2FM.js} +1 -1
  13. package/chunks/{edit-PJD2ABCG.js → edit-O5534MIA.js} +1 -1
  14. package/chunks/{enter-worktree-MTT3VNXA.js → enter-worktree-NWECAVR5.js} +1 -1
  15. package/chunks/{enterPlanMode-KJSXKSQX.js → enterPlanMode-Z5CC6RK4.js} +1 -1
  16. package/chunks/{exit-worktree-CX2HMIRN.js → exit-worktree-5QTROW2K.js} +1 -1
  17. package/chunks/{exitPlanMode-QQ7DSRYT.js → exitPlanMode-VT42OYWF.js} +1 -1
  18. package/chunks/{geminiContentGenerator-HZHMNMGX.js → geminiContentGenerator-DROE6XUC.js} +1 -1
  19. package/chunks/{glob-L6LCKWIV.js → glob-FWADRNRL.js} +1 -1
  20. package/chunks/{grep-PIJYRFHS.js → grep-OFTEAZOC.js} +1 -1
  21. package/chunks/{matildaAgentContentGenerator-Y2ECTUZO.js → matildaAgentContentGenerator-J3PXQMRW.js} +1 -1
  22. package/chunks/{matildaContentGenerator-HATVJLJF.js → matildaContentGenerator-6WVY252A.js} +1 -1
  23. package/chunks/{monitor-A3RDX2JT.js → monitor-W2IPT7L4.js} +1 -1
  24. package/chunks/{notebook-edit-5KEG5MTP.js → notebook-edit-E2RFMINC.js} +1 -1
  25. package/chunks/{openaiContentGenerator-XI6SCJ2G.js → openaiContentGenerator-PGCPCIUM.js} +1 -1
  26. package/chunks/{ripGrep-PXECRMR2.js → ripGrep-CKRSCA2H.js} +1 -1
  27. package/chunks/{scheduler-XG6XEE2W.js → scheduler-AQ72BFMX.js} +1 -1
  28. package/chunks/{serve-RZQK4PGY.js → serve-VAU7AZ4D.js} +1 -1
  29. package/chunks/{shell-CGATWESB.js → shell-LMX4PBFS.js} +1 -1
  30. package/chunks/{src-D4A3YMBH.js → src-3ZEKD73Z.js} +1 -1
  31. package/chunks/{team-create-WADAQUBF.js → team-create-YCCOH5ZI.js} +1 -1
  32. package/chunks/{web-search-XR5V4QRH.js → web-search-LUARHW3X.js} +1 -1
  33. package/chunks/{workflow-NTYIHQG2.js → workflow-7JKMNIOX.js} +2 -2
  34. package/chunks/{write-file-THZKUU47.js → write-file-QR6KKYVC.js} +1 -1
  35. package/cli.js +371 -371
  36. package/package.json +2 -2
  37. package/chunks/chunk-FSRNEJQB.js +0 -8
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Af as c,Bf as d,Cf as e,Df as f,yf as a,zf as b}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.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};
3
+ import{Af as c,Bf as d,Cf as e,Df as f,yf as a,zf as b}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.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 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{$e as c,Ze as a,_e as b}from"./chunk-OREAJC5D.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-FSRNEJQB.js";import"./chunk-S4K76QPI.js";import"./chunk-RAHHGBHX.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.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};
3
+ import{$e as c,Ze as a,_e as b}from"./chunk-UOF5DCHP.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-4EZRS6DY.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.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};
@@ -22,7 +22,7 @@ Human:`;b.AI_PROMPT=`
22
22
 
23
23
  Assistant:`;b.DEFAULT_TIMEOUT=6e5;b.AnthropicError=h;b.APIError=k;b.APIConnectionError=X;b.APIConnectionTimeoutError=ue;b.APIUserAbortError=x;b.NotFoundError=Fe;b.ConflictError=Oe;b.RateLimitError=Le;b.BadRequestError=Me;b.AuthenticationError=ve;b.InternalServerError=qe;b.PermissionDeniedError=Ie;b.UnprocessableEntityError=Be;b.toFile=Yn;b.fileFromPath=ot;b.Completions=ie;b.Messages=H;b.Models=Y;b.ModelInfosPage=ce;b.Beta=D;var{HUMAN_PROMPT:Ga,AI_PROMPT:Wa}=b,yr=b;c();c();function Qe(r){let{inputTokens:e,cacheReadTokens:t,cacheCreationTokens:n,outputTokens:s}=r,i=n===0&&t>0&&e>=t?e:e+t+n;return{promptTokenCount:i,candidatesTokenCount:s,totalTokenCount:i+s,cachedContentTokenCount:t}}var Lt=class{model;schemaCompliance;enableCacheControl;constructor(e,t="auto",n=!0){this.model=e,this.schemaCompliance=t,this.enableCacheControl=n}convertGeminiRequestToAnthropic(e,t={}){let n=[],s=this.extractTextFromContentUnion(e.config?.systemInstruction);this.processContents(e.contents,n),t.stripAssistantThinking&&this.stripThinkingFromAssistantMessages(n),t.normalizeAssistantThinkingSignature&&this.fillMissingThinkingSignatures(n),t.injectThinkingOnToolUseTurns&&this.injectEmptyThinkingOnToolUseTurns(n);let o=t.enableCacheControl??this.enableCacheControl,i=t.useGlobalCacheScope??!1,a=o?this.buildSystemWithCacheControl(s,i):s;return o&&this.addCacheControlToMessages(n),{system:a,messages:n}}async convertGeminiToolsToAnthropic(e,t={}){let n=[];for(let i of e){let a;if("tool"in i?a=await i.tool():a=i,!!a.functionDeclarations)for(let u of a.functionDeclarations){if(!u.name||!u.description)continue;let l;u.parametersJsonSchema?l={...u.parametersJsonSchema}:u.parameters&&(l=u.parameters),l||(l={type:"object",properties:{}}),l=_n(l,this.schemaCompliance),typeof l.type!="string"&&(l.type="object"),n.push({name:u.name,description:u.description,input_schema:l})}}let s=t.enableCacheControl??this.enableCacheControl,o=t.useGlobalCacheScope??!1;if(s&&n.length>0){let i=n.length-1;n[i]={...n[i],cache_control:o?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}}return n}convertAnthropicResponseToGemini(e){let t=new et,n=[];for(let i of e.content||[]){let a=String(i.type||"");if(a==="text"){let u=typeof i.text=="string"?i.text:"";u&&n.push({text:u})}else if(a==="tool_use"){let u=i;n.push({functionCall:{id:typeof u.id=="string"?u.id:void 0,name:typeof u.name=="string"?u.name:void 0,args:this.safeInputToArgs(u.input)}})}else if(a==="thinking"){let u=typeof i.thinking=="string"?i.thinking:"",l=typeof i.signature=="string"?i.signature:"";if(u||l){let m={text:u,thought:!0,thoughtSignature:l};n.push(m)}}else a==="redacted_thinking"&&n.push({text:"",thought:!0})}let s={content:{parts:n,role:"model"},index:0,safetyRatings:[]},o=this.mapAnthropicFinishReasonToGemini(e.stop_reason);return o&&(s.finishReason=o),t.candidates=[s],t.responseId=e.id,t.createTime=Date.now().toString(),t.modelVersion=e.model||this.model,t.promptFeedback={safetyRatings:[]},e.usage&&(t.usageMetadata=Qe({inputTokens:e.usage.input_tokens||0,cacheReadTokens:e.usage.cache_read_input_tokens||0,cacheCreationTokens:e.usage.cache_creation_input_tokens||0,outputTokens:e.usage.output_tokens||0})),t}processContents(e,t){if(Array.isArray(e))for(let n of e)this.processContent(n,t);else e&&this.processContent(e,t)}processContent(e,t){if(typeof e=="string"){t.push({role:"user",content:[{type:"text",text:e}]});return}if(!this.isContentObject(e))return;let n=e.parts||[],s=e.role==="model"?"assistant":"user",o=[],i=0;for(let a of n){if(typeof a=="string"){o.push({type:"text",text:a});continue}if("text"in a&&"thought"in a&&a.thought&&s==="assistant"){let l={type:"thinking",thinking:a.text||""};"thoughtSignature"in a&&typeof a.thoughtSignature=="string"&&(l.signature=a.thoughtSignature),o.push(l)}"text"in a&&a.text&&!("thought"in a&&a.thought)&&o.push({type:"text",text:a.text});let u=this.createMediaBlockFromPart(a);if(u&&o.push(u),"functionCall"in a&&a.functionCall&&s==="assistant"&&(o.push({type:"tool_use",id:a.functionCall.id||`tool_${i}`,name:a.functionCall.name||"",input:a.functionCall.args||{}}),i+=1),a.functionResponse){let l=this.createToolResultBlock(a.functionResponse);l&&s==="user"&&o.push(l)}}o.length>0&&t.push({role:s,content:o})}createToolResultBlock(e){let t=this.extractFunctionResponseContent(e.response),n=[];for(let o of e.parts||[]){let i=this.createMediaBlockFromPart(o);i&&n.push(i)}let s;if(n.length>0){let o=[];t&&o.push({type:"text",text:t}),o.push(...n),s=o}else s=t;return{type:"tool_result",tool_use_id:e.id||"",content:s}}createMediaBlockFromPart(e){if(e.inlineData?.mimeType&&e.inlineData?.data){if(this.isSupportedAnthropicImageMimeType(e.inlineData.mimeType))return{type:"image",source:{type:"base64",media_type:e.inlineData.mimeType,data:e.inlineData.data}};if(e.inlineData.mimeType==="application/pdf")return{type:"document",source:{type:"base64",media_type:"application/pdf",data:e.inlineData.data}};let t=e.inlineData.displayName?` (${e.inlineData.displayName})`:"";return{type:"text",text:`Unsupported inline media type: ${e.inlineData.mimeType}${t}.`}}if(e.fileData?.mimeType&&e.fileData?.fileUri){let t=e.fileData.displayName?` (${e.fileData.displayName})`:"",n=e.fileData.fileUri;return this.isSupportedAnthropicImageMimeType(e.fileData.mimeType)?{type:"image",source:{type:"url",url:n}}:e.fileData.mimeType==="application/pdf"?{type:"document",source:{type:"url",url:n}}:{type:"text",text:`Unsupported file media type: ${e.fileData.mimeType}${t}.`}}return null}isSupportedAnthropicImageMimeType(e){return e==="image/jpeg"||e==="image/png"||e==="image/gif"||e==="image/webp"}extractTextFromContentUnion(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.extractTextFromContentUnion(t)).filter(Boolean).join(`
24
24
  `):typeof e=="object"&&e!==null&&"parts"in e&&e.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
25
- `)||""}extractFunctionResponseContent(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let s=t.error;if(typeof s=="string")return s}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}safeInputToArgs(e){return e&&typeof e=="object"?e:typeof e=="string"?tt(e,{}):{}}mapAnthropicFinishReasonToGemini(e){return e?{end_turn:Z.STOP,stop_sequence:Z.STOP,tool_use:Z.STOP,max_tokens:Z.MAX_TOKENS,content_filter:Z.SAFETY}[e]||Z.FINISH_REASON_UNSPECIFIED:void 0}isContentObject(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}buildSystemWithCacheControl(e,t){return e&&[{type:"text",text:e,cache_control:t?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}]}stripThinkingFromAssistantMessages(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content.filter(s=>{let o=s.type;return o!=="thinking"&&o!=="redacted_thinking"});n.length!==0&&n.length!==t.content.length&&(t.content=n)}}fillMissingThinkingSignatures(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=!1,s=t.content.map(o=>{let i=o;return i.type==="thinking"&&typeof i.signature!="string"?(n=!0,{...o,signature:""}):o});n&&(t.content=s)}}injectEmptyThinkingOnToolUseTurns(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content;if(!n.some(a=>a.type==="tool_use")||n.some(a=>{let u=a.type;return u==="thinking"||u==="redacted_thinking"}))continue;let i={type:"thinking",thinking:"",signature:""};t.content=[i,...n]}}addCacheControlToMessages(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"){let s=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];if(s.length>0){let o=s[s.length-1];if(typeof o=="object"&&"type"in o){let i=o.type,a=i==="text"&&(!("text"in o)||!o.text);(i==="text"||i==="tool_result")&&!a&&(o.cache_control={type:"ephemeral"})}n.content=s}break}}}};var yn=bn("ANTHROPIC");function _r(r){let e=r.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 vs(r){return _r(r)?!0:(r.model??"").toLowerCase().includes("deepseek")}function Is(r){let e=r.baseUrl?.trim();if(e)return e;let t=process.env.ANTHROPIC_BASE_URL?.trim();return t||"https://api.anthropic.com"}function br(r){try{let e=new URL(Is(r)).hostname.toLowerCase();return e==="api.anthropic.com"||e.endsWith(".anthropic.com")}catch{return!1}}var Ye=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t;let n=!br(e),s=this.buildHeaders(n),o=e.baseUrl,i=xn("anthropic",this.cliConfig.getProxy());this.client=new yr({...n?{authToken:e.apiKey,apiKey:null}:{apiKey:e.apiKey,authToken:null},baseURL:o,timeout:e.timeout||12e4,maxRetries:e.maxRetries,defaultHeaders:s,...i}),this.converter=new Lt(e.model,e.schemaCompliance,e.enableCacheControl)}client;converter;effortClampWarned=!1;async generateContent(e){let t;try{let n=await this.buildRequest(e);nt.recordAnthropicWireRequest(n);let s=this.buildPerRequestHeaders(n);t=await this.client.messages.create(n,{signal:e.config?.abortSignal,...s?{headers:s}:{}})}catch(n){throw _e(n)}return this.converter.convertAnthropicResponseToGemini(t)}async generateContentStream(e){let t=await this.buildRequest(e),n=this.buildPerRequestHeaders(t),s={...t,stream:!0};nt.recordAnthropicWireRequest(s);let o;try{o=await this.client.messages.create(s,{signal:e.config?.abortSignal,...n?{headers:n}:{}})}catch(i){throw _e(i)}return this.processStreamWithEmptyFallback(this.redactStreamErrors(o),t,e.config?.abortSignal,n)}async countTokens(e){try{return{totalTokens:(await new Tn().calculateTokens(e)).totalTokens}}catch(t){yn.warn("Failed to calculate tokens with tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){throw new Error("Anthropic does not support embeddings.")}useSummarizedThinking(){return!1}buildHeaders(e){let t=this.cliConfig.getCliVersion()||"unknown",n=e?`claude-cli/${t} (external, cli)`:`MatildaCode/${t} (${process.platform}; ${process.arch})`,{customHeaders:s}=this.contentGeneratorConfig,o={"User-Agent":n};if(e&&(o["x-app"]="cli"),s)for(let[i,a]of Object.entries(s))i.toLowerCase()==="anthropic-beta"||Cn(i)||(o[i]=a);return o}buildPerRequestHeaders(e){let t=[];for(let s of this.collectCustomBetaFlags())t.push(s);return e.thinking&&t.push("interleaved-thinking-2025-05-14"),e.output_config&&t.push("effort-2025-11-24"),this.hasGlobalCacheScopeOnWire(e)&&t.push("prompt-caching-scope-2026-01-05"),t.length===0?void 0:{"anthropic-beta":Array.from(new Set(t)).join(",")}}useGlobalCacheScope(){return this.contentGeneratorConfig.enableCacheControl!==!1&&br(this.contentGeneratorConfig)}hasGlobalCacheScopeOnWire(e){let t=n=>{if(!n||typeof n!="object")return!1;let s=n.cache_control;return!s||typeof s!="object"?!1:s.scope==="global"};if(Array.isArray(e.system)){for(let n of e.system)if(t(n))return!0}if(Array.isArray(e.tools)){for(let n of e.tools)if(t(n))return!0}return!1}collectCustomBetaFlags(){let e=this.contentGeneratorConfig.customHeaders;if(!e)return[];let t=[];for(let[n,s]of Object.entries(e))if(n.toLowerCase()==="anthropic-beta"&&!(typeof s!="string"||!s))for(let o of s.split(",")){let i=o.trim();i&&t.push(i)}return t}async buildRequest(e){let t=this.buildSamplingParameters(e),n=this.resolveEffectiveEffort(e),s=this.buildThinkingConfig(e,n),o=this.buildOutputConfig(e,n),i=vs(this.contentGeneratorConfig),a=i&&!!s,u=i&&!s,l=this.contentGeneratorConfig.enableCacheControl!==!1,m=this.useGlobalCacheScope(),f=e.config?.tools?await this.converter.convertGeminiToolsToAnthropic(e.config.tools,{enableCacheControl:l,useGlobalCacheScope:m}):void 0,_=m&&!!f&&f.length>0,g=m&&!_,{system:S,messages:y}=this.converter.convertGeminiRequestToAnthropic(e,{normalizeAssistantThinkingSignature:a,injectThinkingOnToolUseTurns:a,stripAssistantThinking:u,enableCacheControl:l,useGlobalCacheScope:g});return{model:this.contentGeneratorConfig.model,system:S,messages:y,tools:f,...t,...s?{thinking:s}:{},...o?{output_config:o}:{}}}buildSamplingParameters(e){let t=this.contentGeneratorConfig.samplingParams,n=e.config||{},s=(m,f)=>{let _=t?.[m],g=f?n[f]:void 0;return _!==void 0?_:g},o=s("max_tokens","maxOutputTokens"),i=this.contentGeneratorConfig.model,a=kn(i,"output"),u=Sn(i),l;if(o!=null)l=u?Math.min(o,a):o;else{let m=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,f=m?parseInt(m,10):NaN;!isNaN(f)&&f>0?l=u?Math.min(f,a):f:l=Math.min(a,8e3)}return{max_tokens:l,temperature:s("temperature","temperature")??1,top_p:s("top_p","topP"),top_k:s("top_k","topK")}}resolveEffectiveEffort(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let t=this.contentGeneratorConfig.reasoning;if(t===!1||t===void 0)return;let n=t.effort;if(n!==void 0)return n==="max"&&!_r(this.contentGeneratorConfig)?(this.effortClampWarned||(yn.warn("reasoning.effort='max' is a DeepSeek extension; clamping to 'high' for non-DeepSeek anthropic provider to avoid HTTP 400."),this.effortClampWarned=!0),"high"):n}modelSupportsAdaptiveThinking(){let t=(this.contentGeneratorConfig.model||"").toLowerCase().match(/claude-(?:opus|sonnet|haiku)-(\d+)-(\d+)/);if(!t)return!1;let n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);return n>4||n===4&&s>=6}buildThinkingConfig(e,t){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let n=this.contentGeneratorConfig.reasoning;return n===!1?void 0:n?.budget_tokens!==void 0?{type:"enabled",budget_tokens:n.budget_tokens}:this.modelSupportsAdaptiveThinking()?{type:"adaptive"}:{type:"enabled",budget_tokens:t==="low"?16e3:t==="max"?128e3:t==="high"?64e3:32e3}}buildOutputConfig(e,t){if(t!==void 0)return{effort:t}}async*redactStreamErrors(e){try{for await(let t of e)yield t}catch(t){throw _e(t)}}async*processStream(e){let t,n=this.contentGeneratorConfig.model,s=0,o=0,i=0,a=0,u,l=new Map,m=[];for await(let f of e)switch(f.type){case"message_start":{t=f.message.id??t,n=f.message.model??n,s=f.message.usage?.cache_read_input_tokens??s,o=f.message.usage?.cache_creation_input_tokens??o,i=f.message.usage?.input_tokens??i;break}case"content_block_start":{let _=f.index??0,g=String(f.content_block.type||"text"),S=g==="tool_use"&&"input"in f.content_block?JSON.stringify(f.content_block.input):"";l.set(_,{type:g,id:"id"in f.content_block?f.content_block.id:void 0,name:"name"in f.content_block?f.content_block.name:void 0,inputJson:S!=="{}"?S:"",signature:g==="thinking"&&"signature"in f.content_block&&typeof f.content_block.signature=="string"?f.content_block.signature:""});break}case"content_block_delta":{let _=f.index??0,g=f.delta.type||"",S=l.get(_);if(g==="text_delta"){let y="text"in f.delta?f.delta.text:"";if(y){let M=this.buildGeminiChunk({text:y},t,n);m.push(M),yield M}}else if(g==="thinking_delta"){let y=f.delta.thinking||"";if(y){let M=this.buildGeminiChunk({text:y,thought:!0},t,n);m.push(M),yield M}}else if(g==="signature_delta"&&S){let y=f.delta.signature||"";if(y){S.signature+=y;let M=this.buildGeminiChunk({thought:!0,thoughtSignature:y},t,n);m.push(M),yield M}}else if(g==="input_json_delta"&&S){let y=f.delta.partial_json||"";y&&(S.inputJson+=y)}break}case"content_block_stop":{let _=f.index??0,g=l.get(_);if(g?.type==="tool_use"){let S=tt(g.inputJson||"{}",{}),y=this.buildGeminiChunk({functionCall:{id:g.id,name:g.name,args:S}},t,n);m.push(y),yield y}l.delete(_);break}case"message_delta":{let _=f.delta.stop_reason;_&&(u=_);let g=f.usage,S=g&&typeof g=="object"?g:void 0;if(f.usage?.output_tokens!==void 0&&(a=f.usage.output_tokens),S?.input_tokens!==void 0){let y=S.input_tokens;typeof y=="number"&&(i=y)}if(S?.cache_read_input_tokens!==void 0){let y=S.cache_read_input_tokens;typeof y=="number"&&(s=y)}if(S?.cache_creation_input_tokens!==void 0){let y=S.cache_creation_input_tokens;typeof y=="number"&&(o=y)}if(u||f.usage){let y=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(y),yield y}break}case"message_stop":{if(i||a){let _=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(_),yield _}break}default:break}}async*processStreamWithEmptyFallback(e,t,n,s){let o=!1,i=!1;for await(let u of this.processStream(e)){let l=u.candidates??[];i||=l.some(m=>m.finishReason!==void 0),o||=l.some(m=>m.content?.parts?.some(f=>f.text||f.thought||f.thoughtSignature||f.functionCall)),yield u}if(o||i)return;yn.warn("Anthropic stream ended without assistant payload or finish reason; probing once with a non-streaming request to surface provider errors.");let a;try{nt.recordAnthropicWireRequest(t),a=await this.client.messages.create(t,{signal:n,...s?{headers:s}:{}}),yield this.converter.convertAnthropicResponseToGemini(a)}catch(u){throw _e(u)}}buildGeminiChunk(e,t,n,s,o){let i=new et;i.responseId=t,i.createTime=Date.now().toString(),i.modelVersion=n||this.contentGeneratorConfig.model,i.promptFeedback={safetyRatings:[]};let a=e?[e]:[],u=s!==void 0?this.converter.mapAnthropicFinishReasonToGemini(s):void 0;return i.candidates=[{content:{parts:a,role:"model"},index:0,safetyRatings:[],...u?{finishReason:u}:{}}],o&&(i.usageMetadata=o),i}};function gc(r,e){return new Ye(r,e)}export{Ye as AnthropicContentGenerator,gc as createAnthropicContentGenerator};
25
+ `)||""}extractFunctionResponseContent(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e,n=t.output;if(typeof n=="string")return n;let s=t.error;if(typeof s=="string")return s}try{return JSON.stringify(e)??String(e)}catch{return String(e)}}safeInputToArgs(e){return e&&typeof e=="object"?e:typeof e=="string"?tt(e,{}):{}}mapAnthropicFinishReasonToGemini(e){return e?{end_turn:Z.STOP,stop_sequence:Z.STOP,tool_use:Z.STOP,max_tokens:Z.MAX_TOKENS,content_filter:Z.SAFETY}[e]||Z.FINISH_REASON_UNSPECIFIED:void 0}isContentObject(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&Array.isArray(e.parts)}buildSystemWithCacheControl(e,t){return e&&[{type:"text",text:e,cache_control:t?{type:"ephemeral",scope:"global"}:{type:"ephemeral"}}]}stripThinkingFromAssistantMessages(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content.filter(s=>{let o=s.type;return o!=="thinking"&&o!=="redacted_thinking"});n.length!==0&&n.length!==t.content.length&&(t.content=n)}}fillMissingThinkingSignatures(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=!1,s=t.content.map(o=>{let i=o;return i.type==="thinking"&&typeof i.signature!="string"?(n=!0,{...o,signature:""}):o});n&&(t.content=s)}}injectEmptyThinkingOnToolUseTurns(e){for(let t of e){if(t.role!=="assistant"||!Array.isArray(t.content))continue;let n=t.content;if(!n.some(a=>a.type==="tool_use")||n.some(a=>{let u=a.type;return u==="thinking"||u==="redacted_thinking"}))continue;let i={type:"thinking",thinking:"",signature:""};t.content=[i,...n]}}addCacheControlToMessages(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user"){let s=Array.isArray(n.content)?n.content:[{type:"text",text:n.content}];if(s.length>0){let o=s[s.length-1];if(typeof o=="object"&&"type"in o){let i=o.type,a=i==="text"&&(!("text"in o)||!o.text);(i==="text"||i==="tool_result")&&!a&&(o.cache_control={type:"ephemeral"})}n.content=s}break}}}};var yn=bn("ANTHROPIC");function _r(r){let e=r.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 vs(r){return _r(r)?!0:(r.model??"").toLowerCase().includes("deepseek")}function Is(r){let e=r.baseUrl?.trim();if(e)return e;let t=process.env.ANTHROPIC_BASE_URL?.trim();return t||"https://api.anthropic.com"}function br(r){try{let e=new URL(Is(r)).hostname.toLowerCase();return e==="api.anthropic.com"||e.endsWith(".anthropic.com")}catch{return!1}}var Ye=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t;let n=!br(e),s=this.buildHeaders(n),o=e.baseUrl,i=xn("anthropic",this.cliConfig.getProxy());this.client=new yr({...n?{authToken:e.apiKey,apiKey:null}:{apiKey:e.apiKey,authToken:null},baseURL:o,timeout:e.timeout||6e5,maxRetries:e.maxRetries,defaultHeaders:s,...i}),this.converter=new Lt(e.model,e.schemaCompliance,e.enableCacheControl)}client;converter;effortClampWarned=!1;async generateContent(e){let t;try{let n=await this.buildRequest(e);nt.recordAnthropicWireRequest(n);let s=this.buildPerRequestHeaders(n);t=await this.client.messages.create(n,{signal:e.config?.abortSignal,...s?{headers:s}:{}})}catch(n){throw _e(n)}return this.converter.convertAnthropicResponseToGemini(t)}async generateContentStream(e){let t=await this.buildRequest(e),n=this.buildPerRequestHeaders(t),s={...t,stream:!0};nt.recordAnthropicWireRequest(s);let o;try{o=await this.client.messages.create(s,{signal:e.config?.abortSignal,...n?{headers:n}:{}})}catch(i){throw _e(i)}return this.processStreamWithEmptyFallback(this.redactStreamErrors(o),t,e.config?.abortSignal,n)}async countTokens(e){try{return{totalTokens:(await new Tn().calculateTokens(e)).totalTokens}}catch(t){yn.warn("Failed to calculate tokens with tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){throw new Error("Anthropic does not support embeddings.")}useSummarizedThinking(){return!1}buildHeaders(e){let t=this.cliConfig.getCliVersion()||"unknown",n=e?`claude-cli/${t} (external, cli)`:`MatildaCode/${t} (${process.platform}; ${process.arch})`,{customHeaders:s}=this.contentGeneratorConfig,o={"User-Agent":n};if(e&&(o["x-app"]="cli"),s)for(let[i,a]of Object.entries(s))i.toLowerCase()==="anthropic-beta"||Cn(i)||(o[i]=a);return o}buildPerRequestHeaders(e){let t=[];for(let s of this.collectCustomBetaFlags())t.push(s);return e.thinking&&t.push("interleaved-thinking-2025-05-14"),e.output_config&&t.push("effort-2025-11-24"),this.hasGlobalCacheScopeOnWire(e)&&t.push("prompt-caching-scope-2026-01-05"),t.length===0?void 0:{"anthropic-beta":Array.from(new Set(t)).join(",")}}useGlobalCacheScope(){return this.contentGeneratorConfig.enableCacheControl!==!1&&br(this.contentGeneratorConfig)}hasGlobalCacheScopeOnWire(e){let t=n=>{if(!n||typeof n!="object")return!1;let s=n.cache_control;return!s||typeof s!="object"?!1:s.scope==="global"};if(Array.isArray(e.system)){for(let n of e.system)if(t(n))return!0}if(Array.isArray(e.tools)){for(let n of e.tools)if(t(n))return!0}return!1}collectCustomBetaFlags(){let e=this.contentGeneratorConfig.customHeaders;if(!e)return[];let t=[];for(let[n,s]of Object.entries(e))if(n.toLowerCase()==="anthropic-beta"&&!(typeof s!="string"||!s))for(let o of s.split(",")){let i=o.trim();i&&t.push(i)}return t}async buildRequest(e){let t=this.buildSamplingParameters(e),n=this.resolveEffectiveEffort(e),s=this.buildThinkingConfig(e,n),o=this.buildOutputConfig(e,n),i=vs(this.contentGeneratorConfig),a=i&&!!s,u=i&&!s,l=this.contentGeneratorConfig.enableCacheControl!==!1,m=this.useGlobalCacheScope(),f=e.config?.tools?await this.converter.convertGeminiToolsToAnthropic(e.config.tools,{enableCacheControl:l,useGlobalCacheScope:m}):void 0,_=m&&!!f&&f.length>0,g=m&&!_,{system:S,messages:y}=this.converter.convertGeminiRequestToAnthropic(e,{normalizeAssistantThinkingSignature:a,injectThinkingOnToolUseTurns:a,stripAssistantThinking:u,enableCacheControl:l,useGlobalCacheScope:g});return{model:this.contentGeneratorConfig.model,system:S,messages:y,tools:f,...t,...s?{thinking:s}:{},...o?{output_config:o}:{}}}buildSamplingParameters(e){let t=this.contentGeneratorConfig.samplingParams,n=e.config||{},s=(m,f)=>{let _=t?.[m],g=f?n[f]:void 0;return _!==void 0?_:g},o=s("max_tokens","maxOutputTokens"),i=this.contentGeneratorConfig.model,a=kn(i,"output"),u=Sn(i),l;if(o!=null)l=u?Math.min(o,a):o;else{let m=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,f=m?parseInt(m,10):NaN;!isNaN(f)&&f>0?l=u?Math.min(f,a):f:l=Math.min(a,8e3)}return{max_tokens:l,temperature:s("temperature","temperature")??1,top_p:s("top_p","topP"),top_k:s("top_k","topK")}}resolveEffectiveEffort(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let t=this.contentGeneratorConfig.reasoning;if(t===!1||t===void 0)return;let n=t.effort;if(n!==void 0)return n==="max"&&!_r(this.contentGeneratorConfig)?(this.effortClampWarned||(yn.warn("reasoning.effort='max' is a DeepSeek extension; clamping to 'high' for non-DeepSeek anthropic provider to avoid HTTP 400."),this.effortClampWarned=!0),"high"):n}modelSupportsAdaptiveThinking(){let t=(this.contentGeneratorConfig.model||"").toLowerCase().match(/claude-(?:opus|sonnet|haiku)-(\d+)-(\d+)/);if(!t)return!1;let n=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10);return n>4||n===4&&s>=6}buildThinkingConfig(e,t){if(e.config?.thinkingConfig?.includeThoughts===!1)return;let n=this.contentGeneratorConfig.reasoning;return n===!1?void 0:n?.budget_tokens!==void 0?{type:"enabled",budget_tokens:n.budget_tokens}:this.modelSupportsAdaptiveThinking()?{type:"adaptive"}:{type:"enabled",budget_tokens:t==="low"?16e3:t==="max"?128e3:t==="high"?64e3:32e3}}buildOutputConfig(e,t){if(t!==void 0)return{effort:t}}async*redactStreamErrors(e){try{for await(let t of e)yield t}catch(t){throw _e(t)}}async*processStream(e){let t,n=this.contentGeneratorConfig.model,s=0,o=0,i=0,a=0,u,l=new Map,m=[];for await(let f of e)switch(f.type){case"message_start":{t=f.message.id??t,n=f.message.model??n,s=f.message.usage?.cache_read_input_tokens??s,o=f.message.usage?.cache_creation_input_tokens??o,i=f.message.usage?.input_tokens??i;break}case"content_block_start":{let _=f.index??0,g=String(f.content_block.type||"text"),S=g==="tool_use"&&"input"in f.content_block?JSON.stringify(f.content_block.input):"";l.set(_,{type:g,id:"id"in f.content_block?f.content_block.id:void 0,name:"name"in f.content_block?f.content_block.name:void 0,inputJson:S!=="{}"?S:"",signature:g==="thinking"&&"signature"in f.content_block&&typeof f.content_block.signature=="string"?f.content_block.signature:""});break}case"content_block_delta":{let _=f.index??0,g=f.delta.type||"",S=l.get(_);if(g==="text_delta"){let y="text"in f.delta?f.delta.text:"";if(y){let M=this.buildGeminiChunk({text:y},t,n);m.push(M),yield M}}else if(g==="thinking_delta"){let y=f.delta.thinking||"";if(y){let M=this.buildGeminiChunk({text:y,thought:!0},t,n);m.push(M),yield M}}else if(g==="signature_delta"&&S){let y=f.delta.signature||"";if(y){S.signature+=y;let M=this.buildGeminiChunk({thought:!0,thoughtSignature:y},t,n);m.push(M),yield M}}else if(g==="input_json_delta"&&S){let y=f.delta.partial_json||"";y&&(S.inputJson+=y)}break}case"content_block_stop":{let _=f.index??0,g=l.get(_);if(g?.type==="tool_use"){let S=tt(g.inputJson||"{}",{}),y=this.buildGeminiChunk({functionCall:{id:g.id,name:g.name,args:S}},t,n);m.push(y),yield y}l.delete(_);break}case"message_delta":{let _=f.delta.stop_reason;_&&(u=_);let g=f.usage,S=g&&typeof g=="object"?g:void 0;if(f.usage?.output_tokens!==void 0&&(a=f.usage.output_tokens),S?.input_tokens!==void 0){let y=S.input_tokens;typeof y=="number"&&(i=y)}if(S?.cache_read_input_tokens!==void 0){let y=S.cache_read_input_tokens;typeof y=="number"&&(s=y)}if(S?.cache_creation_input_tokens!==void 0){let y=S.cache_creation_input_tokens;typeof y=="number"&&(o=y)}if(u||f.usage){let y=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(y),yield y}break}case"message_stop":{if(i||a){let _=this.buildGeminiChunk(void 0,t,n,u,Qe({inputTokens:i,cacheReadTokens:s,cacheCreationTokens:o,outputTokens:a}));m.push(_),yield _}break}default:break}}async*processStreamWithEmptyFallback(e,t,n,s){let o=!1,i=!1;for await(let u of this.processStream(e)){let l=u.candidates??[];i||=l.some(m=>m.finishReason!==void 0),o||=l.some(m=>m.content?.parts?.some(f=>f.text||f.thought||f.thoughtSignature||f.functionCall)),yield u}if(o||i)return;yn.warn("Anthropic stream ended without assistant payload or finish reason; probing once with a non-streaming request to surface provider errors.");let a;try{nt.recordAnthropicWireRequest(t),a=await this.client.messages.create(t,{signal:n,...s?{headers:s}:{}}),yield this.converter.convertAnthropicResponseToGemini(a)}catch(u){throw _e(u)}}buildGeminiChunk(e,t,n,s,o){let i=new et;i.responseId=t,i.createTime=Date.now().toString(),i.modelVersion=n||this.contentGeneratorConfig.model,i.promptFeedback={safetyRatings:[]};let a=e?[e]:[],u=s!==void 0?this.converter.mapAnthropicFinishReasonToGemini(s):void 0;return i.candidates=[{content:{parts:a,role:"model"},index:0,safetyRatings:[],...u?{finishReason:u}:{}}],o&&(i.usageMetadata=o),i}};function gc(r,e){return new Ye(r,e)}export{Ye as AnthropicContentGenerator,gc as createAnthropicContentGenerator};
26
26
  /**
27
27
  * @license
28
28
  * Copyright 2025 Matilda
@@ -7,7 +7,7 @@ import{a as U,d as at}from"./chunk-4F4DA5UI.js";import{a as ot,b as it,e as Ie,n
7
7
  `)||""}function Pe(t,e,n=!0){return e.responseParsingOptions?.taggedThinkingTags?e.taggedThinkingParser?e.taggedThinkingParser.parse(t,n):ut(t):t?[{text:t}]:[]}function an(t,e){let n=t.choices?.[0],o=new B;if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let r=n.message.reasoning_content??n.message.reasoning;r&&i.push({text:r,thought:!0})}if(n.message.content&&i.push(...Pe(n.message.content,e)),n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a={};r.function.arguments&&(a=ot(r.function.arguments,{})),i.push({functionCall:{id:r.id,name:r.function.name,args:a}})}}o.candidates=[{content:{parts:i,role:"model"},finishReason:vt(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}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=Tt(t.usage)),o}function sn(t,e){let n=t.choices?.[0],o=new B,i=e.toolCallParser;if(!i)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let d=n.delta?.reasoning_content??n.delta?.reasoning;if(d){let c=gt(d,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&r.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let d=gt(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(d||n.finish_reason)&&r.push(...Pe(d,e,!!n.finish_reason))}else n.finish_reason&&r.push(...Pe("",e,!0));if(n.delta?.tool_calls)for(let d of n.delta.tool_calls){let c=d.index??0;d.function?.arguments?i.addChunk(c,d.function.arguments,d.id,d.function.name):i.addChunk(c,"",d.id,d.function?.name)}let a=!1;if(n.finish_reason){a=i.hasIncompleteToolCalls();let d=i.getCompletedToolCalls();for(let c of d)c.name&&r.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let s=a&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:r,role:"model"},index:0,safetyRatings:[]};s&&(l.finishReason=vt(s)),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=Tt(t.usage)),o}function vt(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 ln(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 Re(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function mt(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===yt}function dn(t){let e=[],n=new Map,o=new Map,i=new Map,r=new Set,a=new Set;for(let s=0;s<t.length;s+=1){let l=t[s];if(Re(l)){let d=[],c=new Set;for(let C of l.tool_calls){let y=C.id;!y||a.has(y)||c.has(y)||(c.add(y),d.push(C))}let g=new Set,u=[],m=[],h=!1;for(let C=s+1;C<t.length;C+=1){let y=t[C];if(y.role==="tool"&&"tool_call_id"in y){if(!y.tool_call_id){h=!1;continue}c.has(y.tool_call_id)&&!g.has(y.tool_call_id)?(g.add(y.tool_call_id),u.push(C),h=!0):h=!1;continue}if(mt(y)){h&&m.push(C);continue}if(!(y.role==="assistant"&&!Re(y)))break}let p=d.filter(C=>g.has(C.id));for(let C of p)a.add(C.id);n.set(s,p),o.set(s,u),i.set(s,m)}}for(let s=0;s<t.length;s+=1){if(r.has(s))continue;let l=t[s];if(Re(l)){let d=l.reasoning_content,c=n.get(s)??[];if(c.length>0){let g={...l};g.tool_calls=c,e.push(g);for(let u of o.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}for(let u of i.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}}else if(typeof l.content=="string"&&l.content.trim()||d){let g={...l};delete g.tool_calls,e.push(g)}else w.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?w.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):mt(l)?w.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function Ct(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 i="tool_calls"in o?o.tool_calls||[]:[],r="tool_calls"in n?n.tool_calls||[]:[],a=o.content,s=n.content,l=Array.isArray(a)||Array.isArray(s),d;if(l){let g=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[],u=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[];d=[...g,...u]}else d=[typeof a=="string"?a:"",typeof s=="string"?s:""].filter(Boolean).join("")||null;let c=[...i,...r];o.content=d||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var ne={convertGeminiToolParametersToOpenAI:At,convertGeminiToolsToOpenAI:Yt,convertGeminiRequestToOpenAI:Xt,convertGeminiResponseToOpenAI:Zt,convertOpenAIResponseToGemini:an,convertOpenAIChunkToGemini:sn};f();import*as _ from"node:path";import{promises as re}from"node:fs";f();f();import cn from"crypto";var ie=new Uint8Array(256),oe=ie.length;function Ee(){return oe>ie.length-16&&(cn.randomFillSync(ie),oe=0),ie.slice(oe,oe+=16)}f();var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function _t(t,e=0){return M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]}f();f();import un from"crypto";var Oe={randomUUID:un.randomUUID};function pn(t,e,n){if(Oe.randomUUID&&!e&&!t)return Oe.randomUUID();t=t||{};let o=t.random||(t.rng||Ee)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return _t(o)}var Ue=pn;import*as E from"os";var ae=b("OPENAI_LOGGER"),gn="########",fn=/^[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 hn(t,e){let n=e||process.cwd();if(!t)return _.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=_.join(E.homedir(),t.slice(1)):_.isAbsolute(t)||(o=_.resolve(n,t)),_.normalize(o)}function xt(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function mn(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function Cn(t){if(t)return K(t)?xt(t):xt(mn(t))}function yn(t){if(!t)return;let e=t.indexOf(gn);if(e>0)return t.slice(0,e);if(fn.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function Tn(t){let e=t?.trim(),n=yn(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var V=class{logDir;initialized=!1;constructor(e,n){this.logDir=hn(e,n)}async initialize(){if(!this.initialized)try{await re.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw ae.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,i){this.initialized||await this.initialize();let r=new Date().toISOString().replace(/:/g,"-"),a=Ue().slice(0,8),s=Cn(i),l=s?`openai-${r}-${a}-${s}.json`:`openai-${r}-${a}.json`,d=_.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:Tn(i),system:{hostname:E.hostname(),platform:E.platform(),release:E.release(),nodeVersion:process.version}};try{return await re.writeFile(d,JSON.stringify(c,null,2),"utf-8"),d}catch(g){throw ae.error("Failed to write OpenAI log file:",g),new Error(`Failed to write OpenAI log file: ${g}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await re.readdir(this.logDir)).filter(i=>i.startsWith("openai-")&&i.endsWith(".json")).map(i=>_.join(this.logDir,i)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(ae.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await re.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw ae.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Uo=new V;f();var se="$runtime|";function Go(t){let e=t;for(;e.startsWith(se);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}f();var le=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],bt=["model","apiKey","apiKeyEnvKey","baseUrl"],de=[...bt,...le],$o={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:[]}},zo={openai:at,"matilda-oauth":U},ce=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],jo=ce.map(t=>t.id);f();f();f();f();Bt();f();import{AsyncLocalStorage as An}from"node:async_hooks";var It=new An;f();function kt(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Mn)}function Mn(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 wt(){let t=rt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var D=b("LOGGING_CONTENT_GENERATOR"),Sn=4096,Rt="...[truncated]",vn=Sn-Rt.length,J=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 V(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let i=JSON.stringify(e);Xe(this.config,new et(n,o,i,P.getStore()))}_logApiResponse(e,n,o,i,r,a){Qe(this.config,new nt(e,o,n,i,this.generatorAuthType,r,a,P.getStore()))}_logApiError(e,n,o,i,r){let a=qe(o),s=H(o),l=o?.requestID||o?.request_id||e,d=j(o);Ze(this.config,new tt({responseId:l,model:i,durationMs:n,promptId:r,authType:this.generatorAuthType,errorMessage:a,errorType:s,statusCode:d,subagentName:P.getStore()}))}safelyLogApiError(e,n,o,i,r){try{this._logApiError(e,n,o,i,r)}catch(a){D.warn("Failed to log API error:",a)}}safelyLogApiResponse(e,n,o,i,r,a){try{this._logApiResponse(e,n,o,i,r,a)}catch(s){D.warn("Failed to log API response:",s)}}async generateContent(e,n){let o=wt(),i=be(e.model,n);try{i.setAttribute("llm_request.stream",!1)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=K(n),l=this.startCaptureSession();try{Ie.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools));let d=await k.with(r,async()=>{s||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),g=Date.now()-a,u=s?void 0:this.extractResponseText(c);s||xe(this.config,i,u),this.safelyLogApiResponse(c.responseId??"",g,c.modelVersion||e.model,n,c.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(m){D.warn("Failed to log OpenAI interaction:",m)}return c});return F(i,{success:!0,inputTokens:d.usageMetadata?.promptTokenCount,outputTokens:d.usageMetadata?.candidatesTokenCount,cachedInputTokens:d.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-a,responseId:d.responseId||void 0,finishReason:d.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:d.usageMetadata?.thoughtsTokenCount,subagentName:P.getStore()||void 0,...o}),d}catch(d){let c=Date.now()-a,g=e.config?.abortSignal?.aborted??!1;throw F(i,{success:!1,durationMs:c,error:g?ee:Q,errorType:H(d),errorStatusCode:j(d),subagentName:P.getStore()||void 0,...o}),await k.with(r,async()=>{this.safelyLogApiError("",c,d,e.model,n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,d,n)}catch(u){D.warn("Failed to log OpenAI interaction:",u)}}),d}}async generateContentStream(e,n){let o=wt(),i=be(e.model,n);try{i.setAttribute("llm_request.stream",!0)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=K(n),l=this.startCaptureSession(),d;try{Ie.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools)),d=await k.with(r,async()=>(s||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(g){let u=Date.now()-a;k.with(r,()=>this.safelyLogApiError("",u,g,e.model,n));let m=e.config?.abortSignal?.aborted??!1;F(i,{success:!1,durationMs:u,error:m?ee:Q,errorType:H(g),errorStatusCode:j(g),subagentName:P.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,g,n)}catch(h){D.warn("Failed to log OpenAI interaction:",h)}throw g}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(g){D.warn("Failed to resolve OpenAI request:",g)}return k.with(r,()=>this.loggingStreamWrapper(d,a,n,e.model,c,i,r,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():It.run(i=>{e=i},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,i,r,a,s,l,d){let c=K(o),g=!c||!!this.openaiLogger,u=[],m="",h="",p,C=!1,y,T,S=P.getStore(),R,z=!1,X=v=>s?k.with(s,v):v(),Ht=5*6e4,I,We=a?()=>{z||(I!==void 0&&clearTimeout(I),I=setTimeout(()=>{try{a.setAttribute("stream.timed_out",!0)}catch{}F(a,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:S||void 0,...d}),z=!0},Ht),I.unref())}:void 0;We?.();try{for await(let x of e){!m&&x.responseId&&(m=x.responseId),!h&&x.modelVersion&&(h=x.modelVersion),g&&u.push(x),x.usageMetadata&&(p=x.usageMetadata);let Je=x.candidates?.[0];Je?.finishReason&&(y=Je.finishReason),R===void 0&&kt(x)&&(R=Date.now()-n),We?.(),yield x}I!==void 0&&(clearTimeout(I),I=void 0);let v=Date.now()-n,Z=g?this.consolidateGeminiResponsesForLogging(u):void 0,Ve=c?void 0:this.extractResponseText(Z);z||(X(()=>this.safelyLogApiResponse(m,v,h||i,o,p,Ve)),!c&&a&&xe(this.config,a,Ve),await X(()=>this.safelyLogOpenAIInteraction(r,Z,void 0,o)))}catch(v){if(C=!0,T=v,!z){let Z=Date.now()-n;X(()=>this.safelyLogApiError(m,Z,v,h||i,o)),await X(()=>this.safelyLogOpenAIInteraction(r,void 0,v,o))}throw v}finally{if(I!==void 0&&clearTimeout(I),a&&!z){let v=l?.aborted??!1;F(a,{success:!C,inputTokens:p?.promptTokenCount,outputTokens:p?.candidatesTokenCount,cachedInputTokens:p?.cachedContentTokenCount,ttftMs:R,durationMs:Date.now()-n,error:C?v?ee:Q:void 0,responseId:m||void 0,finishReason:y,thoughtsTokenCount:p?.thoughtsTokenCount,subagentName:S||void 0,errorType:T?H(T):void 0,errorStatusCode:T?j(T):void 0,...d})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ne.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),i={model:e.model,messages:o};return e.config?.tools&&(i.tools=await ne.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(i.temperature=e.config.temperature),e.config?.topP!==void 0&&(i.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(i.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(i.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(i.frequency_penalty=e.config.frequencyPenalty),i}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,i){if(!this.openaiLogger||!e)return;let r=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,r,o instanceof Error?o:o?new Error(String(o)):void 0,i)}async safelyLogOpenAIInteraction(e,n,o,i){try{await this.logOpenAIInteraction(e,n,o,i)}catch(r){D.warn("Failed to log OpenAI interaction:",r)}}convertGeminiResponseToOpenAIForLogging(e,n){return ne.convertGeminiResponseToOpenAI(e,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new B,o=[],i=new Map,r,a;for(let d of e){d.usageMetadata&&(a=d.usageMetadata);let c=d.candidates?.[0];c?.finishReason&&(r=c.finishReason);let g=c?.content?.parts??[];for(let u of g){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let m=u.functionCall.id||u.functionCall.name||"tool_call",h=i.get(m),p={functionCall:u.functionCall};h!==void 0?o[h]=p:(i.set(m,o.length),o.push(p));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let s=e[e.length-1],l=s.candidates?.[0];return n.responseId=s.responseId,n.createTime=s.createTime,n.modelVersion=s.modelVersion,n.promptFeedback=s.promptFeedback,n.usageMetadata=a,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...r?{finishReason:r}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",i=!1,r=!1,a=s=>{if(i=!0,r)return;let l=vn-o.length;if(s.length<=l){o+=s;return}o+=s.slice(0,Math.max(0,l)),r=!0};for(let s of n){if(typeof s=="string"){a(s);continue}"text"in s&&typeof s.text=="string"&&!("thought"in s&&s.thought)&&a(s.text)}if(i)return r?`${o}${Rt}`: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 r=o.text,a=r?String(r):"",s=a?`${a}
8
8
  ${n}`:n;return{...o,text:s}}return e}};f();function Pt(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 Et(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 O=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends O{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let i=e||"(unknown)",r=n||"(unknown)";super(`Missing credentials for modelProviders model '${r}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${i}[].envKey.`:`Configure modelProviders.${i}[].envKey and set that environment variable.`))}},pe=class extends O{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},ge=class extends O{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}'.`)}},fe=class extends O{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},he=class extends O{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},me=class extends O{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import xn from"node:process";f();var Ot={image:!0,pdf:!0,audio:!0,video:!0},_n=[[/^gemini-3/,Ot],[/^gemini-/,Ot],[/^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 q(t){let e=st(t);for(let[n,o]of _n)if(n.test(e))return{...o};return{}}f();var Ut=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 Ce(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||U}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,i=[];for(let l of n)o.has(l)||(o.add(l),i.push(l));let r=[];i.includes("matilda-oauth")&&r.push("matilda-oauth");for(let l of i)l!=="matilda-oauth"&&r.push(l);let a=this.getRuntimeModelOption(),s=[];for(let l of r)a&&a.authType===l&&s.push(a),s.push(...this.modelRegistry.getModelsForAuthType(l));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}getModelDisplayName(e){return/^matilda-code/i.test(e.trim())?"Matilda":this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===U){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(i){throw this.rollbackToStateSnapshot(o),i}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=q(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=W(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 i=this.extractRuntimeModelSnapshotId(n);if(i){await this.switchToRuntimeModel(i);return}let r=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let a=e!==this.currentAuthType;this.currentAuthType=e;let s=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!s)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=r.generationConfig.model||"",d=!a&&l?this.modelRegistry.getModel(e,l,r.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,c=e!=="matilda-oauth"&&!a&&!!r.generationConfig.apiKey&&!!s.envKey&&d?.envKey===s.envKey&&d.baseUrl===s.baseUrl,g=c?r.generationConfig.apiKey:void 0,u=c?r.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,u&&(this.generationConfigSources.apiKey=t.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0;let m=a?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,m)}catch(a){throw this.rollbackToStateSnapshot(r),a}}buildRuntimeModelSnapshotId(e,n){return`${se}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(se))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 le)!(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:i}=this._generationConfig;if(!(!n||!e||!o||!i)&&!this.modelRegistry.hasModel(e,n,i))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let r=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);r.apiKey=o,r.baseUrl=i,r.modelId=n;let a=this.buildRuntimeModelSnapshotId(r.authType,r.modelId);a!==r.id&&(this.runtimeModelSnapshots.delete(r.id),r.id=a,this.runtimeModelSnapshots.set(a,r),this.activeRuntimeModelSnapshotId=a),r.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of de)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=xn.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 le)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=W(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=q(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),i=this.modelRegistry.getModel(n,e);return!i||!o||i.envKey!==o.envKey||i.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,r=n?this.modelRegistry.getModel(e,n,i)??this.modelRegistry.getModel(e,n):void 0;if(r){let m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==r.envKey||this._generationConfig.baseUrl!==r.baseUrl),h=o===e&&this._generationConfig.model===n&&!m,p=h?this._generationConfig.apiKey:void 0,C=h&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,y=this.generationConfigSources.baseUrl,T=h&&!!this._generationConfig.baseUrl&&(y?.kind==="cli"||y?.kind==="env"||y?.kind==="settings"),S=T?this._generationConfig.baseUrl:void 0,R=T&&y?{...y}:void 0;this.applyResolvedModelDefaults(r),h&&!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,s=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&s?.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 g=this.modelRegistry.getDefaultModelForAuthType(e);if(g){this.applyResolvedModelDefaults(g),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:i,...r}=this._generationConfig,a=this.currentAuthType;if(!e||!a)return;if(this.modelRegistry.hasModel(a,e,o)){this.clearRuntimeModelSnapshotForAuthType(a);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(a,e),d={id:l,authType:a,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,generationConfig:r,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,d),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 i=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 r=i;this.onModelChange&&await this.onModelChange(n.authType,r)}catch(i){throw this.rollbackToStateSnapshot(o),i}}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)}};f();import{readFileSync as zn}from"node:fs";import{join as jn}from"node:path";f();f();import{randomBytes as bn,createHash as In}from"node:crypto";function Lt(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Le(){let t=bn(32).toString("base64url"),e=In("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Y(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 De(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Lt(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 i=await o.json();if(!i.issuer||!i.authorization_endpoint||!i.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:i.issuer,authorization_endpoint:i.authorization_endpoint,token_endpoint:i.token_endpoint,device_authorization_endpoint:i.device_authorization_endpoint}}f();import{promises as ye,openSync as kn,closeSync as wn,unlinkSync as Dt,statSync as Rn}from"node:fs";import{dirname as Pn}from"node:path";var En=1e4,On=3e4,Un=50;function Ge(t){let e=async()=>{try{let i=await ye.readFile(t,"utf8"),r=JSON.parse(i);return r&&typeof r=="object"?r:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},n=async i=>{await ye.mkdir(Pn(t),{recursive:!0}),await ye.writeFile(t,JSON.stringify(i,null,2),{mode:384}),await ye.chmod(t,384).catch(()=>{})};return{store:{async get(i){return(await e())[i]??null},async set(i,r){let a=await e();a[i]=r,await n(a)},async remove(i){let r=await e();i in r&&(delete r[i],await n(r))}},lock:Ln(`${t}.lock`)}}function Ln(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Dn(t);try{return await n()}finally{Gn(t)}});return e=o.then(()=>{},()=>{}),o}}async function Dn(t){let e=Date.now()+En;for(;;)try{wn(kn(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Rn(t).mtimeMs>On){Dt(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Nn(Un)}}function Gn(t){try{Dt(t)}catch{}}function Nn(t){return new Promise(e=>setTimeout(e,t))}f();var $=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Ne(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,i=null,r=async()=>{let l=await t.store.get(e);if(!l)return null;try{let d=JSON.parse(l);return d.accessToken?d:null}catch{return null}},a=l=>l.expiresAt-Date.now()>o,s=l=>t.lock(async()=>{let d=await r()??l;if(d.accessToken!==l.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new $("No refresh token available \u2014 sign in again.");let c=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:d.refreshToken})});if(!c.ok){let m=await c.text().catch(()=>"");throw c.status>=400&&c.status<500&&Kn(m)==="invalid_grant"?(await t.store.remove(e),new $):new Error(`Token refresh failed (${c.status})`)}let g=await c.json(),u=Y(g,d);return await t.store.set(e,JSON.stringify(u)),u.accessToken});return{async getAccessToken(l){let d=await r();if(!d)throw new $("Not signed in.");return!l?.forceRefresh&&a(d)?d.accessToken:(i||(i=s(d).finally(()=>{i=null})),i)}}}function Kn(t){try{return JSON.parse(t).error}catch{return}}f();import{createServer as Fn}from"node:http";import{randomBytes as $n}from"node:crypto";async function Ke(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=h=>t.onEvent?.(h),{codeVerifier:n,codeChallenge:o}=Le(),i=$n(16).toString("hex"),r=t.timeoutMs??5*60*1e3,a=t.transport.successRedirect;e({type:"state",status:"idle"});let s,l,d=new Promise((h,p)=>{s=h,l=p});d.catch(()=>{});let c=Fn((h,p)=>{let C=new URL(h.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){p.writeHead(404).end();return}let y=C.searchParams.get("error"),T=C.searchParams.get("state"),S=C.searchParams.get("code");if(y){Gt(p,a,()=>l(new Error(`OAuth error: ${y}`)));return}if(T!==i){p.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){p.writeHead(400).end("Missing authorization code");return}Gt(p,a,()=>s(S))}),g=await new Promise((h,p)=>{c.once("error",p),c.listen(t.transport.port??0,"127.0.0.1",()=>{h(c.address().port)})}),u=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),r),m=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",m,{once:!0});try{let h=`http://127.0.0.1:${g}/callback`,p=new URL(t.metadata.authorization_endpoint);p.searchParams.set("client_id",t.clientId),p.searchParams.set("response_type","code"),p.searchParams.set("redirect_uri",h),p.searchParams.set("code_challenge",o),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("state",i),p.searchParams.set("scope",t.scope??"openid offline_access");let C=p.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let y=await d;e({type:"state",status:"exchanging"});let T=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:y,code_verifier:n,redirect_uri:h})});if(!T.ok){let R=await T.text().catch(()=>"");throw new Error(`Token exchange failed (${T.status}): ${R}`)}let S=Y(await T.json());return e({type:"state",status:"authenticated"}),S}catch(h){throw e({type:"state",status:"error"}),h}finally{clearTimeout(u),t.signal?.removeEventListener("abort",m),c.close()}}function Gt(t,e,n){t.writeHead(302,{location:e}).end(n)}var Fe="matilda-code",Te="MATILDA_API_KEY",Hn="openid profile email offline_access matilda:code",Ae="matilda";function $e(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Nt(){return jn(Ye.getGlobalMatildaDir(),"matilda-auth.json")}function ze(){return Ge(Nt())}function Bn(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 Wn(t,e){let n=Bn(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 Kt(t){try{return await De(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 N(){try{let t=zn(Nt(),"utf8"),n=JSON.parse(t)[Ae];if(!n)return null;let o=JSON.parse(n);return typeof o?.accessToken=="string"&&typeof o?.baseUrl=="string"?o:null}catch{return null}}async function Vn(t){await ze().store.set(Ae,JSON.stringify(t)),process.env[Te]=t.accessToken}async function Jn(){await ze().store.remove(Ae),delete process.env[Te]}function dr(){let t=N();return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function cr(t){let e=N();if(e?.accessToken){let n=$e(e.baseUrl);await fetch(`${n}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(e.refreshToken?{refreshToken:e.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await Jn()}async function je(t){let e=N();if(!e||t?.baseUrl&&e.baseUrl!==t.baseUrl)return t?.fallbackAccessToken??process.env[Te]??"";let n=$e(e.baseUrl),o=await Kt(n),{store:i,lock:r}=ze(),s=await qn(i,r,o.token_endpoint,e.baseUrl,t?.signal).getAccessToken({forceRefresh:t?.forceRefresh});return process.env[Te]=s,s}async function ur(){await je();let t=N();if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function qn(t,e,n,o,i){return Ne({tokenEndpoint:n,clientId:Fe,store:{get:async s=>{let l=JSON.parse(await t.get(s)??"{}");if(!l.accessToken)return null;let d={accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.accessTokenExpiresAt};return JSON.stringify(d)},set:async(s,l)=>{let d=JSON.parse(l),c=JSON.parse(await t.get(s)??"{}"),g={...c,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??c.refreshToken??"",baseUrl:c.baseUrl??o};await t.set(s,JSON.stringify(g))},remove:s=>t.remove(s)},storageKey:Ae,lock:e,fetchImpl:(s,l)=>fetch(s,{...l,signal:i}),expirySkewMs:3e5})}async function pr(t){let e=$e(t.baseUrl),n=await Kt(e),o="",i=s=>Ke({metadata:n,clientId:Fe,scope:s,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Fe)}`},signal:t.signal,onEvent:l=>{l.type==="authorize_url"&&(o=l.url,t.onAuthorizeUrl?.(l.url))},openBrowser:async l=>{if(t.openBrowser===!1||process.env.MATILDA_AUTH_SKIP_BROWSER==="1")return;let{default:d}=await import("./open-QQ7FWG4A.js");await d(l).catch(()=>{})}}),r;try{r=await i(Hn)}catch(s){if(s instanceof Error&&s.message.includes("invalid_scope"))r=await i("openid offline_access");else throw s}let a=Wn(r,t.baseUrl);return await Vn(a),{...a,authorizeUrl:o}}var G=(r=>(r.USE_OPENAI="openai",r.MATILDA_OAUTH="matilda-oauth",r.USE_GEMINI="gemini",r.USE_VERTEX_AI="vertex-ai",r.USE_ANTHROPIC="anthropic",r))(G||{}),Yn="MATILDA_AGENT_SDK",Me="MATILDA_API_KEY";function Xn(t){if(t.apiKey||t.apiKeyEnvKey!==Me)return;let e=N();e?.accessToken&&(t.apiKey=e.accessToken,process.env[Me]=e.accessToken)}async function Zn(t){if(t.apiKeyEnvKey!==Me)return;let e=N();if(!e?.accessToken)return;let n=await je({baseUrl:t.baseUrl,fallbackAccessToken:e.accessToken});n&&(t.apiKey=n,process.env[Me]=n)}function Qn(t){return t.matildaAgentSdk===!0||process.env[Yn]==="1"}function He(t,e,n){t[e]=n}function eo(t,e){return t?.[e]}function to(t,e,n,o,i){let r={...o||{}},a=i?.strictModelProvider===!0,s={...n||{},authType:e,proxy:t?.getProxy()};He(r,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&He(r,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>eo(o,c)??{kind:"unknown"};for(let c of de)n&&c in n&&!r[c]&&He(r,c,l(c));Xn(s);let d=$t(s,a);if(!d.valid)throw new Error(d.errors.map(c=>c.message).join(`
9
9
  `));return{config:s,sources:r}}function $t(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new ue(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Pt(t.authType);n.push(new ge({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new pe(t.authType));else{let o=Et(t.authType);n.push(new fe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new he({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new me)),{valid:n.length===0,errors:n}}function Tr(t,e,n){return to(t,e,n).config}function Ft(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 Ar(t,e,n){await Zn(t);let o=$t(t,!1);if(!o.valid)throw new Error(o.errors.map(a=>a.message).join(`
10
- `));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(Qn(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-Y2ECTUZO.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-XI6SCJ2G.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-2IUZAZEO.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-HATVJLJF.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Ft(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-CZLOMDXF.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-HZHMNMGX.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Ft(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
10
+ `));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(Qn(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-J3PXQMRW.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-PGCPCIUM.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-2IUZAZEO.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-6WVY252A.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Ft(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-DKMAJXYA.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-DROE6XUC.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Ft(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
11
11
  Please exit and restart Matilda to use the '${i}' provider.`,{cause:s}):a}return new J(r,e,t)}var Be=b("MODEL_REGISTRY");function zt(t){if(Object.values(G).includes(t))return t}function no(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function jt(t,e){return e?`${t}\0${e}`:t}var Ce=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return lt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",ce),e)for(let[n,o]of Object.entries(e)){let i=zt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let i of n){let r=jt(i.id,i.baseUrl);if(o.has(r)){Be.warn(`Duplicate model id "${i.id}"${i.baseUrl?` with baseUrl "${i.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let a=this.resolveModelConfig(i,e);o.set(r,a)}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??W(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let i=this.modelsByAuthType.get(e);if(!i)return;if(o)return i.get(jt(n,o));let r=i.get(n);if(r)return r;for(let a of i.values())if(a.id===n)return a}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,U);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||no(e.id))&&(o.modalities=q(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 i=zt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}};export{we as a,ne as b,It as c,hn as d,V as e,Uo as f,q as g,se as h,Go as i,le as j,$o as k,zo as l,ce as m,jo as n,jt as o,Ce as p,Ut as q,Nt as r,N as s,Vn as t,Jn as u,dr as v,cr as w,je as x,ur as y,pr as z,G as A,to as B,$t as C,Tr as D,Ar as E};
12
12
  /**
13
13
  * @license