@maincode-ai/matilda-code 0.21.12 → 0.21.13-nightly.20261027.e00306cd3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/agent-H5JE3RJQ.js +3 -0
- package/chunks/agent-headless-H2JZZ7UV.js +3 -0
- package/chunks/{askUserQuestion-2QI4NSFJ.js → askUserQuestion-L3WDL2T4.js} +3 -3
- package/chunks/ca-UBWUTZVZ.js +25 -0
- package/chunks/chunk-4CVGYUEL.js +3 -0
- package/chunks/{chunk-RNKDFE2S.js → chunk-5B2QERWR.js} +1 -1
- package/chunks/chunk-62GTGPTP.js +8 -0
- package/chunks/chunk-6365AZBW.js +56 -0
- package/chunks/chunk-6PFK4XTH.js +207 -0
- package/chunks/chunk-7ZODGQO6.js +4 -0
- package/chunks/chunk-DB5LMKXU.js +31 -0
- package/chunks/chunk-EYZPVR7N.js +13 -0
- package/chunks/chunk-FKHUEFMK.js +8 -0
- package/chunks/{chunk-6T2GIM76.js → chunk-GILXFDEG.js} +1 -1
- package/chunks/{chunk-VTGICC67.js → chunk-GKEUZTOB.js} +1 -1
- package/chunks/chunk-GSRXW64P.js +120 -0
- package/chunks/chunk-GT6MSEK4.js +3 -0
- package/chunks/chunk-HEJO7OBH.js +3 -0
- package/chunks/chunk-HPO2YWG4.js +78 -0
- package/chunks/chunk-I3CV4LOD.js +8 -0
- package/chunks/{chunk-DOOFGSRV.js → chunk-J3AMKDX6.js} +1 -1
- package/chunks/chunk-JU7QTSKS.js +14 -0
- package/chunks/chunk-LBQNFSZ2.js +9 -0
- package/chunks/chunk-LOB42ODE.js +9 -0
- package/chunks/chunk-LVDDFAK4.js +89 -0
- package/chunks/{chunk-27Q5KW3A.js → chunk-NK2QMGCC.js} +13 -13
- package/chunks/{chunk-YRQP3SLC.js → chunk-O7VPFJ3R.js} +1 -1
- package/chunks/chunk-OBE5S4GG.js +9 -0
- package/chunks/{chunk-CZGZ3KK7.js → chunk-ONANBLIE.js} +1 -1
- package/chunks/chunk-QXSBPCBA.js +8 -0
- package/chunks/chunk-TUKNB5CQ.js +33 -0
- package/chunks/chunk-UM6CLO7D.js +7 -0
- package/chunks/chunk-V4D3LER3.js +2615 -0
- package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
- package/chunks/chunk-VUJRLLGL.js +8 -0
- package/chunks/{chunk-MCQUPLRE.js → chunk-WTU6GSZH.js} +1 -1
- package/chunks/chunk-XBTBZHRC.js +8 -0
- package/chunks/{chunk-WV3IUPZS.js → chunk-YTB3OFTT.js} +1 -1
- package/chunks/chunk-ZQKABJBB.js +8 -0
- package/chunks/chunk-ZSGBDQXU.js +11 -0
- package/chunks/{computer-use-WKDNUTLD.js → computer-use-N6KGNST6.js} +1 -1
- package/chunks/{cron-create-F2LXM2OA.js → cron-create-4XBY5RVI.js} +1 -1
- package/chunks/cron-delete-BH4VP3LX.js +3 -0
- package/chunks/cron-list-XXRFKNGM.js +5 -0
- package/chunks/de-LEEHWWJ2.js +25 -0
- package/chunks/{devtools-5JRKK3E7.js → devtools-7YNCRYZV.js} +1 -1
- package/chunks/{chunk-OOEH6ZSV.js → dist-UWUWLWTO.js} +2 -2
- package/chunks/{edit-QQNJZ55P.js → edit-6ULTLTJQ.js} +1 -1
- package/chunks/{en-EJLDYIBM.js → en-LNOIHFSQ.js} +4 -4
- package/chunks/{enter-worktree-5X5SAMBJ.js → enter-worktree-V2VANZYJ.js} +1 -1
- package/chunks/enterPlanMode-75H54S3Z.js +18 -0
- package/chunks/{exit-worktree-SRKZBEYF.js → exit-worktree-KPB32K6P.js} +1 -1
- package/chunks/{exitPlanMode-WSPTGGVN.js → exitPlanMode-K7JRP22Y.js} +2 -2
- package/chunks/fr-4TA2AIU6.js +25 -0
- package/chunks/{getMachineId-bsd-ZYBNK2JG.js → getMachineId-bsd-ETKQTB6C.js} +1 -1
- package/chunks/{getMachineId-darwin-CM2MQGUI.js → getMachineId-darwin-AKNRWOWB.js} +1 -1
- package/chunks/{getMachineId-linux-SYE2KMCW.js → getMachineId-linux-2QSD7FTP.js} +1 -1
- package/chunks/{getMachineId-unsupported-6IHVG2XO.js → getMachineId-unsupported-UXSV7I24.js} +1 -1
- package/chunks/{getMachineId-win-S3J3JSUM.js → getMachineId-win-4MTFXGP3.js} +1 -1
- package/chunks/glob-ACAIHWST.js +22 -0
- package/chunks/{goal-tools-C6BSBHCF.js → goal-tools-VPFXBI6M.js} +3 -3
- package/chunks/{grep-MVCOBUYW.js → grep-R4K75RXS.js} +1 -1
- package/chunks/{ja-GGNJR7AR.js → ja-VXDMQKRW.js} +5 -5
- package/chunks/keychain-token-storage-7VYNARRB.js +3 -0
- package/chunks/ls-4ZEICYPK.js +15 -0
- package/chunks/{lsp-DYDK6XCS.js → lsp-4US2RIIV.js} +1 -1
- package/chunks/mcp-client-ZKQFYCFN.js +3 -0
- package/chunks/monitor-KSNFIY54.js +32 -0
- package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
- package/chunks/notebook-edit-655ZNV6Q.js +17 -0
- package/chunks/openaiContentGenerator-BG3OM453.js +52 -0
- package/chunks/pt-WEIMCOKI.js +25 -0
- package/chunks/read-file-4VSUKSRB.js +3 -0
- package/chunks/ripGrep-PNALN2GG.js +3 -0
- package/chunks/ru-WFLK34ZL.js +25 -0
- package/chunks/scheduler-AVYCIBEK.js +8 -0
- package/chunks/send-message-ND2SRKX5.js +8 -0
- package/chunks/shell-GUHQNOMZ.js +3 -0
- package/chunks/{skill-HZPFEAPF.js → skill-AB2X2DTC.js} +1 -1
- package/chunks/src-LZEU4AYF.js +5 -0
- package/chunks/symbol-search-VICSUEZH.js +19 -0
- package/chunks/{syntheticOutput-432LXITX.js → syntheticOutput-Z7DQKMRI.js} +1 -1
- package/chunks/task-create-BQ73FRTH.js +3 -0
- package/chunks/{task-detach-XMSJ3HBM.js → task-detach-JCHSLUOR.js} +1 -1
- package/chunks/task-list-6ESRFO5F.js +9 -0
- package/chunks/{task-stop-NTS62FLG.js → task-stop-74H2CPAJ.js} +1 -1
- package/chunks/{task-update-AR26UFYZ.js → task-update-R3BN6KPQ.js} +1 -1
- package/chunks/{team-create-PYXFVIR5.js → team-create-UTKRPUPZ.js} +3 -3
- package/chunks/team-delete-PCCGTLGL.js +8 -0
- package/chunks/todoWrite-BZI75DFV.js +3 -0
- package/chunks/{tool-search-RKZDSRYS.js → tool-search-FJ5MAPQ6.js} +1 -1
- package/chunks/{web-fetch-VW3SVDQ6.js → web-fetch-DEUGZQZS.js} +17 -17
- package/chunks/{web-search-XQUIZARL.js → web-search-PUUIEFJO.js} +3 -3
- package/chunks/{workflow-YXNXDRWZ.js → workflow-CBADL3IM.js} +2 -2
- package/chunks/write-file-QGCL2AJL.js +15 -0
- package/cli.js +644 -679
- package/examples/starter/README.md +0 -3
- package/locales/ca.js +1 -37
- package/locales/de.js +1 -42
- package/locales/en.js +1 -43
- package/locales/fr.js +1 -39
- package/locales/ja.js +1 -42
- package/locales/pt.js +1 -42
- package/locales/ru.js +1 -42
- package/package.json +2 -2
- package/sandbox-macos-permissive-closed.sb +0 -1
- package/sandbox-macos-permissive-open.sb +0 -1
- package/sandbox-macos-permissive-proxied.sb +1 -2
- package/sandbox-macos-restrictive-closed.sb +14 -2
- package/sandbox-macos-restrictive-open.sb +14 -2
- package/sandbox-macos-restrictive-proxied.sb +15 -3
- package/bundled/mainy/SKILL.md +0 -157
- package/bundled/mainy/docs/_meta.ts +0 -32
- package/bundled/mainy/docs/common-workflow.md +0 -571
- package/bundled/mainy/docs/configuration/_meta.ts +0 -7
- package/bundled/mainy/docs/configuration/auth.md +0 -82
- package/bundled/mainy/docs/configuration/matilda-ignore.md +0 -55
- package/bundled/mainy/docs/configuration/model-providers.md +0 -598
- package/bundled/mainy/docs/configuration/settings.md +0 -790
- package/bundled/mainy/docs/configuration/themes.md +0 -199
- package/bundled/mainy/docs/configuration/trusted-folders.md +0 -67
- package/bundled/mainy/docs/extension/_meta.ts +0 -9
- package/bundled/mainy/docs/extension/extension-releasing.md +0 -204
- package/bundled/mainy/docs/extension/getting-started-extensions.md +0 -299
- package/bundled/mainy/docs/extension/introduction.md +0 -338
- package/bundled/mainy/docs/features/_meta.ts +0 -27
- package/bundled/mainy/docs/features/approval-mode.md +0 -388
- package/bundled/mainy/docs/features/arena.md +0 -219
- package/bundled/mainy/docs/features/auto-mode.md +0 -308
- package/bundled/mainy/docs/features/channels/_meta.ts +0 -8
- package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
- package/bundled/mainy/docs/features/channels/feishu.md +0 -186
- package/bundled/mainy/docs/features/channels/overview.md +0 -336
- package/bundled/mainy/docs/features/channels/plugins.md +0 -87
- package/bundled/mainy/docs/features/channels/telegram.md +0 -120
- package/bundled/mainy/docs/features/channels/weixin.md +0 -106
- package/bundled/mainy/docs/features/code-review.md +0 -291
- package/bundled/mainy/docs/features/commands.md +0 -528
- package/bundled/mainy/docs/features/dual-output.md +0 -627
- package/bundled/mainy/docs/features/followup-suggestions.md +0 -109
- package/bundled/mainy/docs/features/headless.md +0 -448
- package/bundled/mainy/docs/features/hooks.md +0 -1306
- package/bundled/mainy/docs/features/language.md +0 -171
- package/bundled/mainy/docs/features/lsp.md +0 -496
- package/bundled/mainy/docs/features/markdown-rendering.md +0 -183
- package/bundled/mainy/docs/features/mcp.md +0 -423
- package/bundled/mainy/docs/features/memory.md +0 -185
- package/bundled/mainy/docs/features/sandbox.md +0 -249
- package/bundled/mainy/docs/features/scheduled-tasks.md +0 -139
- package/bundled/mainy/docs/features/skills.md +0 -347
- package/bundled/mainy/docs/features/status-line.md +0 -397
- package/bundled/mainy/docs/features/structured-output.md +0 -309
- package/bundled/mainy/docs/features/sub-agents.md +0 -737
- package/bundled/mainy/docs/features/tips.md +0 -54
- package/bundled/mainy/docs/features/token-caching.md +0 -29
- package/bundled/mainy/docs/features/tool-use-summaries.md +0 -178
- package/bundled/mainy/docs/features/worktree.md +0 -345
- package/bundled/mainy/docs/ide-integration/_meta.ts +0 -4
- package/bundled/mainy/docs/ide-integration/ide-companion-spec.md +0 -182
- package/bundled/mainy/docs/ide-integration/ide-integration.md +0 -144
- package/bundled/mainy/docs/integration-github-action.md +0 -241
- package/bundled/mainy/docs/integration-jetbrains.md +0 -81
- package/bundled/mainy/docs/integration-vscode.md +0 -39
- package/bundled/mainy/docs/integration-zed.md +0 -72
- package/bundled/mainy/docs/matilda-serve-deploy-local.md +0 -221
- package/bundled/mainy/docs/matilda-serve.md +0 -661
- package/bundled/mainy/docs/overview.md +0 -64
- package/bundled/mainy/docs/quickstart.md +0 -234
- package/bundled/mainy/docs/reference/_meta.ts +0 -3
- package/bundled/mainy/docs/reference/keyboard-shortcuts.md +0 -91
- package/bundled/mainy/docs/support/Uninstall.md +0 -65
- package/bundled/mainy/docs/support/_meta.ts +0 -6
- package/bundled/mainy/docs/support/tos-privacy.md +0 -94
- package/bundled/mainy/docs/support/troubleshooting.md +0 -127
- package/chunks/agent-WM63A6NK.js +0 -3
- package/chunks/agent-headless-QIUBDKPW.js +0 -3
- package/chunks/anthropicContentGenerator-VKFTAIU3.js +0 -39
- package/chunks/ca-I2HEEIL7.js +0 -25
- package/chunks/chunk-2HTPVSGT.js +0 -3
- package/chunks/chunk-2MOGYHWM.js +0 -8
- package/chunks/chunk-3IRGBRSP.js +0 -113
- package/chunks/chunk-3YLXGE6T.js +0 -8
- package/chunks/chunk-47XR7IMP.js +0 -8
- package/chunks/chunk-4F4DA5UI.js +0 -8
- package/chunks/chunk-4J6DC24J.js +0 -59
- package/chunks/chunk-4Q2SNBUH.js +0 -18
- package/chunks/chunk-5C2RJ5RR.js +0 -37
- package/chunks/chunk-6E766NPX.js +0 -31
- package/chunks/chunk-6EQMZNIY.js +0 -8
- package/chunks/chunk-6GBNB5Z2.js +0 -3
- package/chunks/chunk-6Z2MV7ZY.js +0 -186
- package/chunks/chunk-BVOCFLC4.js +0 -56
- package/chunks/chunk-CSJTA7NE.js +0 -101
- package/chunks/chunk-DC7LAFZZ.js +0 -8
- package/chunks/chunk-DE3HKC2W.js +0 -9
- package/chunks/chunk-EQGA7LH7.js +0 -30
- package/chunks/chunk-FPO57O66.js +0 -39
- package/chunks/chunk-FWDMPRKU.js +0 -3
- package/chunks/chunk-G7R2XEEF.js +0 -7
- package/chunks/chunk-GOJCMVJJ.js +0 -8
- package/chunks/chunk-GTVCJCHR.js +0 -8
- package/chunks/chunk-JCE3JAVC.js +0 -25
- package/chunks/chunk-JRECUFB3.js +0 -2630
- package/chunks/chunk-KHHJYBR5.js +0 -9
- package/chunks/chunk-LJR4RZZ2.js +0 -3
- package/chunks/chunk-LUNDTQ3G.js +0 -8
- package/chunks/chunk-M53RP3YP.js +0 -31
- package/chunks/chunk-MO2HXJG5.js +0 -9
- package/chunks/chunk-MTMU7JYZ.js +0 -11
- package/chunks/chunk-O44XK65C.js +0 -8
- package/chunks/chunk-OA56BXPD.js +0 -3
- package/chunks/chunk-PA6532AY.js +0 -6
- package/chunks/chunk-PGXQZVLX.js +0 -8
- package/chunks/chunk-QKYGQLWC.js +0 -8
- package/chunks/chunk-QN6Y6NPA.js +0 -3
- package/chunks/chunk-QVCGLQCI.js +0 -32
- package/chunks/chunk-S3CWEVTS.js +0 -15
- package/chunks/chunk-SDTWBD62.js +0 -8
- package/chunks/chunk-T2T2UEPY.js +0 -4
- package/chunks/chunk-TISQNFB5.js +0 -3
- package/chunks/chunk-U347OO7S.js +0 -9
- package/chunks/chunk-UIRBHC5X.js +0 -3
- package/chunks/chunk-VI74YQQO.js +0 -8
- package/chunks/chunk-VYZOOSMP.js +0 -30
- package/chunks/chunk-WC2VTVCE.js +0 -27
- package/chunks/chunk-WVY2P6WH.js +0 -26
- package/chunks/chunk-WZ75OGYY.js +0 -14
- package/chunks/chunk-XMZIY7XX.js +0 -13
- package/chunks/chunk-YJAKOETP.js +0 -22
- package/chunks/chunk-YV3PUOBU.js +0 -65
- package/chunks/contextCommand-DAB3HOHY.js +0 -3
- package/chunks/cron-delete-DE6Q2S2L.js +0 -3
- package/chunks/cron-list-IAQEJVV7.js +0 -5
- package/chunks/de-AQXFJYZI.js +0 -25
- package/chunks/dist-7UYRLSLE.js +0 -3
- package/chunks/dist-ME6647DQ.js +0 -195
- package/chunks/dist-P6SLWL5V.js +0 -42
- package/chunks/dist-VG3ZDJ2A.js +0 -28
- package/chunks/dist-YTCHM57U.js +0 -23
- package/chunks/enterPlanMode-HP35SPLN.js +0 -18
- package/chunks/fileFromPath-7UCWPD4W.js +0 -3
- package/chunks/fr-6TDHK7F2.js +0 -25
- package/chunks/geminiContentGenerator-RJ73DQAP.js +0 -8
- package/chunks/glob-QQ6LGKDX.js +0 -22
- package/chunks/keychain-token-storage-KQK6MNOJ.js +0 -3
- package/chunks/ls-JYJXFSXN.js +0 -15
- package/chunks/matildaAgentContentGenerator-YUYS4336.js +0 -8
- package/chunks/matildaContentGenerator-O4Z2QPCP.js +0 -8
- package/chunks/matildaOAuth2-7COTQQR2.js +0 -3
- package/chunks/mcp-client-RXVQU5VI.js +0 -3
- package/chunks/monitor-77KXDXPR.js +0 -32
- package/chunks/notebook-edit-TKJD2EQZ.js +0 -17
- package/chunks/openaiContentGenerator-2EALAM3U.js +0 -3
- package/chunks/pt-D6L2QTDM.js +0 -25
- package/chunks/read-file-3KUAH6ND.js +0 -3
- package/chunks/ripGrep-U2PLKXMY.js +0 -3
- package/chunks/ru-BNJCHDYO.js +0 -25
- package/chunks/scheduler-J7VU2V5Y.js +0 -8
- package/chunks/send-message-P3SMWNEE.js +0 -8
- package/chunks/serve-FXH6EBQ6.js +0 -1015
- package/chunks/shell-PXR2AXDD.js +0 -3
- package/chunks/src-RFAEPLY7.js +0 -3
- package/chunks/src-WZTRMETQ.js +0 -5
- package/chunks/symbol-search-EAIZPWN7.js +0 -19
- package/chunks/task-create-Z3QRCMX4.js +0 -3
- package/chunks/task-list-GXAJW3JP.js +0 -9
- package/chunks/team-delete-OMYVUAQU.js +0 -8
- package/chunks/todoWrite-5NZ7CHTC.js +0 -3
- package/chunks/write-file-XDDLTGSG.js +0 -15
package/chunks/chunk-DC7LAFZZ.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as i}from"./chunk-GZPNIYVZ.js";i();var m="MATILDA_API_KEY";var g="matilda-code-1.0",u="Matilda",_="https://matilda.maincode.com/api/v1/code";var A={id:"matilda",label:"Matilda",description:"Connect to the Matilda Core code API endpoint",protocol:"openai",baseUrl:_,envKey:m,models:[{id:g,displayName:u,contextWindowSize:1048576,description:"Matilda Code model",generationConfig:{openAIRequestProfile:"matilda-code",timeout:6e5,samplingParams:{max_tokens:65536,chat_template_kwargs:{enable_thinking:!0}},schemaCompliance:"openapi_30",splitToolMedia:!0,customHeaders:{"User-Agent":"MatildaCode/0.1"}}}],modelNamePrefix:"",documentationUrl:"https://matilda.maincode.help/welcome/external-api",uiGroup:"third-party"};function h(o){return o.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}async function f(o){let{baseUrl:n,email:s,password:d,signal:l}=o,r=h(n),p=`${r}/api/auth/login`,t;try{t=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:s,password:d}),signal:l})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Could not reach Matilda at ${r}: ${c}`)}if(t.status===401)throw new Error("Invalid email or password.");if(!t.ok)throw new Error(`Matilda sign-in failed (HTTP ${t.status}). Please try again.`);let e;try{e=await t.json()}catch{throw new Error("Matilda sign-in returned an unreadable response.")}if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("Matilda sign-in did not return a token.");return{token:e.token,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,userId:typeof e.userId=="string"?e.userId:void 0,email:typeof e.email=="string"?e.email:void 0,displayName:typeof e.displayName=="string"?e.displayName:void 0}}export{m as a,g as b,u as c,_ as d,A as e,h as f,f as g};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2026 Matilda Team
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-DE3HKC2W.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{ba as f}from"./chunk-27Q5KW3A.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"<").replace(/>/g,">")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
|
|
4
|
-
${this.stopReason}`}},m=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"decision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.decision;if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}}isPermissionDenied(){return this.getPermissionDecision()?.behavior==="deny"}getDenyMessage(){return this.getPermissionDecision()?.message}shouldInterrupt(){return this.getPermissionDecision()?.interrupt===!0}getUpdatedToolInput(){return this.getPermissionDecision()?.updatedInput}getUpdatedPermissions(){return this.getPermissionDecision()?.updatedPermissions}},b=(n=>(n.PermissionPrompt="permission_prompt",n.IdlePrompt="idle_prompt",n.AuthSuccess="auth_success",n.ElicitationDialog="elicitation_dialog",n))(b||{}),H=(t=>(t.Startup="startup",t.Resume="resume",t.Clear="clear",t.Compact="compact",t.Branch="branch",t))(H||{}),I=(t=>(t.Default="default",t.Plan="plan",t.AutoEdit="auto_edit",t.Auto="auto",t.Bogan="bogan",t))(I||{}),T=(t=>(t.Clear="clear",t.Logout="logout",t.PromptInputExit="prompt_input_exit",t.Bypass_permissions_disabled="bypass_permissions_disabled",t.Other="other",t))(T||{}),y=(s=>(s.Manual="manual",s.Auto="auto",s))(y||{}),R=(s=>(s.Manual="manual",s.Auto="auto",s))(R||{}),w=(n=>(n.Bash="Bash",n.Explorer="Explorer",n.Plan="Plan",n.Custom="Custom",n))(w||{});function A(o,e){let s=new Map(o.map(n=>[n.id,n])),u={created:[],completed:[]};for(let n of e){let t=s.get(n.id);t?t.status!=="completed"&&n.status==="completed"&&u.completed.push(n):u.created.push(n)}return u}export{h as a,_ as b,P as c,E as d,S as e,v as f,O as g,C as h,U as i,r as j,p as k,a as l,c as m,d as n,l as o,g as p,m as q,b as r,H as s,I as t,T as u,y as v,R as w,w as x,A as y};
|
|
5
|
-
/**
|
|
6
|
-
* @license
|
|
7
|
-
* Copyright 2026 Matilda Team
|
|
8
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
9
|
-
*/
|
package/chunks/chunk-EQGA7LH7.js
DELETED
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as B,c as D,e as U}from"./chunk-T2T2UEPY.js";import{b as d}from"./chunk-GZPNIYVZ.js";d();d();var C=class{buffer="";idleTimer=null;sending=Promise.resolve();opts;blockCount=0;constructor(e){this.opts=e}push(e){this.buffer+=e,this.clearIdleTimer(),this.checkEmit(),this.buffer.length>0&&this.opts.idleMs>0&&(this.idleTimer=setTimeout(()=>this.onIdle(),this.opts.idleMs))}async flush(){this.clearIdleTimer(),this.buffer.length>0&&(this.emitBlock(this.buffer),this.buffer=""),await this.sending}checkEmit(){for(;this.buffer.length>=this.opts.maxChars;){let e=this.findBreakPoint(this.buffer,this.opts.maxChars);this.emitBlock(this.buffer.slice(0,e)),this.buffer=this.buffer.slice(e)}if(this.buffer.length>=this.opts.minChars){let e=this.findBlockBoundary(this.buffer);e>0&&(this.emitBlock(this.buffer.slice(0,e)),this.buffer=this.buffer.slice(e))}}onIdle(){this.idleTimer=null,this.buffer.length>=this.opts.minChars&&(this.emitBlock(this.buffer),this.buffer="")}emitBlock(e){let t=e.trim();t&&(this.blockCount++,this.sending=this.sending.then(()=>this.opts.send(t)).catch(()=>{}))}findBlockBoundary(e){let t=e.lastIndexOf(`
|
|
4
|
-
|
|
5
|
-
`);return t<0||t<this.opts.minChars?-1:t+2}findBreakPoint(e,t){let s=e.slice(0,t),o=s.lastIndexOf(`
|
|
6
|
-
|
|
7
|
-
`);if(o>0)return o+2;let i=s.lastIndexOf(`
|
|
8
|
-
`);if(i>0)return i+1;let n=s.lastIndexOf(" ");return n>0?n+1:t}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};d();var b=class{policy;groups;constructor(e="disabled",t={}){this.policy=e,this.groups=t}check(e){return e.isGroup?this.policy==="disabled"?{allowed:!1,reason:"disabled"}:this.policy==="allowlist"&&!this.groups[e.chatId]?{allowed:!1,reason:"not_allowlisted"}:((this.groups[e.chatId]||this.groups["*"]||{}).requireMention??!0)&&!e.isMentioned&&!e.isReplyToBot?{allowed:!1,reason:"mention_required"}:{allowed:!0}:{allowed:!0}}};d();var P=class{policy;allowedUsers;pairingStore;constructor(e,t=[],s){this.policy=e,this.allowedUsers=new Set(t),this.pairingStore=s||null}check(e,t){switch(this.policy){case"open":return{allowed:!0};case"allowlist":return{allowed:this.allowedUsers.has(e)};case"pairing":return this.allowedUsers.has(e)?{allowed:!0}:this.pairingStore?.isApproved(e)?{allowed:!0}:{allowed:!1,pairingCode:this.pairingStore?.createRequest(e,t||e)??null};default:throw new Error(`Unknown sender policy: ${this.policy}`)}}};d();import*as j from"node:crypto";import*as p from"node:fs";import*as T from"node:path";d();import*as g from"node:path";import*as k from"node:os";function O(m){let e=m;if(e==="~"||e.startsWith("~/")||e.startsWith("~\\")){let t=e==="~"?[]:e.slice(2).split(/[/\\]+/).filter(Boolean);e=g.join(k.homedir(),...t)}return g.isAbsolute(e)||(e=g.resolve(e)),e}function M(){let m=process.env.MATILDA_HOME;if(m)return O(m);let e=k.homedir();return e?g.join(e,".matilda"):g.join(k.tmpdir(),".matilda")}var F="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",K=8,E=60*60*1e3,z=3,I=class{dir;pendingPath;allowlistPath;constructor(e){this.dir=T.join(M(),"channels"),this.pendingPath=T.join(this.dir,`${e}-pairing.json`),this.allowlistPath=T.join(this.dir,`${e}-allowlist.json`)}isApproved(e){return this.readAllowlist().includes(e)}createRequest(e,t){let s=this.readPending(),o=Date.now(),i=s.filter(a=>o-a.createdAt<E),n=i.find(a=>a.senderId===e);if(n)return n.code;if(i.length>=z)return null;let r=H();return i.push({senderId:e,senderName:t,code:r,createdAt:o}),this.writePending(i),r}approve(e){let t=this.readPending(),s=Date.now(),o=t.findIndex(r=>r.code===e.toUpperCase()&&s-r.createdAt<E);if(o===-1)return null;let i=t[o];t.splice(o,1),this.writePending(t);let n=this.readAllowlist();return n.includes(i.senderId)||(n.push(i.senderId),this.writeAllowlist(n)),i}listPending(){let e=this.readPending(),t=Date.now();return e.filter(s=>t-s.createdAt<E)}getAllowlist(){return this.readAllowlist()}ensureDir(){p.existsSync(this.dir)||p.mkdirSync(this.dir,{recursive:!0})}readPending(){try{let e=p.readFileSync(this.pendingPath,"utf-8");return JSON.parse(e)}catch{return[]}}writePending(e){this.ensureDir(),p.writeFileSync(this.pendingPath,JSON.stringify(e,null,2))}readAllowlist(){try{let e=p.readFileSync(this.allowlistPath,"utf-8");return JSON.parse(e)}catch{return[]}}writeAllowlist(e){this.ensureDir(),p.writeFileSync(this.allowlistPath,JSON.stringify(e,null,2))}};function H(){let m="";for(let e=0;e<K;e++)m+=F[j.randomInt(F.length)];return m}d();import{existsSync as G,readFileSync as Q,writeFileSync as X,unlinkSync as Y}from"node:fs";var x=class{toSession=new Map;toTarget=new Map;toCwd=new Map;bridge;defaultCwd;defaultScope;channelScopes=new Map;persistPath;constructor(e,t,s="user",o){this.bridge=e,this.defaultCwd=t,this.defaultScope=s,this.persistPath=o}setBridge(e){this.bridge=e}setChannelScope(e,t){this.channelScopes.set(e,t)}routingKey(e,t,s,o){switch(this.channelScopes.get(e)||this.defaultScope){case"thread":return`${e}:${o||s}`;case"single":return`${e}:__single__`;case"user":default:return`${e}:${t}:${s}`}}senderPrefix(e,t){return`${e}:${t}:`}async resolve(e,t,s,o,i){let n=this.routingKey(e,t,s,o),r=this.toSession.get(n);if(r)return r;let a=i||this.defaultCwd,f=await this.bridge.newSession(a);return this.toSession.set(n,f),this.toTarget.set(f,{channelName:e,senderId:t,chatId:s,threadId:o}),this.toCwd.set(f,a),this.persist(),f}getTarget(e){return this.toTarget.get(e)}hasSession(e,t,s){if(s)return this.toSession.has(this.routingKey(e,t,s));let o=this.senderPrefix(e,t);for(let i of this.toSession.keys())if(i.startsWith(o))return!0;return!1}removeSession(e,t,s){let o=[];if(s){let i=this.routingKey(e,t,s),n=this.deleteByKey(i);n&&o.push(n)}else{let i=this.senderPrefix(e,t);for(let n of[...this.toSession.keys()])if(n.startsWith(i)){let r=this.deleteByKey(n);r&&o.push(r)}}return o.length>0&&this.persist(),o}deleteByKey(e){let t=this.toSession.get(e);return t?(this.toSession.delete(e),this.toTarget.delete(t),this.toCwd.delete(t),t):null}getAll(){let e=[];for(let[t,s]of this.toSession){let o=this.toTarget.get(s);o&&e.push({key:t,sessionId:s,target:o})}return e}async restoreSessions(){if(!this.persistPath||!G(this.persistPath))return{restored:0,failed:0};let e;try{e=JSON.parse(Q(this.persistPath,"utf-8"))}catch{return{restored:0,failed:0}}let t=0,s=0;for(let[o,i]of Object.entries(e))try{let n=await this.bridge.loadSession(i.sessionId,i.cwd);this.toSession.set(o,n),this.toTarget.set(n,i.target),this.toCwd.set(n,i.cwd),t++}catch{s++}return s>0&&this.persist(),{restored:t,failed:s}}clearAll(){if(this.toSession.clear(),this.toTarget.clear(),this.toCwd.clear(),this.persistPath&&G(this.persistPath))try{Y(this.persistPath)}catch{}}persist(){if(!this.persistPath)return;let e={};for(let[t,s]of this.toSession){let o=this.toTarget.get(s);o&&(e[t]={sessionId:s,target:o,cwd:this.toCwd.get(s)||this.defaultCwd})}try{X(this.persistPath,JSON.stringify(e,null,2),"utf-8")}catch{}}};var A=class{config;bridge;groupGate;gate;router;name;proxy;instructedSessions=new Set;commands=new Map;sessionQueues=new Map;activePrompts=new Map;collectBuffers=new Map;constructor(e,t,s,o){this.name=e,this.config=t,this.bridge=s,this.proxy=o?.proxy,this.groupGate=new b(t.groupPolicy,t.groups);let i=t.senderPolicy==="pairing"?new I(e):void 0;this.gate=new P(t.senderPolicy,t.allowedUsers,i),this.router=o?.router||new x(s,t.cwd,t.sessionScope),this.registerSharedCommands(),o?.router||s.on("toolCall",n=>{let r=this.router.getTarget(n.sessionId);r&&this.onToolCall(r.chatId,n)})}setBridge(e){this.bridge=e}onToolCall(e,t){}onPromptStart(e,t,s){}onPromptEnd(e,t,s){}onResponseChunk(e,t,s){}async onResponseComplete(e,t,s){await this.sendMessage(e,t)}registerCommand(e,t){this.commands.set(e.toLowerCase(),t)}registerSharedCommands(){let e=async t=>{let s=this.router.removeSession(this.name,t.senderId,t.chatId);if(s.length>0){for(let o of s)this.instructedSessions.delete(o);await this.sendMessage(t.chatId,"Session cleared. Your next message will start a fresh conversation.")}else await this.sendMessage(t.chatId,"No active session to clear.");return!0};this.registerCommand("clear",e),this.registerCommand("reset",e),this.registerCommand("new",e),this.registerCommand("help",async t=>{let s=["Commands:","/help \u2014 Show this help","/clear \u2014 Clear your session (aliases: /reset, /new)","/status \u2014 Show session info"],o=new Set(["help","clear","reset","new","status"]),i=[...this.commands.keys()].filter(r=>!o.has(r));if(i.length>0)for(let r of i)s.push(`/${r}`);let n=this.bridge.availableCommands;if(n.length>0){s.push("","Agent commands (forwarded to Matilda Code):");for(let r of n)s.push(`/${r.name} \u2014 ${r.description}`)}return s.push("","Send any text to chat with the agent."),await this.sendMessage(t.chatId,s.join(`
|
|
9
|
-
`)),!0}),this.registerCommand("status",async t=>{let s=this.router.hasSession(this.name,t.senderId,t.chatId),o=this.config.senderPolicy,i=[`Session: ${s?"active":"none"}`,`Access: ${o}`,`Channel: ${this.name}`];return await this.sendMessage(t.chatId,i.join(`
|
|
10
|
-
`)),!0})}isLocalCommand(e){let t=this.parseCommand(e);return t!==null&&this.commands.has(t.command)}parseCommand(e){if(!e.startsWith("/"))return null;let t=e.match(/^\/([a-zA-Z0-9_]+)(?:@\S+)?\s*(.*)/s);return t?{command:t[1].toLowerCase(),args:t[2].trim()}:null}async handleInbound(e){if(!this.groupGate.check(e).allowed)return;let s=this.gate.check(e.senderId,e.senderName);if(!s.allowed){s.pairingCode!==void 0&&await this.onPairingRequired(e.chatId,s.pairingCode);return}let o=this.parseCommand(e.text);if(o){let l=this.commands.get(o.command);if(l&&await l(e,o.args))return}let i=await this.router.resolve(this.name,e.senderId,e.chatId,e.threadId,this.config.cwd);if(e.text.startsWith("!")){let l=e.text.slice(1).trim(),u=this.bridge.shellCommand;if(l&&typeof u=="function"){try{let c=await u(i,l),w=Math.max(0,...Array.from((c.output||"").matchAll(/`+/g),$=>$[0].length)),y="`".repeat(Math.max(3,w+1)),h=c.output?`${y}
|
|
11
|
-
${c.output}
|
|
12
|
-
${y}`:"(no output)",S=c.exitCode!==null&&c.exitCode!==0?`
|
|
13
|
-
Exit code: ${c.exitCode}`:"";await this.sendMessage(e.chatId,`$ ${l}
|
|
14
|
-
${h}${S}`)}catch(c){await this.sendMessage(e.chatId,`Shell command failed: ${c instanceof Error?c.message:String(c)}`)}return}}let n=e.text;e.referencedText&&(n=`[Replying to: "${e.referencedText}"]
|
|
15
|
-
|
|
16
|
-
${n}`);let r=e.imageBase64,a=e.imageMimeType;if(e.attachments?.length){let l=[];for(let u of e.attachments)if(u.type==="image"&&u.data&&!r)r=u.data,a=u.mimeType;else if(u.filePath){let c=u.type==="file"?"file":u.type,w=u.fileName?` "${u.fileName}"`:"";l.push(`User sent a ${c}${w}. It has been saved to: ${u.filePath}`)}l.length>0&&(n=n+`
|
|
17
|
-
|
|
18
|
-
`+l.join(`
|
|
19
|
-
`))}this.config.instructions&&!this.instructedSessions.has(i)&&(n=`${this.config.instructions}
|
|
20
|
-
|
|
21
|
-
${n}`,this.instructedSessions.add(i));let v=(e.isGroup?this.config.groups[e.chatId]||this.config.groups["*"]:void 0)?.dispatchMode||this.config.dispatchMode||"steer",_=this.activePrompts.get(i);if(_)switch(v){case"collect":{let l=this.collectBuffers.get(i);l||(l=[],this.collectBuffers.set(i,l)),l.push({text:n,envelope:e});return}case"steer":{_.cancelled=!0,await this.bridge.cancelSession(i).catch(()=>{}),await _.done,n=`[The user sent a new message while you were working. Their previous request has been cancelled.]
|
|
22
|
-
|
|
23
|
-
${n}`;break}case"followup":break;default:{let l=v;throw new Error(`Unknown dispatch mode: ${l}`)}}let N=this.sessionQueues.get(i)??Promise.resolve(),L=this.config.blockStreaming==="on",R=N.then(async()=>{let l=()=>{},c={cancelled:!1,done:new Promise(h=>{l=h}),resolve:l};this.activePrompts.set(i,c),this.onPromptStart(e.chatId,i,e.messageId);let w=L?new C({minChars:this.config.blockStreamingChunk?.minChars??400,maxChars:this.config.blockStreamingChunk?.maxChars??1e3,idleMs:this.config.blockStreamingCoalesce?.idleMs??1500,send:h=>this.sendMessage(e.chatId,h)}):null,y=(h,S)=>{h===i&&(this.onResponseChunk(e.chatId,S,i),w?.push(S))};this.bridge.on("textChunk",y);try{let h=await this.bridge.prompt(i,n,{imageBase64:r,imageMimeType:a});!c.cancelled&&h&&(w?await w.flush():await this.onResponseComplete(e.chatId,h,i))}finally{this.bridge.off("textChunk",y),this.onPromptEnd(e.chatId,i,e.messageId),this.activePrompts.delete(i),c.resolve();let h=this.collectBuffers.get(i);if(h&&h.length>0){this.collectBuffers.delete(i);let S=h.map(J=>J.text).join(`
|
|
24
|
-
|
|
25
|
-
`),W={...h[h.length-1].envelope,text:S,referencedText:void 0,attachments:void 0,imageBase64:void 0,imageMimeType:void 0};this.handleInbound(W).catch(()=>{})}}});this.sessionQueues.set(i,R.catch(()=>{})),await R}async onPairingRequired(e,t){t?await this.sendMessage(e,`Your pairing code is: ${t}
|
|
26
|
-
|
|
27
|
-
Ask the bot operator to approve you with:
|
|
28
|
-
matilda channel pairing approve ${this.name} ${t}`):await this.sendMessage(e,"Too many pending pairing requests. Please try again later.")}};d();d();import{spawn as V}from"node:child_process";import{Readable as Z,Writable as ee}from"node:stream";import{EventEmitter as te}from"node:events";var q=class extends te{child=null;connection=null;options;_availableCommands=[];constructor(e){super(),this.options=e}get availableCommands(){return this._availableCommands}async start(){let{cliEntryPath:e,cwd:t}=this.options,s=[...process.execArgv.filter(r=>!/^--inspect(-brk)?($|=)/.test(r)),e,"--acp"];if(this.options.model&&s.push("--model",this.options.model),this.child=V(process.execPath,s,{cwd:t,stdio:["pipe","pipe","pipe"],env:{...process.env},shell:!1}),this.child.stderr?.on("data",r=>{let a=r.toString().trim();a&&process.stderr.write(`[AcpBridge] ${a}
|
|
29
|
-
`)}),this.child.on("exit",(r,a)=>{process.stderr.write(`[AcpBridge] Process exited (code=${r}, signal=${a})
|
|
30
|
-
`),this.connection=null,this.child=null,this.emit("disconnected",r,a)}),await new Promise(r=>setTimeout(r,1e3)),!this.child||this.child.killed)throw new Error("ACP process failed to start");let o=Z.toWeb(this.child.stdout),i=ee.toWeb(this.child.stdin),n=D(i,o);this.connection=new U(()=>({sessionUpdate:r=>(this.handleSessionUpdate(r),Promise.resolve()),requestPermission:async r=>{let a=Array.isArray(r.options)?r.options:[];return{outcome:{outcome:"selected",optionId:a.find(v=>v.optionId==="proceed_once")?.optionId||a[0]?.optionId||"proceed_once"}}},extNotification:async()=>{}}),n),await this.connection.initialize({protocolVersion:B,clientCapabilities:{}})}async newSession(e){return(await this.ensureConnection().newSession({cwd:e,mcpServers:[]})).sessionId}async loadSession(e,t){return await this.ensureConnection().loadSession({sessionId:e,cwd:t,mcpServers:[]}),e}async prompt(e,t,s){let o=this.ensureConnection(),i=[],n=(a,f)=>{a===e&&i.push(f)};this.on("textChunk",n);let r=[];s?.imageBase64&&s.imageMimeType&&r.push({type:"image",data:s.imageBase64,mimeType:s.imageMimeType}),r.push({type:"text",text:t});try{await o.prompt({sessionId:e,prompt:r})}finally{this.off("textChunk",n)}return i.join("")}async cancelSession(e){await this.ensureConnection().cancel({sessionId:e})}stop(){this.child&&(this.child.kill(),this.child=null),this.connection=null}get isConnected(){return this.child!==null&&!this.child.killed&&this.child.exitCode===null}handleSessionUpdate(e){let{sessionId:t}=e,s=e.update;if(!s)return;switch(s.sessionUpdate){case"agent_message_chunk":{let i=s.content;i?.type==="text"&&i.text&&this.emit("textChunk",t,i.text);break}case"tool_call":{let i={sessionId:t,toolCallId:s.toolCallId,kind:s.kind||"",title:s.title||"",status:s.status||"pending",rawInput:s.rawInput};this.emit("toolCall",i);break}case"available_commands_update":{Array.isArray(s.availableCommands)&&(this._availableCommands=s.availableCommands);break}default:break}this.emit("sessionUpdate",e)}ensureConnection(){if(!this.connection||!this.isConnected)throw new Error("Not connected to ACP agent");return this.connection}};d();export{O as a,M as b,q as c,I as d,x as e,A as f};
|
package/chunks/chunk-FPO57O66.js
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as ye}from"./chunk-GOJCMVJJ.js";import{b as Y}from"./chunk-VI74YQQO.js";import{c as V,f as O}from"./chunk-YV3PUOBU.js";import{M as pe,N as ce,O as _,Q as de,R as q,S as me,a as re,g as R,h as ae,ha as ge,na as be}from"./chunk-3IRGBRSP.js";import{a as Ce}from"./chunk-DC7LAFZZ.js";import{a as oe,g as ie,k as se,l as N,o as ue,t as fe,v as he}from"./chunk-JCE3JAVC.js";import{e as z}from"./chunk-4J6DC24J.js";import{b as j,c as W,f as le,n as F}from"./chunk-SDTWBD62.js";import{a as H,ba as P,c as ee,e as te,q as J,s as ne,t as K}from"./chunk-27Q5KW3A.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Me(i){return i.toLowerCase().includes("matilda3")}function ve(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?i:{...e,reasoning:e.reasoning_content}}var h=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))le(o)||(r[o]=a);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=V("openai",this.cliConfig.getProxy());return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{}})}buildRequest(e,t){let n=this.contentGeneratorConfig.extra_body,r=this.applyOutputTokenLimit(e),o=Me(e.model)?r.messages.map(ve):r.messages;return{...r,messages:o,...n||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,n=he(e.model,"output"),r=fe(e.model),o;if(t!=null)r?o=Math.min(t,n):o=t;else{let a=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=a?parseInt(a,10):NaN;!isNaN(s)&&s>0?o=r?Math.min(s,n):s:o=Math.min(n,8e3)}return{...e,max_tokens:o}}};var k=class extends h{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let n=super.buildRequest(e,t);return n.stream||delete n.stream_options,n}};p();p();var G=class extends Error{constructor(t,n){super(`No stream activity for ${t}ms after ${n} chunks.`);this.idleMs=t;this.chunksReceived=n;this.name="StreamInactivityTimeoutError"}code="ETIMEDOUT"};function Ae(i,e){return async(t,n)=>{let r=new AbortController,o=n?.signal??void 0,a=()=>r.abort(o?.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",a,{once:!0});let s=()=>o?.removeEventListener("abort",a),l;try{l=await i(t,{...n,signal:r.signal})}catch(C){throw s(),C}let c=l.headers.get("content-type")??"";if(!l.body||!c.includes("text/event-stream"))return l;let u=l.body.getReader(),f=0,m,b=new ReadableStream({async pull(C){let d=new Promise((g,E)=>{m=setTimeout(()=>E(new G(e,f)),e)});try{let g=await Promise.race([u.read(),d]);if(g.done){s(),C.close();return}f+=1,C.enqueue(g.value)}catch(g){s(),C.error(g),g instanceof G&&r.abort(g)}finally{clearTimeout(m)}},cancel(C){return clearTimeout(m),s(),u.cancel(C)}}),y=new Response(b,{status:l.status,statusText:l.statusText,headers:l.headers});return Object.defineProperty(y,"url",{value:l.url}),y}}var we=P("MatildaOpenAICompatibleProvider"),A=class i extends h{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:n}=e;if(t==="matilda-oauth"||!n)return!0;let r=n.endsWith("/")?n.slice(0,-1):n,o=null;try{o=new URL(r).hostname.toLowerCase()}catch{o=null}let a=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),s=N?.endsWith("/")?N.slice(0,-1):N,l=!!(s&&r.toLowerCase()===s.toLowerCase());return s&&!a&&!l&&we.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),a||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=a);return _(this.contentGeneratorConfig)&&Object.assign(r,pe(this.cliConfig)),r}buildClient(){let{apiKey:e,baseUrl:t=se,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=V("openai",this.cliConfig.getProxy()),s=a?.fetch??globalThis.fetch,l=Ae(s,24e4),c=_(this.contentGeneratorConfig)?async(u,f)=>{let m=new Headers(u instanceof Request?u.headers:void 0);new Headers(f?.headers).forEach((d,g)=>{m.set(g,d)});let b=m.has(j)||m.has(W),y=F(),C=b||Object.keys(y).length>0;if(C){m.delete(j),m.delete(W);for(let[g,E]of Object.entries(y))m.set(g,E);let d=m.get("x-stainless-retry-count");m.has(j)&&d!==null&&/^[1-9][0-9]*$/.test(d)&&m.set(W,"retry")}this.cliConfig.getChannel()===void 0&&de({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let d=await l(u,C?{...f,headers:m}:f);return me({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),d}catch(d){throw q(d,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),d}}:void 0;return new H({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{},...c?{fetch:c}:{}})}buildRequest(e,t){let n=e.messages,r=e.tools;if(this.shouldEnableCacheControl()){let{messages:s,tools:l}=this.addCacheControl(e,e.stream?"all":"system_only");n=s,r=l}let o=this.applyOutputTokenLimit(e),a=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...a||{}}:{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},...a||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let n=e.messages,r=n.findIndex(l=>l.role==="system"),o=n.length-1,a=n.length===0?n:n.map((l,c)=>!(c===r&&r!==-1||c===o&&t==="all")||!("content"in l)||l.content===null||l.content===void 0?l:{...l,content:this.addCacheControlToContent(l.content)}),s=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:a,tools:s}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],n=e.length-1;return t[n]={...t[n],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(i.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of i.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function B(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content=="string"?i:{...e,reasoning_content:""}}function S(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Ee(i){return S(i)?!0:(i.model??"").toLowerCase().includes("deepseek")}var I=class extends h{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ee;static isDeepSeekHostname=S;buildRequest(e,t){let n=super.buildRequest(e,t),r=S(this.contentGeneratorConfig)?Ge(n):n;if(!r.messages?.length)return r;let o=r.messages.map(a=>{let s=ke(a);return B(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ke(i){if(!("content"in i))return i;let{content:e}=i;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return i;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
|
|
4
|
-
|
|
5
|
-
`);return{...i,content:t}}function Ge(i){let e=i,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return i;let r={...e};if(typeof r.reasoning_effort!="string"||!r.reasoning_effort){let o=n;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),r.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete r.reasoning;else if(t){let{effort:o,...a}=t;r.reasoning=a}return r}p();var T=class extends h{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};p();var _e=["api.minimaxi.com","api.minimax.io"],Se=[".minimaxi.com",".minimax.io"],M=class extends h{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return _e.includes(t)?!0:Se.some(n=>t.endsWith(n))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};p();var Pe="api.mistral.ai",Le=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ue(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Pe||t.endsWith(`.${Pe}`)}catch{return!1}}function De(i){if(Ue(i))return!0;let e=i.model?.toLowerCase()??"";return Le.some(t=>e.includes(t))}var v=class extends h{static isMistralProvider=De;buildRequest(e,t){let n=super.buildRequest(e,t);return{...n,messages:n.messages.map(He)}}};function He(i){if(!("reasoning_content"in i))return i;let e={...i};return delete e.reasoning_content,e}p();function Ne(i){let e=i.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(i.model??"").toLowerCase().startsWith("mimo-")}var x=class extends h{constructor(e,t){super(e,t)}static isMiMoProvider=Ne;buildRequest(e,t){let n=super.buildRequest(e,t);return n.messages?.length?{...n,messages:n.messages.map(B)}:n}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};p();p();var je=P("STREAMING_TOOL_CALL_PARSER"),$=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,n,r){let o=e,a=!!(n&&this.idToIndexMap.has(n));if(n)if(this.idToIndexMap.has(n))o=this.idToIndexMap.get(n);else{if(this.buffers.has(e)){let d=this.buffers.get(e),g=this.depths.get(e),E=this.toolCallMeta.get(e);if(d.trim()&&g===0&&E?.id&&E.id!==n)try{JSON.parse(d),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(n,o)}else if(this.buffers.has(e)){let d=this.buffers.get(e);if(this.depths.get(e)>0||!d.trim())o=e;else try{JSON.parse(d),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let s=this.buffers.get(o),l=this.depths.get(o);if(a&&s.trim()&&l===0)try{return JSON.parse(s),je.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let c=this.toolCallMeta.get(o);n&&(c.id=n),r&&(c.name=r);let u=this.inStrings.get(o),f=this.escapes.get(o),m=s+t;this.buffers.set(o,m);let b=l,y=u,C=f;for(let d of t)y||(d==="{"||d==="["?b++:(d==="}"||d==="]")&&b--),d==='"'&&!C&&(y=!y),C=d==="\\"&&!C;if(this.depths.set(o,b),this.inStrings.set(o,y),this.escapes.set(o,C),b===0&&m.trim().length>0)try{return{complete:!0,value:JSON.parse(m)}}catch(d){if(y)try{return{complete:!0,value:JSON.parse(m+'"'),repaired:!0}}catch{}return{complete:!1,error:d instanceof Error?d:new Error(String(d))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!0})}getStrictCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!1})}collectCompletedToolCalls({allowJsonRepair:e}){let t=[],n=new Set;for(let[r,o]of this.buffers.entries()){let a=this.toolCallMeta.get(r);if(a?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(a.id){if(n.has(a.id))continue;n.add(a.id)}let c;if(!o.trim())c={};else try{c=JSON.parse(o)}catch{if(!e)continue;let u=oe(o,null);if(!u||typeof u!="object")continue;c=u}t.push({id:a.id,name:a.name,args:c,index:r})}}return t}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),n=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!n?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,n]of this.buffers.entries()){let r=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(r>0||!n.trim()))e=Math.max(e,t);else if(n.trim())try{JSON.parse(n)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e,t]of this.buffers.entries()){let n=this.toolCallMeta.get(e),r=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(r>0||o)return!0;if(!n?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var Re=16e3,Oe=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
6
|
-
`,X=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},L=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(n,r)=>{let o=e.config?.abortSignal,a=o?Y(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}});return R.convertOpenAIResponseToGemini(l,r)}finally{a?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,a=o?Y(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}})}catch(m){throw a?.abort(),m}if(!a)return this.processStreamWithLogging(l,r,e);let c=a,u=this.processStreamWithLogging(l,r,e);async function*f(){try{yield*u}finally{c.abort()}}return f()})}reportedOperationHeaders(){if(!_(this.contentGeneratorConfig))return;let e=F();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null;try{for await(let a of e){if(a.choices?.[0]?.finish_reason==="error_finish"){let c=a.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new X(c)}let s=R.convertOpenAIChunkToGemini(a,t);if(s.candidates?.[0]?.content?.parts?.length===0&&!s.candidates?.[0]?.finishReason&&!s.usageMetadata)continue;this.handleChunkMerging(s,r,c=>{o=c})&&(yield s)}if(!o){let a=R.flushOpenAIStreamToGemini(t);a&&(yield a)}o&&(yield o)}catch(a){let s=o;if(s?.usageMetadata){let l=new z;l.candidates=[],l.usageMetadata=s.usageMetadata,l.responseId=s.responseId,l.modelVersion=s.modelVersion,yield l}if(a instanceof X)throw O(a);await this.handleError(a,t,n)}}handleChunkMerging(e,t,n){let r=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(r){if(o){let a=t[t.length-1];e.usageMetadata&&(a.usageMetadata=e.usageMetadata),n(a)}else t.push(e),n(e);return!1}else if(o){let a=t[t.length-1],s=new z;return s.candidates=a.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=a.usageMetadata,s.responseId=e.responseId??a.responseId,s.createTime=e.createTime??a.createTime,s.modelVersion=e.modelVersion??a.modelVersion,s.promptFeedback=e.promptFeedback??a.promptFeedback,t[t.length-1]=s,n(s),!1}return t.push(e),!0}async buildRequest(e,t,n,r){let o=R.convertGeminiRequestToOpenAI(e,n),a=this.shouldUseMatildaCoreRequestProfile(),s=a?this.toMatildaCoreUserMessages(o):o,l={model:n.model,messages:s,...this.buildGenerateContentConfig(e)};r?(l.stream=!0,l.stream_options={include_usage:!0}):l.stream=!1,!a&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await R.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let c=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let f=c,m=(n.model??"").toLowerCase();if(A.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(m.startsWith("matilda")||m==="coder-model")){f.enable_thinking=!1;let b=f.chat_template_kwargs;typeof b=="object"&&b!==null&&"enable_thinking"in b&&(f.chat_template_kwargs={...b,enable_thinking:!1})}"reasoning"in f&&delete f.reasoning,"reasoning_effort"in f&&delete f.reasoning_effort,S(this.contentGeneratorConfig)&&(f.thinking={type:"disabled"})}return c}toMatildaCoreUserMessages(e){let t=e.filter(n=>n.role==="user").map(n=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(n.content))})).filter(n=>n.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;let n=this.contentGeneratorConfig.customHeaders??{};return Object.entries(n).some(([o,a])=>o.toLowerCase()==="x-matilda-client"&&a.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
|
|
7
|
-
`):""}sanitizeMatildaUserContent(e){let n=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(n.length<=Re)return n;let r=Re-Oe.length;return`${Oe}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let c=n?.[s],u=l?e.config?.[l]:void 0,f=l?t[l]:void 0;return c!==void 0?c:u!==void 0?u:f},o=(s,l,c)=>{let u=r(l,c);return u!==void 0?{[s]:u}:{}};if(n!==void 0){let s=e.config?.maxOutputTokens;return{...n,...s!==void 0&&n.max_tokens!==void 0?{max_tokens:s}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,n,r){let o=this.createRequestContext(e,n);try{let a=await this.buildRequest(e,t,o,n);return ae.getStore()?.(a),ie.recordOpenAIWireRequest(a),await r(a,o)}catch(a){return await this.handleError(a,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(O(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new $:void 0,a=this.config.provider.getResponseParsingOptions?.(),s=t&&a?.taggedThinkingTags?new re:void 0;return{model:n,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:r.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...a?{responseParsingOptions:a}:{},...s?{taggedThinkingParser:s}:{}}}};p();var We=P("OPENAI_ERROR"),U=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=O(e),o=!(r instanceof G)&&this.isTimeoutError(r),a=this.buildErrorMessage(r,t,o);if(this.shouldSuppressErrorLogging(r,n)||We.error("OpenAI API Error:",a),o){let s=new Error(`${a}
|
|
8
|
-
|
|
9
|
-
${this.getTimeoutTroubleshootingTips()}`,{cause:r});typeof r=="object"&&r!==null&&"code"in r&&Object.assign(s,{code:r.code});let l=te(r);throw l!==void 0?Object.assign(s,{status:l}):s}throw r}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),n=e?.code,r=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||r==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,n){let r=Math.round((Date.now()-t.startTime)/1e3);return n?`Request timeout after ${r}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
|
|
10
|
-
${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
|
|
11
|
-
`)}`}};var Ie=P("OPENAI"),w=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new U((o,a)=>this.shouldSuppressErrorLogging(o,a))};this.pipeline=new L(r)}shouldSuppressErrorLogging(e,t){return!!(ee(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new ye().calculateTokens(e)).totalTokens}}catch(t){Ie.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(n=>typeof n=="string"?n:"parts"in n&&n.parts?n.parts.map(r=>typeof r=="string"?r:"text"in r&&r.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(n=>typeof n=="string"?n:"text"in n?n.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(n){let r=O(n);throw Ie.error("OpenAI API Embedding Error:",r),new Error(`OpenAI API error: ${r instanceof Error?r.message:String(r)}`)}}useSummarizedThinking(){return!1}};p();var D=class extends w{contentGeneratorConfig;cliConfig;channel;constructor(e,t,n){super(e,t,n),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return Te(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=()=>super.generateContentStream(e,t),r=await this.withTokenRefresh(n);return this.iterateWithAuthRetry(r,n)}async*iterateWithAuthRetry(e,t){let n=!1;try{for await(let r of e)n||=(r.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield r;return}catch(r){if(!this.isSessionAuthError(r))throw this.toAuthRecoveryError(r);if(n)throw new J("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw this.toAuthRecoveryError(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await be({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(n){throw q(n,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),n}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[Ce]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!this.isSessionAuthError(t))throw this.toAuthRecoveryError(t);await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(n){throw this.toAuthRecoveryError(n)}}}isSessionAuthError(e){return Te(e)&&ge({baseUrl:this.contentGeneratorConfig.baseUrl,channel:this.channel})}toAuthRecoveryError(e){return K(e)?new ne:this.isSessionAuthError(e)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):e}};function Te(i){if(!i||K(i))return!1;let e=i instanceof Error?i.message.toLowerCase():String(i).toLowerCase(),t=i,n=Number(t.status??t.statusCode??t.code);return n>=400&&n<600?n===401:e.includes("unauthorized")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("token")&&e.includes("expired")}function _n(i,e){let t=Fe(i,e);return A.isMatildaCompatibleProvider(i)?new D(i,e,t):new w(i,e,t)}function Fe(i,e){let t=i||e.getContentGeneratorConfig();return A.isMatildaCompatibleProvider(t)?new A(i,e):I.isDeepSeekProvider(t)?new I(i,e):x.isMiMoProvider(t)?new x(i,e):T.isOpenRouterProvider(t)?new T(i,e):k.isModelScopeProvider(t)?new k(i,e):M.isMiniMaxProvider(t)?new M(i,e):v.isMistralProvider(t)?new v(i,e):new h(i,e)}export{A as a,I as b,T as c,M as d,v as e,x as f,L as g,U as h,w as i,D as j,_n as k,Fe as l};
|
|
12
|
-
/**
|
|
13
|
-
* @license
|
|
14
|
-
* Copyright 2026 Matilda
|
|
15
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
16
|
-
*/
|
|
17
|
-
/**
|
|
18
|
-
* @license
|
|
19
|
-
* Copyright 2025 Matilda
|
|
20
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
21
|
-
*/
|
|
22
|
-
/**
|
|
23
|
-
* @license
|
|
24
|
-
* Copyright 2026 Maincode
|
|
25
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
26
|
-
*
|
|
27
|
-
* OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
|
|
28
|
-
*
|
|
29
|
-
* Emulates Grok Build's automatic credential refresh
|
|
30
|
-
* (docs: "Automatic Credential Refresh"):
|
|
31
|
-
* 1. Before each request: ensure a fresh access token (re-read disk; refresh
|
|
32
|
-
* when within the early-invalidation window / already expired).
|
|
33
|
-
* 2. On 401 Unauthorized: force-refresh and retry the request once.
|
|
34
|
-
* 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
|
|
35
|
-
*
|
|
36
|
-
* Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
|
|
37
|
-
* createContentGenerator time, so idle sessions past access-token expiry
|
|
38
|
-
* failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
|
|
39
|
-
*/
|
package/chunks/chunk-FWDMPRKU.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{b as i}from"./chunk-GZPNIYVZ.js";import{c as p,e as Vr}from"./chunk-OWGSC52X.js";var V,Ct=p(()=>{i();(function(t){t[t.INT=0]="INT",t[t.DOUBLE=1]="DOUBLE"})(V||(V={}))});var B,St=p(()=>{i();(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(B||(B={}))});function b(t){return Symbol.for(t)}var Br,L,O=p(()=>{i();Br=function(){function t(r){var e=this;e._currentContext=r?new Map(r):new Map,e.getValue=function(n){return e._currentContext.get(n)},e.setValue=function(n,a){var o=new t(e._currentContext);return o._currentContext.set(n,a),o},e.deleteValue=function(n){var a=new t(e._currentContext);return a._currentContext.delete(n),a}}return t}(),L=new Br});var Lr,Ur,Rt,Mt=p(()=>{i();O();Lr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Ur=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},Rt=function(){function t(){}return t.prototype.active=function(){return L},t.prototype.with=function(r,e,n){for(var a=[],o=3;o<arguments.length;o++)a[o-3]=arguments[o];return e.call.apply(e,Ur([n],Lr(a),!1))},t.prototype.bind=function(r,e){return e},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}()});var wt,Dt=p(()=>{i();wt=globalThis});var Gt=p(()=>{i();Dt()});var Vt=p(()=>{i();Gt()});var d,Z=p(()=>{i();d="1.9.0"});function jr(t){var r=new Set([t]),e=new Set,n=t.match(Bt);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(f){return f===t};function o(c){return e.add(c),!1}function u(c){return r.add(c),!0}return function(f){if(r.has(f))return!0;if(e.has(f))return!1;var g=f.match(Bt);if(!g)return o(f);var m={major:+g[1],minor:+g[2],patch:+g[3],prerelease:g[4]};return m.prerelease!=null||a.major!==m.major?o(f):a.major===0?a.minor===m.minor&&a.patch<=m.patch?u(f):o(f):a.minor<=m.minor?u(f):o(f)}}var Bt,Lt,Ut=p(()=>{i();Z();Bt=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;Lt=jr(d)});function _(t,r,e,n){var a;n===void 0&&(n=!1);var o=C[P]=(a=C[P])!==null&&a!==void 0?a:{version:d};if(!n&&o[t]){var u=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return e.error(u.stack||u.message),!1}if(o.version!==d){var u=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+t+" does not match previously registered API v"+d);return e.error(u.stack||u.message),!1}return o[t]=r,e.debug("@opentelemetry/api: Registered a global for "+t+" v"+d+"."),!0}function v(t){var r,e,n=(r=C[P])===null||r===void 0?void 0:r.version;if(!(!n||!Lt(n)))return(e=C[P])===null||e===void 0?void 0:e[t]}function y(t,r){r.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+d+".");var e=C[P];e&&delete e[t]}var kr,P,C,E=p(()=>{i();Vt();Z();Ut();kr=d.split(".")[0],P=Symbol.for("opentelemetry.js.api."+kr),C=wt});function S(t,r,e){var n=v("diag");if(n)return e.unshift(r),n[t].apply(n,Kr([],Xr(e),!1))}var Xr,Kr,jt,kt=p(()=>{i();E();Xr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Kr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},jt=function(){function t(r){this._namespace=r.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("debug",this._namespace,r)},t.prototype.error=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("error",this._namespace,r)},t.prototype.info=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("info",this._namespace,r)},t.prototype.warn=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("warn",this._namespace,r)},t.prototype.verbose=function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return S("verbose",this._namespace,r)},t}()});var s,U=p(()=>{i();(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(s||(s={}))});function Xt(t,r){t<s.NONE?t=s.NONE:t>s.ALL&&(t=s.ALL),r=r||{};function e(n,a){var o=r[n];return typeof o=="function"&&t>=a?o.bind(r):function(){}}return{error:e("error",s.ERROR),warn:e("warn",s.WARN),info:e("info",s.INFO),debug:e("debug",s.DEBUG),verbose:e("verbose",s.VERBOSE)}}var Kt=p(()=>{i();U()});var Fr,Yr,zr,l,A=p(()=>{i();kt();Kt();U();E();Fr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Yr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},zr="diag",l=function(){function t(){function r(a){return function(){for(var o=[],u=0;u<arguments.length;u++)o[u]=arguments[u];var c=v("diag");if(c)return c[a].apply(c,Yr([],Fr(o),!1))}}var e=this,n=function(a,o){var u,c,f;if(o===void 0&&(o={logLevel:s.INFO}),a===e){var g=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return e.error((u=g.stack)!==null&&u!==void 0?u:g.message),!1}typeof o=="number"&&(o={logLevel:o});var m=v("diag"),Ot=Xt((c=o.logLevel)!==null&&c!==void 0?c:s.INFO,a);if(m&&!o.suppressOverrideMessage){var Pt=(f=new Error().stack)!==null&&f!==void 0?f:"<failed to generate stacktrace>";m.warn("Current logger will be overwritten from "+Pt),Ot.warn("Current logger will overwrite one already registered from "+Pt)}return _("diag",Ot,e,!0)};e.setLogger=n,e.disable=function(){y(zr,e)},e.createComponentLogger=function(a){return new jt(a)},e.verbose=r("verbose"),e.debug=r("debug"),e.info=r("info"),e.warn=r("warn"),e.error=r("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}()});var Wr,Hr,tt,$r,h,R=p(()=>{i();Mt();E();A();Wr=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},Hr=function(t,r,e){if(e||arguments.length===2)for(var n=0,a=r.length,o;n<a;n++)(o||!(n in r))&&(o||(o=Array.prototype.slice.call(r,0,n)),o[n]=r[n]);return t.concat(o||Array.prototype.slice.call(r))},tt="context",$r=new Rt,h=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(r){return _(tt,r,l.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(r,e,n){for(var a,o=[],u=3;u<arguments.length;u++)o[u-3]=arguments[u];return(a=this._getContextManager()).with.apply(a,Hr([r,e,n],Wr(o),!1))},t.prototype.bind=function(r,e){return this._getContextManager().bind(r,e)},t.prototype._getContextManager=function(){return v(tt)||$r},t.prototype.disable=function(){this._getContextManager().disable(),y(tt,l.instance())},t}()});var rt,Ft=p(()=>{i();R();rt=h.getInstance()});var T,et=p(()=>{i();(function(t){t[t.NONE=0]="NONE",t[t.SAMPLED=1]="SAMPLED"})(T||(T={}))});var M,w,j,k=p(()=>{i();et();M="0000000000000000",w="00000000000000000000000000000000",j={traceId:w,spanId:M,traceFlags:T.NONE}});var x,X=p(()=>{i();k();x=function(){function t(r){r===void 0&&(r=j),this._spanContext=r}return t.prototype.spanContext=function(){return this._spanContext},t.prototype.setAttribute=function(r,e){return this},t.prototype.setAttributes=function(r){return this},t.prototype.addEvent=function(r,e){return this},t.prototype.addLink=function(r){return this},t.prototype.addLinks=function(r){return this},t.prototype.setStatus=function(r){return this},t.prototype.updateName=function(r){return this},t.prototype.end=function(r){},t.prototype.isRecording=function(){return!1},t.prototype.recordException=function(r,e){},t}()});function K(t){return t.getValue(nt)||void 0}function Yt(){return K(h.getInstance().active())}function D(t,r){return t.setValue(nt,r)}function zt(t){return t.deleteValue(nt)}function Wt(t,r){return D(t,new x(r))}function F(t){var r;return(r=K(t))===null||r===void 0?void 0:r.spanContext()}var nt,ot=p(()=>{i();O();X();R();nt=b("OpenTelemetry Context Key SPAN")});function at(t){return Qr.test(t)&&t!==w}function it(t){return qr.test(t)&&t!==M}function I(t){return at(t.traceId)&&it(t.spanId)}function Ht(t){return new x(t)}var Qr,qr,Y=p(()=>{i();k();X();Qr=/^([0-9a-f]{32})$/i,qr=/^[0-9a-f]{16}$/i});function Jr(t){return typeof t=="object"&&typeof t.spanId=="string"&&typeof t.traceId=="string"&&typeof t.traceFlags=="number"}var ut,z,pt=p(()=>{i();R();ot();X();Y();ut=h.getInstance(),z=function(){function t(){}return t.prototype.startSpan=function(r,e,n){n===void 0&&(n=ut.active());var a=!!e?.root;if(a)return new x;var o=n&&F(n);return Jr(o)&&I(o)?new x(o):new x},t.prototype.startActiveSpan=function(r,e,n,a){var o,u,c;if(!(arguments.length<2)){arguments.length===2?c=e:arguments.length===3?(o=e,c=n):(o=e,u=n,c=a);var f=u??ut.active(),g=this.startSpan(r,o,f),m=D(f,g);return ut.with(m,c,void 0,g)}},t}()});var Zr,W,ct=p(()=>{i();pt();Zr=new z,W=function(){function t(r,e,n,a){this._provider=r,this.name=e,this.version=n,this.options=a}return t.prototype.startSpan=function(r,e,n){return this._getTracer().startSpan(r,e,n)},t.prototype.startActiveSpan=function(r,e,n,a){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},t.prototype._getTracer=function(){if(this._delegate)return this._delegate;var r=this._provider.getDelegateTracer(this.name,this.version,this.options);return r?(this._delegate=r,this._delegate):Zr},t}()});var $t,Qt=p(()=>{i();pt();$t=function(){function t(){}return t.prototype.getTracer=function(r,e,n){return new z},t}()});var te,G,ft=p(()=>{i();ct();Qt();te=new $t,G=function(){function t(){}return t.prototype.getTracer=function(r,e,n){var a;return(a=this.getDelegateTracer(r,e,n))!==null&&a!==void 0?a:new W(this,r,e,n)},t.prototype.getDelegate=function(){var r;return(r=this._delegate)!==null&&r!==void 0?r:te},t.prototype.setDelegate=function(r){this._delegate=r},t.prototype.getDelegateTracer=function(r,e,n){var a;return(a=this._delegate)===null||a===void 0?void 0:a.getTracer(r,e,n)},t}()});var st,qt,Jt=p(()=>{i();E();ft();Y();ot();A();st="trace",qt=function(){function t(){this._proxyTracerProvider=new G,this.wrapSpanContext=Ht,this.isSpanContextValid=I,this.deleteSpan=zt,this.getSpan=K,this.getActiveSpan=Yt,this.getSpanContext=F,this.setSpan=D,this.setSpanContext=Wt}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalTracerProvider=function(r){var e=_(st,this._proxyTracerProvider,l.instance());return e&&this._proxyTracerProvider.setDelegate(r),e},t.prototype.getTracerProvider=function(){return v(st)||this._proxyTracerProvider},t.prototype.getTracer=function(r,e){return this.getTracerProvider().getTracer(r,e)},t.prototype.disable=function(){y(st,l.instance()),this._proxyTracerProvider=new G},t}()});var lt,Zt=p(()=>{i();Jt();lt=qt.getInstance()});var re,ee,tr,rr=p(()=>{i();re=function(t,r){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var n=e.call(t),a,o=[],u;try{for(;(r===void 0||r-- >0)&&!(a=n.next()).done;)o.push(a.value)}catch(c){u={error:c}}finally{try{a&&!a.done&&(e=n.return)&&e.call(n)}finally{if(u)throw u.error}}return o},ee=function(t){var r=typeof Symbol=="function"&&Symbol.iterator,e=r&&t[r],n=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")},tr=function(){function t(r){this._entries=r?new Map(r):new Map}return t.prototype.getEntry=function(r){var e=this._entries.get(r);if(e)return Object.assign({},e)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(r){var e=re(r,2),n=e[0],a=e[1];return[n,a]})},t.prototype.setEntry=function(r,e){var n=new t(this._entries);return n._entries.set(r,e),n},t.prototype.removeEntry=function(r){var e=new t(this._entries);return e._entries.delete(r),e},t.prototype.removeEntries=function(){for(var r,e,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var o=new t(this._entries);try{for(var u=ee(n),c=u.next();!c.done;c=u.next()){var f=c.value;o._entries.delete(f)}}catch(g){r={error:g}}finally{try{c&&!c.done&&(e=u.return)&&e.call(u)}finally{if(r)throw r.error}}return o},t.prototype.clear=function(){return new t},t}()});var er,nr=p(()=>{i();er=Symbol("BaggageEntryMetadata")});function or(t){return t===void 0&&(t={}),new tr(new Map(Object.entries(t)))}function ar(t){return typeof t!="string"&&(ne.error("Cannot create baggage metadata from unknown type: "+typeof t),t=""),{__TYPE__:er,toString:function(){return t}}}var ne,gt=p(()=>{i();A();rr();nr();ne=l.instance()});var vt,ir,ur=p(()=>{i();vt=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}],ir=function(){function t(){function r(n){return function(){for(var a=[],o=0;o<arguments.length;o++)a[o]=arguments[o];if(console){var u=console[n];if(typeof u!="function"&&(u=console.log),typeof u=="function")return u.apply(console,a)}}}for(var e=0;e<vt.length;e++)this[vt[e].n]=r(vt[e].c)}return t}()});function pr(){return _t}var N,oe,H,ae,ie,ue,pe,mt,ce,fe,se,_t,le,ge,ve,me,_e,ye,de,yt=p(()=>{i();N=function(){var t=function(r,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,a){n.__proto__=a}||function(n,a){for(var o in a)Object.prototype.hasOwnProperty.call(a,o)&&(n[o]=a[o])},t(r,e)};return function(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(r,e);function n(){this.constructor=r}r.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}}(),oe=function(){function t(){}return t.prototype.createGauge=function(r,e){return ge},t.prototype.createHistogram=function(r,e){return ve},t.prototype.createCounter=function(r,e){return le},t.prototype.createUpDownCounter=function(r,e){return me},t.prototype.createObservableGauge=function(r,e){return ye},t.prototype.createObservableCounter=function(r,e){return _e},t.prototype.createObservableUpDownCounter=function(r,e){return de},t.prototype.addBatchObservableCallback=function(r,e){},t.prototype.removeBatchObservableCallback=function(r){},t}(),H=function(){function t(){}return t}(),ae=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.add=function(e,n){},r}(H),ie=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.add=function(e,n){},r}(H),ue=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.record=function(e,n){},r}(H),pe=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.prototype.record=function(e,n){},r}(H),mt=function(){function t(){}return t.prototype.addCallback=function(r){},t.prototype.removeCallback=function(r){},t}(),ce=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),fe=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),se=function(t){N(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r}(mt),_t=new oe,le=new ae,ge=new ue,ve=new pe,me=new ie,_e=new ce,ye=new fe,de=new se});var $,Q,dt=p(()=>{i();$={get:function(t,r){if(t!=null)return t[r]},keys:function(t){return t==null?[]:Object.keys(t)}},Q={set:function(t,r,e){t!=null&&(t[r]=e)}}});var q,cr=p(()=>{i();(function(t){t[t.NOT_RECORD=0]="NOT_RECORD",t[t.RECORD=1]="RECORD",t[t.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(q||(q={}))});var J,fr=p(()=>{i();(function(t){t[t.INTERNAL=0]="INTERNAL",t[t.SERVER=1]="SERVER",t[t.CLIENT=2]="CLIENT",t[t.PRODUCER=3]="PRODUCER",t[t.CONSUMER=4]="CONSUMER"})(J||(J={}))});function sr(t){return Ee.test(t)}function lr(t){return Ae.test(t)&&!Ne.test(t)}var ht,he,xe,Ee,Ae,Ne,gr=p(()=>{i();ht="[_0-9a-z-*/]",he="[a-z]"+ht+"{0,255}",xe="[a-z0-9]"+ht+"{0,240}@[a-z]"+ht+"{0,13}",Ee=new RegExp("^(?:"+he+"|"+xe+")$"),Ae=/^[ -~]{0,255}[!-~]$/,Ne=/,|=/});var vr,be,mr,_r,yr,dr=p(()=>{i();gr();vr=32,be=512,mr=",",_r="=",yr=function(){function t(r){this._internalState=new Map,r&&this._parse(r)}return t.prototype.set=function(r,e){var n=this._clone();return n._internalState.has(r)&&n._internalState.delete(r),n._internalState.set(r,e),n},t.prototype.unset=function(r){var e=this._clone();return e._internalState.delete(r),e},t.prototype.get=function(r){return this._internalState.get(r)},t.prototype.serialize=function(){var r=this;return this._keys().reduce(function(e,n){return e.push(n+_r+r.get(n)),e},[]).join(mr)},t.prototype._parse=function(r){r.length>be||(this._internalState=r.split(mr).reverse().reduce(function(e,n){var a=n.trim(),o=a.indexOf(_r);if(o!==-1){var u=a.slice(0,o),c=a.slice(o+1,n.length);sr(u)&&lr(c)&&e.set(u,c)}return e},new Map),this._internalState.size>vr&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,vr))))},t.prototype._keys=function(){return Array.from(this._internalState.keys()).reverse()},t.prototype._clone=function(){var r=new t;return r._internalState=new Map(this._internalState),r},t}()});function hr(t){return new yr(t)}var xr=p(()=>{i();dr()});var xt,Er=p(()=>{i();A();xt=l.instance()});var Te,Ar,Nr=p(()=>{i();yt();Te=function(){function t(){}return t.prototype.getMeter=function(r,e,n){return _t},t}(),Ar=new Te});var Et,br,Tr=p(()=>{i();Nr();E();A();Et="metrics",br=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalMeterProvider=function(r){return _(Et,r,l.instance())},t.prototype.getMeterProvider=function(){return v(Et)||Ar},t.prototype.getMeter=function(r,e,n){return this.getMeterProvider().getMeter(r,e,n)},t.prototype.disable=function(){y(Et,l.instance())},t}()});var At,Ir=p(()=>{i();Tr();At=br.getInstance()});var Or,Pr=p(()=>{i();Or=function(){function t(){}return t.prototype.inject=function(r,e){},t.prototype.extract=function(r,e){return r},t.prototype.fields=function(){return[]},t}()});function bt(t){return t.getValue(Nt)||void 0}function Cr(){return bt(h.getInstance().active())}function Sr(t,r){return t.setValue(Nt,r)}function Rr(t){return t.deleteValue(Nt)}var Nt,Mr=p(()=>{i();R();O();Nt=b("OpenTelemetry Baggage Key")});var Tt,Ie,wr,Dr=p(()=>{i();E();Pr();dt();Mr();gt();A();Tt="propagation",Ie=new Or,wr=function(){function t(){this.createBaggage=or,this.getBaggage=bt,this.getActiveBaggage=Cr,this.setBaggage=Sr,this.deleteBaggage=Rr}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(r){return _(Tt,r,l.instance())},t.prototype.inject=function(r,e,n){return n===void 0&&(n=Q),this._getGlobalPropagator().inject(r,e,n)},t.prototype.extract=function(r,e,n){return n===void 0&&(n=$),this._getGlobalPropagator().extract(r,e,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){y(Tt,l.instance())},t.prototype._getGlobalPropagator=function(){return v(Tt)||Ie},t}()});var It,Gr=p(()=>{i();Dr();It=wr.getInstance()});var Pe={};Vr(Pe,{DiagConsoleLogger:()=>ir,DiagLogLevel:()=>s,INVALID_SPANID:()=>M,INVALID_SPAN_CONTEXT:()=>j,INVALID_TRACEID:()=>w,ProxyTracer:()=>W,ProxyTracerProvider:()=>G,ROOT_CONTEXT:()=>L,SamplingDecision:()=>q,SpanKind:()=>J,SpanStatusCode:()=>B,TraceFlags:()=>T,ValueType:()=>V,baggageEntryMetadataFromString:()=>ar,context:()=>rt,createContextKey:()=>b,createNoopMeter:()=>pr,createTraceState:()=>hr,default:()=>Oe,defaultTextMapGetter:()=>$,defaultTextMapSetter:()=>Q,diag:()=>xt,isSpanContextValid:()=>I,isValidSpanId:()=>it,isValidTraceId:()=>at,metrics:()=>At,propagation:()=>It,trace:()=>lt});var Oe,Ce=p(()=>{i();gt();O();ur();U();yt();Ct();dt();ct();ft();cr();fr();St();et();xr();Y();k();Ft();Er();Ir();Gr();Zt();Oe={context:rt,diag:xt,metrics:At,propagation:It,trace:lt}});export{s as a,L as b,V as c,T as d,I as e,J as f,B as g,rt as h,xt as i,At as j,It as k,lt as l,Pe as m,Ce as n};
|
package/chunks/chunk-G7R2XEEF.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{a as W}from"./chunk-OA56BXPD.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{a as R,d as b}from"./chunk-OWGSC52X.js";var A=b((de,L)=>{p();function J(e){t.debug=t,t.default=t,t.coerce=U,t.disable=G,t.enable=d,t.enabled=P,t.humanize=W(),t.destroy=z,Object.keys(e).forEach(o=>{t[o]=e[o]}),t.names=[],t.skips=[],t.formatters={};function r(o){let n=0;for(let i=0;i<o.length;i++)n=(n<<5)-n+o.charCodeAt(i),n|=0;return t.colors[Math.abs(n)%t.colors.length]}t.selectColor=r;function t(o){let n,i=null,u,g;function f(...a){if(!f.enabled)return;let h=f,y=Number(new Date),V=y-(n||y);h.diff=V,h.prev=n,h.curr=y,n=y,a[0]=t.coerce(a[0]),typeof a[0]!="string"&&a.unshift("%O");let w=0;a[0]=a[0].replace(/%([a-zA-Z%])/g,(I,$)=>{if(I==="%%")return"%";w++;let M=t.formatters[$];if(typeof M=="function"){let Y=a[w];I=M.call(h,Y),a.splice(w,1),w--}return I}),t.formatArgs.call(h,a),(h.log||t.log).apply(h,a)}return f.namespace=o,f.useColors=t.useColors(),f.color=t.selectColor(o),f.extend=s,f.destroy=t.destroy,Object.defineProperty(f,"enabled",{enumerable:!0,configurable:!1,get:()=>i!==null?i:(u!==t.namespaces&&(u=t.namespaces,g=t.enabled(o)),g),set:a=>{i=a}}),typeof t.init=="function"&&t.init(f),f}function s(o,n){let i=t(this.namespace+(typeof n>"u"?":":n)+o);return i.log=this.log,i}function d(o){t.save(o),t.namespaces=o,t.names=[],t.skips=[];let n=(typeof o=="string"?o:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let i of n)i[0]==="-"?t.skips.push(i.slice(1)):t.names.push(i)}function m(o,n){let i=0,u=0,g=-1,f=0;for(;i<o.length;)if(u<n.length&&(n[u]===o[i]||n[u]==="*"))n[u]==="*"?(g=u,f=i,u++):(i++,u++);else if(g!==-1)u=g+1,f++,i=f;else return!1;for(;u<n.length&&n[u]==="*";)u++;return u===n.length}function G(){let o=[...t.names,...t.skips.map(n=>"-"+n)].join(",");return t.enable(""),o}function P(o){for(let n of t.skips)if(m(o,n))return!1;for(let n of t.names)if(m(o,n))return!0;return!1}function U(o){return o instanceof Error?o.stack||o.message:o}function z(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}L.exports=J});var j=b((C,v)=>{p();C.formatArgs=H;C.save=K;C.load=Q;C.useColors=Z;C.storage=X();C.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();C.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Z(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function H(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+v.exports.humanize(this.diff),!this.useColors)return;let r="color: "+this.color;e.splice(1,0,r,"color: inherit");let t=0,s=0;e[0].replace(/%[a-zA-Z%]/g,d=>{d!=="%%"&&(t++,d==="%c"&&(s=t))}),e.splice(s,0,r)}C.log=console.debug||console.log||(()=>{});function K(e){try{e?C.storage.setItem("debug",e):C.storage.removeItem("debug")}catch{}}function Q(){let e;try{e=C.storage.getItem("debug")||C.storage.getItem("DEBUG")}catch{}return!e&&typeof process<"u"&&"env"in process&&(e=process.env.DEBUG),e}function X(){try{return localStorage}catch{}}v.exports=A()(C);var{formatters:ee}=v.exports;ee.j=function(e){try{return JSON.stringify(e)}catch(r){return"[UnexpectedJSONParseError]: "+r.message}}});var N=b((he,B)=>{"use strict";p();B.exports=(e,r)=>{r=r||process.argv;let t=e.startsWith("-")?"":e.length===1?"-":"--",s=r.indexOf(t+e),d=r.indexOf("--");return s!==-1&&(d===-1?!0:s<d)}});var D=b((be,k)=>{"use strict";p();var te=R("os"),F=N(),l=process.env,O;F("no-color")||F("no-colors")||F("color=false")?O=!1:(F("color")||F("colors")||F("color=true")||F("color=always"))&&(O=!0);"FORCE_COLOR"in l&&(O=l.FORCE_COLOR.length===0||parseInt(l.FORCE_COLOR,10)!==0);function re(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function oe(e){if(O===!1)return 0;if(F("color=16m")||F("color=full")||F("color=truecolor"))return 3;if(F("color=256"))return 2;if(e&&!e.isTTY&&O!==!0)return 0;let r=O?1:0;if(process.platform==="win32"){let t=te.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in l)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(t=>t in l)||l.CI_NAME==="codeship"?1:r;if("TEAMCITY_VERSION"in l)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(l.TEAMCITY_VERSION)?1:0;if(l.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in l){let t=parseInt((l.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(l.TERM_PROGRAM){case"iTerm.app":return t>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(l.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(l.TERM)||"COLORTERM"in l?1:(l.TERM==="dumb",r)}function T(e){let r=oe(e);return re(r)}k.exports={supportsColor:T,stdout:T(process.stdout),stderr:T(process.stderr)}});var S=b((c,E)=>{p();var ne=R("tty"),x=R("util");c.init=Ce;c.log=le;c.formatArgs=ie;c.save=ue;c.load=fe;c.useColors=se;c.destroy=x.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");c.colors=[6,2,3,4,5,1];try{let e=D();e&&(e.stderr||e).level>=2&&(c.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}c.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,r)=>{let t=r.substring(6).toLowerCase().replace(/_([a-z])/g,(d,m)=>m.toUpperCase()),s=process.env[r];return/^(yes|on|true|enabled)$/i.test(s)?s=!0:/^(no|off|false|disabled)$/i.test(s)?s=!1:s==="null"?s=null:s=Number(s),e[t]=s,e},{});function se(){return"colors"in c.inspectOpts?!!c.inspectOpts.colors:ne.isatty(process.stderr.fd)}function ie(e){let{namespace:r,useColors:t}=this;if(t){let s=this.color,d="\x1B[3"+(s<8?s:"8;5;"+s),m=` ${d};1m${r} \x1B[0m`;e[0]=m+e[0].split(`
|
|
4
|
-
`).join(`
|
|
5
|
-
`+m),e.push(d+"m+"+E.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=ce()+r+" "+e[0]}function ce(){return c.inspectOpts.hideDate?"":new Date().toISOString()+" "}function le(...e){return process.stderr.write(x.formatWithOptions(c.inspectOpts,...e)+`
|
|
6
|
-
`)}function ue(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function fe(){return process.env.DEBUG}function Ce(e){e.inspectOpts={};let r=Object.keys(c.inspectOpts);for(let t=0;t<r.length;t++)e.inspectOpts[r[t]]=c.inspectOpts[r[t]]}E.exports=A()(c);var{formatters:q}=E.exports;q.o=function(e){return this.inspectOpts.colors=this.useColors,x.inspect(e,this.inspectOpts).split(`
|
|
7
|
-
`).map(r=>r.trim()).join(" ")};q.O=function(e){return this.inspectOpts.colors=this.useColors,x.inspect(e,this.inspectOpts)}});var ae=b((we,_)=>{p();typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?_.exports=j():_.exports=S()});export{ae as a};
|
package/chunks/chunk-GOJCMVJJ.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{g as w,i as x}from"./chunk-YV3PUOBU.js";import{ba as I}from"./chunk-27Q5KW3A.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();m();var p=I("IMAGE_TOKENIZER"),E=class l{static PIXELS_PER_TOKEN=28*28;static MIN_TOKENS_PER_IMAGE=4;static MAX_TOKENS_PER_IMAGE=16384;static VISION_SPECIAL_TOKENS=2;async extractImageMetadata(t,e){try{if(!x(e))return p.warn(`Unsupported image format: ${e}`),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)};let n=t.replace(/^data:[^;]+;base64,/,""),r=Buffer.from(n,"base64"),i=await this.extractDimensions(r,e);return{width:i.width,height:i.height,mimeType:e,dataSize:r.length}}catch(n){return p.warn("Failed to extract image metadata:",n),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)}}}async extractDimensions(t,e){return e.includes("png")?this.extractPngDimensions(t):e.includes("jpeg")||e.includes("jpg")?this.extractJpegDimensions(t):e.includes("webp")?this.extractWebpDimensions(t):e.includes("gif")?this.extractGifDimensions(t):e.includes("bmp")?this.extractBmpDimensions(t):e.includes("tiff")?this.extractTiffDimensions(t):e.includes("heic")?this.extractHeicDimensions(t):{width:512,height:512}}extractPngDimensions(t){if(t.length<24)throw new Error("Invalid PNG: buffer too short");let e=t.subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!e.equals(n))throw new Error("Invalid PNG signature");let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}extractJpegDimensions(t){if(t.length<4||t[0]!==255||t[1]!==216)throw new Error("Invalid JPEG signature");let e=2;for(;e<t.length-8;){if(t[e]!==255){e++;continue}let n=t[e+1];if(n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207){let i=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:i}}let r=t.readUInt16BE(e+2);e+=2+r}throw new Error("Could not find JPEG dimensions")}extractWebpDimensions(t){if(t.length<30)throw new Error("Invalid WebP: too short");let e=t.subarray(0,4).toString("ascii"),n=t.subarray(8,12).toString("ascii");if(e!=="RIFF"||n!=="WEBP")throw new Error("Invalid WebP signature");let r=t.subarray(12,16).toString("ascii");if(r==="VP8 "){let i=t.readUInt16LE(26)&16383,a=t.readUInt16LE(28)&16383;return{width:i,height:a}}else if(r==="VP8L"){let i=t.readUInt32LE(21),a=(i&16383)+1,s=(i>>14&16383)+1;return{width:a,height:s}}else if(r==="VP8X"){let i=(t.readUInt32LE(24)&16777215)+1,a=(t.readUInt32LE(26)&16777215)+1;return{width:i,height:a}}throw new Error("Unsupported WebP format")}extractGifDimensions(t){if(t.length<10)throw new Error("Invalid GIF: too short");let e=t.subarray(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")throw new Error("Invalid GIF signature");let n=t.readUInt16LE(6),r=t.readUInt16LE(8);return{width:n,height:r}}calculateTokens(t){return this.calculateTokensWithScaling(t.width,t.height)}calculateTokensWithScaling(t,e){let n=Math.round(e/28)*28,r=Math.round(t/28)*28,i=l.MIN_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN,a=l.MAX_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN;if(n*r>a){let o=Math.sqrt(e*t/a);n=Math.floor(e/o/28)*28,r=Math.floor(t/o/28)*28}else if(n*r<i){let o=Math.sqrt(i/(e*t));n=Math.ceil(e*o/28)*28,r=Math.ceil(t*o/28)*28}return Math.floor(n*r/l.PIXELS_PER_TOKEN)+l.VISION_SPECIAL_TOKENS}async calculateTokensBatch(t){let e=[];for(let{data:n,mimeType:r}of t)try{let i=await this.extractImageMetadata(n,r);e.push(this.calculateTokens(i))}catch(i){p.warn("Error calculating tokens for image:",i),e.push(l.MIN_TOKENS_PER_IMAGE+l.VISION_SPECIAL_TOKENS)}return e}extractBmpDimensions(t){if(t.length<26)throw new Error("Invalid BMP: buffer too short");if(t[0]!==66||t[1]!==77)throw new Error("Invalid BMP signature");let e=t.readUInt32LE(18),n=t.readUInt32LE(22);return{width:e,height:Math.abs(n)}}extractTiffDimensions(t){if(t.length<8)throw new Error("Invalid TIFF: buffer too short");let e=t.subarray(0,2).toString("ascii"),n=e==="II";if(!n&&!(e==="MM"))throw new Error("Invalid TIFF byte order");if((n?t.readUInt16LE(2):t.readUInt16BE(2))!==42)throw new Error("Invalid TIFF magic number");let a=n?t.readUInt32LE(4):t.readUInt32BE(4);if(a>=t.length)throw new Error("Invalid TIFF IFD offset");let s=n?t.readUInt16LE(a):t.readUInt16BE(a),o=0,h=0;for(let g=0;g<s;g++){let c=a+2+g*12;if(c+12>t.length)break;let u=n?t.readUInt16LE(c):t.readUInt16BE(c),f=(n?t.readUInt16LE(c+2):t.readUInt16BE(c+2))===3?n?t.readUInt16LE(c+8):t.readUInt16BE(c+8):n?t.readUInt32LE(c+8):t.readUInt32BE(c+8);if(u===256?o=f:u===257&&(h=f),o>0&&h>0)break}if(o===0||h===0)throw new Error("Could not find TIFF dimensions");return{width:o,height:h}}extractHeicDimensions(t){if(t.length<12)throw new Error("Invalid HEIC: buffer too short");if(t.subarray(4,8).toString("ascii")!=="ftyp")throw new Error("Invalid HEIC: missing ftyp box");let n=t.subarray(8,12).toString("ascii");if(!["heic","heix","hevc","hevx"].includes(n))throw new Error("Invalid HEIC brand");let r=0;for(;r<t.length-8;){let i=t.readUInt32BE(r);if(t.subarray(r+4,r+8).toString("ascii")==="meta"){let o=r+8+4;for(;o<r+i-8;){let h=t.readUInt32BE(o);if(t.subarray(o+4,o+8).toString("ascii")==="ispe"&&o+20<=t.length){let c=t.readUInt32BE(o+12),u=t.readUInt32BE(o+16);return{width:c,height:u}}if(h===0)break;o+=h}}if(i===0)break;r+=i}return p.warn("Could not extract HEIC dimensions, using default"),{width:512,height:512}}};var d=I("TOKENIZER"),T=class{textTokenizer;imageTokenizer;constructor(){this.textTokenizer=new w,this.imageTokenizer=new E}async calculateTokens(t){let e=performance.now();try{let{textContents:n,imageContents:r,audioContents:i,otherContents:a}=this.processAndGroupContents(t);if(n.length===0&&r.length===0&&i.length===0&&a.length===0)return{totalTokens:0,breakdown:{textTokens:0,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e};let s=await this.calculateTextTokens(n),o=await this.calculateImageTokens(r),h=await this.calculateAudioTokens(i),g=await this.calculateOtherTokens(a),c=s+o+h+g,u=performance.now()-e;return{totalTokens:c,breakdown:{textTokens:s,imageTokens:o,audioTokens:h,otherTokens:g},processingTime:u}}catch(n){d.error("Error calculating tokens:",n);let r=this.calculateFallbackTokens(t);return{totalTokens:r,breakdown:{textTokens:r,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e}}}async calculateTextTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating text tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}async calculateImageTokens(t){if(t.length===0)return 0;try{return(await this.imageTokenizer.calculateTokensBatch(t)).reduce((n,r)=>n+r,0)}catch(e){return d.warn("Error calculating image tokens:",e),t.length*6}}async calculateAudioTokens(t){if(t.length===0)return 0;let e=0;for(let n of t)try{let r=Math.floor(n.data.length*.75);e+=Math.max(Math.ceil(r/100),10)}catch(r){d.warn("Error calculating audio tokens:",r),e+=10}return e}async calculateOtherTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating other content tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}calculateFallbackTokens(t){try{let e=JSON.stringify(t.contents);return Math.ceil(e.length/4)}catch(e){return d.warn("Error in fallback token calculation:",e),100}}processAndGroupContents(t){let e=[],n=[],r=[],i=[];if(!t.contents)return{textContents:e,imageContents:n,audioContents:r,otherContents:i};let a=Array.isArray(t.contents)?t.contents:[t.contents];for(let s of a)this.processContent(s,e,n,r,i);return{textContents:e,imageContents:n,audioContents:r,otherContents:i}}processContent(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("parts"in t&&t.parts){for(let a of t.parts)this.processPart(a,e,n,r,i);return}this.processPart(t,e,n,r,i)}processPart(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("text"in t&&t.text){e.push(t.text);return}if("inlineData"in t&&t.inlineData){let{data:a,mimeType:s}=t.inlineData;if(s&&s.startsWith("image/")){n.push({data:a||"",mimeType:s});return}if(s&&s.startsWith("audio/")){r.push({data:a||"",mimeType:s});return}}if("fileData"in t&&t.fileData){i.push(JSON.stringify(t.fileData));return}if("functionCall"in t&&t.functionCall){i.push(JSON.stringify(t.functionCall));return}if("functionResponse"in t&&t.functionResponse){i.push(JSON.stringify(t.functionResponse));return}try{let a=JSON.stringify(t);a&&a!=="{}"&&i.push(a)}catch(a){d.warn("Failed to serialize unknown part type:",a)}}};m();export{T as a};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Matilda
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-GTVCJCHR.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{ba as d}from"./chunk-27Q5KW3A.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
|
|
4
|
-
/**
|
|
5
|
-
* @license
|
|
6
|
-
* Copyright 2025 Google LLC
|
|
7
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
-
*/
|
package/chunks/chunk-JCE3JAVC.js
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
// Force strict mode and setup for ESM
|
|
2
|
-
"use strict";
|
|
3
|
-
import{ba as te}from"./chunk-27Q5KW3A.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
|
|
4
|
-
+`.includes(t)}function P(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function q(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var $=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,F=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function K(t){return`,[]/{}
|
|
5
|
-
+`.includes(t)}function J(t){return E(t)||Ke.test(t)}var Ke=/^[[{\w-]$/;function le(t){return t===`
|
|
6
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function C(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function me(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function fe(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function E(t){return Q(t)||L(t)}function Q(t){return t==='"'||t==="\u201C"||t==="\u201D"}function z(t){return t==='"'}function L(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function G(t){return t==="'"}function B(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function h(t,e){let n=t.length;if(!C(t,n-1))return t+e;for(;C(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function pe(t,e,n){return t.substring(0,e)+t.substring(e+n)}function de(t){return/[,\n][ \t\r]*$/.test(t)}var Je={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Qe={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
7
|
-
`,r:"\r",t:" "};function x(t){let e=0,n="";V(["```","[```","{```"]),u()||_e(),V(["```","```]","```}"]);let r=S(",");for(r&&a(),J(t[e])&&de(n)?(r||(n=h(n,",")),Ae()):r&&(n=B(n,","));t[e]==="}"||t[e]==="]";)e++,a();if(e>=t.length)return n;De();function u(){a();let s=Ce()||ke()||T()||Te()||we()||H(!1)||Be();return a(),s}function a(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,c=e,l=d(s);do l=ye(),l&&(l=d(s));while(l);return e>c}function d(s){let c=s?C:me,l="";for(;;)if(c(t,e))l+=t[e],e++;else if(fe(t,e))l+=" ",e++;else break;return l.length>0?(n+=l,!0):!1}function ye(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!ze(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
8
|
-
`;)e++;return!0}return!1}function V(s){if(Re(s)){if(P(t[e]))for(;e<t.length&&q(t[e]);)e++;return a(),!0}return!1}function Re(s){d(!0);for(let c of s){let l=e+c.length;if(t.slice(e,l)===c)return e=l,!0}return!1}function S(s){return t[e]===s?(n+=t[e],e++,!0):!1}function O(s){return t[e]===s?(e++,!0):!1}function be(){return O("\\")}function j(){return a(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,a(),O(","),!0):!1}function Ce(){if(t[e]==="{"){n+="{",e++,a(),O(",")&&a();let s=!0;for(;e<t.length&&t[e]!=="}";){let c;if(s?(c=!0,s=!1):(c=S(","),c||(n=h(n,",")),a()),j(),!(T()||H(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?n=B(n,","):Ee();break}a();let I=S(":"),A=e>=t.length;I||(J(t[e])||A?n=h(n,":"):Z()),u()||(I||A?n+="null":Z())}return t[e]==="}"?(n+="}",e++):n=h(n,"}"),!0}return!1}function ke(){if(t[e]==="["){n+="[",e++,a(),O(",")&&a();let s=!0;for(;e<t.length&&t[e]!=="]";)if(s?s=!1:S(",")||(n=h(n,",")),j(),!u()){n=B(n,",");break}return t[e]==="]"?(n+="]",e++):n=h(n,"]"),!0}return!1}function Ae(){let s=!0,c=!0;for(;c;)s?s=!1:S(",")||(n=h(n,",")),c=u();c||(n=B(n,",")),n=`[
|
|
9
|
-
${n}
|
|
10
|
-
]`}function T(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,l=t[e]==="\\";if(l&&(e++,l=!0),E(t[e])){let I=z(t[e])?z:G(t[e])?G:L(t[e])?L:Q,A=e,D=n.length,m='"';for(e++;;){if(e>=t.length){let g=Y(e-1);return!s&&_(t.charAt(g))?(e=A,n=n.substring(0,D),T(!0)):(m=h(m,'"'),n+=m,!0)}if(e===c)return m=h(m,'"'),n+=m,!0;if(I(t[e])){let g=e,U=m.length;if(m+='"',e++,n+=m,a(!1),s||e>=t.length||_(t[e])||E(t[e])||k(t[e]))return X(),!0;let R=Y(g-1),ee=t.charAt(R);if(ee===",")return e=A,n=n.substring(0,D),T(!1,R);if(_(ee))return e=A,n=n.substring(0,D),T(!0);n=n.substring(0,D),e=g+1,m=`${m.substring(0,U)}\\${m.substring(U)}`}else if(s&&K(t[e])){if(t[e-1]===":"&&$.test(t.substring(A+1,e+2)))for(;e<t.length&&F.test(t[e]);)m+=t[e],e++;return m=h(m,'"'),n+=m,X(),!0}else if(t[e]==="\\"){let g=t.charAt(e+1);if(Qe[g]!==void 0)m+=t.slice(e,e+2),e+=2;else if(g==="u"){let R=2;for(;R<6&&ae(t[e+R]);)R++;R===6?(m+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Oe()}else m+=g,e+=2}else{let g=t.charAt(e);g==='"'&&t[e-1]!=="\\"?(m+=`\\${g}`,e++):le(g)?(m+=Je[g],e++):(ce(g)||Se(g),m+=g,e++)}l&&be()}}return!1}function X(){let s=!1;for(a();t[e]==="+";){s=!0,e++,a(),n=B(n,'"',!0);let c=n.length;T()?n=pe(n,c,1):n=h(n,'"')}return s}function Te(){let s=e;if(t[e]==="-"){if(e++,N())return v(s),!0;if(!k(t[e]))return e=s,!1}for(;k(t[e]);)e++;if(t[e]==="."){if(e++,N())return v(s),!0;if(!k(t[e]))return e=s,!1;for(;k(t[e]);)e++}if(t[e]==="e"||t[e]==="E"){if(e++,(t[e]==="-"||t[e]==="+")&&e++,N())return v(s),!0;if(!k(t[e]))return e=s,!1;for(;k(t[e]);)e++}if(!N())return e=s,!1;if(e>s){let c=t.slice(s,e),l=/^0\d/.test(c);return n+=l?`"${c}"`:c,!0}return!1}function we(){return w("true","true")||w("false","false")||w("null","null")||w("True","true")||w("False","false")||w("None","null")}function w(s,c){return t.slice(e,e+s.length)===s?(n+=c,e+=s.length,!0):!1}function H(s){let c=e;if(P(t[e])){for(;e<t.length&&q(t[e]);)e++;let l=e;for(;C(t,l);)l++;if(t[l]==="(")return e=l+1,u(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!K(t[e])&&!E(t[e])&&(!s||t[e]!==":");)e++;if(t[e-1]===":"&&$.test(t.substring(c,e+2)))for(;e<t.length&&F.test(t[e]);)e++;if(e>c){for(;C(t,e-1)&&e>0;)e--;let l=t.slice(c,e);return n+=l==="undefined"?"null":JSON.stringify(l),t[e]==='"'&&e++,!0}}function Be(){if(t[e]==="/"){let s=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=`"${t.substring(s,e)}"`,!0}}function Y(s){let c=s;for(;c>0&&C(t,c);)c--;return c}function N(){return e>=t.length||_(t[e])||C(t,e)}function v(s){n+=`${t.slice(s,e)}0`}function Se(s){throw new y(`Invalid character ${JSON.stringify(s)}`,e)}function De(){throw new y(`Unexpected character ${JSON.stringify(t[e])}`,e)}function _e(){throw new y("Unexpected end of json string",t.length)}function Ee(){throw new y("Object key expected",e)}function Z(){throw new y("Colon expected",e)}function Oe(){let s=t.slice(e,e+6);throw new y(`Invalid unicode character "${s}"`,e)}}function ze(t,e){return t[e]==="*"&&t[e+1]==="/"}var Ge=te("JSON_PARSE");function Ve(t,e={}){if(!t||typeof t!="string")return e;try{return JSON.parse(t)}catch(n){let o=je(t);if(o!==void 0)return o;try{let r=x(t);return JSON.parse(r)}catch(r){let u=he(t);if(u&&u!==t)try{return JSON.parse(x(u))}catch{}return Ge.error("Failed to parse JSON even with jsonrepair:",{originalError:n,repairError:r,jsonString:t}),e}}}var ge=Symbol("tool-args-parse-failed");function Tt(t){if(t==null)return{};let e=typeof t=="string"?t.trim():"";if(!e)return{};let n=Ve(e,ge);return n===ge?null:n&&typeof n=="object"&&!Array.isArray(n)?n:null}function je(t){let e=he(t);if(e&&e!==t.trim())try{return JSON.parse(e)}catch{return}}function he(t){let e=t.trimStart();if(!e)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let o=0,r=!1,u=!1;for(let a=0;a<e.length;a++){let d=e[a];if(r){u?u=!1:d==="\\"?u=!0:d==='"'&&(r=!1);continue}if(d==='"'){r=!0;continue}if(d==="{"||d==="[")o++;else if(d==="}"||d==="]"){if(o--,o===0)return e.slice(0,a+1);if(o<0)return null}}return null}f();function St(t,e="auto"){return e==="openapi_30"?Xe(t):t}function Xe(t){let e=n=>{if(typeof n!="object"||n===null)return n;if(Array.isArray(n))return n.map(e);let o=n,r={};if(Array.isArray(o.type)){let u=o.type;u.length===2&&u.includes("null")?(r.type=u.find(a=>a!=="null"),r.nullable=!0):r.type=u[0]}else o.type!==void 0&&(r.type=o.type);o.const!==void 0&&(r.enum=[o.const],delete r.const),typeof o.exclusiveMinimum=="number"&&(r.minimum=o.exclusiveMinimum,r.exclusiveMinimum=!0),typeof o.exclusiveMaximum=="number"&&(r.maximum=o.exclusiveMaximum,r.exclusiveMaximum=!0),Array.isArray(o.items)?delete r.items:typeof o.items=="object"&&o.items!==null&&(r.items=e(o.items)),Array.isArray(o.enum)&&(r.enum=o.enum.map(String));for(let[u,a]of Object.entries(o))u==="type"||u==="const"||u==="exclusiveMinimum"||u==="exclusiveMaximum"||u==="items"||u==="enum"||u==="$schema"||u==="$id"||u==="default"||u==="dependencies"||u==="patternProperties"||(r[u]=e(a));return r};return e(t)}f();var Et="https://api.openai.com/v1",Ot="https://matilda.maincode.com/api/v1/code";var Nt=process.env.MATILDA_COMPAT_PROXY_BASE_URL;export{Ve as a,Tt as b,he as c,St as d,ne as e,W as f,He as g,Ie as h,Le as i,Et as j,Ot as k,Nt as l,et as m,tt as n,nt as o,ot as p,rt as q,st as r,ie as s,it as t,Fe as u,ut as v};
|
|
11
|
-
/**
|
|
12
|
-
* @license
|
|
13
|
-
* Copyright 2026 Matilda
|
|
14
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
15
|
-
*/
|
|
16
|
-
/**
|
|
17
|
-
* @license
|
|
18
|
-
* Copyright 2025 Matilda
|
|
19
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
20
|
-
*/
|
|
21
|
-
/**
|
|
22
|
-
* @license
|
|
23
|
-
* Copyright 2025 Google LLC
|
|
24
|
-
* SPDX-License-Identifier: Apache-2.0
|
|
25
|
-
*/
|