@maincode-ai/matilda-code 0.19.9 → 0.20.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/{qc-helper → mainy}/SKILL.md +2 -2
- package/bundled/{qc-helper → mainy}/docs/features/commands.md +6 -6
- package/bundled/{qc-helper → mainy}/docs/features/headless.md +37 -0
- package/bundled/{qc-helper → mainy}/docs/features/mcp.md +3 -3
- package/chunks/{agent-HKORTAHR.js → agent-CE34X462.js} +1 -1
- package/chunks/{agent-headless-F7NN2K2V.js → agent-headless-CNI7H4BU.js} +1 -1
- package/chunks/{anthropicContentGenerator-DKMAJXYA.js → anthropicContentGenerator-ATLOKYPR.js} +1 -1
- package/chunks/chunk-3YLXGE6T.js +8 -0
- package/chunks/{chunk-GTR4V2PV.js → chunk-DC7LAFZZ.js} +1 -1
- package/chunks/chunk-DHBNZZZO.js +95 -0
- package/chunks/{chunk-KP6BLFQS.js → chunk-GIIMOLLN.js} +1 -1
- package/chunks/chunk-IMYUVCF7.js +27 -0
- package/chunks/{chunk-3KCDX6MY.js → chunk-ISW2QC5B.js} +1 -1
- package/chunks/{chunk-H5PGSQP2.js → chunk-J56KRT6Z.js} +458 -458
- package/chunks/chunk-OCXGNAAT.js +8 -0
- package/chunks/{chunk-2GMJHSBF.js → chunk-OQVITNHW.js} +1 -1
- package/chunks/{chunk-GN7ECS3T.js → chunk-SKBC2YV2.js} +4 -4
- package/chunks/{chunk-XXZH7C44.js → chunk-SS5WUOSJ.js} +1 -1
- package/chunks/chunk-T75X5DJI.js +101 -0
- package/chunks/{chunk-TDVEFJRU.js → chunk-WUQZ3WFM.js} +1 -1
- package/chunks/chunk-XJDC3ZQZ.js +8 -0
- package/chunks/{computer-use-BBMGDR5Q.js → computer-use-4533FJAL.js} +1 -1
- package/chunks/contextCommand-M7LA5BRD.js +3 -0
- package/chunks/edit-U4P4JWQ6.js +38 -0
- package/chunks/{enter-worktree-VQHP27VO.js → enter-worktree-CUDNIQNH.js} +1 -1
- package/chunks/enterPlanMode-SUTLQUZO.js +18 -0
- package/chunks/{exit-worktree-JNQ5QJ3V.js → exit-worktree-72O3N4X4.js} +1 -1
- package/chunks/{exitPlanMode-VTB3FQTP.js → exitPlanMode-ZP75YCUK.js} +14 -14
- package/chunks/geminiContentGenerator-KPR5Q3XX.js +8 -0
- package/chunks/{glob-A3AI5R62.js → glob-V7YUXA6Z.js} +1 -1
- package/chunks/{grep-IH2T7KTD.js → grep-WOVNDJPG.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-QKMXPB2A.js → matildaAgentContentGenerator-Y5CHD2WJ.js} +1 -1
- package/chunks/matildaContentGenerator-F2DTT47Z.js +8 -0
- package/chunks/matildaOAuth2-LKOMJUC6.js +3 -0
- package/chunks/{monitor-4DTQSZEC.js → monitor-G7G765XR.js} +1 -1
- package/chunks/{notebook-edit-CZRTFD7U.js → notebook-edit-QK7K5ALF.js} +1 -1
- package/chunks/{openaiContentGenerator-AZI4WQN4.js → openaiContentGenerator-XLDE2S4K.js} +1 -1
- package/chunks/ripGrep-W5JZVWA4.js +3 -0
- package/chunks/{scheduler-5LM4YZEI.js → scheduler-C7N3Q67S.js} +1 -1
- package/chunks/{serve-7IPJHK45.js → serve-WDV5Q7R4.js} +1 -1
- package/chunks/shell-IEGVNM6S.js +3 -0
- package/chunks/src-Y3JZTLKR.js +3 -0
- package/chunks/{team-create-TRYOTUXF.js → team-create-OPP7B3G2.js} +1 -1
- package/chunks/{update-goal-DH2TEYYU.js → update-goal-6WDBMJ2I.js} +1 -1
- package/chunks/{web-fetch-5F7C7MXU.js → web-fetch-QP42GV23.js} +1 -1
- package/chunks/{web-search-6RI3HXMN.js → web-search-FURCBRRK.js} +1 -1
- package/chunks/{workflow-TTK6ZMKW.js → workflow-B3DRPVNT.js} +2 -2
- package/chunks/write-file-T7MBHX53.js +11 -0
- package/cli.js +476 -456
- package/package.json +2 -2
- package/chunks/chunk-7VGUNT5L.js +0 -8
- package/chunks/chunk-CLUEFPSU.js +0 -8
- package/chunks/chunk-LLQVLTPB.js +0 -27
- package/chunks/chunk-LNTXZVVL.js +0 -101
- package/chunks/chunk-PKETH5KK.js +0 -90
- package/chunks/contextCommand-HGBI6TH7.js +0 -3
- package/chunks/edit-RF2YFGIO.js +0 -38
- package/chunks/enterPlanMode-6FANAN7K.js +0 -17
- package/chunks/geminiContentGenerator-UJMSJR23.js +0 -8
- package/chunks/matildaContentGenerator-O2TF3IDJ.js +0 -8
- package/chunks/matildaOAuth2-2IUZAZEO.js +0 -3
- package/chunks/ripGrep-BZMM5FLN.js +0 -3
- package/chunks/shell-5O45TMEX.js +0 -3
- package/chunks/src-6MF6HV7Q.js +0 -3
- package/chunks/write-file-HOM26KX6.js +0 -11
- /package/bundled/{qc-helper → mainy}/docs/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/common-workflow.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/auth.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/matilda-ignore.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/model-providers.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/settings.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/themes.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/configuration/trusted-folders.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/extension/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/extension/extension-releasing.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/extension/getting-started-extensions.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/extension/introduction.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/approval-mode.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/arena.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/auto-mode.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/dingtalk.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/feishu.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/overview.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/plugins.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/telegram.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/channels/weixin.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/code-review.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/dual-output.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/followup-suggestions.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/hooks.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/language.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/lsp.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/markdown-rendering.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/memory.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/sandbox.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/scheduled-tasks.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/skills.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/status-line.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/structured-output.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/sub-agents.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/tips.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/token-caching.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/tool-use-summaries.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/features/worktree.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/ide-integration/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/ide-integration/ide-companion-spec.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/ide-integration/ide-integration.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/integration-github-action.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/integration-jetbrains.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/integration-vscode.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/integration-zed.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/matilda-serve-deploy-local.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/matilda-serve.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/overview.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/quickstart.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/reference/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/reference/keyboard-shortcuts.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/support/Uninstall.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/support/_meta.ts +0 -0
- /package/bundled/{qc-helper → mainy}/docs/support/tos-privacy.md +0 -0
- /package/bundled/{qc-helper → mainy}/docs/support/troubleshooting.md +0 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"bundled"
|
|
23
23
|
],
|
|
24
24
|
"config": {
|
|
25
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.
|
|
25
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.20.1"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {},
|
|
28
28
|
"optionalDependencies": {
|
package/chunks/chunk-7VGUNT5L.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as t}from"./chunk-GZPNIYVZ.js";t();import{AsyncLocalStorage as e}from"node:async_hooks";var o=new e;export{o as a};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-CLUEFPSU.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as s}from"./chunk-7VGUNT5L.js";import{b as d}from"./chunk-GZPNIYVZ.js";d();import{AsyncLocalStorage as O}from"node:async_hooks";import{randomUUID as E}from"node:crypto";var T="x-matilda-reported-operation-id",c="x-matilda-reported-attempt-purpose",P=[T,c],A=new Set(P),f=["answer","tool_followup","continuation","retry","compaction","unknown"],m=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,_=new Set(f),a=new O,x=new WeakSet;function u(){return E()}function p(t,e){let r=Object.freeze({operationId:t,attemptPurpose:e});return x.add(r),r}function N(t){return A.has(t.toLowerCase())}function i(){let t=a.getStore();return t&&x.has(t)?t:void 0}var R=class{activeOperationId;begin(e){return this.activeOperationId=u(),p(this.activeOperationId,e)}continue(e){let r=i()?.operationId??this.activeOperationId??u();return this.activeOperationId=r,p(r,e)}};function n(t,e){return a.run(t,e)}function S(t){a.enterWith(t)}function h(t,e){let r=i();return r?n(p(r.operationId,t),e):e()}function I(t,e){let r={next:(...o)=>n(t,()=>e.next(...o)),return:o=>n(t,()=>e.return(o)),throw:o=>n(t,()=>e.throw(o)),[Symbol.asyncIterator]:()=>r};return r}function w(t,e){let r=i();return r?I(p(r.operationId,t),e):e}function D(){let t=i();if(!t||!m.test(t.operationId))return{};let e=s.getStore()?.attempt,r=e!==void 0&&e>1?"retry":t.attemptPurpose;return _.has(r)?{[T]:t.operationId,[c]:r}:{}}export{T as a,c as b,P as c,f as d,N as e,i as f,R as g,n as h,S as i,h as j,I as k,w as l,D as m};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-LLQVLTPB.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{c as N}from"./chunk-XKDGRW3K.js";import{c as Q}from"./chunk-ESSYHTAZ.js";import{b as X}from"./chunk-IOCF4XSR.js";import{L as F,Y as x}from"./chunk-QWBNNEV2.js";import{b as D}from"./chunk-GZPNIYVZ.js";D();import ie from"crypto";import j from"node:path";import{promises as M}from"node:fs";import{EventEmitter as Ae}from"events";import{randomUUID as se}from"node:crypto";D();import{execFile as de,spawn as ue}from"node:child_process";import{promisify as he}from"node:util";import{platform as me}from"node:os";import{resolve as Z}from"node:path";import{URL as fe,fileURLToPath as pe}from"node:url";D();var le=["www-browser"];function U(o){let e=o.replace(/\\/g,"/").split("/").pop();return!!e&&le.includes(e)}function H(o={}){let r=process.env.BROWSER?.trim()?.match(/^\S+/)?.[0];if(!o.ignoreBrowserBlocklist&&process.platform!=="win32"&&r&&U(r)||process.env.CI||process.env.DEBIAN_FRONTEND==="noninteractive")return!1;let t=!!process.env.SSH_CONNECTION;return!(process.platform==="linux"&&!["DISPLAY","WAYLAND_DISPLAY","MIR_SOCKET"].some(s=>!!process.env[s])||t&&process.platform!=="linux")}var ee=he(de);function ge(o,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new fe(o)}catch{throw new Error(`Invalid URL: ${o}`)}let i=e?["http:","https:","file:"]:["http:","https:"];if(!i.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${i.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(pe(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(o))throw new Error("URL contains invalid characters")}async function te(o,e={}){ge(o,e);let r=me(),t,i,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:Ee(n,o);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${we(l)}. Falling back to the platform browser opener.`)}if(!H({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${o}`);return}switch(r){case"darwin":t="open",i=[o];break;case"win32":t="powershell.exe",i=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${o.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",i=[o];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,i,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[o]):await ee(d,[o],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${o}`);return}}async function re(o,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,i)=>{let n=ue(o,e,r),s=!1;n.once("error",c=>{s||(s=!0,i(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function we(o){return o instanceof Error?o.message:String(o)}function Ee(o,e){if(!o)return;let r=ke(o);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(U(r.command))return;let t=!1,i=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||i.push(e),{command:r.command,args:i}}function ke(o){let e=[],r="",t;for(let s of o){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[i,...n]=e;if(i)return{command:i,args:n}}function Ye(){return H()}D();import B from"node:path";import{promises as y,unlinkSync as _e}from"node:fs";import{randomUUID as ne}from"node:crypto";var R=x("MATILDA_OAUTH"),Ce="oauth_creds.json",ve="oauth_creds.lock",ye=30*1e3,Te=35e3,De=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var u=class extends Error{constructor(r,t,i){super(t);this.type=r;this.originalError=i;this.name="TokenManagerError"}};function Re(o){if(!o||typeof o!="object")throw new Error("Invalid credentials format");let e=o,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var A=class o{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return o.instance||(o.instance=new o),o.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();_e(e)}catch{}},process.on("exit",this.cleanupFunction),process.on("SIGINT",this.cleanupFunction),process.on("SIGTERM",this.cleanupFunction),process.on("uncaughtException",this.cleanupFunction),process.on("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof u?t:new u("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<De)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let i;return Promise.race([e.finally(()=>{i&&clearTimeout(i)}),new Promise((n,s)=>{i=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new u("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),i=(await y.stat(r)).mtimeMs;i>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=i,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new u("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),i=JSON.parse(t),n=Re(i),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&R.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),i=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new u("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(i),n=!0;let c=Date.now()-t;if(c>5e3&&R.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&R.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new u("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new u("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof O?(R.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new u("REFRESH_FAILED",s.message,s)):s instanceof u?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new u("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new u("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(i)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=B.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let i=JSON.stringify(e,null,2);try{await X(r,i,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ye}getCredentialFilePath(){return B.join(F.getGlobalMatildaDir(),Ce)}getLockFilePath(){return B.join(F.getGlobalMatildaDir(),ve)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:i}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>Te){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),R.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){R.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){R.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,i)}else throw new u("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new u("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&R.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),process.removeListener("SIGINT",this.cleanupFunction),process.removeListener("SIGTERM",this.cleanupFunction),process.removeListener("uncaughtException",this.cleanupFunction),process.removeListener("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var h=x("MATILDA_OAUTH"),Y="https://chat.matilda.ai",be=`${Y}/api/v1/oauth2/device/code`,K=`${Y}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",Se="urn:ietf:params:oauth:grant-type:device_code",Fe=3e4,Oe="oauth_creds.json";function Pe(){return ie.randomBytes(32).toString("base64url")}function Ie(o){let e=ie.createHash("sha256");return e.update(o),e.digest("base64url")}function xe(){let o=Pe(),e=Ie(o);return{code_verifier:o,code_challenge:e}}function W(o){return Object.keys(o).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(o[e])}`).join("&")}function q(o,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${N(o,{url:K})}`,{cause:o})}var O=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},V=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function G(o){return"device_code"in o}function Le(o){return"access_token"in o&&o.access_token!==null&&o.access_token!==void 0&&typeof o.access_token=="string"&&o.access_token.length>0}function $e(o){return"status"in o&&o.status==="pending"}function L(o){return"error"in o}var J=class{credentials={};sharedManager;constructor(){this.sharedManager=A.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return h.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},i=await fetch(be,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:W(t),...r?.signal?{signal:r.signal}:{}});if(!i.ok){let s=await i.text();throw new Error(`Device authorization failed: ${i.status} ${i.statusText}. Response: ${s}`)}let n=await i.json();if(G(n))h.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;h.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!G(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:Se,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},i=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:W(t),...r?.signal?{signal:r.signal}:{}});if(!i.ok){let n=await i.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${i.status} ${i.statusText}. Response: ${n}`);throw l.status=i.status,l}if(i.status===400&&s.error==="authorization_pending")return{status:"pending"};if(i.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new V({oauthError:s.error,description:s.error_description,status:i.status})}return await i.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Fe});h.debug("Refreshing access token...");try{let i;try{i=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:W(e),signal:r})}catch(a){throw q(a,r.aborted)}if(!i.ok){let a;try{a=await i.text()}catch(d){throw q(d,r.aborted)}throw i.status===400||i.status===401?(await ae(),new O("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:i.status,response:a})):new Error(`Token refresh failed: ${i.status} ${i.statusText}. Response: ${a}`)}let n;try{n=await i.text()}catch(a){throw q(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},Ne=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))(Ne||{}),S=new Ae;async function _r(o,e){let r=new J,t=A.getInstance();try{let i=await t.getValidCredentials(r);return r.setCredentials(i),r}catch(i){if(i instanceof u)switch(i.type){case"NO_REFRESH_TOKEN":h.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":h.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":h.warn("Network error during token refresh, trying device flow");break;default:h.warn("Token manager error:",i.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await He(r,o);if(!n.success){n.reason==="timeout"&&S.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ue(o){let e="Legacy OAuth Device Authorization",r=o,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(f,T)=>{if(f.startsWith("http://")||f.startsWith("https://")){let v=[];for(let I=0;I<f.length;I+=T)v.push(f.substring(I,I+T));return v}let b=f.split(" "),C=[],_="";for(let v of b)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",E="|"+" ".repeat(n-2)+"|",P="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),m=c(r,s),k="Waiting for authorization to complete...";process.stderr.write(`
|
|
4
|
-
`+w+`
|
|
5
|
-
`),process.stderr.write(E+`
|
|
6
|
-
`);for(let f of g)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
|
|
7
|
-
`);process.stderr.write(E+`
|
|
8
|
-
`);for(let f of m)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
|
|
9
|
-
`);process.stderr.write(E+`
|
|
10
|
-
`),process.stderr.write("| "+k+" ".repeat(s-k.length)+` |
|
|
11
|
-
`),process.stderr.write(E+`
|
|
12
|
-
`),process.stderr.write(P+`
|
|
13
|
-
|
|
14
|
-
`)}async function He(o,e){let r=!1,t=()=>{r=!0};S.once("auth-cancel",t);let i=()=>{if(!r)return null;let c="Authentication cancelled by user.";return h.debug(`
|
|
15
|
-
`+c),S.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{S.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);h.warn(`Failed to open browser automatically: ${a}`),h.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=xe(),a=await o.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!G(a)){let E=a;throw new Error(`Device authorization failed: ${E?.error||"Unknown error"} - ${E?.error_description||"No details provided"}`)}S.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ue(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),h.debug(`Waiting for authorization...
|
|
16
|
-
`);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let E=0;E<p;E++){let P=i();if(P)return P;try{h.debug("polling for token...");let g=await o.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Le(g)){let m=g,k={access_token:m.access_token,refresh_token:m.refresh_token||void 0,token_type:m.token_type,resource_url:m.resource_url,expiry_date:m.expires_in?Date.now()+m.expires_in*1e3:void 0};return o.setCredentials(k),await Be(k),n("success","Authentication successful! Access token obtained."),h.debug("Authentication successful! Access token obtained."),{success:!0}}if($e(g)){g.slowDown?(d=Math.min(d*1.5,1e4),h.debug(`
|
|
17
|
-
Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${E+1}/${p})`),await new Promise(f=>{let b=0,C=setInterval(()=>{if(b+=100,r){clearInterval(C),f();return}if(b>=d){clearInterval(C),f();return}},100)});let k=i();if(k)return k;continue}if(L(g)){let m=g;throw new Error(`Token polling failed: ${m?.error||"Unknown error"} - ${m?.error_description||"No details provided"}`)}}catch(g){let m=g instanceof Error?g.message:String(g),k=g instanceof Error?g.status:null,f=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=i();if(T)return T;if(m.includes("Failed to cache credentials"))return f("error",m);if(m.includes("401")||k===401)return f("error","Device code expired or invalid, please restart the authorization process.");if(m.includes("429")||k===429)return f("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let b=`Error polling for token: ${m}`;n("error",b),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${N(c,{url:Y})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{S.off("auth-cancel",t)}}var $=384;async function Be(o,e){let r=ce();try{await M.mkdir(j.dirname(r),{recursive:!0});let t=JSON.stringify(o,null,2),i=`${r}.tmp.${process.pid}.${se()}`;try{await M.writeFile(i,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await M.chmod(i,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);h.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${i} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await M.rename(i,r)}catch(n){try{await M.unlink(i)}catch{}throw n}try{A.getInstance().clearCache()}catch(n){h.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let i=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${j.dirname(r)}\` and writing to \`${r}\`. ${i}. Please check permissions.`)}}async function ae(){try{let o=ce();await M.unlink(o),h.debug("Cached legacy OAuth credentials cleared successfully.")}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return;h.warn("Warning: Failed to clear cached legacy OAuth credentials:",o)}finally{try{A.getInstance().clearCache()}catch{}}}function ce(){return j.join(F.getGlobalMatildaDir(),Oe)}var Cr=ae;export{U as a,H as b,te as c,Ye as d,A as e,Pe as f,Ie as g,xe as h,O as i,V as j,G as k,Le as l,$e as m,L as n,J as o,Ne as p,S as q,_r as r,$ as s,Be as t,ae as u,Cr as v};
|
|
18
|
-
/**
|
|
19
|
-
* @license
|
|
20
|
-
* Copyright 2025 Google LLC
|
|
21
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
22
|
-
*/
|
|
23
|
-
/**
|
|
24
|
-
* @license
|
|
25
|
-
* Copyright 2025 Matilda
|
|
26
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
27
|
-
*/
|
package/chunks/chunk-LNTXZVVL.js
DELETED
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as U,d as at}from"./chunk-4F4DA5UI.js";import{a as ot,b as it,e as Ie,n as st,q as W,r as lt}from"./chunk-XYA3SFGC.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as rt}from"./chunk-7VGUNT5L.js";import{Jc as et,Kc as tt,Mb as Xe,Mc as nt,Pb as Ze,Rb as Qe,Sa as K,Wa as ve,Xa as _e,Ya as xe,eb as be,f as P,fb as F,tb as Q,ub as ee}from"./chunk-CFBZKYFB.js";import{L as Ye,Y as b,c as qe,d as j,e as H}from"./chunk-QWBNNEV2.js";import{h as k,l as Se,n as Bt}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();f();var te=b("TAGGED_THINKING_PARSER"),dt=["<think>","<thinking>"],ct=["</think>","</thinking>"],Wt=Math.max(...dt.map(t=>t.length),...ct.map(t=>t.length));function ke(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Vt(t,e,n){let o=t.length-e;return o<=0||o>Wt?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function Jt(t,e,n){return n.find(o=>t.startsWith(o,e))}var we=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){let s=this.mode==="text"?dt:ct,l=Jt(o,a,s);if(l){te.debug(`taggedThinking: detected tag "${l}" at offset ${a}`),ke(i,r,this.mode),r="",this.mode=this.mode==="text"?"thought":"text",a+=l.length;continue}if(!n&&Vt(o,a,s))break;r+=this.buffer[a],a+=1}return a<this.buffer.length?(ke(i,r,this.mode),this.buffer=this.buffer.slice(a),te.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),i):(this.buffer="",this.mode==="thought"&&r&&te.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),ke(i,r,this.mode),te.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),i)}};function ut(t){return new we().parse(t,!0)}var w=b("CONVERTER"),yt="(attached media from previous tool call)";function Tt(t){let e=t.prompt_tokens||0,n=t.completion_tokens||0,o=t.total_tokens||0,i=t.prompt_tokens_details?.cached_tokens??t.cached_tokens??0,r=t.completion_tokens_details?.reasoning_tokens||0,a=t.usage_is_incomplete===!0||n>0&&e===0||o>0&&e===0&&n===0,s=e,l=n,d=o;return d===0&&(s>0||l>0)&&(d=s+l),{promptTokenCount:s,candidatesTokenCount:l,totalTokenCount:d,cachedContentTokenCount:i,thoughtsTokenCount:r,...a?{usageIsIncomplete:!0}:{}}}var qt=64,pt=1024;function gt(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)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.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,i=n>=pt&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=qt?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<pt&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function At(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 i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function Yt(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=At(r.parameters)),a&&(a=it(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function Xt(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return Qt(t,o),en(t.contents,o,e),o=Ct(o),n.cleanOrphanToolCalls&&(o=dn(o),o=Ct(o)),o}function Zt(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let p of o)typeof p=="string"?r.push(p):"text"in p&&p.text?"thought"in p&&p.thought?i.push(p.text):r.push(p.text):"functionCall"in p&&p.functionCall&&(a.push({id:p.functionCall.id||`call_${s}`,type:"function",function:{name:p.functionCall.name||"",arguments:JSON.stringify(p.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},d=i.join("");d&&(l.reasoning_content=d),a.length>0&&(l.tool_calls=a);let c=ln(n?.finishReason),g=t.usageMetadata,u={prompt_tokens:g?.promptTokenCount||0,completion_tokens:g?.candidatesTokenCount||0,total_tokens:g?.totalTokenCount||0};g?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:g.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:u}}function Qt(t,e){if(!t.config?.systemInstruction)return;let n=St(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function en(t,e,n){if(Array.isArray(t))for(let o of t)ft(o,e,n);else t&&ft(t,e,n)}function ft(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!rn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,d=new Set,c=new Set,g=[];for(let u of o){if(typeof u=="string"){r.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&i==="assistant"&&u.text&&a.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&r.push({type:"text",text:u.text});let m=Mt(u,n);if(m&&i==="user"&&r.push(m),"functionCall"in u&&u.functionCall&&i==="assistant"){let h=u.functionCall.id;if(h){if(d.has(h)){w.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}d.add(h)}s.push({id:h||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&i==="user"){let h=u.functionResponse.id;if(h){if(c.has(h))continue;c.add(h)}let p=nn(u.functionResponse,n);if(p){if(n.splitToolMedia&&Array.isArray(p.content)){let C=[],y=[];for(let T of p.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
|
|
4
|
-
`);p.content=T||"[media attached in following user message]",g.push(...C)}}e.push(p)}}}if(g.length>0&&e.push({role:"user",content:[{type:"text",text:yt},...g]}),i==="assistant"){if(r.length===0&&s.length===0&&a.length===0)return;let m={role:"assistant",content:r.filter(p=>p.type==="text").map(p=>p.text).join("")||(a.length>0?"":null)};s.length>0&&(m.tool_calls=s);let h=a.join("");h&&(m.reasoning_content=h),e.push(m);return}r.length>0&&e.push({role:"user",content:r})}function tn(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 nn(t,e){let n=tn(t.response),o=[];n&&o.push({type:"text",text:n});for(let i of t.parts||[]){if("text"in i&&typeof i.text=="string"){i.text.length>0&&o.push({type:"text",text:i.text});continue}let r=Mt(i,e);r&&o.push(r)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function Mt(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,i=ht(o),r=t.inlineData.displayName||o;if(i==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:L("image",r,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}`}}:L("pdf",r,e);if(i==="audio"){if(!n.audio)return L("audio",r,e);let a=on(o);if(a)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:a}}}return i==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:L("video",r,e):{type:"text",text:`Unsupported inline media type: ${o} (${r}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",i=t.fileData.fileUri,r=t.fileData.mimeType,a=ht(r);if(a==="image")return n.image?{type:"image_url",image_url:{url:i}}:L("image",o,e);if(r==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:i}}:L("pdf",o,e);if(a==="video")return n.video?{type:"video_url",video_url:{url:i}}:L("video",o,e);let s=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${r}${s}.`}}return null}function L(t,e,n){w.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 ht(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function on(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function rn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function St(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>St(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 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
|
-
${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
|
-
`));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-QKMXPB2A.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-AZI4WQN4.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-2IUZAZEO.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-O2TF3IDJ.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-UJMSJR23.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
|
-
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
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2025 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2025 Google LLC
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* @license
|
|
24
|
-
* Copyright 2025 Matilda Team
|
|
25
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
26
|
-
*/
|
|
27
|
-
/**
|
|
28
|
-
* @license
|
|
29
|
-
* Copyright 2026 Matilda Team
|
|
30
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
31
|
-
*/
|
|
32
|
-
/**
|
|
33
|
-
* @license
|
|
34
|
-
* Copyright 2026 Maincode
|
|
35
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
36
|
-
*
|
|
37
|
-
* Low-level OAuth primitives for core-auth's unified `/api/auth/oauth/*` flow
|
|
38
|
-
* (ADR-029): PKCE pair generation, RFC 8414 discovery, the RFC 8628 device
|
|
39
|
-
* grant, and refresh. Vendored (as source) from matilda-core's
|
|
40
|
-
* `packages/client-sdk/src/auth.ts` and extended to carry the `id_token`
|
|
41
|
-
* (display identity) that the higher-level flows need. Node built-ins only —
|
|
42
|
-
* no third-party runtime dependencies.
|
|
43
|
-
*/
|
|
44
|
-
/**
|
|
45
|
-
* @license
|
|
46
|
-
* Copyright 2026 Maincode
|
|
47
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
48
|
-
*
|
|
49
|
-
* File-backed token store + cross-process lock. The store persists a JSON map
|
|
50
|
-
* (`{ [key]: value }`) at 0600 so callers can key several credentials in one
|
|
51
|
-
* file; the lock is an O_EXCL lockfile that serialises refreshes across
|
|
52
|
-
* processes (the guarantee a plaintext read/modify/write can't give).
|
|
53
|
-
*/
|
|
54
|
-
/**
|
|
55
|
-
* @license
|
|
56
|
-
* Copyright 2026 Maincode
|
|
57
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
58
|
-
*
|
|
59
|
-
* Hardened access-token manager: returns a valid access token, refreshing via
|
|
60
|
-
* core-auth's token endpoint when expired or forced. Single-flight within the
|
|
61
|
-
* process, serialised across processes by the store's lock, carries a prior
|
|
62
|
-
* refresh token forward when the response omits one, and evicts on a terminal
|
|
63
|
-
* `invalid_grant` so a dead session doesn't wedge the caller in a refresh loop.
|
|
64
|
-
*/
|
|
65
|
-
/**
|
|
66
|
-
* @license
|
|
67
|
-
* Copyright 2026 Maincode
|
|
68
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
69
|
-
*
|
|
70
|
-
* Browser login orchestration: PKCE + a loopback capture server, driven off
|
|
71
|
-
* discovery metadata. Unlike a bare loopback helper, this emits lifecycle
|
|
72
|
-
* events for a UI, honours an AbortSignal, and — instead of serving its own
|
|
73
|
-
* HTML — 302-redirects the browser to an app-owned branded landing
|
|
74
|
-
* (`successRedirect`). Returns a TokenSet including the `id_token`.
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* @license
|
|
78
|
-
* Copyright 2026 Maincode
|
|
79
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
80
|
-
*
|
|
81
|
-
* Node auth surface for `@maincode-ai/matilda-client-sdk/auth/node`.
|
|
82
|
-
* Re-exports the OAuth primitives plus the higher-level login flow, file token
|
|
83
|
-
* store, and hardened token manager that the CLI (`packages/core`) and the
|
|
84
|
-
* Electron desktop app consume.
|
|
85
|
-
*/
|
|
86
|
-
/**
|
|
87
|
-
* @license
|
|
88
|
-
* Copyright 2026 Maincode
|
|
89
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
90
|
-
*
|
|
91
|
-
* Matilda account auth for the CLI, backed by the shared client SDK.
|
|
92
|
-
*
|
|
93
|
-
* The OAuth dance (PKCE, loopback capture, code exchange, refresh, cross-process
|
|
94
|
-
* token locking) is owned by `@maincode-ai/matilda-client-sdk/auth/node` — the
|
|
95
|
-
* auth team's tested implementation of ADR-029's unified `/api/auth/oauth/*`
|
|
96
|
-
* flow. This module keeps ONLY the CLI-specific concerns: which endpoint, the
|
|
97
|
-
* on-disk credential shape the rest of the CLI already reads, and surfacing the
|
|
98
|
-
* authorize URL to the Ink UI. No PKCE crypto, no loopback server, no token
|
|
99
|
-
* exchange lives here anymore (replaced the 391-line hand-rolled beta that hit
|
|
100
|
-
* the divergent `/api/auth/cli/*` endpoints and stored tokens in plaintext).
|
|
101
|
-
*/
|