/** * MCP Server for GUI.for.Cores(GFC/GFS)v1.1.0 * 把 RESTful-Api v1 的业务能力映射为 MCP tools,并支持操作当前程序 WebView 页面。 * 传输:Plugins.StartServer,JSON-only Streamable HTTP,/mcp,协议 2025-06-18,无 session。 * 扩展:业务工具写在 tools;共享辅助方法写在 Utils 并用 Utils.xxx 调用。 */ /** @type {EsmPlugin} */ export default (Plugin) => { const PROTOCOL = '2025-06-18' const JSON_HEADERS = { 'Content-Type': 'application/json' } const MMDB_DIR = 'data/.cache/mmdbs' const MMDB_CONFIG = 'data/.cache/mmdbs_config.json' const MMDB_TYPES = ['ASN', 'AnonymousIP', 'City', 'ConnectionType', 'Country', 'Domain', 'Enterprise'] const SECRET_KEY = /pass|secret|token|auth|uuid|psk|private|cert|^key$|authorization|cookie|script|^header$/i const CORE_MODES = ['direct', 'global', 'rule'] const METHOD_NAME = /^[A-Za-z_]\w*$/ const ro = { readOnlyHint: true, destructiveHint: false, openWorldHint: false } const wr = { readOnlyHint: false, destructiveHint: false, openWorldHint: false } const dest = { readOnlyHint: false, destructiveHint: true, openWorldHint: false } let runtimeToken = '' let mmdbs = [] /** * 通用辅助方法。新增共享逻辑放这里;业务工具写在 tools,协议分发与生命周期保持在下方。 * 方法互调用一律写 Utils.xxx,不要依赖 this,以便解构后也能安全调用。 */ const Utils = { /** * 把返回值包成 MCP text content 数组。 * @param {*} value 字符串原样放入,其它值 JSON 格式化 * @returns {{type:'text', text:string}[]} */ text(value) { return [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] }, /** * 构造成功的 tools/call 结果。 * @param {*} value 放入 content * @returns {{content: object[], isError: false}} */ okText(value) { return { content: Utils.text(value), isError: false } }, /** * 构造失败的 tools/call 结果(isError: true)。 * @param {Error|string} error * @returns {{content: object[], isError: true}} */ failText(error) { return { content: Utils.text(error?.message || error), isError: true } }, /** * 构造 JSON-RPC 成功响应对象。 * @param {string|number} id * @param {*} result */ ok(id, result) { return { jsonrpc: '2.0', id, result } }, /** * 构造 JSON-RPC 错误响应对象。 * @param {string|number|null} id * @param {number} code * @param {string} message */ fail(id, code, message) { return { jsonrpc: '2.0', id: id ?? null, error: { code, message } } }, /** * 是否为普通对象(非数组、非 null)。 * @param {*} value * @returns {boolean} */ isPlainObject(value) { return !!value && typeof value === 'object' && !Array.isArray(value) }, /** * 当前宿主是否为 GUI.for.Clash。 * @returns {boolean} */ isClash() { return String(Plugins.APP_TITLE || '').includes('Clash') }, /** * 读取配置中的监听地址,缺省为 127.0.0.1:8765。原样返回,不改写。 * @returns {string} */ address() { return String(Plugin.Address || '127.0.0.1:8765').trim() || '127.0.0.1:8765' }, /** * 由 Address 构造 http 基址。IPv6 需写成 [host]:port,例如 [::1]:8765。 * @returns {string} */ httpBase() { return 'http://' + Utils.address() }, /** * MCP Streamable HTTP 完整 URL(不含令牌)。 * @returns {string} */ endpoint() { return Utils.httpBase() + '/mcp' }, /** * 该插件的 HTTP 服务是否已在运行。 * @returns {Promise} */ async isRunning() { return (await Plugins.ListServer()).includes(Plugin.id) }, /** * 读取插件开关(兼容布尔值与字符串 'true')。 * @param {string} key 配置键 * @returns {boolean} */ flagOn(key) { return Plugin[key] === true || Plugin[key] === 'true' }, /** * 开关未开启则抛出中文提示,供写操作/核心/代理等门控使用。 * @param {string} key 配置键 * @param {string} label 错误信息里的开关名 */ assertFlag(key, label) { if (!Utils.flagOn(key)) throw '已禁用:' + label + '。在插件配置中打开后再试。' }, /** * 从 Address 解析监听主机名;非法则回退 127.0.0.1。 * @returns {string} */ listenHostname() { try { return new URL(Utils.httpBase()).hostname } catch { return '127.0.0.1' } }, /** * 是否为回环主机名。 * @param {string} hostname * @returns {boolean} */ isLoopbackHost(hostname) { return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1' || hostname === '0:0:0:0:0:0:0:1' }, /** * 从 URL 或 host:port 中取出 hostname;失败返回空字符串。 * @param {string} value * @returns {string} */ parseHostname(value) { if (!value) return '' try { return new URL(value.includes('://') ? value : 'http://' + value).hostname } catch { return '' } }, /** * 按大小写不敏感方式读取第一个请求头值。 * @param {Record} headers * @param {string} name * @returns {string} */ header(headers, name) { const hit = Object.entries(headers || {}).find(([key]) => key.toLowerCase() === name.toLowerCase()) return hit ? String(hit[1] || '') .split(',')[0] .trim() : '' }, /** * 从 Authorization Bearer 或 X-Api-Token / X-Auth-Token 取出令牌。 * @param {{headers?: object}} req * @returns {string} */ requestToken(req) { const auth = Utils.header(req.headers, 'Authorization') if (/^Bearer\s+/i.test(auth)) return auth.replace(/^Bearer\s+/i, '').trim() return Utils.header(req.headers, 'X-Api-Token') || Utils.header(req.headers, 'X-Auth-Token') }, /** * 生成临时鉴权密钥。优先使用宿主 generateSecureKey。 * @returns {string} */ makeToken() { if (Plugins.generateSecureKey) return String(Plugins.generateSecureKey(256) || '').trim() const bytes = new Uint8Array(32) globalThis.crypto.getRandomValues(bytes) return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') }, /** * 确定本次运行时令牌:已配置 AuthToken 则用之,否则生成临时密钥。 * @returns {{configured: boolean, token: string}} */ resolveToken() { const configured = String(Plugin.AuthToken || '').trim() runtimeToken = configured || Utils.makeToken() return { configured: Boolean(configured), token: runtimeToken } }, /** * Origin 是否允许。回环始终允许;绑定回环时拒绝非回环;绑定 0.0.0.0 或 :: 时允许带主机名的 Origin;绑定具体地址时需主机名一致。 * @param {string} origin * @returns {boolean} */ allowedOrigin(origin) { const host = Utils.parseHostname(origin) if (Utils.isLoopbackHost(host)) return true const listen = Utils.listenHostname() if (Utils.isLoopbackHost(listen)) return false if (listen === '0.0.0.0' || listen === '::') return Boolean(host) return Boolean(host) && host === listen }, /** * Host 头是否允许。空 Host 放行(真实 GFC 往往拿不到 Host)。规则与 allowedOrigin 类似。 * @param {string} hostHeader * @returns {boolean} */ allowedHost(hostHeader) { const host = Utils.parseHostname(hostHeader) if (!host) return true if (Utils.isLoopbackHost(host)) return true const listen = Utils.listenHostname() if (Utils.isLoopbackHost(listen)) return false if (listen === '0.0.0.0' || listen === '::') return true return host === listen }, /** * 结束 HTTP 响应;非字符串体会被 JSON.stringify。 * @param {{end: Function}} res * @param {number} status * @param {object} headers * @param {*|string} body */ end(res, status, headers, body) { const payload = body == null || body === '' ? '' : typeof body === 'string' ? body : JSON.stringify(body) res.end(status, headers, payload) }, /** * 读取请求体;非 JSON 文本则尝试按宿主约定做 base64 解码。 * @param {{body?: string}} req * @returns {string} */ readBody(req) { const raw = typeof req.body === 'string' ? req.body : req.body == null ? '' : String(req.body) if (!raw) return '' const trimmed = raw.trim() if (trimmed.startsWith('{') || trimmed.startsWith('[')) return trimmed return Plugins.base64Decode ? Plugins.base64Decode(raw) : raw }, /** * 递归脱敏敏感字段与疑似密钥字符串。 * @param {*} value * @param {string} [key] 当前字段名,用于判断是否敏感 * @returns {*} */ sanitize(value, key = '') { if (typeof key === 'string' && SECRET_KEY.test(key)) return '' if (typeof value === 'string') { if (SECRET_KEY.test(key) || /token=|access_token=|auth=/i.test(value)) return '' return value } if (Array.isArray(value)) return value.map((item) => Utils.sanitize(item, key)) if (Utils.isPlainObject(value)) { const out = {} const namedSecret = typeof value.key === 'string' && SECRET_KEY.test(value.key) for (const [k, v] of Object.entries(value)) { if (namedSecret && (k === 'value' || k === 'data')) out[k] = '' else out[k] = Utils.sanitize(v, k) } return out } return value }, /** * 按 id 或 name 查找列表项,可选用 store getter。 * @param {object[]} list * @param {Function} [getter] * @param {string} id * @returns {object|undefined} */ findItem(list, getter, id) { if (!id) return if (typeof getter === 'function') { const hit = getter(id) if (hit) return hit } return (list || []).find((item) => item && (item.id === id || item.name === id)) }, /** * 从缓存文件加载 MMDB 登记列表到内存。 * @returns {Promise} */ async loadMmdbs() { const raw = await Plugins.ignoredError?.(Plugins.ReadFile, MMDB_CONFIG) if (!raw) { mmdbs = [] return } try { const parsed = JSON.parse(raw) mmdbs = Array.isArray(parsed) ? parsed : [] } catch { mmdbs = [] } }, /** * 把内存中的 MMDB 列表写回缓存文件。 * @returns {Promise} */ async saveMmdbs() { await Plugins.WriteFile(MMDB_CONFIG, JSON.stringify(mmdbs)) }, /** * 按 id 查找已登记的 MMDB。 * @param {string} id * @returns {object|undefined} */ findMmdb(id) { return mmdbs.find((item) => item.id === id) }, /** * 按宿主类型调用对应的 TUN 更新接口(GFC / GFS 签名不同)。 * @param {boolean} enable * @returns {Promise} */ async setTun(enable) { const store = Plugins.useKernelApiStore() if (Utils.isClash()) await store.updateConfig({ tun: { enable } }) else await store.updateConfig('tun', { enable }) }, /** * 对工具 arguments 做有限校验(必填、额外字段、部分 enum),不是完整 JSON Schema 校验。 * @param {object} schema * @param {*} args * @returns {string} 错误原因;通过时为空字符串 */ invalidArgs(schema, args) { if (args === undefined) args = {} if (!Utils.isPlainObject(args)) return 'arguments must be an object' const properties = schema?.properties || {} if (schema?.additionalProperties === false) { for (const key of Object.keys(args)) { if (!Object.hasOwn(properties, key)) return 'Unexpected param: ' + key } } for (const key of schema?.required || []) { if (!Object.hasOwn(args, key)) return 'Missing param: ' + key } for (const [key, prop] of Object.entries(properties)) { if (prop?.enum && args[key] !== undefined && !prop.enum.includes(args[key])) { return 'Invalid param: ' + key } } return '' }, /** * 生成 tools/list 所需的工具清单。 * @returns {object[]} */ toolList() { return Object.entries(tools).map(([name, tool]) => ({ name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} }, annotations: tool.annotations })) } } const PageControl = (() => { const clean = (text) => String(text ?? '') .replace(/\s+/g, ' ') .trim() const truncateText = (text, maxLength, label = '内容', hint) => { const value = String(text ?? '') const limit = Math.floor(maxLength) if (!Number.isFinite(maxLength) || limit <= 0 || value.length <= limit) return value const marker = `\n\n...[${label}已截断:原始 ${value.length} 字符。${hint || '请缩小查询范围或筛选字段后重试'}]...\n\n` if (marker.length >= limit) return marker.slice(0, limit) const available = limit - marker.length const headLength = Math.ceil(available * 0.75) const tailLength = available - headLength return value.slice(0, headLength) + marker + (tailLength > 0 ? value.slice(-tailLength) : '') } const SKIP_TAGS = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE', 'HEAD']) const STRUCTURAL_TAGS = new Set(['MAIN', 'NAV', 'HEADER', 'FOOTER', 'FORM', 'DIALOG', 'SECTION', 'UL', 'OL', 'TABLE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']) const STRUCTURAL_ROLES = new Set(['navigation', 'main', 'dialog', 'tablist', 'menu', 'toolbar', 'region', 'complementary', 'banner', 'contentinfo']) const INTERACTIVE_ROLES = new Set([ 'button', 'link', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'radio', 'checkbox', 'switch', 'tab', 'textbox', 'combobox', 'listbox', 'slider', 'spinbutton', 'searchbox' ]) let refs = new Map() let cursorX = null let cursorY = null let gestureToken = 0 let hoveredEl = null const isInteractive = (el) => { const tag = el.tagName if (tag === 'BUTTON' || tag === 'SUMMARY' || tag === 'SELECT' || tag === 'TEXTAREA') return true if (tag === 'A' && el.hasAttribute('href')) return true if (tag === 'INPUT') return (el.getAttribute('type') || 'text').toLowerCase() !== 'hidden' if (el.isContentEditable) return true const role = el.getAttribute('role') if (role && INTERACTIVE_ROLES.has(role)) return true const tab = el.getAttribute('tabindex') return tab !== null && Number(tab) >= 0 } const isStructural = (el) => STRUCTURAL_TAGS.has(el.tagName) || STRUCTURAL_ROLES.has(el.getAttribute('role') || '') const isShown = (el) => { if (!el.isConnected) return false if (el.hidden) return false const style = getComputedStyle(el) if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse' || style.opacity === '0') return false const rect = el.getBoundingClientRect() return rect.width > 0 && rect.height > 0 } const inViewport = (el) => { const rect = el.getBoundingClientRect() return rect.bottom > 0 && rect.right > 0 && rect.top < window.innerHeight && rect.left < window.innerWidth } const ownText = (el) => { let text = '' for (const node of el.childNodes) { if (node.nodeType === Node.TEXT_NODE) text += node.nodeValue } return clean(text) } const elementName = (el) => { const aria = clean(el.getAttribute('aria-label') || '') if (aria) return aria.slice(0, 80) const labelledby = el.getAttribute('aria-labelledby') if (labelledby) { const text = clean( labelledby .split(/\s+/) .map((id) => document.getElementById(id)?.innerText || '') .join(' ') ) if (text) return text.slice(0, 80) } const label = clean(el.labels?.[0]?.innerText || '') if (label) return label.slice(0, 80) const title = clean(el.getAttribute('title') || '') if (title && (isInteractive(el) || el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement)) { return title.slice(0, 80) } if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) return '' if (/^H[1-6]$/.test(el.tagName) || isInteractive(el) || el.children.length === 0) return clean(el.innerText || '').slice(0, 80) return ownText(el).slice(0, 80) } const roleOf = (el) => { const explicit = el.getAttribute('role') if (explicit) return explicit if (el.tagName === 'INPUT') { const type = (el.getAttribute('type') || 'text').toLowerCase() if (type === 'checkbox') return 'checkbox' if (type === 'radio') return 'radio' if (type === 'button' || type === 'submit' || type === 'reset') return 'button' if (type === 'hidden') return '' if (type === 'search') return 'searchbox' return 'textbox' } if (el.isContentEditable) return 'textbox' return ( { A: 'link', BUTTON: 'button', SELECT: 'combobox', TEXTAREA: 'textbox', SUMMARY: 'button', IMG: 'image', NAV: 'navigation', MAIN: 'main', FORM: 'form', DIALOG: 'dialog', TABLE: 'table', UL: 'list', OL: 'list', HEADER: 'banner', FOOTER: 'contentinfo', H1: 'heading', H2: 'heading', H3: 'heading', H4: 'heading', H5: 'heading', H6: 'heading' }[el.tagName] || el.tagName.toLowerCase() ) } const stateOf = (el) => { const state = [] if (el.disabled || el.getAttribute('aria-disabled') === 'true') state.push('disabled') const checked = el.getAttribute('aria-checked') if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) state.push(el.checked ? 'checked' : 'unchecked') else if (checked === 'true') state.push('checked') else if (checked === 'false') state.push('unchecked') if (el.getAttribute('aria-expanded') === 'true') state.push('expanded') if (el.getAttribute('aria-expanded') === 'false') state.push('collapsed') if (el.getAttribute('aria-selected') === 'true') state.push('selected') if (el.getAttribute('aria-pressed') === 'true') state.push('pressed') const secret = el instanceof HTMLInputElement && el.type === 'password' if (secret) state.push('password') else if ((el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) && el.type !== 'checkbox' && el.type !== 'radio' && el.value) { state.push(`value=${JSON.stringify(clean(el.value).slice(0, 40))}`) } if (el instanceof HTMLSelectElement && el.value) { state.push(`value=${JSON.stringify(clean(el.selectedOptions?.[0]?.text || el.value).slice(0, 40))}`) } const placeholder = clean(el.getAttribute('placeholder') || '') if (placeholder) state.push(`placeholder=${JSON.stringify(placeholder.slice(0, 40))}`) return state } const format = (el, kind) => { if (el.tagName === 'IFRAME') return `iframe ${JSON.stringify(el.getAttribute('src') || '')} 跨源不可操作` const role = kind === 'text' ? 'text' : roleOf(el) const name = elementName(el) const parts = [role || el.tagName.toLowerCase()] if (name) parts.push(JSON.stringify(name)) if (/^H[1-6]$/.test(el.tagName)) parts.push(`level=${el.tagName.slice(1)}`) parts.push(...stateOf(el)) return parts.join(' ') } const brief = (el) => { const rect = el.getBoundingClientRect() return `${format(el)} @${Math.round(rect.left)},${Math.round(rect.top)}` } const findAgentLayer = () => { const mark = document.querySelector('[data-gui-agent]') if (!mark) return null let el = mark const viewportArea = Math.max(1, window.innerWidth * window.innerHeight) while (el.parentElement && el.parentElement !== document.body && el.parentElement !== document.documentElement) { const parent = el.parentElement const hasBigSibling = [...parent.children].some((child) => { if (child === el || child.contains(mark)) return false const rect = child.getBoundingClientRect() return (rect.width * rect.height) / viewportArea > 0.3 }) if (hasBigSibling) break const rect = parent.getBoundingClientRect() if ((rect.width * rect.height) / viewportArea > 0.92) break el = parent } return el } const createContext = () => { const layer = findAgentLayer() return { layer, isAgent(el) { return !!(layer && el && (el === layer || layer.contains(el))) } } } const queryAllDeep = (selector, root = document) => { let matched try { matched = [...root.querySelectorAll(selector)] } catch (error) { throw new Error(`选择器无效:${error?.message || error}`) } for (const el of root.querySelectorAll('*')) { if (el.shadowRoot) matched.push(...queryAllDeep(selector, el.shadowRoot)) } return matched } const eachElement = (visitor, root = document) => { for (const el of root.querySelectorAll('*')) { visitor(el) if (el.shadowRoot) eachElement(visitor, el.shadowRoot) } } const textScore = (el, needle) => { const fields = [clean(el.getAttribute('aria-label') || ''), clean(el.getAttribute('placeholder') || ''), clean(el.getAttribute('alt') || ''), ownText(el)] if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) { fields.push(clean(el.labels?.[0]?.innerText || '')) } const values = fields.map((item) => item.toLowerCase()).filter(Boolean) if (values.some((item) => item === needle)) return 2 const interactive = isInteractive(el) if (!(interactive || el.children.length === 0)) return 0 if (values.some((item) => item.includes(needle))) return 1 if (!interactive) return 0 const name = clean(el.innerText || '').toLowerCase() if (name === needle) return 2 if (name.includes(needle)) return 1 return 0 } const preferOuter = (list) => list.filter((el) => !list.some((other) => other !== el && other.contains(el))) const isOperatingChrome = (el) => !!el.closest?.('[data-gui-agent-effect], [data-gui-mcp-effect]') const visibleTargets = (list, ctx) => list.filter((el) => el.isConnected && !ctx.isAgent(el) && !isOperatingChrome(el) && isShown(el)) const findMatches = (args, ctx) => { if (args.ref !== undefined && args.ref !== null && args.ref !== '') { const el = refs.get(Number(args.ref)) return el ? [el] : [] } if (args.selector) return visibleTargets(queryAllDeep(String(args.selector)), ctx) if (args.text) { const needle = clean(args.text).toLowerCase() if (!needle) throw new Error('text 不能为空') const exact = [] const partial = [] eachElement((el) => { if (ctx.isAgent(el)) return const score = textScore(el, needle) if (score === 2) exact.push(el) else if (score === 1) partial.push(el) }) return visibleTargets(preferOuter(exact.length ? exact : partial), ctx) } return null } const hasTarget = (args) => (args.ref !== undefined && args.ref !== null && args.ref !== '') || !!args.selector || (args.text !== undefined && args.text !== null && args.text !== '') const ambiguous = (list) => { const lines = list.slice(0, 8).map((el, index) => `${index}. ${brief(el)}`) return `匹配到 ${list.length} 个元素,请改用 snapshot 的 ref,或传入 index:\n${lines.join('\n')}` } const resolve = (args, ctx) => { if (!hasTarget(args)) throw new Error('需要 ref、selector 或 text') if (args.ref !== undefined && args.ref !== null && args.ref !== '') { const el = refs.get(Number(args.ref)) if (!el || !el.isConnected) throw new Error('ref 已失效或不存在,请重新 snapshot') if (ctx.isAgent(el)) throw new Error('不能操作 Agent 自己的窗口') return el } const list = findMatches(args, ctx) || [] if (!list.length) throw new Error('没有匹配到可见元素') if (list.length === 1) return list[0] if (args.index === undefined || args.index === null || args.index === '') throw new Error(ambiguous(list)) const el = list[Number(args.index)] if (!el) throw new Error(`index 超出范围,共 ${list.length} 个`) return el } const snapshot = (args, ctx) => { refs = new Map() const limit = Math.min(400, Math.max(1, Math.floor(Number(args.limit) || 250))) const scope = args.scope === 'all' ? 'all' : 'viewport' const lines = [] let omitted = 0 const emit = (el, depth, kind) => { if (scope === 'viewport' && !inViewport(el)) { if (kind === 'interactive') omitted++ return } const id = refs.size + 1 refs.set(id, el) lines.push(`${' '.repeat(Math.min(depth, 6))}[${id}] ${format(el, kind)}`) } const walk = (el, depth) => { if (lines.length >= limit || ctx.isAgent(el) || isOperatingChrome(el) || SKIP_TAGS.has(el.tagName) || !isShown(el)) return if (el.tagName === 'IFRAME') { emit(el, depth, 'iframe') return } const interactive = isInteractive(el) const structural = !interactive && isStructural(el) const textBlock = !interactive && !structural && el.children.length === 0 && !!ownText(el) if (interactive || structural || textBlock) emit(el, depth, interactive ? 'interactive' : textBlock ? 'text' : 'structural') if (interactive || el.tagName === 'SVG') return const next = depth + (structural ? 1 : 0) if (el.shadowRoot) { for (const child of el.shadowRoot.children) walk(child, next) } for (const child of el.children) walk(child, next) } if (document.body) walk(document.body, 0) return [ `页面${document.title ? ' ' + JSON.stringify(clean(document.title)) : ''} ${location.href}`, `视口 ${window.innerWidth}x${window.innerHeight},范围 ${scope},元素 ${lines.length}${ctx.layer ? ',已排除 Agent 窗口' : ''}`, ...lines, omitted ? `视口外还有 ${omitted} 个可交互元素。可 scroll,或用 scope "all"。` : '', lines.length >= limit ? `已达到上限 ${limit}。可提高 limit(最大 400),或用 query 缩小范围。` : '' ] .filter(Boolean) .join('\n') } const query = async (args, ctx) => { if (!args.selector && (args.text === undefined || args.text === null || args.text === '')) throw new Error('query 需要 selector 或 text') const list = findMatches(args, ctx) || [] if (!list.length) return '没有匹配到可见元素' if (list.length === 1) { const motion = await beginGesture(list[0], 'hover', 0, 0, false) if (motion) await motion } const shown = list.slice(0, 30).map((el, index) => `${index}. ${brief(el)}`) if (list.length > 30) shown.push(`另有 ${list.length - 30} 个未列出`) return shown.join('\n') } const read = async (args, ctx) => { const el = resolve(args, ctx) const motion = await beginGesture(el, 'hover', 0, 0, false) if (motion) await motion const secret = el instanceof HTMLInputElement && el.type === 'password' const text = secret ? '' : clean(el.innerText || '') const value = secret ? '(password)' : el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement ? clean(el.value || '') : '' return truncateText( [format(el), value ? `value: ${value}` : '', text ? `text: ${text}` : ''].filter(Boolean).join('\n'), 8000, '页面文本', '请改用更具体的 selector。' ) } const withoutInert = async (fn) => { const mark = document.querySelector('[data-gui-agent]') const nodes = [...document.querySelectorAll('[inert]')].filter((node) => !(mark && node.contains(mark))) for (const node of nodes) node.inert = false try { return await fn() } finally { for (const node of nodes) node.inert = true } } // Vue 监听的是原型上的 value setter,直接给 el.value 赋值不会更新绑定。 const setNativeValue = (el, value) => { const prototype = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : el instanceof HTMLSelectElement ? HTMLSelectElement.prototype : HTMLInputElement.prototype const setter = Object.getOwnPropertyDescriptor(prototype, 'value')?.set if (setter) setter.call(el, value) else el.value = value el.dispatchEvent(new InputEvent('input', { bubbles: true, data: value, inputType: 'insertText' })) el.dispatchEvent(new Event('change', { bubbles: true })) } const selectOption = (el, value) => { const needle = clean(value) const option = [...el.options].find((item) => item.value === value || clean(item.text) === needle || clean(item.label) === needle) if (!option) throw new Error(`没有选项 ${JSON.stringify(needle)}`) if (option.disabled) throw new Error('选项已禁用') setNativeValue(el, option.value) return `已选择 ${JSON.stringify(clean(option.text) || option.value)}` } const click = (args, ctx) => act(async () => { const el = resolve(args, ctx) if (el.disabled || el.getAttribute('aria-disabled') === 'true') throw new Error('元素已禁用') if (el instanceof HTMLInputElement && el.type === 'file') throw new Error('不能通过工具选择本地文件') const motion = await beginGesture(el, 'click') placePointer(el) const anchor = el.closest?.('a[href]') const href = anchor?.getAttribute('href') const leaves = href !== null && href !== undefined && !href.startsWith('#') const form = el.form || el.closest?.('form') const block = (event) => event.preventDefault() if (form) form.addEventListener('submit', block) if (anchor && leaves) anchor.addEventListener('click', block) try { el.click() } finally { if (form) form.removeEventListener('submit', block) if (anchor && leaves) anchor.removeEventListener('click', block) } if (motion) await motion return `已点击 ${format(el)}${leaves ? ',已阻止离开当前页面' : ''}` }) // CodeEditor 的 update:modelValue 防抖 300ms。提前离开时,父组件会用旧值把文档盖回去。 const codeMirrorEditors = (el) => { const editors = [] const seen = new Set() const add = (node) => { if (!node || seen.has(node)) return seen.add(node) const content = node.classList?.contains('cm-content') ? node : node.querySelector?.('.cm-content') const view = content?.cmTile?.root?.view if (view?.state?.doc && typeof view.dispatch === 'function') editors.push({ view, content }) } add(el.closest?.('.cm-editor')) add(el.closest?.('.cm-content')) add(el) for (const node of el.querySelectorAll?.('.cm-editor') || []) add(node) return editors } const fill = (args, ctx) => act(async () => { let el = resolve(args, ctx) const editors = codeMirrorEditors(el) const codeEditor = editors.find((item) => item.content?.isContentEditable) || null if (editors.length && !codeEditor) throw new Error('编辑器不可编辑') if ( !(el instanceof HTMLInputElement) && !(el instanceof HTMLTextAreaElement) && !(el instanceof HTMLSelectElement) && !el.isContentEditable && !codeEditor ) { const inner = el.querySelector('input, textarea, select, [contenteditable="true"]') if (inner) el = inner } if (el instanceof HTMLInputElement && el.type === 'file') throw new Error('不能通过工具选择本地文件') if (el.disabled || el.readOnly) throw new Error('元素不可编辑') if ( !(el instanceof HTMLInputElement) && !(el instanceof HTMLTextAreaElement) && !(el instanceof HTMLSelectElement) && !el.isContentEditable && !codeEditor ) { throw new Error('目标不是可填写的输入框') } const value = args.value === undefined || args.value === null ? '' : String(args.value) const typing = el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio') ? 'click' : el instanceof HTMLSelectElement ? 'click' : 'type' const field = codeEditor?.content || el const motion = await beginGesture(field, typing) field.focus?.({ preventScroll: true }) if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) { const want = !/^(false|0|off|no|unchecked)$/i.test(value) if (el.checked !== want) el.click() if (motion) await motion return `已将 ${format(el)} 设为 ${el.checked ? 'checked' : 'unchecked'}` } if (el instanceof HTMLSelectElement) { const message = selectOption(el, value) if (motion) await motion return message } if (codeEditor) { const doc = codeEditor.view.state.doc if (doc.toString() !== value) { codeEditor.view.dispatch({ changes: { from: 0, to: doc.length, insert: value } }) } if (motion) await motion await sleep(320) return `已填写 ${format(codeEditor.content || el)}` } if (el.isContentEditable) { el.textContent = value el.dispatchEvent(new InputEvent('input', { bubbles: true, data: value, inputType: 'insertText' })) if (motion) await motion return `已填写 ${format(el)}` } setNativeValue(el, value) if (motion) await motion if (el instanceof HTMLInputElement && el.type === 'password') return '已填写密码框' return `已填写 ${format(el)} 为 ${JSON.stringify(value.slice(0, 80))}` }) const select = (args, ctx) => act(async () => { let el = resolve(args, ctx) if (!(el instanceof HTMLSelectElement)) el = el.querySelector?.('select') || el if (!(el instanceof HTMLSelectElement)) throw new Error('目标不是 select,自定义下拉框请用 click') if (args.value === undefined || args.value === null) throw new Error('select 需要 value') const motion = await beginGesture(el, 'click') const message = selectOption(el, String(args.value)) if (motion) await motion return message }) const press = (args, ctx) => act(async () => { const rawKey = String(args.key || '') if (!rawKey) throw new Error('press 需要 key') const key = rawKey === 'Space' ? ' ' : rawKey const el = hasTarget(args) ? resolve(args, ctx) : document.activeElement || document.body if (ctx.isAgent(el)) throw new Error('不能操作 Agent 自己的窗口') const motion = await beginGesture(el, 'click') el.focus?.({ preventScroll: true }) const code = key === ' ' ? 'Space' : key.length === 1 && /[a-z]/i.test(key) ? `Key${key.toUpperCase()}` : key.length === 1 && /[0-9]/.test(key) ? `Digit${key}` : key const init = { key, code, bubbles: true, cancelable: true } el.dispatchEvent(new KeyboardEvent('keydown', init)) const editable = !el.readOnly && !el.disabled && (el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement && /^(text|search|url|tel|password|email|number)$/i.test(el.type || 'text'))) if (editable && (key === 'Backspace' || key.length === 1)) { const start = typeof el.selectionStart === 'number' ? el.selectionStart : el.value.length const end = typeof el.selectionEnd === 'number' ? el.selectionEnd : el.value.length const next = key === 'Backspace' ? el.value.slice(0, start === end ? Math.max(0, start - 1) : start) + el.value.slice(end) : el.value.slice(0, start) + key + el.value.slice(end) setNativeValue(el, next) } el.dispatchEvent(new KeyboardEvent('keyup', init)) if (motion) await motion return `已按下 ${rawKey}` }) const scrollable = (el) => { let node = el || null while (node && node !== document.documentElement) { const style = getComputedStyle(node) const can = /(auto|scroll|overlay)/.test(`${style.overflowY} ${style.overflowX}`) if (can && (node.scrollHeight > node.clientHeight + 1 || node.scrollWidth > node.clientWidth + 1)) return node node = node.parentElement } return document.scrollingElement || document.documentElement } const animateScroll = async (node, left, top) => { if (!node) return const maxLeft = Math.max(0, node.scrollWidth - node.clientWidth) const maxTop = Math.max(0, node.scrollHeight - node.clientHeight) const destLeft = Math.min(maxLeft, Math.max(0, left)) const destTop = Math.min(maxTop, Math.max(0, top)) const startLeft = node.scrollLeft const startTop = node.scrollTop const deltaX = destLeft - startLeft const deltaY = destTop - startTop const distance = Math.hypot(deltaX, deltaY) if (distance < 1) return if (reducedMotion() || distance < 2) { node.scrollTo({ left: destLeft, top: destTop, behavior: 'instant' }) return } const duration = Math.round(Math.min(640, Math.max(220, distance * 0.45))) const start = performance.now() await new Promise((resolve) => { const step = (now) => { const t = Math.min(1, (now - start) / duration) const eased = 1 - (1 - t) ** 3 node.scrollTo({ left: startLeft + deltaX * eased, top: startTop + deltaY * eased, behavior: 'instant' }) if (t < 1) requestAnimationFrame(step) else resolve() } requestAnimationFrame(step) }) } // 已经完整可见的元素不再挪到正中,避免每次点击都跳一下。 const reveal = async (el) => { const scrollingElement = document.scrollingElement || document.documentElement const chain = [] for (let node = el.parentElement; node; node = node.parentElement) { const style = getComputedStyle(node) const scrollY = /(auto|scroll|overlay)/.test(style.overflowY) && node.scrollHeight > node.clientHeight + 1 const scrollX = /(auto|scroll|overlay)/.test(style.overflowX) && node.scrollWidth > node.clientWidth + 1 if (scrollY || scrollX || node === scrollingElement) chain.push(node) } if ( !chain.includes(scrollingElement) && (scrollingElement.scrollHeight > scrollingElement.clientHeight + 1 || scrollingElement.scrollWidth > scrollingElement.clientWidth + 1) ) { chain.push(scrollingElement) } for (const container of chain) { const rect = el.getBoundingClientRect() const viewport = container === scrollingElement || container === document.documentElement || container === document.body const box = viewport ? { top: 0, left: 0, right: window.innerWidth, bottom: window.innerHeight, width: window.innerWidth, height: window.innerHeight } : container.getBoundingClientRect() const fits = rect.height <= box.height + 1 && rect.width <= box.width + 1 const fully = fits && rect.top >= box.top - 1 && rect.bottom <= box.bottom + 1 && rect.left >= box.left - 1 && rect.right <= box.right + 1 if (fully) continue const deltaY = rect.height > box.height ? rect.top - box.top : rect.top + rect.height / 2 - (box.top + box.height / 2) let deltaX = 0 if (rect.width > box.width) deltaX = rect.left - box.left else if (rect.left < box.left) deltaX = rect.left - box.left else if (rect.right > box.right) deltaX = rect.right - box.right if (Math.abs(deltaX) < 2 && Math.abs(deltaY) < 2) continue await animateScroll(container, container.scrollLeft + deltaX, container.scrollTop + deltaY) } } const scrollPage = async (args, ctx) => { const el = hasTarget(args) ? resolve(args, ctx) : null if (!args.to && args.dx === undefined && args.dy === undefined) { if (!el) throw new Error('scroll 需要 ref、selector、text,或 dx、dy、to') const motion = await beginGesture(el, 'hover') if (motion) await motion return withSnapshot(`已将元素滚入视口:${format(el)}`) } if (args.to && args.to !== 'top' && args.to !== 'bottom') throw new Error('to 只能是 top 或 bottom') let aimed = false if (el) aimed = await aim(el, false) else { await moveCursor(window.innerWidth / 2, window.innerHeight / 2) aimed = true } const distanceX = Number(args.dx) || 0 const distanceY = args.to === 'top' ? -80 : args.to === 'bottom' ? 80 : Number(args.dy) || 0 const target = scrollable(el) const motion = aimed ? playCursor('scroll', distanceX, distanceY) : null const nextLeft = args.to ? 0 : target.scrollLeft + distanceX const nextTop = args.to === 'top' ? 0 : args.to === 'bottom' ? target.scrollHeight : target.scrollTop + distanceY await animateScroll(target, nextLeft, nextTop) if (motion) await motion return withSnapshot(`已滚动到 top=${Math.round(target.scrollTop)} left=${Math.round(target.scrollLeft)}`) } // mouseenter 不冒泡。下拉和提示的监听在父节点上,只对目标派发 mouseover 不会打开。 const ancestorChain = (el) => { const chain = [] for (let node = el; node && node.nodeType === 1; node = node.parentElement) chain.push(node) return chain } const pointerInit = (x, y, related) => ({ bubbles: false, cancelable: true, composed: true, view: window, clientX: x, clientY: y, screenX: x, screenY: y, button: 0, buttons: 0, relatedTarget: related || null, pointerId: 1, pointerType: 'mouse', isPrimary: true }) const dispatchHover = (type, node, init) => { const bubbles = type === 'mouseover' || type === 'mouseout' || type === 'mousemove' || type === 'pointerover' || type === 'pointerout' || type === 'pointermove' const eventInit = { ...init, bubbles } if (type.startsWith('pointer')) node.dispatchEvent(new PointerEvent(type, eventInit)) else node.dispatchEvent(new MouseEvent(type, eventInit)) } const placePointer = (el) => { if (!el?.isConnected) return const rect = el.getBoundingClientRect() const x = rect.left + Math.max(rect.width, 1) / 2 const y = rect.top + Math.max(rect.height, 1) / 2 const previous = hoveredEl?.isConnected ? hoveredEl : null if (previous === el) { const move = pointerInit(x, y, null) dispatchHover('pointermove', el, move) dispatchHover('mousemove', el, move) return } const nextChain = ancestorChain(el) const prevChain = previous ? ancestorChain(previous) : [] let shared = 0 while (shared < prevChain.length && shared < nextChain.length && prevChain[prevChain.length - 1 - shared] === nextChain[nextChain.length - 1 - shared]) shared++ const leave = pointerInit(x, y, el) for (let i = 0; i < prevChain.length - shared; i++) { const node = prevChain[i] if (i === 0) { dispatchHover('pointerout', node, leave) dispatchHover('mouseout', node, leave) } dispatchHover('pointerleave', node, leave) dispatchHover('mouseleave', node, leave) } const enter = pointerInit(x, y, previous) dispatchHover('pointerover', el, enter) dispatchHover('mouseover', el, enter) for (let i = nextChain.length - shared - 1; i >= 0; i--) { dispatchHover('pointerenter', nextChain[i], enter) dispatchHover('mouseenter', nextChain[i], enter) } const move = pointerInit(x, y, null) dispatchHover('pointermove', el, move) dispatchHover('mousemove', el, move) hoveredEl = el } const hover = (args, ctx) => act(async () => { const el = resolve(args, ctx) const motion = await beginGesture(el, 'hover') placePointer(el) await sleep(0) if (motion) await motion return `已悬停 ${format(el)}` }) const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) const reducedMotion = () => !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches const ensureCursor = () => { ensureChromeStyle() const cursorHtml = '
' let cursor = document.getElementById('gui-mcp-cursor') if (cursor) { if (!cursor.innerHTML.includes('M1.8 1.4')) cursor.innerHTML = cursorHtml raiseStatus() return cursor } cursor = document.createElement('div') cursor.id = 'gui-mcp-cursor' cursor.setAttribute('data-gui-mcp-effect', '') cursor.setAttribute('aria-hidden', 'true') cursor.innerHTML = cursorHtml document.documentElement.appendChild(cursor) raiseStatus() return cursor } // 先无过渡地放到起点,再开过渡。否则指针第一次会从左上角跳到目标。 const moveCursor = async (x, y) => { const cursor = ensureCursor() const fromX = cursorX ?? window.innerWidth / 2 const fromY = cursorY ?? window.innerHeight / 2 const targetX = Math.round(x) const targetY = Math.round(y) const distance = Math.hypot(targetX - fromX, targetY - fromY) const duration = reducedMotion() || distance < 2 ? 0 : Math.round(Math.min(520, Math.max(180, distance * 0.55))) if (cursorX === null || duration === 0) { cursor.style.transition = 'none' cursor.style.transform = `translate(${duration === 0 ? targetX : fromX}px, ${duration === 0 ? targetY : fromY}px)` } if (duration === 0) { cursorX = targetX cursorY = targetY return } void cursor.offsetWidth cursor.style.transition = `transform ${duration}ms cubic-bezier(0.22, 0.61, 0.36, 1)` cursor.style.transform = `translate(${targetX}px, ${targetY}px)` cursorX = targetX cursorY = targetY await sleep(duration + 40) } const aim = async (el, scroll = true) => { if (!el?.isConnected || !el.getBoundingClientRect) return false if (scroll) await reveal(el) await new Promise((resolve) => requestAnimationFrame(resolve)) const rect = el.getBoundingClientRect() if (rect.width < 1 && rect.height < 1) return false const x = Math.min(window.innerWidth - 2, Math.max(2, rect.left + rect.width / 2)) const y = Math.min(window.innerHeight - 2, Math.max(2, rect.top + rect.height / 2)) await moveCursor(x, y) return true } // 指针先到位,动画开始后立刻返回,调用方在这一拍里执行真正的点击或输入。 const beginGesture = async (el, kind, nudgeX = 0, nudgeY = 0, scroll = true) => { if (!(await aim(el, scroll))) return null return playCursor(kind, nudgeX, nudgeY) } const playCursor = async (kind, nudgeX = 0, nudgeY = 0) => { const cursor = ensureCursor() const token = ++gestureToken if (kind === 'scroll') { const length = Math.hypot(nudgeX, nudgeY) || 1 const scale = 18 / length cursor.style.setProperty('--nudge-x', `${Math.round(nudgeX * scale)}px`) cursor.style.setProperty('--nudge-y', `${Math.round(nudgeY * scale)}px`) } cursor.classList.remove('is-click', 'is-hover', 'is-type', 'is-scroll') void cursor.offsetWidth cursor.classList.add(`is-${kind}`) const duration = reducedMotion() ? 0 : { click: 320, hover: 420, type: 460, scroll: 360 }[kind] || 320 if (duration) await sleep(duration) if (token === gestureToken) cursor.classList.remove(`is-${kind}`) } const settle = async () => { const tick = globalThis.Vue?.nextTick const flush = async () => { if (typeof tick !== 'function') return try { await tick() } catch { // Vue 不可用时只等浏览器绘制。 } } // 点击触发的更新可能再排队一次子组件渲染,只等一拍会拍到旧页面。 await flush() await new Promise((resolve) => requestAnimationFrame(resolve)) await flush() await new Promise((resolve) => requestAnimationFrame(resolve)) } const withSnapshot = async (message) => { await settle() let shot = '' try { shot = snapshot({}, createContext()) } catch { return message } return `${message}\n\n操作后的页面(已附带最新 snapshot,不要再为刷新调用 snapshot):\n${shot}` } const act = async (fn) => withSnapshot(await withoutInert(fn)) const waitFor = async (args, ctx) => { const timeout = Math.min(10000, Math.max(0, Math.floor(Number(args.timeout) || 1000))) const found = async (el) => { const motion = await beginGesture(el, 'hover') if (motion) await motion return withSnapshot(`元素已出现:${brief(el)}`) } if (!hasTarget(args)) { await sleep(timeout) return withSnapshot(`已等待 ${timeout}ms`) } const start = Date.now() do { const list = findMatches(args, ctx) || [] if (list.length === 1) return found(list[0]) if (list.length > 1 && args.index !== undefined && args.index !== null && args.index !== '') { const el = list[Number(args.index)] if (el) return found(el) } if (list.length > 1) return ambiguous(list) if (Date.now() - start >= timeout) break await sleep(100) } while (Date.now() - start < timeout) throw new Error(`等待超时(${timeout}ms)`) } const effectCss = ` #gui-mcp-operating { position: fixed !important; inset: 0 !important; z-index: 2147483647 !important; pointer-events: none !important; overflow: hidden !important; } #gui-mcp-operating .gui-mcp-edge { position: absolute !important; pointer-events: none !important; background-size: 200% 200%; animation: gui-mcp-flow 2.4s linear infinite; } #gui-mcp-operating .gui-mcp-edge-top, #gui-mcp-operating .gui-mcp-edge-bottom { left: 0; right: 0; height: 5px; background-image: linear-gradient(90deg, #ff4d6a, #ff9f1a, #ffe14d, #2ee59d, #3ecbff, #7a6cff, #ff4d9a, #ff4d6a); box-shadow: 0 0 14px rgba(62, 203, 255, 0.7); } #gui-mcp-operating .gui-mcp-edge-top { top: 0; } #gui-mcp-operating .gui-mcp-edge-bottom { bottom: 0; animation-direction: reverse; } #gui-mcp-operating .gui-mcp-edge-left, #gui-mcp-operating .gui-mcp-edge-right { top: 0; bottom: 0; width: 5px; background-image: linear-gradient(180deg, #ff4d6a, #ff9f1a, #ffe14d, #2ee59d, #3ecbff, #7a6cff, #ff4d9a, #ff4d6a); box-shadow: 0 0 14px rgba(255, 77, 154, 0.7); } #gui-mcp-operating .gui-mcp-edge-left { left: 0; } #gui-mcp-operating .gui-mcp-edge-right { right: 0; animation-direction: reverse; } @keyframes gui-mcp-flow { to { background-position: 200% 200%; } } #gui-mcp-cursor { position: fixed !important; left: 0 !important; top: 0 !important; z-index: 2147483647 !important; width: 0 !important; height: 0 !important; pointer-events: none !important; will-change: transform; } #gui-mcp-cursor .gui-mcp-cursor-pointer { position: absolute; left: -1.8px; top: -1.4px; overflow: visible; transform-origin: 1.8px 1.4px; /* mac-arrow */ filter: drop-shadow(0 0.5px 0.6px rgba(0, 0, 0, 0.45)); } #gui-mcp-cursor .gui-mcp-cursor-ring { position: absolute; left: 0; top: 0; width: 36px; height: 36px; margin: -18px 0 0 -18px; border: 2px solid #3ecbff; border-radius: 50%; box-shadow: 0 0 12px rgba(62, 203, 255, 0.85); opacity: 0; transform: scale(0.2); } #gui-mcp-cursor.is-click .gui-mcp-cursor-ring { animation: gui-mcp-ripple 320ms ease-out; } #gui-mcp-cursor.is-click .gui-mcp-cursor-pointer { animation: gui-mcp-press 320ms ease-out; } #gui-mcp-cursor.is-hover .gui-mcp-cursor-ring { border-color: #ffe14d; box-shadow: 0 0 12px rgba(255, 225, 77, 0.85); animation: gui-mcp-ripple 420ms ease-out; } #gui-mcp-cursor.is-type .gui-mcp-cursor-ring { border-color: #2ee59d; box-shadow: 0 0 12px rgba(46, 229, 157, 0.85); animation: gui-mcp-ripple 460ms ease-out; } #gui-mcp-cursor.is-type .gui-mcp-cursor-pointer { animation: gui-mcp-type 460ms ease-in-out; } #gui-mcp-cursor.is-scroll .gui-mcp-cursor-ring { border-color: #ff9f1a; box-shadow: 0 0 12px rgba(255, 159, 26, 0.85); animation: gui-mcp-ripple 360ms ease-out; } #gui-mcp-cursor.is-scroll .gui-mcp-cursor-pointer { animation: gui-mcp-nudge 360ms ease-in-out; } @keyframes gui-mcp-ripple { 0% { opacity: 0.9; transform: scale(0.15); } 100% { opacity: 0; transform: scale(1.7); } } @keyframes gui-mcp-press { 0% { transform: scale(1); } 35% { transform: scale(0.76); } 100% { transform: scale(1); } } @keyframes gui-mcp-type { 0%, 100% { transform: translate(0, 0); } 30% { transform: translate(4px, 2px); } 60% { transform: translate(0, 0); } 80% { transform: translate(3px, 1px); } } @keyframes gui-mcp-nudge { 0%, 100% { transform: translate(0, 0); } 45% { transform: translate(var(--nudge-x, 0px), var(--nudge-y, 16px)); } } @media (prefers-reduced-motion: reduce) { #gui-mcp-operating .gui-mcp-edge { animation: none; } #gui-mcp-cursor, #gui-mcp-cursor .gui-mcp-cursor-ring, #gui-mcp-cursor .gui-mcp-cursor-pointer { animation: none !important; transition: none !important; } } `.trim() const ensureChromeStyle = () => { let style = document.getElementById('gui-mcp-operating-style') if (!style) { style = document.createElement('style') style.id = 'gui-mcp-operating-style' ;(document.head || document.documentElement).appendChild(style) } if (!style.textContent.includes('mac-arrow')) style.textContent = effectCss } const clearEffect = () => { cursorX = null cursorY = null pageOperating = false if (typeof document === 'undefined') return document.getElementById('gui-mcp-operating')?.remove() document.getElementById('gui-mcp-cursor')?.remove() document.getElementById('gui-mcp-operating-style')?.remove() clearStatus() } const statusCss = ` #gui-mcp-status { position: fixed; top: 12px; left: 50%; z-index: 2147483647; display: flex; align-items: center; gap: 8px; max-width: min(72vw, 560px); box-sizing: border-box; margin: 0; padding: 6px 8px 6px 12px; border: 1px solid transparent; border-radius: 999px; background: linear-gradient(rgba(18, 18, 22, 0.94), rgba(18, 18, 22, 0.94)) padding-box, linear-gradient(90deg, #ff4d6a, #ff9f1a, #ffe14d, #2ee59d, #3ecbff, #7a6cff) border-box; color: #fff; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.32); font: 13px/1.3 system-ui, sans-serif; pointer-events: auto; user-select: none; transform: translateX(-50%); } #gui-mcp-status .gui-mcp-status-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #3ecbff; box-shadow: 0 0 8px #3ecbff; animation: gui-mcp-status-pulse 1.2s ease-in-out infinite; } #gui-mcp-status[data-tone="warn"] .gui-mcp-status-dot, #gui-mcp-status[data-tone="confirm"] .gui-mcp-status-dot { background: #ffe14d; box-shadow: 0 0 8px #ffe14d; } #gui-mcp-status[data-tone="error"] .gui-mcp-status-dot { background: #ff4d6a; box-shadow: 0 0 8px #ff4d6a; animation: none; } #gui-mcp-status[data-tone="done"] .gui-mcp-status-dot { background: #2ee59d; box-shadow: 0 0 8px #2ee59d; animation: none; } #gui-mcp-status .gui-mcp-status-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #gui-mcp-status button { flex: none; width: auto; margin: 0; padding: 3px 10px; border: 0; border-radius: 999px; background: rgba(255, 255, 255, 0.14); color: #fff; font: inherit; line-height: 1.3; cursor: pointer; } #gui-mcp-status button[hidden] { display: none; } #gui-mcp-status .gui-mcp-status-yes { background: #2ee59d; color: #06281c; } @keyframes gui-mcp-status-pulse { 50% { opacity: 0.45; transform: scale(0.72); } } @media (prefers-reduced-motion: reduce) { #gui-mcp-status .gui-mcp-status-dot { animation: none; } } `.trim() let statusStop = null let statusDecide = null let statusObserver = null let pageOperating = false const raiseStatus = () => { const status = typeof document === 'undefined' ? null : document.getElementById('gui-mcp-status') if (!status || status.parentElement?.lastElementChild === status) return status.parentElement.appendChild(status) } const ensureStatusStyle = () => { let style = document.getElementById('gui-mcp-status-style') if (!style) { style = document.createElement('style') style.id = 'gui-mcp-status-style' ;(document.head || document.documentElement).appendChild(style) } if (!style.textContent.includes('#gui-mcp-status')) style.textContent = statusCss } const watchStatusLayer = () => { if (statusObserver || typeof MutationObserver !== 'function') return statusObserver = new MutationObserver(() => raiseStatus()) statusObserver.observe(document.documentElement, { childList: true }) } const setStatus = (text, tone = 'run') => { if (!pageOperating) return if (typeof document === 'undefined' || !document.documentElement) return ensureStatusStyle() let root = document.getElementById('gui-mcp-status') if (!root) { root = document.createElement('div') root.id = 'gui-mcp-status' root.setAttribute('data-gui-mcp-effect', '') root.setAttribute('role', 'status') root.setAttribute('aria-live', 'polite') const dot = document.createElement('span') dot.className = 'gui-mcp-status-dot' const label = document.createElement('span') label.className = 'gui-mcp-status-text' const reject = document.createElement('button') reject.type = 'button' reject.className = 'gui-mcp-status-no' reject.textContent = '拒绝' const allow = document.createElement('button') allow.type = 'button' allow.className = 'gui-mcp-status-yes' allow.textContent = '允许' const stop = document.createElement('button') stop.type = 'button' stop.className = 'gui-mcp-status-stop' stop.textContent = '停止' const press = (event, action) => { event.preventDefault() event.stopPropagation() action?.() } reject.addEventListener('click', (event) => press(event, () => statusDecide?.(false))) allow.addEventListener('click', (event) => press(event, () => statusDecide?.(true))) stop.addEventListener('click', (event) => press(event, () => statusStop?.())) root.append(dot, label, reject, allow, stop) } root.dataset.tone = tone root.querySelector('.gui-mcp-status-text').textContent = String(text || '') root.querySelector('.gui-mcp-status-stop').hidden = !statusStop || (tone !== 'run' && tone !== 'confirm') root.querySelector('.gui-mcp-status-yes').hidden = !statusDecide || tone !== 'confirm' root.querySelector('.gui-mcp-status-no').hidden = !statusDecide || tone !== 'confirm' document.documentElement.appendChild(root) watchStatusLayer() } const clearStatus = () => { statusObserver?.disconnect() statusObserver = null if (typeof document === 'undefined') return document.getElementById('gui-mcp-status')?.remove() document.getElementById('gui-mcp-status-style')?.remove() } const pageChangeActions = new Set(['click', 'fill', 'select', 'press', 'hover']) const pageStatusText = (action, args) => { const names = { snapshot: '正在查看界面', query: '正在查找元素', read: '正在读取界面', click: '正在点击', fill: '正在填写', select: '正在选择', press: '正在按键', scroll: '正在滚动', hover: '正在悬停', wait: '正在等待界面', begin: '正在标记操作范围', end: '正在结束界面操作' } const hint = action === 'press' ? args.key : action === 'wait' && !args.text && !args.selector && (args.ref === undefined || args.ref === null || args.ref === '') ? '' : args.text || args.selector || (args.ref !== undefined && args.ref !== null && args.ref !== '' ? `#${args.ref}` : '') const extra = String(hint || '') .replace(/\s+/g, ' ') .trim() .slice(0, 36) return extra ? `${names[action] || '正在操作界面'} ${extra}` : names[action] || '正在操作界面' } const beginEffect = () => { if (!document.body) throw new Error('页面尚未就绪') ensureChromeStyle() if (document.getElementById('gui-mcp-operating')) return '炫彩边框已经开着' const root = document.createElement('div') root.id = 'gui-mcp-operating' root.setAttribute('data-gui-mcp-effect', '') root.setAttribute('aria-hidden', 'true') for (const edge of ['top', 'right', 'bottom', 'left']) { const bar = document.createElement('div') bar.className = `gui-mcp-edge gui-mcp-edge-${edge}` root.appendChild(bar) } document.documentElement.appendChild(root) const cursor = document.getElementById('gui-mcp-cursor') if (cursor) document.documentElement.appendChild(cursor) raiseStatus() return '已开启炫彩边框,表示正在操作界面' } const endEffect = () => { const hadBorder = !!document.getElementById('gui-mcp-operating') const hadCursor = !!document.getElementById('gui-mcp-cursor') clearEffect() if (hadBorder) return '已关闭炫彩边框和鼠标指针' if (hadCursor) return '已关闭鼠标指针' return '炫彩边框已经关闭' } return { clearEffect, clearStatus, bindStatus(handlers = {}) { statusStop = handlers.onStop || null statusDecide = handlers.onDecide || null }, async run(args = {}) { if (!document.body) throw new Error('页面尚未就绪') const action = String(args.action || 'snapshot').toLowerCase() if (action === 'begin') { pageOperating = true setStatus(pageStatusText(action, args)) return beginEffect() } if (action === 'end') { pageOperating = false clearStatus() return endEffect() } if (pageChangeActions.has(action) && !pageOperating) { pageOperating = true beginEffect() } setStatus(pageStatusText(action, args)) const ctx = createContext() if (action === 'snapshot') return snapshot(args, ctx) if (action === 'query') return query(args, ctx) if (action === 'read') return read(args, ctx) if (action === 'click') return click(args, ctx) if (action === 'fill') return fill(args, ctx) if (action === 'select') return select(args, ctx) if (action === 'press') return press(args, ctx) if (action === 'scroll') return scrollPage(args, ctx) if (action === 'hover') return hover(args, ctx) if (action === 'wait') return waitFor(args, ctx) throw new Error(`不支持的 Page 操作:${action}。可用 snapshot、query、read、click、fill、select、press、scroll、hover、wait、begin、end`) } } })() // 在此追加工具。协议方法不必写在这里。 const tools = { /** 健康检查,返回 pong。 */ ping: { description: 'Health check', annotations: ro, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { return Utils.okText('pong') } }, /** 读取应用与 MCP 服务信息(不含密钥)。 */ get_app_info: { description: '读取应用与 MCP 服务信息(不含密钥)', annotations: ro, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { return Utils.okText({ appName: Plugins.APP_TITLE, appVersion: Plugins.APP_VERSION, plugin: Plugin.name || 'MCP Server', pluginVersion: Plugin.version || 'v1.1.0', protocol: PROTOCOL, endpoint: Utils.endpoint(), address: Utils.address(), autoStart: Utils.flagOn('AutoStart'), allowWrites: Utils.flagOn('AllowWrites'), allowCoreControl: Utils.flagOn('AllowCoreControl'), allowSystemProxy: Utils.flagOn('AllowSystemProxy'), allowPluginRun: Utils.flagOn('AllowPluginRun'), allowPageControl: Utils.flagOn('AllowPageControl'), authConfigured: Boolean(String(Plugin.AuthToken || '').trim()) }) } }, /** 读取核心运行状态、模式、TUN 和系统代理。 */ get_runtime_status: { description: '读取核心运行状态、模式、TUN 和系统代理(只读,不改状态)', annotations: ro, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { const kernel = Plugins.useKernelApiStore() const env = Plugins.useEnvStore() return Utils.okText({ running: !!kernel.running, starting: !!kernel.starting, stopping: !!kernel.stopping, restarting: !!kernel.restarting, mode: kernel.config?.mode || '', tun: !!kernel.config?.tun?.enable, systemProxy: !!env.systemProxy, os: env.env?.os, arch: env.env?.arch }) } }, /** 读取 APP 与插件设置,密钥已脱敏。 */ get_settings: { description: '读取 APP 与插件设置;密钥类字段已脱敏', annotations: ro, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { return Utils.okText(Utils.sanitize(Plugins.useAppSettingsStore().app)) } }, /** 浅合并修改 APP/插件设置,需 AllowWrites。 */ update_settings: { description: '按对象浅合并修改 APP/插件设置。需要开启 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { data: { type: 'object', description: '要合并进 app 设置的字段' } }, required: ['data'], additionalProperties: false }, async run({ data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.useAppSettingsStore() store.app = Plugins.deepAssign(store.app, data) return Utils.okText(Utils.sanitize(store.app)) } }, /** 列出配置,或按 id/name 获取单个配置。 */ get_profiles: { description: '列出配置,或用 id/name 获取单个配置(敏感字段脱敏)', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string', description: '配置 id 或名称;省略则返回列表' } }, additionalProperties: false }, async run({ id } = {}) { const store = Plugins.useProfilesStore() if (!id) return Utils.okText(Utils.sanitize(store.profiles || [])) const profile = Utils.findItem(store.profiles, store.getProfileById, id) if (!profile) throw '配置不存在' return Utils.okText(Utils.sanitize(profile)) } }, /** 由配置生成核心配置(脱敏,不写入、不启动核心)。 */ generate_profile_config: { description: '由配置生成核心配置(脱敏后返回,不写入、不启动核心)', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string', description: '配置 id 或名称' } }, required: ['id'], additionalProperties: false }, async run({ id }) { const store = Plugins.useProfilesStore() const profile = Utils.findItem(store.profiles, store.getProfileById, id) if (!profile) throw '配置不存在' const config = await Plugins.generateConfig(profile) const safe = Utils.sanitize(config) if (Utils.isClash() && Plugins.YAML?.stringify) return Utils.okText(Plugins.YAML.stringify(safe)) return Utils.okText(safe) } }, /** 新建配置,需 AllowWrites。 */ create_profile: { description: '新建配置。可只给 name,或用 data 覆盖模板字段。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { name: { type: 'string' }, data: { type: 'object', description: '与模板合并的字段' } }, additionalProperties: false }, async run({ name, data } = {}) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useProfilesStore() const base = store.getProfileTemplate?.(name || data?.name || '') || { id: Plugins.sampleID?.(), name: name || '' } const profile = Plugins.deepAssign(base, Utils.isPlainObject(data) ? data : {}) if (name) profile.name = name await store.addProfile(profile) return Utils.okText({ ok: true, id: profile.id, name: profile.name }) } }, /** 修改配置,需 AllowWrites。 */ update_profile: { description: '修改配置。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, data: { type: 'object' } }, required: ['id', 'data'], additionalProperties: false }, async run({ id, data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.useProfilesStore() const profile = Utils.findItem(store.profiles, store.getProfileById, id) if (!profile) throw '配置不存在' const next = Plugins.deepAssign(Plugins.deepClone ? Plugins.deepClone(profile) : { ...profile }, data) await store.editProfile(profile.id, next) return Utils.okText(Utils.sanitize(next)) } }, /** 删除配置,需 AllowWrites。 */ delete_profile: { description: '删除配置。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useProfilesStore() const profile = Utils.findItem(store.profiles, store.getProfileById, id) if (!profile) throw '配置不存在' await store.deleteProfile(profile.id) return Utils.okText({ ok: true, id: profile.id }) } }, /** 列出或按 id/name 获取订阅。 */ get_subscriptions: { description: '列出订阅,或用 id/name 获取单个订阅。url、请求头等已脱敏。', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string', description: '订阅 id 或名称;省略则返回列表' } }, additionalProperties: false }, async run({ id } = {}) { const store = Plugins.useSubscribesStore() if (!id) return Utils.okText(Utils.sanitize(store.subscribes || [])) const item = Utils.findItem(store.subscribes, store.getSubscribeById, id) if (!item) throw '订阅不存在' return Utils.okText(Utils.sanitize(item)) } }, /** 读取订阅节点列表(脱敏)。 */ get_subscription_proxies: { description: '读取订阅节点列表(脱敏,不返回密码/uuid/token)', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { const store = Plugins.useSubscribesStore() const item = Utils.findItem(store.subscribes, store.getSubscribeById, id) if (!item) throw '订阅不存在' if (!item.path) throw '订阅没有本地节点文件' let proxies = await Plugins.ReadFile(item.path) if (Utils.isClash()) proxies = Plugins.YAML.parse(proxies).proxies else proxies = JSON.parse(proxies) return Utils.okText(Utils.sanitize(proxies)) } }, /** 新建订阅,需 AllowWrites。 */ create_subscription: { description: '新建订阅。可只给 name/url,或用 data 覆盖模板。需要 AllowWrites。不会更新现有订阅。', annotations: wr, inputSchema: { type: 'object', properties: { name: { type: 'string' }, url: { type: 'string' }, data: { type: 'object', description: '与模板合并的字段' } }, additionalProperties: false }, async run({ name, url, data } = {}) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useSubscribesStore() const base = store.getSubscribeTemplate?.(name || data?.name || '', { url: url || data?.url || '' }) || { id: Plugins.sampleID?.(), name: name || '', url: url || '' } const item = Plugins.deepAssign(base, Utils.isPlainObject(data) ? data : {}) if (name) item.name = name if (url) item.url = url await store.addSubscribe(item) return Utils.okText({ ok: true, id: item.id, name: item.name }) } }, /** 修改订阅元数据,不会拉取节点,需 AllowWrites。 */ update_subscription: { description: '修改订阅元数据,不会拉取节点。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, data: { type: 'object' } }, required: ['id', 'data'], additionalProperties: false }, async run({ id, data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.useSubscribesStore() const item = Utils.findItem(store.subscribes, store.getSubscribeById, id) if (!item) throw '订阅不存在' const next = Plugins.deepAssign(Plugins.deepClone ? Plugins.deepClone(item) : { ...item }, data) await store.editSubscribe(item.id, next) return Utils.okText(Utils.sanitize(next)) } }, /** 删除订阅,需 AllowWrites。 */ delete_subscription: { description: '删除订阅。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useSubscribesStore() const item = Utils.findItem(store.subscribes, store.getSubscribeById, id) if (!item) throw '订阅不存在' await store.deleteSubscribe(item.id) return Utils.okText({ ok: true, id: item.id }) } }, /** 从远端更新订阅节点,需 AllowWrites。 */ refresh_subscription: { description: '从远端更新某个订阅的节点。需要 AllowWrites。会改动该订阅已有节点文件。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useSubscribesStore() const item = Utils.findItem(store.subscribes, store.getSubscribeById, id) if (!item) throw '订阅不存在' await store.updateSubscribe(item.id) return Utils.okText(Utils.sanitize(store.getSubscribeById(item.id) || item)) } }, /** 列出或按 id/name 获取规则集。 */ get_rulesets: { description: '列出规则集,或用 id/name 获取单个规则集(url 已脱敏)', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, additionalProperties: false }, async run({ id } = {}) { const store = Plugins.useRulesetsStore() if (!id) return Utils.okText(Utils.sanitize(store.rulesets || [])) const item = Utils.findItem(store.rulesets, store.getRulesetById, id) if (!item) throw '规则集不存在' return Utils.okText(Utils.sanitize(item)) } }, /** 添加规则集,需 AllowWrites。 */ create_ruleset: { description: '添加规则集。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { data: { type: 'object' } }, required: ['data'], additionalProperties: false }, async run({ data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' await Plugins.useRulesetsStore().addRuleset(data) return Utils.okText({ ok: true, id: data.id, name: data.name }) } }, /** 修改规则集元数据,需 AllowWrites。 */ update_ruleset: { description: '修改规则集元数据。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, data: { type: 'object' } }, required: ['id', 'data'], additionalProperties: false }, async run({ id, data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.useRulesetsStore() const item = Utils.findItem(store.rulesets, store.getRulesetById, id) if (!item) throw '规则集不存在' const next = Plugins.deepAssign(Plugins.deepClone ? Plugins.deepClone(item) : { ...item }, data) await store.editRuleset(item.id, next) return Utils.okText(Utils.sanitize(next)) } }, /** 删除规则集,需 AllowWrites。 */ delete_ruleset: { description: '删除规则集。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useRulesetsStore() const item = Utils.findItem(store.rulesets, store.getRulesetById, id) if (!item) throw '规则集不存在' await store.deleteRuleset(item.id) return Utils.okText({ ok: true, id: item.id }) } }, /** 从远端更新规则集,需 AllowWrites。 */ refresh_ruleset: { description: '从远端更新规则集。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useRulesetsStore() const item = Utils.findItem(store.rulesets, store.getRulesetById, id) if (!item) throw '规则集不存在' await store.updateRuleset(item.id) return Utils.okText(Utils.sanitize(store.getRulesetById(item.id) || item)) } }, /** 列出或获取插件摘要(配置脱敏,不含源码)。 */ get_plugins: { description: '列出插件,或用 id/name 获取单个插件。配置中的密钥已脱敏,不含源码。', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, additionalProperties: false }, async run({ id } = {}) { const store = Plugins.usePluginsStore() const summarize = (plugin) => Utils.sanitize({ id: plugin.id, name: plugin.name, version: plugin.version, disabled: plugin.disabled, installed: plugin.installed, type: plugin.type, triggers: plugin.triggers, hasUI: plugin.hasUI, configuration: plugin.configuration }) if (!id) return Utils.okText((store.plugins || []).map(summarize)) const item = Utils.findItem(store.plugins, store.getPluginById, id) if (!item) throw '插件不存在' return Utils.okText(summarize(item)) } }, /** 添加插件记录,需 AllowWrites。 */ create_plugin: { description: '添加插件记录。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { data: { type: 'object' } }, required: ['data'], additionalProperties: false }, async run({ data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' await Plugins.usePluginsStore().addPlugin(data) return Utils.okText({ ok: true, id: data.id, name: data.name }) } }, /** 修改插件元数据或配置,需 AllowWrites。 */ update_plugin: { description: '修改插件元数据或配置。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, data: { type: 'object' } }, required: ['id', 'data'], additionalProperties: false }, async run({ id, data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.usePluginsStore() const item = Utils.findItem(store.plugins, store.getPluginById, id) if (!item) throw '插件不存在' const next = Plugins.deepAssign(Plugins.deepClone ? Plugins.deepClone(item) : { ...item }, data) await store.editPlugin(item.id, next) return Utils.okText(Utils.sanitize({ id: next.id, name: next.name, version: next.version, disabled: next.disabled })) } }, /** 删除插件,需 AllowWrites。 */ delete_plugin: { description: '删除插件。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.usePluginsStore() const item = Utils.findItem(store.plugins, store.getPluginById, id) if (!item) throw '插件不存在' await store.deletePlugin(item.id) return Utils.okText({ ok: true, id: item.id }) } }, /** 从远端更新插件源码,需 AllowWrites。 */ refresh_plugin: { description: '从远端更新插件源码。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.usePluginsStore() const item = Utils.findItem(store.plugins, store.getPluginById, id) if (!item) throw '插件不存在' await store.updatePlugin(item.id) return Utils.okText({ ok: true, id: item.id }) } }, /** 调用插件已声明的方法,需 AllowPluginRun。 */ run_plugin: { description: '调用插件已声明的方法(默认 onRun)。需要 AllowPluginRun。不能执行任意 JS。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' }, method: { type: 'string', description: '插件方法名,默认 onRun' }, args: { type: 'array', description: '传给方法的参数列表', items: {} } }, required: ['id'], additionalProperties: false }, async run({ id, method, args } = {}) { Utils.assertFlag('AllowPluginRun', 'AllowPluginRun') const event = method || 'onRun' if (typeof event !== 'string' || !METHOD_NAME.test(event)) throw '非法方法名' if (args !== undefined && !Array.isArray(args)) throw 'args 必须是数组' const store = Plugins.usePluginsStore() const item = Utils.findItem(store.plugins, store.getPluginById, id) if (!item) throw '插件不存在' const result = await store.manualTrigger(item.id, event, ...(args || [])) return Utils.okText(result ?? '插件执行完毕,无返回值') } }, /** 列出或获取计划任务(脚本内容已脱敏)。 */ get_tasks: { description: '列出计划任务,或用 id/name 获取单个任务。脚本内容已脱敏。', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, additionalProperties: false }, async run({ id } = {}) { const store = Plugins.useScheduledTasksStore() if (!id) return Utils.okText(Utils.sanitize(store.scheduledtasks || [])) const item = Utils.findItem(store.scheduledtasks, store.getScheduledTaskById, id) if (!item) throw '计划任务不存在' return Utils.okText(Utils.sanitize(item)) } }, /** 添加计划任务,需 AllowWrites。 */ create_task: { description: '添加计划任务。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { data: { type: 'object' } }, required: ['data'], additionalProperties: false }, async run({ data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' await Plugins.useScheduledTasksStore().addScheduledTask(data) return Utils.okText({ ok: true, id: data.id, name: data.name }) } }, /** 修改计划任务,需 AllowWrites。 */ update_task: { description: '修改计划任务。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, data: { type: 'object' } }, required: ['id', 'data'], additionalProperties: false }, async run({ id, data }) { Utils.assertFlag('AllowWrites', 'AllowWrites') if (!Utils.isPlainObject(data)) throw 'data 必须是对象' const store = Plugins.useScheduledTasksStore() const item = Utils.findItem(store.scheduledtasks, store.getScheduledTaskById, id) if (!item) throw '计划任务不存在' const next = Plugins.deepAssign(Plugins.deepClone ? Plugins.deepClone(item) : { ...item }, data) await store.editScheduledTask(item.id, next) return Utils.okText(Utils.sanitize(next)) } }, /** 删除计划任务,需 AllowWrites。 */ delete_task: { description: '删除计划任务。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useScheduledTasksStore() const item = Utils.findItem(store.scheduledtasks, store.getScheduledTaskById, id) if (!item) throw '计划任务不存在' await store.deleteScheduledTask(item.id) return Utils.okText({ ok: true, id: item.id }) } }, /** 立即执行一个计划任务,需 AllowWrites。 */ run_task: { description: '立即执行一个计划任务。需要 AllowWrites(任务可能更新订阅/规则/插件)。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') const store = Plugins.useScheduledTasksStore() const item = Utils.findItem(store.scheduledtasks, store.getScheduledTaskById, id) if (!item) throw '计划任务不存在' const result = await store.runScheduledTask(item.id) return Utils.okText(Utils.sanitize(result)) } }, /** 启动核心,需 AllowCoreControl。 */ start_core: { description: '启动核心。需要 AllowCoreControl。GFS 可传 id 指定配置;GFC 使用当前配置。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string', description: '可选,仅 GFS 使用的配置 id' } }, additionalProperties: false }, async run({ id } = {}) { Utils.assertFlag('AllowCoreControl', 'AllowCoreControl') const kernel = Plugins.useKernelApiStore() if (id && !Utils.isClash()) { const profile = Utils.findItem(Plugins.useProfilesStore().profiles, Plugins.useProfilesStore().getProfileById, id) if (!profile) throw '配置不存在' await kernel.startCore(profile) } else { await kernel.startCore() } return Utils.okText('已启动') } }, /** 停止核心,需 AllowCoreControl。 */ stop_core: { description: '停止核心。需要 AllowCoreControl。', annotations: dest, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { Utils.assertFlag('AllowCoreControl', 'AllowCoreControl') await Plugins.useKernelApiStore().stopCore() return Utils.okText('已停止') } }, /** 重启核心,需 AllowCoreControl。 */ restart_core: { description: '重启核心。需要 AllowCoreControl。', annotations: dest, inputSchema: { type: 'object', properties: {}, additionalProperties: false }, async run() { Utils.assertFlag('AllowCoreControl', 'AllowCoreControl') await Plugins.useKernelApiStore().restartCore() return Utils.okText('已重新启动') } }, /** 切换核心工作模式,需 AllowCoreControl。 */ set_core_mode: { description: '切换核心工作模式:direct / global / rule。需要 AllowCoreControl。', annotations: dest, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: CORE_MODES } }, required: ['mode'], additionalProperties: false }, async run({ mode }) { Utils.assertFlag('AllowCoreControl', 'AllowCoreControl') if (!CORE_MODES.includes(mode)) throw 'mode 必须是 direct、global 或 rule' await Plugins.handleChangeMode(mode) return Utils.okText('已切换') } }, /** 开启或关闭 TUN,需 AllowCoreControl。 */ set_tun: { description: '开启或关闭 TUN。需要 AllowCoreControl。GFC/GFS 会使用各自的 updateConfig 签名。', annotations: dest, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['on', 'off'], description: 'on 或 off' } }, required: ['mode'], additionalProperties: false }, async run({ mode }) { Utils.assertFlag('AllowCoreControl', 'AllowCoreControl') if (mode !== 'on' && mode !== 'off') throw 'mode 必须是 on 或 off' await Utils.setTun(mode === 'on') return Utils.okText('已完成') } }, /** 显示或隐藏 GUI 窗口。 */ set_window: { description: '显示或隐藏 GUI 窗口。', annotations: wr, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['show', 'hide'] } }, required: ['mode'], additionalProperties: false }, async run({ mode }) { if (mode === 'hide') await Plugins.WindowHide() else if (mode === 'show') { await Plugins.WindowShow() setTimeout(() => { Plugins.WindowSetAlwaysOnTop(true) setTimeout(() => Plugins.WindowSetAlwaysOnTop(false), 100) }, 100) } else throw 'mode 必须是 show 或 hide' return Utils.okText('已切换') } }, /** 设置或清除系统代理,需 AllowSystemProxy。 */ set_system_proxy: { description: '设置或清除系统代理。需要 AllowSystemProxy。', annotations: dest, inputSchema: { type: 'object', properties: { mode: { type: 'string', enum: ['set', 'clear'] } }, required: ['mode'], additionalProperties: false }, async run({ mode }) { Utils.assertFlag('AllowSystemProxy', 'AllowSystemProxy') const env = Plugins.useEnvStore() if (mode === 'set') await env.setSystemProxy() else if (mode === 'clear') await env.clearSystemProxy() else throw 'mode 必须是 set 或 clear' return Utils.okText('已完成') } }, /** 列出或按 id 获取已登记的 MMDB。 */ get_mmdbs: { description: '列出已登记的 MMDB,或用 id 获取单个信息', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, additionalProperties: false }, async run({ id } = {}) { await Utils.loadMmdbs() if (!id) return Utils.okText(mmdbs) const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' return Utils.okText(item) } }, /** 下载并登记一个 MMDB,需 AllowWrites。 */ add_mmdb: { description: '下载并登记一个 MMDB。需要 AllowWrites。仅写入插件自己的 data/.cache/mmdbs。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' }, type: { type: 'string', enum: MMDB_TYPES }, url: { type: 'string' } }, required: ['id', 'type', 'url'], additionalProperties: false }, async run({ id, type, url }) { Utils.assertFlag('AllowWrites', 'AllowWrites') await Utils.loadMmdbs() if (!id || !String(id).trim()) throw '缺少必要的参数:id' if (Utils.findMmdb(id)) throw '数据库已存在' if (!MMDB_TYPES.includes(type)) throw '数据库的类型错误' if (!url || !String(url).trim()) throw '缺少必要的参数:url' if (!(await Plugins.FileExists(MMDB_DIR))) await Plugins.MakeDir(MMDB_DIR) const savedPath = MMDB_DIR + '/' + id + '.mmdb' await Plugins.Download(url, savedPath) const item = { id, type, url, path: savedPath } mmdbs.push(item) await Utils.saveMmdbs() return Utils.okText({ ok: true, id, type, path: savedPath }) } }, /** 删除已登记的 MMDB 文件,需 AllowWrites。 */ delete_mmdb: { description: '删除已登记的 MMDB 文件。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') await Utils.loadMmdbs() const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' await Plugins.RemoveFile(item.path) mmdbs = mmdbs.filter((db) => db.id !== id) await Utils.saveMmdbs() return Utils.okText({ ok: true, id }) } }, /** 按已登记 URL 重新下载 MMDB,需 AllowWrites。 */ refresh_mmdb: { description: '按已登记 URL 重新下载 MMDB。需要 AllowWrites。', annotations: dest, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') await Utils.loadMmdbs() const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' await Plugins.Download(item.url, item.path) return Utils.okText({ ok: true, id }) } }, /** 打开 MMDB 以供查询,需 AllowWrites。 */ open_mmdb: { description: '打开 MMDB 以供查询。需要 AllowWrites(会占用宿主 MMDB 句柄)。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') await Utils.loadMmdbs() const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' await Plugins.OpenMMDB(item.path, Plugin.id) return Utils.okText('打开数据库成功') } }, /** 关闭已打开的 MMDB,需 AllowWrites。 */ close_mmdb: { description: '关闭已打开的 MMDB。需要 AllowWrites。', annotations: wr, inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false }, async run({ id }) { Utils.assertFlag('AllowWrites', 'AllowWrites') await Utils.loadMmdbs() const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' await Plugins.CloseMMDB(item.path, Plugin.id) return Utils.okText('关闭数据库成功') } }, /** 查询 MMDB;尚未打开时会先打开再查。 */ query_mmdb: { description: '查询 MMDB。只读;若尚未打开会自动打开后再查。', annotations: ro, inputSchema: { type: 'object', properties: { id: { type: 'string' }, ip: { type: 'string' }, type: { type: 'string', enum: MMDB_TYPES, description: '默认 Country' } }, required: ['id', 'ip'], additionalProperties: false }, async run({ id, ip, type }) { if (!ip) throw '缺少必要的参数:ip' const queryType = type || 'Country' if (!MMDB_TYPES.includes(queryType)) throw '查询的类型错误' await Utils.loadMmdbs() const item = Utils.findMmdb(id) if (!item) throw '数据库不存在' try { return Utils.okText(await Plugins.QueryMMDB(item.path, ip, queryType)) } catch (error) { const msg = error?.message || String(error) if (String(msg).includes('Database not open')) { await Plugins.OpenMMDB(item.path, Plugin.id) return Utils.okText(await Plugins.QueryMMDB(item.path, ip, queryType)) } throw error } } }, /** 查看和操作当前程序 WebView 页面。改界面的 action 需 AllowPageControl。 */ page: { description: '查看和操作当前程序的 WebView 页面,不是外部浏览器,也不能操作跨源 iframe。配置、订阅、规则、插件、任务等请优先用专用工具;本工具用于查看当前界面、处理弹窗,以及专用工具覆盖不到的交互。snapshot 返回带编号的可见元素,编号在下一次 snapshot 前有效。snapshot、query、read 只查看;scroll、wait 只查看或滚动;click、fill、select、press、hover 会改变界面,需要开启 AllowPageControl。click、fill、select、press、hover、scroll、wait 的结果已附带操作后 snapshot,不要紧接着再调用 snapshot。改变界面前先调用 begin 显示炫彩边框,同一轮只调用一次;全部完成后调用 end 关掉边框,只查看时不要开关。begin/end 也需要 AllowPageControl。若 GUI Agent 窗口已打开,则不能把它当作操作目标。会离开当前页面的导航会被阻止。页面上的鼠标指针只表示当前操作位置,不要点击或描述它。', annotations: wr, inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['snapshot', 'query', 'read', 'click', 'fill', 'select', 'press', 'scroll', 'hover', 'wait', 'begin', 'end'], description: 'snapshot 列出带编号的可见元素。query、read 查看。click、fill、select、press、hover、scroll、wait 操作后已附带最新 snapshot。begin 打开炫彩操作边框,end 关闭边框和指针。click/fill/select/press/hover/begin/end 需要 AllowPageControl。', default: 'snapshot' }, ref: { type: 'number', description: '最近一次 snapshot 中的元素编号。' }, selector: { type: 'string', description: 'CSS 选择器。除非同时给 index,否则必须只匹配一个可见元素。' }, text: { type: 'string', description: '按无障碍名称或可见文本匹配。' }, index: { type: 'number', description: 'selector 或 text 匹配到多个元素时的从 0 开始的序号。' }, value: { type: 'string', description: 'fill 或 select 的值。复选框可用 true/false、on/off 或 1/0。' }, key: { type: 'string', description: 'press 的按键,如 Enter、Escape、Tab、Backspace、ArrowDown,或单个字符。' }, dx: { type: 'number', description: '水平滚动距离(像素)。' }, dy: { type: 'number', description: '垂直滚动距离(像素)。' }, to: { type: 'string', enum: ['top', 'bottom'], description: '将目标或页面滚动到顶部或底部。' }, scope: { type: 'string', enum: ['viewport', 'all'], description: 'snapshot 范围,默认 viewport。', default: 'viewport' }, limit: { type: 'number', description: 'snapshot 最多返回的元素数。默认 250,最大 400。' }, timeout: { type: 'number', description: 'wait 超时毫秒数。默认 1000,最大 10000。' } }, required: ['action'], additionalProperties: false }, async run(args = {}) { const action = String(args.action || 'snapshot').toLowerCase() if (['click', 'fill', 'select', 'press', 'hover', 'begin', 'end'].includes(action)) { Utils.assertFlag('AllowPageControl', 'AllowPageControl') } return Utils.okText(await PageControl.run(args)) } } } /** * 分发单条 JSON-RPC 消息到 initialize、tools/list、tools/call。 * @param {*} message 已解析的请求体 * @returns {Promise<{status: number, body: object|string}>} */ const dispatch = async (message) => { if (!Utils.isPlainObject(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') { return { status: 400, body: Utils.fail(message?.id, -32600, 'Invalid Request') } } if (!Object.hasOwn(message, 'id')) { return message.method === 'notifications/initialized' ? { status: 202, body: '' } : { status: 400, body: Utils.fail(null, -32601, 'Method not found: ' + message.method) } } if (message.method === 'initialize') { return { status: 200, body: Utils.ok(message.id, { protocolVersion: PROTOCOL, capabilities: { tools: {} }, serverInfo: { name: Plugin.name || 'mcp-server', version: Plugin.version || 'v1.1.0' }, instructions: 'GUI.for.Cores MCP. Read-only tools are safe by default; writes/core/proxy/plugin-run/page-control require explicit plugin flags. Secrets are redacted.' }) } } if (message.method === 'tools/list') return { status: 200, body: Utils.ok(message.id, { tools: Utils.toolList() }) } if (message.method === 'tools/call') { const params = message.params if (!Utils.isPlainObject(params) || typeof params.name !== 'string' || !params.name) { return { status: 200, body: Utils.fail(message.id, -32602, 'Invalid params') } } if (!Object.hasOwn(tools, params.name)) return { status: 200, body: Utils.fail(message.id, -32602, 'Unknown tool: ' + params.name) } const tool = tools[params.name] const reason = Utils.invalidArgs(tool.inputSchema, params.arguments) if (reason) return { status: 200, body: Utils.fail(message.id, -32602, reason) } try { const result = (await tool.run(params.arguments || {})) || {} return { status: 200, body: Utils.ok(message.id, { content: result.content || Utils.text(''), isError: !!result.isError }) } } catch (error) { return { status: 200, body: Utils.ok(message.id, { content: Utils.text(error?.message || error), isError: true }) } } } return { status: 200, body: Utils.fail(message.id, -32601, 'Method not found: ' + message.method) } } /** * HTTP 入口:校验 Origin/Host、Bearer、协议版本,解析后交给 dispatch。 * 真实 GFC 通常拿不到 Host,Host 校验在实机上无效。 * @param {{method: string, url: string, headers: object, body?: string}} req * @param {{end: Function}} res */ const onRequest = async (req, res) => { const origin = Utils.header(req.headers, 'Origin') if (origin && !Utils.allowedOrigin(origin)) return Utils.end(res, 403, { 'Content-Type': 'text/plain; charset=utf-8' }, 'Forbidden origin') const hostHeader = Utils.header(req.headers, 'Host') if (hostHeader && !Utils.allowedHost(hostHeader)) return Utils.end(res, 403, { 'Content-Type': 'text/plain; charset=utf-8' }, 'Forbidden host') const pathname = new URL(req.url, 'http://127.0.0.1').pathname if (pathname !== '/mcp') return Utils.end(res, 404, { 'Content-Type': 'text/plain; charset=utf-8' }, 'Not Found') if (req.method !== 'POST') { return Utils.end( res, 405, { Allow: 'POST', 'Content-Type': 'text/plain; charset=utf-8' }, req.method === 'GET' ? 'SSE is not supported' : 'Method Not Allowed' ) } if (!runtimeToken || Utils.requestToken(req) !== runtimeToken) { return Utils.end(res, 401, { 'Content-Type': 'text/plain; charset=utf-8', 'WWW-Authenticate': 'Bearer' }, 'Unauthorized') } const protocolHeader = Utils.header(req.headers, 'MCP-Protocol-Version') if (protocolHeader && protocolHeader !== PROTOCOL) { return Utils.end(res, 400, { 'Content-Type': 'text/plain; charset=utf-8' }, 'Unsupported MCP-Protocol-Version') } let message try { message = JSON.parse(Utils.readBody(req)) } catch { return Utils.end(res, 400, JSON_HEADERS, Utils.fail(null, -32700, 'Parse error')) } if (Array.isArray(message)) return Utils.end(res, 400, JSON_HEADERS, Utils.fail(null, -32600, 'JSON-RPC batches are not supported')) try { const result = await dispatch(message) return Utils.end(res, result.status, result.body ? JSON_HEADERS : {}, result.body) } catch (error) { return Utils.end(res, 500, JSON_HEADERS, Utils.fail(message?.id, -32603, error?.message || String(error))) } } /** * 启动 MCP HTTP 服务。绑定地址完全由 Address 决定,不会改写。 * @returns {Promise<1>} */ const Start = async () => { if (await Utils.isRunning()) throw '该服务已经在运行了' const auth = Utils.resolveToken() await Utils.loadMmdbs() await Plugins.StartServer(Utils.address(), Plugin.id, onRequest) const url = Utils.endpoint() Plugins.message?.success?.('MCP 已监听 ' + url) if (auth.configured) { await Plugins.alert?.('MCP Server', '服务已启动:' + url + '\n请在请求头携带 Authorization: Bearer <你配置的 AuthToken>\n密钥不会在此显示。') } else { await Plugins.alert?.( 'MCP Server', '服务已启动:' + url + '\n本次临时密钥(重启或写入 AuthToken 前有效):\n' + auth.token + '\n建议在插件配置中设置 AuthToken 以免每次变化。' ) } return 1 } /** * 停止服务并清空本次运行时令牌。 * @returns {Promise<2>} */ const Stop = async () => { PageControl.clearEffect() runtimeToken = '' if (Plugins.ignoredError) await Plugins.ignoredError(Plugins.StopServer, Plugin.id) else await Plugins.StopServer(Plugin.id).catch(() => {}) Plugins.message?.success?.('MCP 已停止') return 2 } /** * 把服务地址复制到剪贴板,不含密钥。 * @returns {Promise} */ const CopyURL = async () => { await Plugins.ClipboardSetText(Utils.endpoint()) Plugins.message?.success?.('已复制地址(不含密钥):' + Utils.endpoint()) } /** * 手动运行:已启动则返回状态,否则启动服务。 * @returns {Promise<1|2>} */ const onRun = async () => ((await Utils.isRunning()) ? 1 : Start()) /** * 宿主就绪:按 AutoStart 启动;若服务仍在跑则先停再拉起以套用当前配置。 * @returns {Promise<1|2>} */ const onReady = async () => { if (Utils.flagOn('AutoStart') && !(await Utils.isRunning())) return Start() if (await Utils.isRunning()) { await Stop() return Start() } return 2 } /** * 关键配置变更且服务在运行时,重启以套用新地址或令牌。 * @param {object} config 新配置 * @param {object} old 旧配置 */ const onConfigure = async (config, old) => { const keys = ['Address', 'AuthToken', 'AutoStart'] if (keys.some((key) => config?.[key] !== old?.[key]) && (await Utils.isRunning())) { await Stop() return Start() } } return { onRun, onReady, onConfigure, onShutdown: Stop, onDispose: Stop, onDisabled: Stop, Start, Stop, CopyURL } }