Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active October 5, 2026 09:41
Show Gist options
  • Select an option

  • Save qianlifeng/db55c71d2bef5359af515f309be4d23d to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/db55c71d2bef5359af515f309be4d23d to your computer and use it in GitHub Desktop.
Wox.Plugin.ClashVerge
// {
// "Id": "c4a8e2b7-1d63-4f90-8a55-6e0b9d3c7f21",
// "Name": "i18n:plugin_name",
// "Author": "qianlifeng",
// "Version": "1.0.0",
// "MinWoxVersion": "2.4.5",
// "Runtime": "NODEJS",
// "Description": "i18n:plugin_description",
// "Icon": "base64:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAQM0lEQVR4nMRae4wV13n/fTOz9959v2B3wQvGJsbgxsYLOGSpH6mLKQ1N/rEtxXZaqrZpY5pKrVpVqtL/+o9VxZLVqLVbNW4dR03Uoki2Sm0rSlAIDtgo8YKJWR4B7N0FlmVf7O7du3fvnK/65p5v5tzXsjQ2/c6enZkz5/X7Xuc7Z26AT4j46mwPLl3vN5em+mh8bpOZnr+DZnI9yC22gSgDgADKeem6KbRkRtGcvoAVTYNY1TyAtR1HqLNhWPv6OIn05uMgHs+uMe8NfRknrzzJk9k+EJUNwrWHZoIn9YlgmIDW+l9493T9F+5f+R3qbvulVvtViaqW3gQxM4UnR/fwuxf38dD0YwQEBK5VPcJMOnJUrVibIIA9GMskZg+AJ+9CrGo5RFtve9HfuvL7RBRqV7cc8OIHV3aGb555HtPz90lH5Eg06djYJ2WCt8RUyDJAJO2BRdKS4cHABzXVn/F39v510LfiNW11SwDz2Nzq3Jtnn+ez174UdUBsO7JXSmAtNQDD1QULWABGjBPpFp85krS4Gz+6x9qW1+v39P4F9WTOa+tPDPDCseEnFt849y0KTYsHrjF9U7THKoOQfTJlpcm1mA28mAGMoAgUvi33wRTMp3+z+2uphzpf1l6WQ1RZVD0xc3p+/+Dzi++P7rOuRX2SysJ2yGCS6ZGFRUs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JuasGpz/8uHmtYQSPaRS2i2q9Kk/yc70cH8M/DZ/BUrLIK2PakthartTOC1rkZIq5Ucc060Oq1OPDQ49jb0kLj2m4puskpAAMH+avHf4gXCkA6CToSgO59LG1ra+5odr5LTkiDEG3vdiEr1+Yd+Pr2ndW9MZbR/7JpbJg3HDmAb44OY5c6MlXp2HHZrN/nNPhQ0nrViGpcpUNxWp1dONz/W/iz3jtoQF8tl6js+abog2P8pXd+gOdyOdyuKu1egdoSJSp9Xo5XTaVwZevD+Nu+frzshos3Q3RTtauQ/OjrxLt4+v1jeHZqDNv15FAl7g7gvqsgxxmVJAZaOjDw6a14aUs/vk1E8/rq/0K09OubS0Pn+b7T72Pv+UE8kcthrSsCVe/lTiidwuU7N+L7G+/FK2vX0zFb/CsnWnbNmyD5GePly9h45SJ2XL2KvslxbLo+iXXZLFYxUF+mqrn6Bow2t+JiaycGu3rwXs8aHOntxUk5g9JKHxf97wCgORPmgieStgAAAABJRU5ErkJggg==",
// "TriggerKeywords": ["cv", "clash"],
// "SupportedOS": ["Windows", "Linux", "Darwin"],
// "Features": [
// { "Name": "debounce", "Params": { "IntervalMs": 250 } },
// { "Name": "mru", "Params": { "HashBy": "scoreKey" } },
// { "Name": "ignoreAutoScore" }
// ],
// "Commands": [
// { "Command": "mode", "Description": "i18n:command_mode" },
// { "Command": "nodes", "Description": "i18n:command_nodes" }
// ],
// "SettingDefinitions": [
// {
// "Type": "textbox",
// "Value": {
// "Key": "api_url",
// "Label": "i18n:setting_api_url",
// "DefaultValue": "",
// "Tooltip": "i18n:setting_api_url_tip",
// "Style": { "Width": 420 }
// },
// "IsPlatformSpecific": true
// },
// {
// "Type": "password",
// "Value": {
// "Key": "secret",
// "Label": "i18n:setting_secret",
// "DefaultValue": "",
// "Tooltip": "i18n:setting_secret_tip",
// "Style": { "Width": 420 }
// },
// "IsPlatformSpecific": true
// },
// {
// "Type": "textbox",
// "Value": {
// "Key": "group",
// "Label": "i18n:setting_group",
// "DefaultValue": "",
// "Tooltip": "i18n:setting_group_tip",
// "Style": { "Width": 420 }
// },
// "IsPlatformSpecific": false
// }
// ],
// "I18n": {
// "en_US": {
// "plugin_name": "Clash Verge",
// "plugin_description": "Show the local Clash Verge core and switch proxy nodes.",
// "command_mode": "Switch rule, global, or direct mode",
// "command_nodes": "Search nodes in the main selector",
// "setting_api_url": "Controller URL",
// "setting_api_url_tip": "Optional. Leave this empty to connect automatically.\n\nClash Verge leaves External Controller off by default. The core still listens on a local named pipe on Windows, or a local socket on macOS and Linux.\n\n1. Type cv to read the running core\n2. Turn on External Controller only when you want a fixed HTTP address\n3. Enter that address here, for example http://127.0.0.1:9097",
// "setting_secret": "Controller secret",
// "setting_secret_tip": "Optional. Leave this empty to read the secret from the Clash Verge config. A new install often uses set-your-secret.\n\n1. Open the generated clash-verge.yaml next to the Clash Verge profile\n2. Copy the top-level secret value\n3. Paste it here if automatic auth is rejected",
// "setting_group": "Node group",
// "setting_group_tip": "Optional. Leave this empty to search the main selector, usually the group named Proxies.\n\n1. Type cv to list selector groups and the node each one is using\n2. Type cv followed by a group name to list that group's nodes\n3. Put a group name here to make an empty node search use that group",
// "group_status": "Status",
// "group_proxy": "Groups",
// "group_nodes": "Nodes",
// "group_mode": "Mode",
// "status_title": "Clash Verge",
// "status_connections": "{n} connections",
// "tail_mode_rule": "Rule",
// "tail_mode_global": "Global",
// "tail_mode_direct": "Direct",
// "tail_tun_on": "TUN on",
// "tail_tun_off": "TUN off",
// "tail_proxy_on": "System proxy on",
// "tail_proxy_off": "System proxy off",
// "tail_current": "Current",
// "tail_default": "Main",
// "tail_delay": "{n} ms",
// "tail_timeout": "Timeout",
// "action_nodes": "Show nodes",
// "action_select": "Use this node",
// "action_mode_rule": "Rule mode",
// "action_mode_global": "Global mode",
// "action_mode_direct": "Direct mode",
// "action_delay": "Test delay",
// "action_copy": "Copy status",
// "mode_rule": "Rule mode",
// "mode_global": "Global mode",
// "mode_direct": "Direct mode",
// "mode_subtitle": "Outbound mode",
// "empty_title": "No matching node",
// "empty_subtitle": "Type part of a group or node name",
// "more_title": "{n} more nodes",
// "more_subtitle": "Keep typing to narrow the list",
// "error_unreachable_title": "Clash Verge is not running",
// "error_unreachable_subtitle": "Start Clash Verge and keep the core running. External Controller can stay off.",
// "error_unauthorized_title": "Controller secret was rejected",
// "error_unauthorized_subtitle": "Leave the secret empty to read it from Clash Verge, or paste the controller secret in plugin settings.",
// "notify_selected": "Switched {group} to {name}",
// "notify_select_failed": "Could not switch the node",
// "notify_mode": "Mode is now {mode}",
// "notify_mode_failed": "Could not change the mode",
// "notify_delay": "{name}: {delay}",
// "notify_delay_failed": "Delay test failed",
// "notify_copied": "Status copied",
// "copy_version": "Version",
// "copy_mode": "Mode",
// "copy_tun": "TUN",
// "copy_system_proxy": "System proxy",
// "copy_port": "Mixed port",
// "copy_connections": "Connections",
// "copy_group": "Group",
// "copy_node": "Node",
// "copy_on": "on",
// "copy_off": "off",
// "copy_unknown": "unknown",
// "tool_get_status": "Read the local Clash Verge core: version, mode, TUN, system proxy, and the main selector.",
// "tool_list_groups": "List Clash Verge selector groups and the node selected in each group.",
// "tool_select_proxy": "Switch the selected node of one Clash Verge selector group. This changes live traffic for that group.",
// "tool_set_mode": "Set the Clash Verge outbound mode to rule, global, or direct."
// },
// "zh_CN": {
// "plugin_name": "Clash Verge",
// "plugin_description": "查看本机 Clash Verge 运行状态,并切换代理节点。",
// "command_mode": "切换规则、全局或直连模式",
// "command_nodes": "在主策略组里搜索节点",
// "setting_api_url": "控制器地址",
// "setting_api_url_tip": "可选。留空则自动连接。\n\nClash Verge 默认关闭外部控制器。内核仍会在 Windows 本机命名管道,或 macOS / Linux 本机套接字上提供接口。\n\n1. 输入 cv 查看正在运行的内核\n2. 只有需要固定 HTTP 地址时,才打开外部控制器\n3. 把地址填在这里,例如 http://127.0.0.1:9097",
// "setting_secret": "控制器密钥",
// "setting_secret_tip": "可选。留空则从 Clash Verge 的配置读取密钥。新安装常见的默认值是 set-your-secret。\n\n1. 打开 Clash Verge 配置目录里生成的 clash-verge.yaml\n2. 复制顶层的 secret\n3. 如果自动认证失败,再粘贴到这里",
// "setting_group": "节点策略组",
// "setting_group_tip": "可选。留空则搜索主选择组,通常是名为 Proxies 的组。\n\n1. 输入 cv 查看各个选择组当前节点\n2. 输入 cv 加策略组名称,列出该组节点\n3. 把策略组名称填在这里后,直接搜索节点会用这个组",
// "group_status": "状态",
// "group_proxy": "策略组",
// "group_nodes": "节点",
// "group_mode": "模式",
// "status_title": "Clash Verge",
// "status_connections": "{n} 个连接",
// "tail_mode_rule": "规则",
// "tail_mode_global": "全局",
// "tail_mode_direct": "直连",
// "tail_tun_on": "TUN 开",
// "tail_tun_off": "TUN 关",
// "tail_proxy_on": "系统代理开",
// "tail_proxy_off": "系统代理关",
// "tail_current": "当前",
// "tail_default": "主组",
// "tail_delay": "{n} ms",
// "tail_timeout": "超时",
// "action_nodes": "查看节点",
// "action_select": "使用此节点",
// "action_mode_rule": "规则模式",
// "action_mode_global": "全局模式",
// "action_mode_direct": "直连模式",
// "action_delay": "测试延迟",
// "action_copy": "复制状态",
// "mode_rule": "规则模式",
// "mode_global": "全局模式",
// "mode_direct": "直连模式",
// "mode_subtitle": "出站模式",
// "empty_title": "没有匹配的节点",
// "empty_subtitle": "继续输入策略组或节点名称",
// "more_title": "还有 {n} 个节点",
// "more_subtitle": "继续输入以缩小范围",
// "error_unreachable_title": "Clash Verge 未在运行",
// "error_unreachable_subtitle": "请先启动 Clash Verge 并保持内核运行。外部控制器可以保持关闭。",
// "error_unauthorized_title": "控制器密钥被拒绝",
// "error_unauthorized_subtitle": "密钥留空可自动读取 Clash Verge 配置;如果仍失败,把控制器密钥填到插件设置。",
// "notify_selected": "已将 {group} 切换为 {name}",
// "notify_select_failed": "切换节点失败",
// "notify_mode": "模式已改为 {mode}",
// "notify_mode_failed": "切换模式失败",
// "notify_delay": "{name}:{delay}",
// "notify_delay_failed": "延迟测试失败",
// "notify_copied": "已复制状态",
// "copy_version": "版本",
// "copy_mode": "模式",
// "copy_tun": "TUN",
// "copy_system_proxy": "系统代理",
// "copy_port": "混合端口",
// "copy_connections": "连接数",
// "copy_group": "策略组",
// "copy_node": "节点",
// "copy_on": "开",
// "copy_off": "关",
// "copy_unknown": "未知",
// "tool_get_status": "读取本机 Clash Verge 内核的版本、模式、TUN、系统代理和主策略组。",
// "tool_list_groups": "列出 Clash Verge 的选择策略组,以及每个组当前选中的节点。",
// "tool_select_proxy": "切换一个 Clash Verge 选择组的当前节点。这会改变该组的实际流量。",
// "tool_set_mode": "把 Clash Verge 的出站模式设为 rule、global 或 direct。"
// }
// }
// }
const fs = require("fs")
const http = require("http")
const https = require("https")
const net = require("net")
const os = require("os")
const path = require("path")
const NODE_LIMIT = 40
const RESERVED_OUTBOUNDS = new Set(["DIRECT", "REJECT", "REJECT-DROP", "PASS", "COMPATIBLE", "GLOBAL", "REJECTDROP"])
const MODE_ORDER = ["rule", "global", "direct"]
const RESULT_ICON_DATA = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAQM0lEQVR4nMRae4wV13n/fTOz9959v2B3wQvGJsbgxsYLOGSpH6mLKQ1N/rEtxXZaqrZpY5pKrVpVqtL/+o9VxZLVqLVbNW4dR03Uoki2Sm0rSlAIDtgo8YKJWR4B7N0FlmVf7O7du3fvnK/65p5v5tzXsjQ2/c6enZkz5/X7Xuc7Z26AT4j46mwPLl3vN5em+mh8bpOZnr+DZnI9yC22gSgDgADKeem6KbRkRtGcvoAVTYNY1TyAtR1HqLNhWPv6OIn05uMgHs+uMe8NfRknrzzJk9k+EJUNwrWHZoIn9YlgmIDW+l9493T9F+5f+R3qbvulVvtViaqW3gQxM4UnR/fwuxf38dD0YwQEBK5VPcJMOnJUrVibIIA9GMskZg+AJ+9CrGo5RFtve9HfuvL7RBRqV7cc8OIHV3aGb555HtPz90lH5Eg06djYJ2WCt8RUyDJAJO2BRdKS4cHABzXVn/F39v510LfiNW11SwDz2Nzq3Jtnn+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V97EktVMF5bC6POgnu4HRyelSpLZLarvWeWlX6XoMff4PsUP2B7aoInkVJQ61ttLEr/8+dmeacVqdkbETVDVVYPHVYUA52FiFrRPTwEDraK5Wrioc2uDC1SQpCzIY+tyXsWspsMq8G5JI+sf/ireuX8O2GJiVtoLWdVZBxieJZYCXNQNbkcqkHUsVpdJuasGpz/8uHmtYQSPaRS2i2q9Kk/yc70cH8M/DZ/BUrLIK2PakthartTOC1rkZIq5Ucc060Oq1OPDQ49jb0kLj2m4puskpAAMH+avHf4gXCkA6CToSgO59LG1ra+5odr5LTkiDEG3vdiEr1+Yd+Pr2ndW9MZbR/7JpbJg3HDmAb44OY5c6MlXp2HHZrN/nNPhQ0nrViGpcpUNxWp1dONz/W/iz3jtoQF8tl6js+abog2P8pXd+gOdyOdyuKu1egdoSJSp9Xo5XTaVwZevD+Nu+frzshos3Q3RTtauQ/OjrxLt4+v1jeHZqDNv15FAl7g7gvqsgxxmVJAZaOjDw6a14aUs/vk1E8/rq/0K09OubS0Pn+b7T72Pv+UE8kcthrSsCVe/lTiidwuU7N+L7G+/FK2vX0zFb/CsnWnbNmyD5GePly9h45SJ2XL2KvslxbLo+iXXZLFYxUF+mqrn6Bow2t+JiaycGu3rwXs8aHOntxUk5g9JKHxf97wCgORPmgieStgAAAABJRU5ErkJggg=="
const EXECUTE_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='var(--wox-theme-icon-color)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M13 2 4.5 13.5h5.5L9 22l10-13h-6z'/></svg>"
const COPY_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='var(--wox-theme-icon-color)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><rect x='8' y='8' width='12' height='12' rx='2'/><path d='M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2'/></svg>"
const SEARCH_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='var(--wox-theme-icon-color)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><circle cx='11' cy='11' r='7'/><path d='m20 20-4-4'/></svg>"
const RESULT_ICON = { ImageType: "base64", ImageData: RESULT_ICON_DATA }
const ACTION_EXECUTE = { ImageType: "svg", ImageData: EXECUTE_SVG }
const ACTION_COPY = { ImageType: "svg", ImageData: COPY_SVG }
const ACTION_SEARCH = { ImageType: "svg", ImageData: SEARCH_SVG }
const I18N = {
en_US: {
plugin_name: "Clash Verge",
status_title: "Clash Verge",
status_connections: "{n} connections",
tail_mode_rule: "Rule",
tail_mode_global: "Global",
tail_mode_direct: "Direct",
tail_tun_on: "TUN on",
tail_tun_off: "TUN off",
tail_proxy_on: "System proxy on",
tail_proxy_off: "System proxy off",
tail_current: "Current",
tail_default: "Main",
tail_delay: "{n} ms",
tail_timeout: "Timeout",
action_nodes: "Show nodes",
action_select: "Use this node",
action_mode_rule: "Rule mode",
action_mode_global: "Global mode",
action_mode_direct: "Direct mode",
action_delay: "Test delay",
action_copy: "Copy status",
mode_rule: "Rule mode",
mode_global: "Global mode",
mode_direct: "Direct mode",
mode_subtitle: "Outbound mode",
empty_title: "No matching node",
empty_subtitle: "Type part of a group or node name",
more_title: "{n} more nodes",
more_subtitle: "Keep typing to narrow the list",
error_unreachable_title: "Clash Verge is not running",
error_unreachable_subtitle: "Start Clash Verge and keep the core running. External Controller can stay off.",
error_unauthorized_title: "Controller secret was rejected",
error_unauthorized_subtitle: "Leave the secret empty to read it from Clash Verge, or paste the controller secret in plugin settings.",
notify_selected: "Switched {group} to {name}",
notify_select_failed: "Could not switch the node",
notify_mode: "Mode is now {mode}",
notify_mode_failed: "Could not change the mode",
notify_delay: "{name}: {delay}",
notify_delay_failed: "Delay test failed",
notify_copied: "Status copied",
copy_version: "Version",
copy_mode: "Mode",
copy_tun: "TUN",
copy_system_proxy: "System proxy",
copy_port: "Mixed port",
copy_connections: "Connections",
copy_group: "Group",
copy_node: "Node",
copy_on: "on",
copy_off: "off",
copy_unknown: "unknown",
group_status: "Status",
group_proxy: "Groups",
group_nodes: "Nodes",
group_mode: "Mode"
}
}
function fill(template, values) {
return String(template || "").replace(/\{(\w+)\}/g, (_, key) => (values[key] == null ? "" : String(values[key])))
}
function cleanSecret(value) {
return String(value || "").replace(/[\r\n]/g, "").trim()
}
// Clash Verge writes a generated config whose pipe path can lag the live core.
// Only the top-level keys are needed; nested proxy lists stay unread.
function parseTopLevelYaml(text) {
const values = {}
for (const line of String(text || "").split(/\r?\n/)) {
if (!line || /^\s/.test(line) || line.startsWith("#")) continue
const matched = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
if (!matched) continue
let value = matched[2].trim()
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
value = value.slice(1, -1)
}
values[matched[1]] = value
}
return values
}
function clashConfigDirectories() {
const home = os.homedir()
if (process.platform === "win32") {
const appData = process.env.APPDATA || path.join(home, "AppData", "Roaming")
return [path.join(appData, "io.github.clash-verge-rev.clash-verge-rev")]
}
if (process.platform === "darwin") {
return [path.join(home, "Library", "Application Support", "io.github.clash-verge-rev.clash-verge-rev")]
}
return [
path.join(home, ".local", "share", "io.github.clash-verge-rev.clash-verge-rev"),
path.join(home, ".config", "clash-verge-rev")
]
}
function readOptionalFile(filePath) {
try {
return fs.readFileSync(filePath, "utf8")
} catch {
return ""
}
}
function loadLocalClashFiles(directories = clashConfigDirectories()) {
let clashText = ""
let vergeText = ""
let directory = ""
for (const dir of directories) {
const clash = readOptionalFile(path.join(dir, "clash-verge.yaml"))
const verge = readOptionalFile(path.join(dir, "verge.yaml"))
if (!clash && !verge) continue
directory = dir
clashText = clash
vergeText = verge
break
}
const clash = parseTopLevelYaml(clashText)
const verge = parseTopLevelYaml(vergeText)
let systemProxy = null
if (verge.enable_system_proxy === "true") systemProxy = true
if (verge.enable_system_proxy === "false") systemProxy = false
return {
directory,
secret: clash.secret || "",
externalController: clash["external-controller"] || "",
systemProxy
}
}
function listWindowsPipes() {
if (process.platform !== "win32") return []
try {
return fs.readdirSync("\\\\.\\pipe\\")
} catch {
return []
}
}
function socketCandidates(directory) {
const home = os.homedir()
return [
directory ? path.join(directory, "verge-mihomo.sock") : "",
path.join(home, ".local", "share", "clash-verge-rev", "ipc", "verge-mihomo.sock"),
path.join(home, ".local", "share", "io.github.clash-verge-rev.clash-verge-rev", "verge-mihomo.sock"),
"/tmp/verge/verge-mihomo.sock",
path.join(home, "Library", "Application Support", "io.github.clash-verge-rev.clash-verge-rev", "verge-mihomo.sock")
].filter(Boolean)
}
function existingSockets(candidates) {
return candidates.filter((item) => {
try {
return fs.existsSync(item)
} catch {
return false
}
})
}
function pipeRank(name) {
const lower = String(name || "").toLowerCase()
if (!lower.startsWith("verge-mihomo") || lower.includes("service")) return -1
let score = 1
if (lower.includes("production")) score += 10
return score
}
function windowsPipePath(name) {
const text = String(name || "")
if (text.startsWith("\\\\.\\pipe\\") || text.startsWith("\\\\?\\pipe\\")) return text
return `\\\\.\\pipe\\${text}`
}
function normalizeBaseUrl(value) {
const text = String(value || "").trim()
if (!text) return ""
if (/^https?:\/\//i.test(text)) return text.replace(/\/+$/, "")
return `http://${text.replace(/\/+$/, "")}`
}
function resolveSecret(settingSecret, fileSecret) {
return cleanSecret(settingSecret) || cleanSecret(fileSecret) || "set-your-secret"
}
// Prefer a live named pipe or socket. The HTTP controller is optional and off by default.
function planEndpoints(env) {
const settings = env.settings || {}
const files = env.files || {}
const secret = resolveSecret(settings.secret, files.secret)
const apiUrl = normalizeBaseUrl(settings.apiUrl)
if (apiUrl) return [{ kind: "http", baseUrl: apiUrl, secret, source: "setting", required: true }]
const endpoints = []
const pipes = (env.pipes || [])
.map((name) => ({ name, score: pipeRank(name) }))
.filter((item) => item.score >= 0)
.sort((a, b) => b.score - a.score || String(a.name).localeCompare(String(b.name)))
for (const pipe of pipes) {
endpoints.push({ kind: "pipe", pipePath: windowsPipePath(pipe.name), secret, source: "pipe", required: false })
}
for (const socketPath of env.sockets || []) {
endpoints.push({ kind: "socket", socketPath, secret, source: "socket", required: false })
}
const controller = String(files.externalController || "").trim()
if (controller && !controller.startsWith("\\")) {
endpoints.push({
kind: "http",
baseUrl: normalizeBaseUrl(controller),
secret,
source: "config",
required: false
})
}
return endpoints
}
function collectEnvironment(settings) {
const files = loadLocalClashFiles()
return {
settings: settings || {},
files,
pipes: listWindowsPipes(),
sockets: existingSockets(socketCandidates(files.directory))
}
}
class ClashError extends Error {
constructor(code, message) {
super(message)
this.code = code
}
}
function statusCodeFrom(line) {
const matched = /^HTTP\/\d+(?:\.\d+)?\s+(\d+)/.exec(String(line || ""))
return matched ? Number(matched[1]) : 0
}
function decodeChunked(buffer) {
const parts = []
let offset = 0
let complete = false
while (offset < buffer.length) {
const lineEnd = buffer.indexOf("\r\n", offset)
if (lineEnd < 0) break
const sizeText = buffer.slice(offset, lineEnd).toString("utf8").split(";")[0].trim()
const size = Number.parseInt(sizeText, 16)
if (!Number.isFinite(size)) break
if (size === 0) {
complete = true
break
}
const start = lineEnd + 2
const end = start + size
if (end > buffer.length) break
parts.push(buffer.slice(start, end))
offset = end + 2
}
return { complete, body: Buffer.concat(parts) }
}
// mihomo speaks HTTP on the named pipe and often frames large JSON as chunks.
function parseHttpMessage(buffer, ended) {
const sep = buffer.indexOf("\r\n\r\n")
if (sep < 0) return null
const head = buffer.slice(0, sep).toString("utf8")
const lines = head.split("\r\n")
const headers = {}
for (const line of lines.slice(1)) {
const index = line.indexOf(":")
if (index > 0) headers[line.slice(0, index).trim().toLowerCase()] = line.slice(index + 1).trim()
}
const rest = buffer.slice(sep + 4)
const statusCode = statusCodeFrom(lines[0])
if ((headers["transfer-encoding"] || "").toLowerCase().includes("chunked")) {
const decoded = decodeChunked(rest)
if (!decoded.complete && !ended) return null
if (!decoded.complete && decoded.body.length === 0) return null
return { statusCode, body: decoded.body.toString("utf8") }
}
if (headers["content-length"] != null && headers["content-length"] !== "") {
const length = Number(headers["content-length"])
if (!Number.isFinite(length) || rest.length < length) return null
return { statusCode, body: rest.slice(0, length).toString("utf8") }
}
if (!ended) return null
return { statusCode, body: rest.toString("utf8") }
}
function parseJsonBody(text) {
const trimmed = String(text || "").trim()
if (!trimmed) return null
return JSON.parse(trimmed)
}
function readSocketHttp(socket, timeoutMs) {
return new Promise((resolve, reject) => {
const chunks = []
let settled = false
const timer = setTimeout(() => finish(new Error("timeout")), timeoutMs)
const finish = (error, value) => {
if (settled) return
settled = true
clearTimeout(timer)
socket.destroy()
if (error) reject(error)
else resolve(value)
}
socket.on("data", (chunk) => {
chunks.push(chunk)
const parsed = parseHttpMessage(Buffer.concat(chunks), false)
if (parsed) finish(null, parsed)
})
socket.on("end", () => {
try {
const parsed = parseHttpMessage(Buffer.concat(chunks), true)
if (!parsed) finish(new Error("incomplete http response"))
else finish(null, parsed)
} catch (error) {
finish(error)
}
})
socket.on("error", (error) => finish(error))
})
}
function writeRawRequest(socket, endpoint, method, requestPath, body) {
const payload = body == null ? "" : JSON.stringify(body)
const headers = [
`${method} ${requestPath} HTTP/1.1`,
"Host: localhost",
"Accept: application/json",
"Connection: close"
]
if (endpoint.secret) headers.push(`Authorization: Bearer ${endpoint.secret}`)
if (payload) {
headers.push("Content-Type: application/json")
headers.push(`Content-Length: ${Buffer.byteLength(payload)}`)
}
socket.write(`${headers.join("\r\n")}\r\n\r\n${payload}`)
}
function requestHttp(endpoint, method, requestPath, body, timeoutMs) {
const target = new URL(requestPath, `${endpoint.baseUrl}/`)
const lib = target.protocol === "https:" ? https : http
const payload = body == null ? "" : JSON.stringify(body)
const headers = { Accept: "application/json", Connection: "close" }
if (endpoint.secret) headers.Authorization = `Bearer ${endpoint.secret}`
if (payload) {
headers["Content-Type"] = "application/json"
headers["Content-Length"] = Buffer.byteLength(payload)
}
return new Promise((resolve, reject) => {
const req = lib.request({
protocol: target.protocol,
hostname: target.hostname,
port: target.port,
path: `${target.pathname}${target.search}`,
method,
headers
}, (res) => {
const chunks = []
res.on("data", (chunk) => chunks.push(chunk))
res.on("end", () => {
resolve({
statusCode: res.statusCode || 0,
body: Buffer.concat(chunks).toString("utf8")
})
})
})
req.setTimeout(timeoutMs, () => req.destroy(new Error("timeout")))
req.on("error", reject)
if (payload) req.write(payload)
req.end()
})
}
function createClashClient(endpoint, options = {}) {
const timeoutMs = options.timeoutMs || 4000
async function request(method, requestPath, body) {
if (endpoint.kind === "http") return requestHttp(endpoint, method, requestPath, body, timeoutMs)
const socket = net.connect(endpoint.kind === "socket" ? endpoint.socketPath : endpoint.pipePath)
const pending = readSocketHttp(socket, timeoutMs)
writeRawRequest(socket, endpoint, method, requestPath, body)
return pending
}
return {
async getJson(requestPath) {
const response = await request("GET", requestPath)
return { statusCode: response.statusCode, json: parseJsonBody(response.body), text: response.body }
},
async sendJson(method, requestPath, body) {
const response = await request(method, requestPath, body)
return { statusCode: response.statusCode, json: parseJsonBody(response.body), text: response.body }
}
}
}
function ensureOk(response, label) {
const statusCode = response ? response.statusCode : 0
if (statusCode < 200 || statusCode >= 300) {
const code = statusCode === 401 || statusCode === 403 ? "unauthorized" : "request"
throw new ClashError(code, `${label} HTTP ${statusCode}`)
}
}
async function openClash(env, options = {}) {
const endpoints = planEndpoints(env)
if (!endpoints.length) throw new ClashError("unreachable", "no clash endpoint")
let last = new ClashError("unreachable", "no clash endpoint")
for (const endpoint of endpoints) {
const client = createClashClient(endpoint, { timeoutMs: options.timeoutMs || 2000 })
try {
const version = await client.getJson("/version")
if (version.statusCode === 401 || version.statusCode === 403) {
last = new ClashError("unauthorized", "controller secret was rejected")
if (endpoint.required) break
continue
}
if (version.statusCode < 200 || version.statusCode >= 300 || !version.json) {
last = new ClashError("unreachable", `version HTTP ${version.statusCode}`)
continue
}
return { client, endpoint, version: version.json }
} catch (error) {
last = error instanceof ClashError ? error : new ClashError("unreachable", error.message || "connect failed")
}
}
throw last
}
function lastDelay(proxy) {
const history = proxy && Array.isArray(proxy.history) ? proxy.history : []
if (!history.length) return null
const delay = history[history.length - 1] && history[history.length - 1].delay
return typeof delay === "number" ? delay : null
}
function normalizeSnapshot(payload, preferredGroup) {
const proxies = payload && payload.proxies && payload.proxies.proxies ? payload.proxies.proxies : {}
const delays = {}
const groups = []
for (const [name, proxy] of Object.entries(proxies)) {
const delay = lastDelay(proxy)
if (delay != null) delays[name] = delay
if (proxy && proxy.type === "Selector" && Array.isArray(proxy.all)) {
groups.push({ name, type: proxy.type, now: proxy.now || "", all: proxy.all.slice() })
}
}
const configs = payload.configs || {}
const tun = configs.tun && typeof configs.tun.enable === "boolean" ? configs.tun.enable : null
const connections = payload.connections && Array.isArray(payload.connections.connections)
? payload.connections.connections.length
: null
return {
version: payload.version && payload.version.version ? payload.version.version : "",
mode: String(configs.mode || "").toLowerCase(),
mixedPort: configs["mixed-port"] == null ? null : configs["mixed-port"],
tun,
systemProxy: payload.systemProxy == null ? null : payload.systemProxy,
connectionCount: connections,
groups,
delays,
preferredGroup: preferredGroup || "",
endpointSource: payload.endpointSource || ""
}
}
async function readSnapshot(client, seed = {}) {
const [configs, proxies, connections] = await Promise.all([
client.getJson("/configs"),
client.getJson("/proxies"),
client.getJson("/connections").catch(() => null)
])
ensureOk(configs, "configs")
ensureOk(proxies, "proxies")
return {
version: seed.version || null,
configs: configs.json,
proxies: proxies.json,
connections: connections && connections.statusCode >= 200 && connections.statusCode < 300 ? connections.json : null
}
}
function realMemberCount(group, groupNames) {
let count = 0
for (const name of group.all || []) {
if (groupNames.has(name) || RESERVED_OUTBOUNDS.has(name)) continue
count += 1
}
return count
}
// The main selector is the group currently pointing at a real node, not GLOBAL or a group-of-groups.
function pickDefaultGroup(groups, preferred) {
const selectors = (groups || []).filter((group) => group && group.type === "Selector")
const wanted = String(preferred || "").trim().toLowerCase()
if (wanted) {
const found = selectors.find((group) => group.name.toLowerCase() === wanted)
if (found) return found
}
const names = new Set(selectors.map((group) => group.name))
const ranked = selectors
.filter((group) => group.name !== "GLOBAL")
.map((group) => ({
group,
real: realMemberCount(group, names),
concreteNow: Boolean(group.now) && !names.has(group.now) && !RESERVED_OUTBOUNDS.has(group.now)
}))
.sort((a, b) => {
if (a.concreteNow !== b.concreteNow) return a.concreteNow ? -1 : 1
return b.real - a.real
})
if (ranked.length) return ranked[0].group
return selectors[0] || null
}
function parseIntent(query, groups) {
let command = String(query && query.Command || "").trim().toLowerCase()
let search = String(query && query.Search || "").trim()
if (!command) {
const lower = search.toLowerCase()
if (lower === "mode" || lower.startsWith("mode ") || search === "模式" || search.startsWith("模式 ")) {
command = "mode"
search = search.replace(/^(mode|模式)\s*/i, "").trim()
} else if (/^(nodes|node|节点)(\s|$)/i.test(search)) {
command = "nodes"
search = search.replace(/^(nodes|node|节点)\s*/i, "").trim()
}
}
if (command === "mode") return { kind: "mode", search }
const selectors = (groups || []).filter((group) => group.type === "Selector")
const prefixed = matchGroupPrefix(selectors, search)
if (prefixed) return { kind: "nodes", group: prefixed.group, search: prefixed.search }
if (command === "nodes") return { kind: "nodes", search, group: null }
if (!search) return { kind: "home", search: "" }
return { kind: "filter", search }
}
function matchGroupPrefix(groups, search) {
const text = String(search || "")
const lower = text.toLowerCase()
const sorted = (groups || []).slice().sort((a, b) => b.name.length - a.name.length)
for (const group of sorted) {
const name = group.name.toLowerCase()
if (!name) continue
if (lower === name || lower.startsWith(`${name} `)) {
return { group, search: text.slice(group.name.length).trim() }
}
}
return null
}
function modeLabel(labels, mode) {
if (mode === "global") return labels.tail_mode_global
if (mode === "direct") return labels.tail_mode_direct
if (mode === "rule") return labels.tail_mode_rule
return mode || ""
}
function onOff(labels, value) {
if (value === true) return labels.copy_on
if (value === false) return labels.copy_off
return labels.copy_unknown
}
function statusSubtitle(snapshot, group, labels) {
const parts = []
if (snapshot.version) parts.push(snapshot.version)
if (snapshot.connectionCount != null) parts.push(fill(labels.status_connections, { n: snapshot.connectionCount }))
if (group) parts.push(`${group.name} → ${group.now || "-"}`)
return parts.join(" · ")
}
function statusTails(snapshot, labels) {
const tails = []
const mode = modeLabel(labels, snapshot.mode)
if (mode) tails.push({ Type: "text", Text: mode })
if (snapshot.tun === true) tails.push({ Type: "text", Text: labels.tail_tun_on, TextCategory: "success" })
if (snapshot.tun === false) tails.push({ Type: "text", Text: labels.tail_tun_off })
if (tails.length < 3 && snapshot.systemProxy === true) tails.push({ Type: "text", Text: labels.tail_proxy_on, TextCategory: "success" })
if (tails.length < 3 && snapshot.systemProxy === false) tails.push({ Type: "text", Text: labels.tail_proxy_off })
return tails.slice(0, 3)
}
function copySummary(snapshot, group, labels) {
const lines = [
labels.status_title,
`${labels.copy_version}: ${snapshot.version || "-"}`,
`${labels.copy_mode}: ${snapshot.mode || "-"}`,
`${labels.copy_tun}: ${onOff(labels, snapshot.tun)}`,
`${labels.copy_system_proxy}: ${onOff(labels, snapshot.systemProxy)}`,
`${labels.copy_port}: ${snapshot.mixedPort == null ? "-" : snapshot.mixedPort}`,
`${labels.copy_connections}: ${snapshot.connectionCount == null ? "-" : snapshot.connectionCount}`
]
if (group) {
lines.push(`${labels.copy_group}: ${group.name}`)
lines.push(`${labels.copy_node}: ${group.now || "-"}`)
}
return lines.join("\n")
}
function nodeTails(labels, current, delay) {
const tails = []
if (current) tails.push({ Type: "text", Text: labels.tail_current, TextCategory: "success" })
if (delay === 0) tails.push({ Type: "text", Text: labels.tail_timeout, TextCategory: "danger" })
else if (typeof delay === "number" && delay > 0) tails.push({ Type: "text", Text: fill(labels.tail_delay, { n: delay }) })
return tails.slice(0, 3)
}
function orderedNodes(group, filter) {
const text = String(filter || "").trim().toLowerCase()
const names = (group.all || []).filter((name) => !text || String(name).toLowerCase().includes(text))
const current = names.filter((name) => name === group.now)
const rest = names.filter((name) => name !== group.now)
return current.concat(rest)
}
function buildResults(snapshot, query, labels, host) {
const groups = snapshot.groups || []
const defaultGroup = pickDefaultGroup(groups, snapshot.preferredGroup)
const intent = parseIntent(query, groups)
const trigger = String(query && query.TriggerKeyword || "cv").trim() || "cv"
if (intent.kind === "mode") return modeResults(snapshot, labels, host)
if (intent.kind === "nodes") {
const group = intent.group || defaultGroup
return group ? nodeResults(snapshot, group, intent.search, labels, host) : [emptyResult(labels)]
}
if (intent.kind === "filter") return filterResults(snapshot, defaultGroup, intent.search, labels, host, trigger)
return homeResults(snapshot, defaultGroup, labels, host, trigger)
}
function homeResults(snapshot, defaultGroup, labels, host, trigger) {
const results = [statusResult(snapshot, defaultGroup, labels, host, trigger)]
const groups = (snapshot.groups || []).slice().sort((a, b) => {
if (defaultGroup && a.name === defaultGroup.name) return -1
if (defaultGroup && b.name === defaultGroup.name) return 1
return a.name.localeCompare(b.name)
})
groups.forEach((group, index) => {
results.push(groupResult(group, group === defaultGroup || (defaultGroup && group.name === defaultGroup.name), labels, host, trigger, 800 - index))
})
return results
}
function filterResults(snapshot, defaultGroup, search, labels, host, trigger) {
const text = search.toLowerCase()
const results = []
const groups = (snapshot.groups || []).filter((group) => group.name.toLowerCase().includes(text))
groups.forEach((group, index) => {
results.push(groupResult(group, defaultGroup && group.name === defaultGroup.name, labels, host, trigger, 900 - index))
})
if (defaultGroup) {
const nodes = orderedNodes(defaultGroup, search).slice(0, NODE_LIMIT)
nodes.forEach((name, index) => {
results.push(nodeResult(defaultGroup, name, snapshot.delays || {}, labels, host, 700 - index))
})
const hidden = orderedNodes(defaultGroup, search).length - nodes.length
if (hidden > 0) results.push(moreResult(hidden, labels))
}
return results.length ? results : [emptyResult(labels)]
}
function nodeResults(snapshot, group, search, labels, host) {
const matched = orderedNodes(group, search)
const visible = matched.slice(0, NODE_LIMIT)
if (!visible.length) return [emptyResult(labels)]
const results = visible.map((name, index) => nodeResult(group, name, snapshot.delays || {}, labels, host, 900 - index))
const hidden = matched.length - visible.length
if (hidden > 0) results.push(moreResult(hidden, labels))
return results
}
function modeResults(snapshot, labels, host) {
return MODE_ORDER.map((mode, index) => ({
Id: `mode:${mode}`,
Title: labels[`mode_${mode}`],
SubTitle: labels.mode_subtitle,
Icon: RESULT_ICON,
Score: 900 - index,
ScoreKey: `clash:mode:${mode}`,
Group: "i18n:group_mode",
GroupScore: 100,
Tails: snapshot.mode === mode ? [{ Type: "text", Text: labels.tail_current, TextCategory: "success" }] : [],
Actions: [modeAction(mode, labels, host, true)]
}))
}
function statusResult(snapshot, group, labels, host, trigger) {
const actions = []
if (group) actions.push(showNodesAction(group, labels, host, trigger, true))
for (const mode of MODE_ORDER) actions.push(modeAction(mode, labels, host, false))
actions.push(copyAction(snapshot, group, labels, host))
return {
Id: "status",
Title: labels.status_title,
SubTitle: statusSubtitle(snapshot, group, labels),
Icon: RESULT_ICON,
Score: 1000,
ScoreKey: "clash:status",
Group: "i18n:group_status",
GroupScore: 100,
Tails: statusTails(snapshot, labels),
Actions: actions
}
}
function groupResult(group, isDefault, labels, host, trigger, score) {
const tails = []
if (isDefault) tails.push({ Type: "text", Text: labels.tail_default })
return {
Id: `group:${group.name}`,
Title: group.name,
SubTitle: group.now || "-",
Icon: RESULT_ICON,
Score: score,
ScoreKey: `clash:group:${group.name}`,
Group: "i18n:group_proxy",
GroupScore: 80,
Tails: tails,
Actions: [showNodesAction(group, labels, host, trigger, true)]
}
}
function nodeResult(group, name, delays, labels, host, score) {
return {
Id: `node:${group.name}:${name}`,
Title: name,
SubTitle: group.name,
Icon: RESULT_ICON,
Score: score,
ScoreKey: `clash:node:${group.name}:${name}`,
Group: "i18n:group_nodes",
GroupScore: 90,
Tails: nodeTails(labels, name === group.now, delays[name]),
Actions: [
selectAction(group.name, name, labels, host, true),
delayAction(group.name, name, labels, host)
]
}
}
function emptyResult(labels) {
return {
Id: "empty",
Title: labels.empty_title,
SubTitle: labels.empty_subtitle,
Icon: RESULT_ICON,
Score: 1,
Actions: []
}
}
function moreResult(count, labels) {
return {
Id: "more",
Title: fill(labels.more_title, { n: count }),
SubTitle: labels.more_subtitle,
Icon: RESULT_ICON,
Score: 1,
Group: "i18n:group_nodes",
GroupScore: 90,
Actions: []
}
}
function showNodesAction(group, labels, host, trigger, isDefault) {
return {
Id: `open:${group.name}`,
Name: "i18n:action_nodes",
Icon: ACTION_SEARCH,
IsDefault: isDefault,
PreventHideAfterAction: true,
Action: async (ctx) => {
if (host && host.changeQuery) await host.changeQuery(ctx, `${trigger} ${group.name} `)
}
}
}
function selectAction(group, name, labels, host, isDefault) {
return {
Id: `select:${group}:${name}`,
Name: "i18n:action_select",
Icon: ACTION_EXECUTE,
IsDefault: isDefault,
PreventHideAfterAction: true,
ContextData: { kind: "node", group, name },
Action: async (ctx) => {
if (host && host.select) await host.select(ctx, group, name)
}
}
}
function modeAction(mode, labels, host, isDefault) {
return {
Id: `set-mode:${mode}`,
Name: `i18n:action_mode_${mode}`,
Icon: ACTION_EXECUTE,
IsDefault: isDefault,
PreventHideAfterAction: true,
ContextData: { kind: "mode", mode },
Action: async (ctx) => {
if (host && host.setMode) await host.setMode(ctx, mode)
}
}
}
function delayAction(group, name, labels, host) {
return {
Id: `delay:${group}:${name}`,
Name: "i18n:action_delay",
Icon: ACTION_EXECUTE,
PreventHideAfterAction: true,
Action: async (ctx) => {
if (host && host.testDelay) await host.testDelay(ctx, group, name)
}
}
}
function copyAction(snapshot, group, labels, host) {
return {
Id: "copy-status",
Name: "i18n:action_copy",
Icon: ACTION_COPY,
PreventHideAfterAction: true,
Action: async (ctx) => {
if (host && host.copy) await host.copy(ctx, copySummary(snapshot, group, labels))
}
}
}
function errorResult(error, labels) {
const unauthorized = error && error.code === "unauthorized"
return {
Id: unauthorized ? "error-auth" : "error-offline",
Title: unauthorized ? labels.error_unauthorized_title : labels.error_unreachable_title,
SubTitle: unauthorized ? labels.error_unauthorized_subtitle : labels.error_unreachable_subtitle,
Icon: RESULT_ICON,
Score: 1,
Actions: []
}
}
async function loadLabels(api, ctx) {
const keys = Object.keys(I18N.en_US)
const pairs = await Promise.all(keys.map(async (key) => {
let value = I18N.en_US[key]
if (api && ctx && typeof api.GetTranslation === "function") {
try {
const translated = await api.GetTranslation(ctx, key)
if (translated && translated !== key && !String(translated).startsWith("i18n:")) value = translated
} catch {
// Keep the English string when the host has no translation yet.
}
}
return [key, value]
}))
return Object.fromEntries(pairs)
}
class ClashVergePlugin {
constructor() {
this.api = null
this.apiUrl = ""
this.secret = ""
this.preferredGroup = ""
this.cachedLabels = I18N.en_US
this.visible = []
this.init = this.init.bind(this)
this.query = this.query.bind(this)
}
async init(ctx, params) {
this.api = params.API
this.apiUrl = (await this.api.GetSetting(ctx, "api_url")) || ""
this.secret = (await this.api.GetSetting(ctx, "secret")) || ""
this.preferredGroup = (await this.api.GetSetting(ctx, "group")) || ""
this.cachedLabels = await loadLabels(this.api, ctx)
if (typeof this.api.OnSettingChanged === "function") {
await this.api.OnSettingChanged(ctx, async (_ctx, key, value) => {
if (key === "api_url") this.apiUrl = value || ""
if (key === "secret") this.secret = value || ""
if (key === "group") this.preferredGroup = value || ""
})
}
if (typeof this.api.OnMRURestore === "function") {
await this.api.OnMRURestore(ctx, async (_ctx, mruData) => this.restoreMRU(mruData))
}
await this.registerTools(ctx)
}
async registerTools(ctx) {
if (!this.api || typeof this.api.RegisterPluginTool !== "function") return
const tools = [
{
Name: "get_clash_status",
Description: "i18n:tool_get_status",
InputSchema: { type: "object", properties: {}, additionalProperties: false },
OutputSchema: {
type: "object",
properties: {
version: { type: "string" },
mode: { type: "string" },
mixedPort: { type: "integer" },
tun: { type: "string" },
systemProxy: { type: "string" },
group: { type: "string" },
now: { type: "string" },
connectionCount: { type: "integer" }
},
required: ["version", "mode", "tun", "systemProxy", "group", "now"],
additionalProperties: true
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async () => {
try {
const snapshot = await this.loadSnapshot()
const group = pickDefaultGroup(snapshot.groups, snapshot.preferredGroup)
return {
Output: {
version: snapshot.version,
mode: snapshot.mode,
mixedPort: snapshot.mixedPort == null ? 0 : snapshot.mixedPort,
tun: snapshot.tun ? "on" : "off",
systemProxy: snapshot.systemProxy === true ? "on" : snapshot.systemProxy === false ? "off" : "unknown",
group: group ? group.name : "",
now: group ? group.now : "",
connectionCount: snapshot.connectionCount == null ? 0 : snapshot.connectionCount
}
}
} catch (error) {
return { Error: { Code: error.code === "unauthorized" ? "CLASH_UNAUTHORIZED" : "CLASH_UNREACHABLE", Message: error.message } }
}
}
},
{
Name: "list_proxy_groups",
Description: "i18n:tool_list_groups",
InputSchema: { type: "object", properties: {}, additionalProperties: false },
OutputSchema: {
type: "object",
properties: {
groups: {
type: "array",
items: {
type: "object",
properties: {
name: { type: "string" },
type: { type: "string" },
now: { type: "string" },
count: { type: "integer" }
},
required: ["name", "type", "now", "count"]
}
}
},
required: ["groups"]
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async () => {
try {
const snapshot = await this.loadSnapshot()
return {
Output: {
groups: snapshot.groups.map((group) => ({
name: group.name,
type: group.type,
now: group.now,
count: group.all.length
}))
}
}
} catch (error) {
return { Error: { Code: error.code === "unauthorized" ? "CLASH_UNAUTHORIZED" : "CLASH_UNREACHABLE", Message: error.message } }
}
}
},
{
Name: "select_proxy",
Description: "i18n:tool_select_proxy",
InputSchema: {
type: "object",
properties: { group: { type: "string" }, name: { type: "string" } },
required: ["group", "name"],
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: { group: { type: "string" }, name: { type: "string" } },
required: ["group", "name"]
},
Annotations: { ReadOnly: false, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async (_ctx, option) => {
const group = option && option.Arguments && option.Arguments.group
const name = option && option.Arguments && option.Arguments.name
try {
await this.putProxy(group, name)
return { Output: { group, name } }
} catch (error) {
return { Error: { Code: error.code === "unauthorized" ? "CLASH_UNAUTHORIZED" : "CLASH_REQUEST_FAILED", Message: error.message } }
}
}
},
{
Name: "set_clash_mode",
Description: "i18n:tool_set_mode",
InputSchema: {
type: "object",
properties: { mode: { type: "string", enum: ["rule", "global", "direct"] } },
required: ["mode"],
additionalProperties: false
},
OutputSchema: {
type: "object",
properties: { mode: { type: "string" } },
required: ["mode"]
},
Annotations: { ReadOnly: false, Destructive: false, Idempotent: true, RequiresUI: false },
Handler: async (_ctx, option) => {
const mode = String(option && option.Arguments && option.Arguments.mode || "").toLowerCase()
try {
await this.patchMode(mode)
return { Output: { mode } }
} catch (error) {
return { Error: { Code: error.code === "unauthorized" ? "CLASH_UNAUTHORIZED" : "CLASH_REQUEST_FAILED", Message: error.message } }
}
}
}
]
for (const tool of tools) {
try {
const result = await this.api.RegisterPluginTool(ctx, {
Tool: {
Name: tool.Name,
Description: tool.Description,
InputSchema: tool.InputSchema,
OutputSchema: tool.OutputSchema,
Annotations: tool.Annotations
},
Handler: tool.Handler
})
if (result && result.Error && this.api.Log) {
await this.api.Log(ctx, "Warning", `tool ${tool.Name}: ${result.Error.Code || ""} ${result.Error.Message || ""}`.trim())
}
} catch (error) {
if (this.api.Log) await this.api.Log(ctx, "Warning", `tool ${tool.Name} was not registered: ${error.message}`)
}
}
}
environment() {
return collectEnvironment({ apiUrl: this.apiUrl, secret: this.secret })
}
async open() {
return openClash(this.environment())
}
async loadSnapshot() {
const env = this.environment()
const opened = await openClash(env)
const payload = await readSnapshot(opened.client, { version: opened.version })
const snapshot = normalizeSnapshot(payload, this.preferredGroup)
snapshot.systemProxy = env.files.systemProxy
snapshot.endpointSource = opened.endpoint.source
return snapshot
}
async putProxy(group, name) {
const opened = await this.open()
const response = await opened.client.sendJson("PUT", `/proxies/${encodeURIComponent(group)}`, { name })
ensureOk(response, "select")
}
async patchMode(mode) {
const opened = await this.open()
const response = await opened.client.sendJson("PATCH", "/configs", { mode })
ensureOk(response, "mode")
}
async query(ctx, query) {
const labels = this.cachedLabels || I18N.en_US
const host = this.host()
try {
const snapshot = await this.loadSnapshot()
const results = buildResults(snapshot, query, labels, host)
this.visible = results
if (this.api && this.api.Log) {
await this.api.Log(ctx, "Info", `Clash Verge ${snapshot.version} mode=${snapshot.mode} via=${snapshot.endpointSource} results=${results.length}`)
}
return { Results: results }
} catch (error) {
if (this.api && this.api.Log) await this.api.Log(ctx, "Error", `Clash Verge query failed: ${error.code || ""} ${error.message}`.trim())
const results = [errorResult(error, labels)]
this.visible = results
return { Results: results }
}
}
host() {
return {
changeQuery: (ctx, text) => this.changeQuery(ctx, text),
select: (ctx, group, name) => this.select(ctx, group, name),
setMode: (ctx, mode) => this.setMode(ctx, mode),
testDelay: (ctx, group, name) => this.testDelay(ctx, group, name),
copy: (ctx, text) => this.copy(ctx, text)
}
}
async changeQuery(ctx, text) {
if (this.api && typeof this.api.ChangeQuery === "function") {
await this.api.ChangeQuery(ctx, { QueryType: "input", QueryText: text })
}
}
async select(ctx, group, name) {
const labels = this.cachedLabels || I18N.en_US
try {
await this.putProxy(group, name)
await this.markSelected(ctx, group, name)
if (this.api && this.api.Notify) await this.api.Notify(ctx, fill(labels.notify_selected, { group, name }))
if (this.api && this.api.HideApp) await this.api.HideApp(ctx)
} catch (error) {
if (this.api && this.api.Notify) await this.api.Notify(ctx, labels.notify_select_failed)
if (this.api && this.api.Log) await this.api.Log(ctx, "Error", `select failed: ${error.message}`)
}
}
async setMode(ctx, mode) {
const labels = this.cachedLabels || I18N.en_US
try {
await this.patchMode(mode)
await this.markMode(ctx, mode)
if (this.api && this.api.Notify) await this.api.Notify(ctx, fill(labels.notify_mode, { mode: modeLabel(labels, mode) }))
if (this.api && this.api.HideApp) await this.api.HideApp(ctx)
} catch (error) {
if (this.api && this.api.Notify) await this.api.Notify(ctx, labels.notify_mode_failed)
if (this.api && this.api.Log) await this.api.Log(ctx, "Error", `mode failed: ${error.message}`)
}
}
async testDelay(ctx, group, name) {
const labels = this.cachedLabels || I18N.en_US
try {
const opened = await this.open()
const requestPath = `/proxies/${encodeURIComponent(name)}/delay?timeout=3000&url=${encodeURIComponent("https://www.gstatic.com/generate_204")}`
const response = await opened.client.getJson(requestPath)
ensureOk(response, "delay")
const delay = response.json && typeof response.json.delay === "number" ? response.json.delay : 0
await this.markDelay(ctx, group, name, delay)
const delayText = delay > 0 ? fill(labels.tail_delay, { n: delay }) : labels.tail_timeout
if (this.api && this.api.Notify) await this.api.Notify(ctx, fill(labels.notify_delay, { name, delay: delayText }))
} catch (error) {
if (this.api && this.api.Notify) await this.api.Notify(ctx, labels.notify_delay_failed)
if (this.api && this.api.Log) await this.api.Log(ctx, "Error", `delay failed: ${error.message}`)
}
}
async copy(ctx, text) {
const labels = this.cachedLabels || I18N.en_US
if (this.api && this.api.Copy) await this.api.Copy(ctx, { type: "text", text })
if (this.api && this.api.Notify) await this.api.Notify(ctx, labels.notify_copied)
}
async markSelected(ctx, group, name) {
for (const result of this.visible) {
if (!result || !result.Actions) continue
const select = result.Actions.find((action) => action.ContextData && action.ContextData.kind === "node" && action.ContextData.group === group)
if (!select) continue
const current = select.ContextData.name === name
const delayTail = (result.Tails || []).find((tail) => tail && tail.Text && tail.Text !== (this.cachedLabels || I18N.en_US).tail_current)
const tails = []
if (current) tails.push({ Type: "text", Text: (this.cachedLabels || I18N.en_US).tail_current, TextCategory: "success" })
if (delayTail) tails.push(delayTail)
result.Tails = tails.slice(0, 3)
await this.pushResult(ctx, result)
}
}
async markMode(ctx, mode) {
const labels = this.cachedLabels || I18N.en_US
for (const result of this.visible) {
if (!String(result.Id || "").startsWith("mode:")) continue
result.Tails = result.Id === `mode:${mode}` ? [{ Type: "text", Text: labels.tail_current, TextCategory: "success" }] : []
await this.pushResult(ctx, result)
}
}
async markDelay(ctx, group, name, delay) {
const labels = this.cachedLabels || I18N.en_US
const result = this.visible.find((item) => item.Id === `node:${group}:${name}`)
if (!result) return
const current = (result.Tails || []).some((tail) => tail && tail.Text === labels.tail_current)
result.Tails = nodeTails(labels, current, delay)
await this.pushResult(ctx, result)
}
async pushResult(ctx, result) {
if (!this.api || typeof this.api.UpdateResult !== "function") return
await this.api.UpdateResult(ctx, {
Id: result.Id,
Title: result.Title,
SubTitle: result.SubTitle,
Icon: result.Icon,
Tails: result.Tails,
Actions: result.Actions
})
}
// MRU restore only rebuilds a row from the stored strings. It does not call Clash.
restoreMRU(mruData) {
const data = mruData && mruData.ContextData ? mruData.ContextData : {}
const labels = this.cachedLabels || I18N.en_US
const host = this.host()
if (data.kind === "node" && data.group && data.name) {
return nodeResult({ name: data.group, type: "Selector", now: "", all: [data.name] }, data.name, {}, labels, host, 100)
}
if (data.kind === "mode" && MODE_ORDER.includes(data.mode)) {
return {
Id: `mode:${data.mode}`,
Title: labels[`mode_${data.mode}`],
SubTitle: labels.mode_subtitle,
Icon: RESULT_ICON,
Score: 100,
ScoreKey: `clash:mode:${data.mode}`,
Actions: [modeAction(data.mode, labels, host, true)]
}
}
return null
}
}
const plugin = new ClashVergePlugin()
module.exports = {
plugin,
clashVerge: {
I18N,
parseTopLevelYaml,
parseHttpMessage,
planEndpoints,
pickDefaultGroup,
parseIntent,
buildResults,
normalizeSnapshot,
createClashClient,
openClash,
readSnapshot,
collectEnvironment,
copySummary,
pipeRank
}
}
@qianlifeng

Copy link
Copy Markdown
Author
image

@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment