diff --git a/plugins/Wzdhehe/mcode-webui/CONTRIBUTING.md b/plugins/Wzdhehe/mcode-webui/CONTRIBUTING.md new file mode 100644 index 0000000..e48dbfa --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing to Mcode-webui plugin + +This is the packaged plugin view of the project. The full +contribution guide lives in the **source repo**: + +**[github.com/Wzdhehe/Mcode-webui → CONTRIBUTING.md](https://github.com/Wzdhehe/Mcode-webui/blob/main/CONTRIBUTING.md)** + +## Quick reference + +| Need to … | Read | +|-----------|------| +| Add a route, event, or UI panel | [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | +| Update a config / env var | [server/lib/config.js](server/lib/config.js) + [docs/API.md](docs/API.md) | +| Bump the version | `package.json` (root + plugin copy) + `plugin.json` | +| Update capability list | [docs/CAPABILITIES.md](docs/CAPABILITIES.md) + `plugin.json#extensions.capabilities` | +| Change a security disclosure | [references/SECURITY-NOTES.md](references/SECURITY-NOTES.md) (the single source of truth) | + +## Sync rule + +The plugin tree here (`server/`, `public/`, `test/`, `docs/`) is a +**real copy** of the source-repo root. When you change a file at +the root, mirror the same change here in the same commit, or run +`npm run package:plugin` at the source repo to regenerate the +plugin tree. + +## Submitting to the community registry + +The official +[MiniMax-Code-Plugins](https://github.com/MiniMax-AI/MiniMax-Code-Plugins) +repo accepts plugin submissions as folders under +`plugins///`. The `plugins/Wzdhehe/mcode-webui/` +tree in this repo is the unit of submission — fork the registry, +copy this folder in, open a PR. + +The official gate is `npm run check` at the registry root. This +repo ships a mirror (`npm run validate:plugin`) that runs the same +checks locally before you push. diff --git a/plugins/Wzdhehe/mcode-webui/LICENSE b/plugins/Wzdhehe/mcode-webui/LICENSE new file mode 100644 index 0000000..73c5531 --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Wzdhehe + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/Wzdhehe/mcode-webui/PR_DESCRIPTION.md b/plugins/Wzdhehe/mcode-webui/PR_DESCRIPTION.md new file mode 100644 index 0000000..5e0660d --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/PR_DESCRIPTION.md @@ -0,0 +1,154 @@ +# PR Description — Mcode-webui plugin + +> **Submission body for the upstream PR to the +> [MiniMax-Code-Plugins](https://github.com/MiniMax-AI/MiniMax-Code-Plugins) +> community registry. Use this as the PR body verbatim.** + +## What this PR adds + +- New plugin at `plugins/Wzdhehe/mcode-webui/` per Agent Plugins 1.0 spec + - `plugin.json` with the 10 white-listed top-level fields + - `skills/mcode-webui/SKILL.md` with `{name, description}` frontmatter (343 chars) + body (official skills/ layout) + - `LICENSE` (MIT) + - `README.md` (user-facing quick start) + - `references/SECURITY-NOTES.md` (canonical security disclosure) + - `docs/` (ARCHITECTURE, API, CAPABILITIES, DEVELOPMENT, TROUBLESHOOTING) + - `server/`, `public/`, `test/` (real directory copies, kept in sync with + the project root; packaged as-is into `dist/` for the release artifact) + - `package.json` (copy of project root, with `setup:plugin` and + `package:plugin` scripts) + +## Why this plugin + +A Kimi-Code-style web frontend for the `mcode` agent runtime. It lets +users open `mcode` sessions in a browser instead of the terminal, +stream real-time tool events, switch workspaces, and use the +`ask-user` modal — all without the Mcode TUI eating their terminal. + +## Example prompts (with expected results) + +**Prompt 1** — User: "open Mcode webui" + +Expected: +1. Run `node server.js` (foreground or background, your call) +2. Wait for the SSE `open` log line on stdout +3. Tell the user: "webui running at http://127.0.0.1:8080/ (or http://:8080/ for LAN)" + +**Prompt 2** — User: "Mcode webui status" + +Expected: +1. Check if port 8080 is in use +2. If listening: report "running" + URL; if not: report "not running" +3. Optionally read `.server.err` for last error + +**Prompt 3** — User: "show Mcode webui url" + +Expected: +1. Print `http://:8080/` +2. (If `TOKEN` is set) also print the full URL with `?token=…` + +Full trigger list in [`SKILL.md`](SKILL.md#when-to-use-this-skill). + +## Dependencies + +- **Runtime**: Node 22.19+ stdlib only (zero npm deps) +- **External binary**: `mcode` CLI 0.1.4+ (for `mcode acp` transport) +- **Optional**: `sqlite3` binary (for usage panel) — auto-detected via + `server/lib/config.js#detectSqlite3Bin` +- **Optional**: `mavis` 0.1.0+ (for real token usage; degrades to + estimates if missing) + +## Network & data behavior + +- **Binds `0.0.0.0:8080` by default** — loopback-only via `HOST=127.0.0.1` +- **`?token=` query string** supported (browser convenience); + `Authorization: Bearer` header also accepted +- **No outbound network** — only local subprocesses (`mcode`, `mmx quota`) +- **Reads**: `~/.minimax/v2/sqlite/runtime-state.sqlite` (read-only) +- **Writes**: + - `~/.minimax/v2/sqlite/runtime-state.sqlite` — only on + `DELETE /api/sessions/:id` (with `?dryRun=true` opt-in preview) + - `MCODE_WEBUI_UPLOAD_DIR` (default `.webui-uploads/`) for file uploads + - `~/.minimax-code/webui/.webui-sessions.json` for session store +- **No telemetry, no remote endpoints** + +Full disclosure: [`references/SECURITY-NOTES.md`](references/SECURITY-NOTES.md). + +## Automated test evidence + +``` +$ npm test +ℹ tests 291 +ℹ suites 86 +ℹ pass 290 +ℹ fail 0 +ℹ skipped 1 +ℹ duration_ms ~550 + +$ npm run lint +> eslint server/ test/ +(0 errors, 0 warnings) +``` + +Test breakdown: +- `lib-config.test.js` — 28 tests (constants, env loading, sqlite detection) +- `lib-lan.test.js` — local request detection, LAN IP detection +- `lib-db.test.js` — `deleteMcodeSessionFromDb` happy path + missing-table + tolerance, dryRun path +- `lib-state-bus.test.js` — per-cid state isolation, SSE channel mgmt +- `mavis-usage.test.js` — real sqlite3 fixture, per-turn context math +- `sessions.test.js` — `?dryRun=true` preview, route-level session + CRUD with rollback +- `chat.test.js`, `routes-*.test.js` — error path coverage + +CI: GitHub Actions on Node 22 / Node 24, Windows + Linux + macOS. + +## Manual test evidence + +- Installed plugin via `mavis plugin install` (path mode) +- Set `TOKEN=$(openssl rand -hex 16)` +- Opened `http://127.0.0.1:8080/?token=…` in browser — SSE stream + connected, model stream rendered +- Opened same URL on phone (LAN) — token auth accepted, mobile + layout responsive +- Ran a multi-turn session with tool calls (Bash, Read, Edit) — + all events rendered, quota panel updated +- Toggled `lanBroadcast: false` — phone got 403 with friendly page +- Deleted a session — log shows rows removed from all session-keyed + tables. v1.0 E2E evidence: ran the real-delete path against a copy of + the production `runtime-state.sqlite` (713 MB) via + `MCODE_RUNTIME_DB=`; a session with 11,176 rows across 12 tables + was reduced to 7 rows (only `questionnaire_requests` remains, skipped + by design — not `local_runtime_*`-prefixed). The table list covers + 32 of the 33 session-keyed tables in the Mcode schema. +- Re-ran delete with `?dryRun=true` — preview shows row count, no + modification +- Restarted server — orphan mcode acp child cleaned up via SIGTERM + +## Red-line compliance (mcode-plugin-guide) + +- **Red-line 1 (destructive ops)**: `DELETE /api/sessions/:id` has + `?dryRun=true` opt-in preview. Real delete runs in a SQLite + `transaction()` with per-table error tolerance. +- **Red-line 2 (cross-platform)**: sqlite3 binary is auto-detected via + `detectSqlite3Bin()` — no hardcoded host paths. +- **Red-line 3 (披露完整性)**: `references/SECURITY-NOTES.md` is the + single source of truth; `SKILL.md` (TL;DR + link), `plugin.json` + (`extensions.securityNotes`), this PR description, and the plugin + `README.md` all reference it. +- **Red-line 7 (披露完整性)**: 3-place consistency — README, + plugin.json description + `extensions.securityNotes`, PR template. + +## Checklist + +- [x] `plugin.json` validates against `https://agent-plugins.org/schemas/1.0.0/plugin.schema.json` +- [x] `npm run validate-plugin` (planned batch H) passes +- [x] `npm test` — 261 pass, 0 fail, 0 lint warning +- [x] `references/SECURITY-NOTES.md` covers all red-line 7 topics +- [x] LICENSE present (MIT) +- [x] README.md present and non-empty +- [x] No symlinks (release artifact expands junctions) +- [x] No UTF-8 BOM in any text file +- [x] No placeholder markers in shipped files +- [x] No `hooks` / unsupported capability fields +- [x] One plugin per PR (this PR is only `plugins/Wzdhehe/mcode-webui/`) diff --git a/plugins/Wzdhehe/mcode-webui/README.md b/plugins/Wzdhehe/mcode-webui/README.md new file mode 100644 index 0000000..130938b --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/README.md @@ -0,0 +1,83 @@ +# Mcode Web UI Plugin + +> **Browser-based chat frontend for the Mcode agent runtime.** +> Streams `mcode acp` / `mcode exec` sessions in real time. Zero npm +> dependencies; runs on Node 22.19+. + +This is the mcode-plugin-guide (Agent Plugins 1.0) packaging of the +[Mcode-webui](https://github.com/Wzdhehe/Mcode-webui) web frontend. + +## Quick start + +```bash +# 1. Install the plugin (per mavis / MiniMax Code plugin loader) +# 2. Set TOKEN (recommended on non-loopback networks) +export TOKEN="$(openssl rand -hex 16)" +# 3. Start the plugin +node server.js +# 4. Open in browser +# http://127.0.0.1:8080/?token=$TOKEN +``` + +## What's in the box + +| File | What | +|------|------| +| `plugin.json` | Agent Plugins 1.0 manifest (10 top-level fields, white-listed) | +| `SKILL.md` | This plugin's skill description (frontmatter + body) | +| `LICENSE` | MIT | +| `README.md` | This file | +| `references/SECURITY-NOTES.md` | **Canonical security disclosure** (read this before installing) | +| `docs/` | ARCHITECTURE, API, CAPABILITIES, DEVELOPMENT, TROUBLESHOOTING | +| `server/` | Node.js HTTP + SSE server | +| `public/` | Static frontend SPA | +| `test/` | `node:test` unit tests | +| `package.json` | Project metadata + scripts | + +## Configuration + +All settings are environment variables. See +[SKILL.md § Configuration](SKILL.md#configuration-environment-variables) +and [`server/lib/config.js`](server/lib/config.js) for the canonical +list. Most relevant: + +| Variable | Default | Purpose | +|----------|---------|---------| +| `PORT` | `8080` | HTTP listen port (default was `7890` before v0.5) | +| `HOST` | `0.0.0.0` | Bind address (override to `127.0.0.1` for loopback-only) | +| `TOKEN` | (empty) | Required token for non-local requests | + +## Security disclosure (READ THIS) + +Full disclosure is in +[`references/SECURITY-NOTES.md`](references/SECURITY-NOTES.md). Key points: + +- Default binds `0.0.0.0` — reachable from any device on the LAN. Use + `HOST=127.0.0.1` for loopback-only mode. +- `?token=` query string is supported for browser convenience. Prefer + `Authorization: Bearer` header for any non-browser caller. +- `DELETE /api/sessions/:id` writes to the user's real mavis sqlite + (`~/.minimax/v2/sqlite/runtime-state.sqlite`). Pass `?dryRun=true` to + preview before committing. +- No telemetry, no remote endpoints, no third-party subprocesses. + +## Documentation + +| Doc | What | +|-----|------| +| [SKILL.md](SKILL.md) | Plugin skill description + trigger examples | +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Module topology, request lifecycle, SSE schema | +| [docs/API.md](docs/API.md) | Every HTTP endpoint with request/response schema | +| [docs/CAPABILITIES.md](docs/CAPABILITIES.md) | Capability matrix — what works, what doesn't | +| [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | Dev setup + how to add a route/UI panel | +| [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) | Common errors with verified fixes | + +## License + +MIT — see [LICENSE](LICENSE). + +## Maintainer + +- **Author**: Wzdhehe +- **Repository**: https://github.com/Wzdhehe/Mcode-webui +- **Homepage**: https://github.com/Wzdhehe/Mcode-webui diff --git a/plugins/Wzdhehe/mcode-webui/README.zh-CN.md b/plugins/Wzdhehe/mcode-webui/README.zh-CN.md new file mode 100644 index 0000000..09bcf54 --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/README.zh-CN.md @@ -0,0 +1,112 @@ +# mcode Web UI + +**[English](README.md) | [简体中文](README.zh-CN.md)** + +`mcode` 命令行工具的**浏览器前端** —— 在浏览器里跑 `mcode`, +不用占用终端。直接对接 mcode 自有的协议(`mcode acp` JSON-RPC + +`mcode exec` stream-json),不是 TUI 套壳。**零 npm 运行时依赖** +(只用 Node 22+ 标准库)。 + +> 三栏布局(会话 / 对话 / 上下文),`/` 命令搜索,附件上传, +> 套餐用量右向展开,token 鉴权局域网,移动端响应。 + +``` +[浏览器 :8080] ←─ SSE /api/events ─ [Node server.js] ─ mcode acp / exec ─ [mcode CLI] + │ │ + └──── REST /api/* ────────────────────┴── ~/.minimax/v2 sqlite(读 + 删会话) +``` + +## 功能 + +- **三栏布局** —— 会话列表 / 对话区 / 上下文面板 +- **实时流式输出** —— 模型输出、工具事件(Bash / Read / Edit / + Glob / Grep / WebFetch …)、智能体思考片段 +- **斜杠命令搜索** —— `/` 打开面板,模糊搜索 mcode 内置命令 + + webui 自定义命令 +- **文件附件** —— 点击 / 拖拽 / Ctrl+V 粘贴;以 `@file` 形式注入 +- **用量面板** —— 右侧可展开:5 小时 + 周配额、上下文进度条、 + 缓存命中率、tok/s、每个会话的 token 统计 +- **计划审阅 & 反问弹窗** —— plan 模式和 `AskUserQuestion` 工具 + 以原生 UI 呈现,不是终端 prompt +- **工作区切换** —— 目录树浏览器(Windows 各盘符、Linux `/`) +- **Token 鉴权的局域网共享** —— `0.0.0.0` 绑定,`?token=` 或 + `Authorization: Bearer` 两种方式,运行时可开关(关时返回 403 友好页) +- **移动端响应** —— `<900px` 抽屉式布局,`<600px` 单列 +- **双语界面** —— 英文 / 简体中文,即时切换 +- **单色主题** —— "Ink & Paper" 暗 / 亮双主题,跟随系统 +- **两种传输** —— `mcode acp`(默认,多轮)+ `mcode exec` + 兜底(用于老版本客户端 / 降级模式) + +## 快速开始 + +```bash +git clone https://github.com/Wzdhehe/mcode-webui.git +cd mcode-webui +node server.js # mcode CLI 自动探测 +# → http://127.0.0.1:8080/ (局域网:http://<局域网IP>:8080/) + +# 在共享网络上推荐加 token: +TOKEN=$(openssl rand -hex 16) node server.js +# → 打开 http://127.0.0.1:8080/?token=$TOKEN +``` + +## 配置 + +全部环境变量,都是可选: + +| 变量 | 默认 | 作用 | +|------|------|------| +| `PORT` | `8080` | HTTP 端口(v1.0 之前是 `7890`) | +| `HOST` | `0.0.0.0` | 绑定地址(`127.0.0.1` = 仅本机) | +| `TOKEN` | (空) | 非本机请求必带的 token | +| `MCODE_MODEL` | `minimax_api/MiniMax-M3` | 默认模型 | +| `MCODE_CMD` | 自动探测 | `mcode` / `mcode.cmd` 路径 | +| `MCODE_WEBUI_UPLOAD_DIR` | 自动 | 附件目录 | +| `MCODE_RUNTIME_DB` | `~/.minimax/v2/...` | mcode 运行库(测试用副本) | + +## 已知限制(mcode 0.1.5 acp) + +2026-08 已上报上游:`session/set_mode`、`session/cancel`、 +`session/fork`、`session/delete` 等返回 "Method not found"。 +webui 在 `mcode-rpc.js` 把这些列白名单 + 优雅降级(toast + 兜底), +不渲染假的 UI 按钮。完整能力矩阵: +[docs/CAPABILITIES.md](docs/CAPABILITIES.md)。 + +## 文档 + +| 文档 | 内容 | +|------|------| +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | 模块拓扑、SSE schema、请求生命周期 | +| [docs/CAPABILITIES.md](docs/CAPABILITIES.md) | 哪些能用 / 哪些不能 / 兜底方案 | +| [docs/API.md](docs/API.md) | 每个 HTTP 端点 | +| [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md) | 开发环境、新增路由 / 命令 / 面板 | +| [docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md) | 常见报错 + 验证过的修法 | +| [CHANGELOG.md](CHANGELOG.md) | 发布历史 | +| [SECURITY-NOTES](plugins/Wzdhehe/mcode-webui/references/SECURITY-NOTES.md) | 安全披露(权威源) | + +## 插件打包 + +`plugins/Wzdhehe/mcode-webui/` 是 Agent Plugins 1.0 规范的产物, +会提交到[官方插件社区](https://github.com/MiniMax-AI/MiniMax-Code-Plugins)。 + +```bash +npm run validate:plugin # 契约检查(跟官方门禁镜像) +npm run package:plugin # dist/Wzdhehe/mcode-webui/ + .zip +``` + +## 贡献 + +见 [CONTRIBUTING.md](CONTRIBUTING.md)。`npm test`(302 个测试) +和 `npm run lint` 必须保持全绿;插件树(`plugins/.../mcode-webui/`) +的副本与仓库根保持同步。 + +## 开源协议 + +MIT —— 见 [LICENSE](plugins/Wzdhehe/mcode-webui/LICENSE)。 + +## 命名说明 + +"mcode-webui" 这个名字里 "mcode" 是上游 CLI 工具名,"webui" 是 +它的 Web 界面后缀。所以 "mcode CLI 的 webui" = "mcode 这个命令行 +工具的 Web 界面",不是 "mcode 命令行版的 Web 工具"。两者方向 +相反。 diff --git a/plugins/Wzdhehe/mcode-webui/acp.mjs b/plugins/Wzdhehe/mcode-webui/acp.mjs new file mode 100644 index 0000000..d3044dd --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/acp.mjs @@ -0,0 +1,271 @@ +// acp.mjs — mcode acp JSON-RPC client (Node stdio, zero deps) +// +// Spawns `mcode acp` (Agent Client Protocol server) and exposes: +// - request(method, params) → Promise +// - notify(method, params) → fire-and-forget +// - on(event, handler) → subscribe to server notifications +// - newSession(cwd) → {sessionId} +// - loadSession(sid, cwd) → {} (attach to any TUI session, 0.1.3+) +// - listSessions() → {sessions: [{sessionId, cwd, title, updatedAt}], nextCursor} +// - prompt(sid, text, cbs) → full lifecycle: init → stream chunks → stopReason +// - stop() → kill subprocess +// +// Event types from mcode 0.1.3 (verified via probe): +// - session/update {sessionUpdate: "available_commands_update"} → list of slash cmds +// - session/update {sessionUpdate: "agent_thought_chunk"} → {messageId, content: {type, text}} +// - session/update {sessionUpdate: "agent_message_chunk"} → {messageId, content: {type, text}} +// - prompt response: {stopReason: "end_turn" | "max_tokens" | "refusal" | ...} + +import { spawn } from 'node:child_process' +import { EventEmitter } from 'node:events' +import { homedir } from 'node:os' +import { existsSync } from 'node:fs' +import { join } from 'node:path' + +const DEFAULT_CWD = process.cwd() + +// v1.0: mcode 可执行文件动态解析 — 之前硬编码 C:\Users\\... 绝对路径, +// 插件分发到别人机器上必然失效。优先级: env MCODE_CMD > ~/.minimax-code/mcode.cmd > PATH 里的 mcode +function resolveMcodeCmd() { + if (process.env.MCODE_CMD) return process.env.MCODE_CMD + if (process.platform === 'win32') { + const p = join(homedir(), '.minimax-code', 'mcode.cmd') + if (existsSync(p)) return p + } + return 'mcode' +} + +export class McodeAcpClient extends EventEmitter { + constructor({ mcodeCmd = 'mcode', cwd = DEFAULT_CWD, debug = false } = {}) { + super() + this.mcodeCmd = mcodeCmd + this.cwd = cwd + this.debug = debug + this.child = null + this.buf = '' + this.nextId = 0 + this.pending = new Map() // id → {resolve, reject, method} + this.capabilities = null + this.started = false + } + + // 启动 subprocess + initialize + 解析 capabilities + async start() { + if (this.started) return this.capabilities + // Windows: 直接 spawn mcode.cmd(Node CreateProcess 知道 .cmd shim,不用 cmd.exe 套) + // - cmd.exe /c mcode 会输出 Windows 横幅污染 stdout JSON 解析 + // Linux/macOS: spawn 'mcode' 走 PATH + // Windows: spawn('cmd.exe', ['/c', 'mcode.cmd', 'acp']) 是 node probe 验证能 work 的姿势 + // - 直接 spawn mcode.cmd + shell:false → Node 22+ EINVAL(不让直接 CreateProcess .cmd) + // - shell:true → Node 内置 cmd.exe 解释,但会输出 Windows 横幅污染 JSON + // - cmd.exe /c <.cmd> → cmd.exe 作为父进程,不解释不打印横幅,只 exec mcode.cmd + const args = process.platform === 'win32' + ? ['/c', resolveMcodeCmd(), 'acp'] + : ['acp'] + const cmd = process.platform === 'win32' ? 'cmd.exe' : 'mcode' + this.child = spawn(cmd, args, { + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true, + shell: false, // 关键:false 让 cmd.exe 不打印横幅 + }) + this.child.on('error', (e) => this.emit('error', e)) + this.child.on('exit', (code, signal) => { + this.emit('exit', { code, signal }) + // 拒绝所有 pending + for (const [id, p] of this.pending) { + p.reject(new Error(`mcode acp exited (code=${code} signal=${signal})`)) + } + this.pending.clear() + }) + this.child.stdout.setEncoding('utf8') + this.child.stdout.on('data', (chunk) => this._onData(chunk)) + this.child.stderr.setEncoding('utf8') + this.child.stderr.on('data', (c) => { + if (this.debug) process.stderr.write('[acp stderr] ' + c) + }) + // initialize + this.capabilities = await this.request('initialize', { + protocolVersion: 1, + clientInfo: { name: 'mcode-webui', version: '0.1.0' }, + capabilities: { mcpCapabilities: { http: false, sse: false } }, + }) + this.started = true + return this.capabilities + } + + get cmd() { + return process.platform === 'win32' ? resolveMcodeCmd() : 'mcode' + } + + // 解析 stdout(每行一条 JSON) + _onData(chunk) { + this.buf += chunk + let nl + while ((nl = this.buf.indexOf('\n')) !== -1) { + const line = this.buf.slice(0, nl).trim() + this.buf = this.buf.slice(nl + 1) + if (!line) continue + this._dispatch(line) + } + } + + _dispatch(line) { + let msg + try { msg = JSON.parse(line) } catch (e) { + if (this.debug) process.stderr.write('[acp] non-json line: ' + line + '\n') + return + } + // 响应(带 id) + if (typeof msg.id !== 'undefined' && (msg.result !== undefined || msg.error !== undefined)) { + const p = this.pending.get(msg.id) + if (p) { + this.pending.delete(msg.id) + if (msg.error) p.reject(Object.assign(new Error(msg.error.message || 'acp error'), { data: msg.error })) + else p.resolve(msg.result) + } + return + } + // notification(method 但无 id) + if (msg.method) { + // 内部 raw 事件 + this.emit('notification', msg) + // 细粒度事件 + if (msg.method === 'session/update' && msg.params?.update) { + const u = msg.params.update + this.emit('sessionUpdate', u) + if (u.sessionUpdate) this.emit(u.sessionUpdate, u) + } else { + this.emit(msg.method, msg.params) + } + } + } + + // 通用 request + request(method, params) { + if (!this.child) return Promise.reject(new Error('acp not started')) + const id = ++this.nextId + const msg = { jsonrpc: '2.0', id, method, params } + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, method }) + try { + this.child.stdin.write(JSON.stringify(msg) + '\n') + } catch (e) { + this.pending.delete(id) + reject(new Error(`acp write failed: ${e.message}`)) + } + }) + } + + notify(method, params) { + if (!this.child) throw new Error('acp not started') + const msg = { jsonrpc: '2.0', method, params } + this.child.stdin.write(JSON.stringify(msg) + '\n') + } + + // --- 高级 API --- + + async newSession(cwd = this.cwd) { + return await this.request('session/new', { cwd, mcpServers: [] }) + } + + async loadSession(sessionId, cwd = this.cwd) { + return await this.request('session/load', { sessionId, cwd, mcpServers: [] }) + } + + async listSessions(cursor) { + return await this.request('session/list', cursor ? { cursor } : {}) + } + + // 发 prompt + 等 stopReason + 收集 thinking/answer + // onChunk({kind: 'thought'|'message'|'other'|'done', text?, update?, stopReason?}) + async prompt(sessionId, text, onChunk) { + // 先清理之前 listener,避免多个 prompt 串 + return await new Promise((resolve, reject) => { + const result = { thinking: '', answer: '', messageIds: new Set(), stopReason: null, events: [] } + const onUpdate = (u) => { + result.events.push(u) + if (u.sessionUpdate === 'agent_thought_chunk' && u.content?.type === 'text') { + result.thinking += u.content.text + if (u.messageId) result.messageIds.add(u.messageId) + try { onChunk?.({ kind: 'thought', text: u.content.text }) } catch {} + } else if (u.sessionUpdate === 'agent_message_chunk' && u.content?.type === 'text') { + result.answer += u.content.text + if (u.messageId) result.messageIds.add(u.messageId) + try { onChunk?.({ kind: 'message', text: u.content.text }) } catch {} + } else if (u.sessionUpdate === 'tool_call') { + // v0.5.bs: mcode acp 工具调用开始 — 透传完整 update 给上层(字段:toolCallId/title/name/status/rawInput) + try { onChunk?.({ kind: 'tool_call', update: u }) } catch {} + } else if (u.sessionUpdate === 'tool_call_update') { + // v0.5.bs: 工具完成 — 透传 rawOutput 等给上层 + try { onChunk?.({ kind: 'tool_update', update: u }) } catch {} + } else if (u.sessionUpdate === 'usage_update') { + // v0.5.bx: mcode acp 上下文用量({used, size, cost} — 当前 session 已用 vs 上限) + // 字段是累计值(不是 incremental),直接覆盖 cs.context + try { onChunk?.({ kind: 'usage', update: u }) } catch {} + } else if (u.sessionUpdate === 'plan_update') { + // v0.5.bx-9: mcode acp 0.1.5+ 可能发 plan_update 事件(plan 模式 LLM 出方案) + // 字段: {sessionId, planId, title, summary, options: [{label, description}]} + // 0.1.4 probe 没发过(available_commands 也没 /plan),但先透传以备未来 + try { onChunk?.({ kind: 'plan_update', update: u }) } catch {} + } else if (u.sessionUpdate === 'plan_removed') { + // v0.5.bx-9: 取消 plan 模式 + try { onChunk?.({ kind: 'plan_removed', update: u }) } catch {} + } else if (u.sessionUpdate === 'current_mode_update') { + // v0.5.bx-9: mcode 切到 plan/ask 模式时发 — 透传给 webui 决定弹 PlanMode/Ask modal + try { onChunk?.({ kind: 'mode_update', update: u }) } catch {} + } else if (u.sessionUpdate === 'goal_update') { + // v0.5.bx-9: 目标追踪(mcode 0.1.4 acp 没见,但 0.1.5+ 可能加) + try { onChunk?.({ kind: 'goal_update', update: u }) } catch {} + } else if (u.sessionUpdate === 'config_option_update') { + // v0.5.by: mcode acp 0.1.5 推的 config 变化 (如 permissionMode 被改) + // payload: { sessionId, key, value, ... } — 透传给上层, 上层按 key 分发 + try { onChunk?.({ kind: 'config_option_update', update: u }) } catch {} + } else if (u.sessionUpdate === 'session_info_update') { + // v0.5.by: mcode acp 0.1.5 推的 session info 变化 (mcode docs 没列具体字段, 透传) + try { onChunk?.({ kind: 'session_info_update', update: u }) } catch {} + } else { + try { onChunk?.({ kind: 'other', update: u }) } catch {} + } + } + this.on('sessionUpdate', onUpdate) + // 发 prompt + this.request('session/prompt', { + sessionId, + prompt: [{ type: 'text', text }], + }).then((r) => { + result.stopReason = r?.stopReason || 'end_turn' + // v0.5.bx: 捕获 usage 字段(Gcm schema: totalTokens/inputTokens/outputTokens/thoughtTokens/cachedReadTokens/cachedWriteTokens) + // mcode acp 0.1.3 把 usage 放在 session/prompt response 里,不发独立 usage_update event + if (r && r.usage) result.usage = r.usage + // v0.5.bx-7: debug — 看 mcode 0.1.4 实际 response 结构 + if (process.env.MCODE_ACP_DEBUG) { + console.log('[acp.prompt.response]', JSON.stringify({ + stopReason: r?.stopReason, + hasUsage: !!r?.usage, + usageKeys: r?.usage ? Object.keys(r.usage) : null, + usage: r?.usage, + respKeys: r ? Object.keys(r) : null, + fullResp: r, + }).slice(0, 2000)) + } + this.off('sessionUpdate', onUpdate) + try { onChunk?.({ kind: 'done', stopReason: result.stopReason, usage: result.usage }) } catch {} + resolve(result) + }).catch((e) => { + this.off('sessionUpdate', onUpdate) + reject(e) + }) + }) + } + + stop() { + if (this.child) { + try { this.child.kill() } catch {} + this.child = null + } + this.started = false + } + + // 别名:跟 child_process 的 child.kill() 接口一致,/api/stop 能直接用 + kill() { this.stop() } +} diff --git a/plugins/Wzdhehe/mcode-webui/docs/API.md b/plugins/Wzdhehe/mcode-webui/docs/API.md new file mode 100644 index 0000000..5e68e68 --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/docs/API.md @@ -0,0 +1,566 @@ +# HTTP API reference + +> Complete enumeration of every endpoint. REST is JSON unless noted; the +> only SSE endpoint is `/api/events`. + +All non-API routes return static files (`server.js` → `serveStatic` / +`serveIndex`). + +## Conventions + +- **Base URL**: `http://127.0.0.1:8080` (or LAN IP if enabled) +- **Path prefix**: `/api/` +- **Content-Type**: `application/json; charset=utf-8` for both request and response +- **Auth header**: if `TOKEN` env is set, every request must include either + - query: `?token=…` + - header: `Authorization: Bearer …` + - 401 if missing or wrong +- **CID**: every request must include `?cid=` to identify the webui + tab. The webui injects this automatically; the API is unusable without it. +- **Errors**: every error response is `{ok: false, error: 'human-readable message'}` + with an appropriate 4xx/5xx status. Some legacy endpoints still return + `{ok: true, …}` even on soft failures — those are called out below. + +--- + +## Health + +### `GET /api/health` + +Returns server status. No auth required, no CID required. + +**Response 200** +```json +{ + "ok": true, + "port": 8080, + "defaultModel": "minimax_api/MiniMax-M3", + "defaultWorkspace": "C:\\Users\\you\\.minimax-code\\webui", + "mcodeCmd": "C:\\Users\\you\\.minimax-code\\mcode.cmd", + "mcodeVersion": "0.1.2", + "maxConcurrent": 3 +} +``` + +--- + +## State & SSE + +### `GET /api/state` + +Returns the current `state` object for this CID. See +[ARCHITECTURE.md §4](ARCHITECTURE.md) for the full shape. + +**Response 200** +```json +{ "ok": true, "version": "0.1.3", "running": {"active": false}, … } +``` + +### `GET /api/events` + +Server-Sent Events stream for this CID. The connection stays open +indefinitely. Events are listed in +[ARCHITECTURE.md §5](ARCHITECTURE.md). + +**Response 200** (`Content-Type: text/event-stream`) +``` +event: state +data: {"version":"0.1.3","running":{"active":false},…} + +event: delta +data: {"text":"hello","isPartial":true} + +event: exec +data: {"status":"ok","durationMs":12345} +``` + +The connection is held open until the client closes it (`EventSource.close()`) +or the server shuts down. No automatic reconnect from the server side; +the webui handles reconnection with exponential backoff. + +--- + +## Chat + +### `POST /api/send` + +Send a user message. Spawns (or reuses) the Mcode subprocess for this CID +and streams the result via SSE. + +**Request** +```json +{ + "content": "refactor the workspace picker to use a tree", + "attachments": ["@C:\\path\\to\\file.py"], + "isAskAnswer": false +} +``` + +- `content` (string, required) — the user message. May include `@path` + references to attachments; the webui injects these automatically. +- `attachments` (string[], optional) — list of `@path` strings to + prepend to the content. The webui populates this from the attachment + UI; you usually don't pass it directly. +- `isAskAnswer` (bool, optional) — when `true`, the content is the + answer to an active `ask_user` question. Set by the ask modal + automatically. + +**Response 200** `{ok: true}` immediately. The actual response is +streamed via `/api/events`. + +**Errors** +- 409 if `state.running.active === true` (already running) +- 400 if `content` is empty + +### `POST /api/stop` + +Cancel the current run. Best-effort: tries `session/cancel` via acp +(unimplemented in 0.1.5), then SIGTERM, then SIGKILL after 2s. + +**Request** `{}` + +**Response 200** `{ok: true}` + +### `POST /api/cmd` + +Send a raw slash command (e.g. `/compact`, `/clear`). The server sends +the command to Mcode and streams the result. + +**Request** +```json +{ "cmd": "/compact" } +``` + +**Response 200** `{ok: true}` + +--- + +## Sessions + +### `GET /api/sessions` + +List webui sessions + mcode sessions (merged, deduplicated). + +**Response 200** +```json +{ + "ok": true, + "count": 12, + "sessions": [ + { "id": "uuid", "title": "…", "workspace": "C:\\…", "mcodeSessionId": "mvs_…", "updatedAt": 1234567890 } + ] +} +``` + +### `POST /api/sessions` + +Create a new webui session. Optionally tied to a workspace. + +**Request** +```json +{ "workspace": "C:\\path\\to\\project" } +``` + +**Response 200** `{ok: true, id: "uuid"}` + +### `POST /api/sessions/switch` + +Switch to an existing session. Loads its chat history and (if linked) +re-attaches to the Mcode session. + +**Request** +```json +{ "id": "uuid" } +``` + +**Response 200** `{ok: true}` + +### `POST /api/sessions/cleanup-orphans` + +Delete mcode sessions that no webui session references. Two scopes: + +- `scope: "orphans"` (default) — only delete mcode sessions with no + webui reference. The currently-active session is always preserved. +- `scope: "all"` — delete every mcode session, then re-link webui + sessions that had a `mcodeSessionId` (which now points to a deleted + session — they become "webui-only" again). + +**Request** +```json +{ "scope": "orphans" } +``` + +**Response 200** +```json +{ + "ok": true, + "scope": "orphans", + "total": 37, + "targets": 18, + "deleted": 18, + "failed": 0, + "log": ["deleted mvs_5103ca…", "deleted mvs_88c796…", …] +} +``` + +### `DELETE /api/sessions/:id` + +Delete a webui session AND its linked mcode session (if any). The mcode +deletion is a transaction across 8 sqlite tables. + +**Response 200** `{ok: true}` + +### `GET /api/acp-sessions` + +Raw mcode session list (from sqlite). No webui merge. + +**Response 200** `{ok: true, sessions: [...]}` + +### `GET /api/acp-session-title?sessionId=mvs_…` + +Get the title of an mcode session. + +**Response 200** `{ok: true, title: "…"}` + +--- + +## Workspace + +### `POST /api/workspace` + +Change the workspace for the current CID. + +**Request** +```json +{ + "dir": "C:\\path\\to\\project", + "syncTui": true +} +``` + +- `dir` (string, required) — absolute path +- `syncTui` (bool, optional) — also write the path to `cwd.json` so the + mcode TUI sees it +- `action: "detect"` — instead of changing, return the current TUI cwd +- `action: "useTui"` — copy the TUI's cwd to webui +- `action: "reset"` — restore webui's default workspace + +**Response 200** `{ok: true, dir: "…", branch: "main", treeState: "clean"}` + +### `GET /api/workspace/browse?path=…` + +List a directory for the tree browser. + +**Request** query: `?path=C:\\Users` (omit for drive roots on Windows +or `/` for Linux) + +**Response 200** +```json +{ + "ok": true, + "path": "C:\\Users", + "children": [ + { "name": "Public", "path": "C:\\Users\\Public", "isDir": true } + ] +} +``` + +When `path` is omitted: +- Windows: `roots: ["C:", "D:", …]` +- Linux: `children: [{name: "/", path: "/", isDir: true}]` + +--- + +## Settings + +### `GET /api/settings` + +Returns the full settings snapshot. **This endpoint is exempt from +the LAN guard** — it's how a remote user toggles LAN back on after +locking themselves out. + +**Response 200** +```json +{ + "ok": true, + "lanBroadcast": true, + "port": 8080, + "host": "0.0.0.0", + "lanIp": "192.168.1.50", + "lanUrl": "http://192.168.1.50:8080", + "localUrl": "http://127.0.0.1:8080", + "mcodeCmd": "C:\\…\\mcode.cmd", + "mcodeVersion": "0.1.2", + "defaultWorkspace": "C:\\…", + "defaultModel": "minimax_api/MiniMax-M3" +} +``` + +### `POST /api/settings` + +Update one or more settings. Only `lanBroadcast` is currently settable. + +**Request** +```json +{ "lanBroadcast": false } +``` + +**Response 200** `{ok: true, lanBroadcast: false, …}` + +--- + +## Upload + +### `POST /api/upload` + +Multipart file upload. Saves to `MCODE_WEBUI_UPLOAD_DIR` and returns +the absolute path. + +**Request** `multipart/form-data` with a `file` field. + +**Response 200** +```json +{ + "ok": true, + "filename": "screenshot.png", + "path": "C:\\…\\.webui-uploads\\screenshot.png", + "size": 12345, + "mime": "image/png" +} +``` + +--- + +## Model + +### `GET /api/models` + +Returns the builtin + currently-configured model list. + +**Response 200** +```json +{ + "ok": true, + "current": "minimax_api/MiniMax-M3", + "models": [ + { "id": "minimax_api/MiniMax-M3", "label": "MiniMax-M3", "provider": "minimax_api" } + ] +} +``` + +If the list is empty, the response includes a `hint` field pointing +the user at the Mcode TUI for model configuration. + +### `POST /api/set-model` + +Change the model for the current CID. + +**Request** +```json +{ "model": "minimax_api/MiniMax-M3" } +``` + +**Response 200** `{ok: true, model: "…"}` + +### `POST /api/permissions` + +Change the session-level permission mode. + +**Request** +```json +{ "permissions": "ask" } +``` + +- `permissions` (string) — one of `ask`, `auto`, `full`, `plan` + +**Response 200** `{ok: true, permissions: "ask"}` + +> Note: mcode 0.1.5 acp does not implement `session/set_mode`. The +> webui's UI shows the mode the user selected, but the underlying mcode +> session does not change. This is logged in the server console as +> `[mcode-rpc] UNSUPPORTED session/set_mode`. Will start working when +> mcode implements the method. + +### `GET /api/permissions-modes` + +List the available permission modes. + +**Response 200** `{ok: true, modes: ["default", "bypassPermissions", "auto", "off", "read", "full"]}` + +### `POST /api/answer` + +Respond to an active permission / plan / ask_user prompt. + +**Request** +```json +{ "type": "permission", "option": "ask" } +``` + +- `type` (string) — `permission` | `plan` | `planmode` | `ask` +- `option` (string) — depends on type: + - `permission`: `ask` | `auto` | `full` + - `plan`: `agree` | `skip` | `add` + - `planmode`: `continue` | `deny` + - `ask`: `esc` (skip) | `` (option) | `` (free-form) + +**Response 200** `{ok: true}` + +--- + +## Usage + +### `GET /api/usage` and `POST /api/usage` and `POST /api/usage-trigger` + +Fetch the current `mmx quota show` snapshot. `POST /api/usage-trigger` +also triggers a fresh fetch from the CLI. `GET /api/usage` and +`POST /api/usage` return the cached value if recent. + +**Response 200** +```json +{ + "ok": true, + "remaining": 91, + "resetAt": 1234567890, + "weeklyResetAt": 1234567890, + "fetchedAt": 1234567890, + "source": "mmx" +} +``` + +### `GET /api/usage-real` + +Fetch per-turn context usage from the `mavis` runtime db. This is the +source of truth for "已用 N / 占比 N%" in the right panel. + +**Response 200** +```json +{ + "ok": true, + "lastTurnContextTokens": 12345, + "lastInputTokens": 1000, + "lastCacheReadTokens": 500, + "lastCacheWriteTokens": 200, + "lastOutputTokens": 800, + "contextLimit": 524288, + "model": "MiniMax-M3", + "ts": 1234567890 +} +``` + +### `POST /api/refresh` + +Re-fetch quota + per-turn context. The webui calls this when the user +clicks the "刷新" button in the usage popover. + +**Response 200** `{ok: true}` + +--- + +## Protocol (acp shim) + +These endpoints wrap the acp protocol methods that the webui *can* +call. Methods that mcode 0.1.5 doesn't implement return 501 with +`{code: 'unsupported'}`. + +### `POST /api/protocol/set-mode` + +Calls `session/set_mode`. **Currently returns 501** (mcode 0.1.5). + +### `POST /api/protocol/set-config-option` + +Calls `session/set_config_option`. **Currently returns 501**. + +### `POST /api/protocol/cancel` + +Calls `session/cancel`. **Currently returns 501** (falls back to +SIGTERM on the subprocess). + +### `POST /api/protocol/load-session` + +Calls `session/load`. Works in 0.1.5. + +**Request** `{sessionId: "mvs_…", cwd: "C:\\…"}` + +### `POST /api/protocol/activate-session` + +Calls `session/activate`. **Currently returns 501**. + +### `GET /api/protocol/list-sessions` + +Calls `session/list`. Works in 0.1.5. + +### `GET /api/protocol/capabilities` + +Returns the list of acp methods the webui knows about and their +support status. Used by the webui to decide which UI controls to +enable. + +**Response 200** +```json +{ + "ok": true, + "agentInfo": { "name": "mcode", "title": "mcode", "version": "0.1.5" }, + "supported": ["session/new", "session/list", "session/load", "session/prompt", "session/close"], + "unsupported": ["session/set_mode", "session/set_config_option", "session/cancel", …] +} +``` + +--- + +## Debug (gated) + +### `POST /api/debug/inject` + +Inject a fake event into the SSE channel for a CID. Used for testing +the UI without a real Mcode subprocess. + +**Request** +```json +{ "cid": "uuid", "type": "delta", "text": "hello" } +``` + +**Response 200** `{ok: true}` + +**Gating**: this endpoint only works if `DEBUG_INJECT=1` is set in the +server's environment. The server logs a warning every time it's +called. Production deployments should leave the env unset. + +### `GET /api/debug/state` + +Returns the full per-cid state including internal flags. Same +`DEBUG_INJECT` gating. + +--- + +## Static + +### `GET /` + +Returns `public/index.html`. + +### `GET /` + +Returns the file from `public/` if it exists. Served by `serveStatic`. +Cache headers: `public, max-age=3600`. The HTML/JS/CSS paths +embed a `?v=N` cache-bust query string; bump it in `index.html` when +you want clients to refetch. + +--- + +## Error responses + +All errors follow one of these shapes: + +```json +{ "ok": false, "error": "human-readable message" } +``` + +```json +{ "ok": false, "code": "unsupported", "error": "mcode 0.1.5 acp does not implement session/set_mode" } +``` + +```json +{ "ok": false, "error": "LAN 访问已关闭。在本机打开设置开启。" } +``` + +The HTTP status is appropriate to the cause (400 / 401 / 403 / 404 / 409 / 500 / 501). diff --git a/plugins/Wzdhehe/mcode-webui/docs/ARCHITECTURE.md b/plugins/Wzdhehe/mcode-webui/docs/ARCHITECTURE.md new file mode 100644 index 0000000..2f3e66a --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/docs/ARCHITECTURE.md @@ -0,0 +1,383 @@ +# Architecture + +> Companion to [README.md](../README.md). This document is for people +> modifying the webui or integrating with it. It describes the runtime +> topology, the module boundaries, the request lifecycle, and the SSE +> payload contract. + +## 1. High-level topology + +``` + ┌─────────────────────────────────────────────┐ + │ Browser (public/) │ + │ • index.html (markup) │ + │ • app/main.js (ES module) │ + │ • styles/main.css │ + └─────────────────────────────────────────────┘ + │ ▲ │ ▲ + fetch / JSON │ │ EventSource / SSE │ │ + ▼ │ ▼ │ + ┌──────────────────────────────────────────────────────────────────────┐ + │ server.js — bootstrap only (≈ 100 lines) │ + │ • installGlobalErrorHandlers() │ + │ • preflight: mcode.cmd exists, upload dir writable, etc. │ + │ • http.createServer(handleRequest) │ + └──────────────────────────────────────────────────────────────────────┘ + │ + ▼ + ┌──────────────────────────────────────────────────────────────────────┐ + │ server/router.js — declarative route table │ + │ │ + │ LAN guard: !isLocalRequest(req) && !getLanBroadcast() → 403 │ + │ │ + │ ┌─ static ┐ ┌─ /api/health ┐ ┌─ /api/state ┐ ┌─ /api/sessions ┐ │ + │ │ index │ │ health.js │ │ state.js │ │ sessions.js │ │ + │ │ .html │ └───────────────┘ │ + /api/events│ │ + acp- │ │ + │ │ .css/js │ │ (SSE) │ │ sessions/* │ │ + │ │ .png │ └──────────────┘ └────────────────┘ │ + │ └─────────┘ │ + │ ┌─ /api/send ┐ ┌─ /api/usage ┐ ┌─ /api/workspace ┐ │ + │ │ chat.js │ │ usage.js │ │ workspace.js │ │ + │ │ + /stop /cmd │ │ + -real │ │ + /workspace/ │ │ + │ │ │ │ + /refresh │ │ browse │ │ + │ └──────────────┘ └──────────────┘ └──────────────────┘ │ + │ ┌─ /api/upload ┐ ┌─ /api/settings ┐ ┌─ /api/models ┐ │ + │ │ upload.js │ │ settings.js │ │ model.js │ │ + │ └──────────────┘ └─────────────────┘ │ + /set-model │ │ + │ │ + /permissions │ │ + │ │ + /answer │ │ + │ └──────────────────┘ │ + │ ┌─ /api/protocol/* ┐ ┌─ /api/debug/* ┐ │ + │ │ protocol.js │ │ debug.js │ │ + │ │ /set-mode │ │ /inject (gated)│ │ + │ │ /set-config-option│ │ /state │ │ + │ │ /cancel │ └────────────────┘ │ + │ │ /load-session … │ │ + │ │ /capabilities │ │ + │ └───────────────────┘ │ + └──────────────────────────────────────────────────────────────────────┘ + │ + ▼ + ┌──────────────────────────────────────────────────────────────────────┐ + │ server/lib/ — pure modules (one concern each) │ + │ │ + │ config · lan · models · db · sessions │ + │ state-bus · acp-client · mcode-rpc · mcode-acp · mcode-exec │ + │ mavis-usage · usage · settings · upload · workspace · slash │ + └──────────────────────────────────────────────────────────────────────┘ + │ ▲ + ▼ │ JSON-RPC over stdio + ┌──────────────────────────────────────┐ ┌─────────────────────────────┐ + │ mcode exec subprocess │ │ mcode acp subprocess │ + │ (legacy single-turn, fallback) │ │ (default multi-turn) │ + │ stdio: line-delimited stream-json │ │ stdio: newline-delimited │ + │ │ │ JSON-RPC 2.0 │ + └──────────────────────────────────────┘ └─────────────────────────────┘ +``` + +## 2. Request lifecycle + +A user clicks **Send**. The events that follow: + +``` +browser server/router.js server/lib/* mcode + │ POST /api/send {content,…} │ │ + │ ──────────────────────────────►│ │ + │ │ chat.js: validate, │ + │ │ cs = getClient(cid) │ + │ │ cid → state-bus │ + │ │ ─────────────────► │ + │ │ │ mcode-acp.js / mcode-exec.js + │ │ │ ─── spawn / pipe stdin ───► + │ │ │ + │ │ state-bus: pushStateFor(cid) │ + │ ◄──────────── SSE event ────│ {type:'state', running:…} │ + │ {type:'chat', lines:[…]} │ │ + │ ◄──────────── SSE event ────│ ◄── line ◄─── stdout ────│ + │ {type:'delta', text:'…'} │ │ + │ … │ │ + │ ◄──────────── SSE event ────│ ◄── exec.result ──────────│ + │ {type:'exec', status:'ok'} │ │ + │ ◄──────────── SSE event ────│ │ + │ {type:'state', running:false}│ │ + │ … │ │ + │ connection closes / kept open │ │ +``` + +Key invariants: + +- **One `mcode` subprocess per active webui tab** (keyed by `cid` = + client id, a UUID stored in `localStorage.webui_cid`). A new tab gets a new + subprocess; a closed tab kills its subprocess. State is per-cid, not + per-connection. +- **The SSE channel is the only source of state updates** for the client. + REST endpoints mutate server state but do not push to the client. The + client treats SSE as truth. +- **`pushStateFor(cid, opts)` is the only function that mutates per-cid + state on the server.** Everything else is read-only. This is why + `state-bus.js` is the size it is — it's the single chokepoint. + +## 3. Module contracts + +Each `server/lib/*.js` file exports a small set of named functions. No +file reaches into another's internals. The notable contracts: + +### `config.js` +- Exports frozen-ish constants: `PORT`, `HOST`, `MCODE_ROOT`, `MCODE_CMD`, + `DEFAULT_MODEL`, `DEFAULT_WORKSPACE`, `DEFAULT_TIMEOUT`, + `MCODE_RUNTIME_DB`, `MAVIS_DB_PATH`. +- Reads `process.env.*` exactly once at module load. No per-request + re-reading. +- `installGlobalErrorHandlers()` writes uncaught exceptions to + `.server.err` so they survive a process restart. + +### `state-bus.js` +The chokepoint. Exports: + +| Function | Purpose | +|---|---| +| `getClient(cid)` | Returns the `clientState` object: `state`, `sse`, `activeChild`, `chatHistory`, `requestSeq`. Lazily creates on first call. | +| `pushStateFor(cid, opts)` | Build a normalized `state` object and write it to `clientState.state`. Broadcasts to the SSE channel unless `opts.silent`. | +| `pushEvent(cid, event)` | Append an arbitrary event to the SSE channel (`{type, …}`). | +| `pushOnlineCount(lanBroadcast)` | Count `sseByCid.size` and broadcast to all clients. Called on connect/disconnect. | +| `SSE_HEADERS` | Standard headers: `Content-Type: text/event-stream`, `Cache-Control: no-cache`, `Connection: keep-alive`, `X-Accel-Buffering: no`. | + +The `state` payload is documented in § 5 below. The `clientState.state` +object is the **only** thing the rest of the codebase reads from. + +### `acp-client.js` +Wraps Mcode's JSON-RPC-over-stdio protocol. Exports: + +- `McodeAcpClient` class — `start()`, `request(method, params)`, + `notify(method, params)`, `stop()`, `events` EventEmitter. +- `getMcodeAcpClient()` — process-wide singleton. Init is + `pInitPromise` de-duplicated so concurrent `start()` callers share a + single subprocess. +- Cache: `mcodeCommandsCache` and `mcodeSessionsCache` avoid + repeated JSON-RPC round-trips for `session/list` and + `session/commands`. + +### `mcode-rpc.js` +The shim for methods mcode 0.1.5 does not implement: + +```js +const UNSUPPORTED = new Set([ + 'session/set_mode', + 'session/set_config_option', + 'session/cancel', + 'session/activate', 'session/fork', 'session/resume', 'session/delete', + 'session/request_permission', 'session/subscribe', +]) +``` + +`callRpc(method, params)` returns +`{ok:false, code:'unsupported', error:'…'}` synchronously when the +method is unsupported. The caller decides what to do — usually a toast +on the client. + +### `mcode-acp.js` vs `mcode-exec.js` +Two transports with a shared shape. The transport layer is selected +by `mcode-rpc.js` based on `Mcode version >= 0.1.4` and the per-request +`/exec` opt-in. + +Both expose: +- `runMcode(content, opts)` → `AsyncGenerator` +- `stopExec()` → `void` +- `isRunning()` → `boolean` + +`NormalizedEvent` is a tagged union (`{type, …}`) with these types: +`state`, `chat`, `delta`, `tool`, `permission`, `plan`, `ask`, +`exec`, `usage`. See § 5. + +## 4. The `clientState.state` payload + +This is the shape every SSE `state` event contains. The webui mirrors +it 1:1 into the `state` JS variable. + +```ts +{ + version: string, // webui version (from package.json) + running: { active: boolean, + sessionId?: string, // mcode acp session id (if any) + cid: string, // webui tab id + startTime?: number, // ms epoch + pendingPermission?: object, + pendingPlan?: object, + pendingAsk?: object }, + workspace: { dir: string, // absolute path, "" if unset + branch?: string, // git branch (best-effort, "" on error) + treeState?: 'clean'|'dirty'|'unknown' }, + model: { name: string, // e.g. "minimax_api/MiniMax-M3" + ctx: string, // e.g. "512k" + thinking: 'On'|'Off'|string }, + permissions: string, // Mcode-side: 'ask'|'auto'|'full'|'plan'|... + commands: Array<{ // mcode slash commands + cmd: string, zh: string, en: string, + description_zh?: string, description_en?: string, + hint?: string, + input_hint?: string, + destructive?: boolean }>, + sessions: Array<{ // webui-side session list (merged w/ mcode) + id: string, + title: string, + workspace: string, + mcodeSessionId?: string, // linked mcode session id + updatedAt: number }>, + mcodeSessions: Array<{ // Mcode-side session list (raw) + sessionId: string, + title: string, + cwd: string, + updatedAt: number }>, + mcodeSessionId?: string, // currently-active mcode session + context?: { // updated by SSE delta accumulation + used: number, // tokens used (per-turn) + percent: number, // 0..100 + cacheRead: number, // per-turn cache reads + tps: number, // current tok/s + source: 'mavis'|'mmx' }, // which backend provided the data + usage?: { // from /api/usage + remaining: number, // percent + resetAt: number, // ms epoch + weeklyResetAt: number, + fetchedAt: number }, + plan?: { active: boolean, title: string, summary: string, + options: Array<{label:string}>, totalLines: number, + summaryLines: number }, + enterPlanMode?: { active: boolean }, + permissionChoice?: { active: boolean, current: string, + options: Array<{label:string}> }, + askUser?: { active: boolean, questions: Array<…> }, + goal?: { active: boolean, text: string, status: 'running'|'done'|'blocked', + duration?: number }, + todo?: Array<{ content: string, status: 'pending'|'in_progress'|'done' }>, + lanBroadcast: boolean, // mirrors /api/settings + onlineCount: number // from pushOnlineCount +} +``` + +The webui **does not** hold additional state outside this object. Any UI +panel that needs data reads it from `state` and reacts to `state` +changes via `render()`. + +## 5. SSE event schema + +``` +event: state +data: {"version":"0.1.3","running":{"active":true,…},…} + +event: chat +data: {"lines":[{"role":"user","content":"…"}]} + +event: delta +data: {"sessionId":"mvs_…","text":"hello","isPartial":true} + +event: tool +data: {"name":"Bash","input":{…},"output":"…","status":"ok"|"err"|"running"} + +event: permission +data: {"id":"perm_…","tool":"Bash","input":{…},"options":["ask","auto","full"]} + +event: plan +data: {"title":"…","summary":"…","options":[…],"totalLines":N,"summaryLines":N} + +event: ask +data: {"questions":[{"header":"…","question":"…","options":[…], "multiSelect":false}]} + +event: exec +data: {"status":"ok"|"err"|"aborted","durationMs":N,"errorMessage"?:string} + +event: usage +data: {"remaining":N,"resetAt":N,…} + +event: online +data: {"count":N,"lanBroadcast":true} +``` + +The webui treats each event as an idempotent update; replaying the +same event is safe. The server uses an at-most-once delivery model +(SSE drops on disconnect → no retry), which the client handles by +fetching `/api/state` on reconnect. + +## 6. Frontend topology + +``` +public/index.html (markup only, no inline + + + + + + + + + + + +
+ + + + + + + diff --git a/plugins/Wzdhehe/mcode-webui/public/lib/marked.min.js b/plugins/Wzdhehe/mcode-webui/public/lib/marked.min.js new file mode 100644 index 0000000..a91afe7 --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/public/lib/marked.min.js @@ -0,0 +1,6 @@ +/** + * marked v12.0.2 - a markdown parser + * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed) + * https://github.com/markedjs/marked + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&","<":"<",">":">",'"':""","'":"'"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const u=/(^|[^\[])\^/g;function k(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(u,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function g(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const f={exec:()=>null};function d(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:x(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=x(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=t[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,"\n $1");e=x(e.replace(/^ *>[ \t]?/gm,""),"\n");const n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=d(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(const e of n)i.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of r)i.rows.push(d(e,i.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^$/.test(e))return;const t=x(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^$/.test(e)?n.slice(1):n.slice(1,-1)),b(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return b(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const m=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,$=k(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,y).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),z=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,T=/(?!\s*\])(?:\\.|[^\[\]\\])+/,R=k(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",T).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),A="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",S=/|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",S).replace("tag",A).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),E=k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),q={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",E).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:R,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:m,html:I,lheading:$,list:_,newline:/^(?: *(?:\n|$))+/,paragraph:E,table:f,text:/^[^\n]+/},Z=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),L={...q,table:Z,paragraph:k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Z).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",S).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(z).replace("hr",m).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,B="\\p{P}\\p{S}",C=k(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,B).getRegex(),M=k(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,B).getRegex(),O=k("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,B).getRegex(),D=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,B).getRegex(),j=k(/\\([punct])/,"gu").replace(/punct/g,B).getRegex(),H=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),U=k(S).replace("(?:--\x3e|$)","--\x3e").getRegex(),X=k("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",U).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,N=k(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G=k(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",T).getRegex(),J=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",T).getRegex(),K={_backpedal:f,anyPunctuation:j,autolink:H,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:f,emStrongLDelim:M,emStrongRDelimAst:O,emStrongRDelimUnd:D,escape:Q,link:N,nolink:J,punctuation:C,reflink:G,reflinkSearch:k("reflink|nolink(?!\\()","g").replace("reflink",G).replace("nolink",J).getRegex(),tag:X,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class se{options;constructor(t){this.options=t||e.defaults}code(e,t,n){const s=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",s?'
'+(n?e:c(e,!0))+"
\n":"
"+(n?e:c(e,!0))+"
\n"}blockquote(e){return`
\n${e}
\n`}html(e,t){return e}heading(e,t,n){return`${e}\n`}hr(){return"
\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"\n"}listitem(e,t,n){return`
  • ${e}
  • \n`}checkbox(e){return"'}paragraph(e){return`

    ${e}

    \n`}table(e,t){return t&&(t=`${t}`),"\n\n"+e+"\n"+t+"
    \n"}tablerow(e){return`\n${e}\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`\n`}strong(e){return`${e}`}em(e){return`${e}`}codespan(e){return`${e}`}br(){return"
    "}del(e){return`${e}`}link(e,t,n){const s=g(e);if(null===s)return n;let r='
    ",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`${n}0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parse(n.tokens,i),l+=this.renderer.listitem(o,r,!!s)}n+=this.renderer.list(l,t,s);continue}case"html":{const e=r;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=r;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let i=r,l=i.tokens?this.parseInline(i.tokens):i.text;for(;s+1{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new se(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new w(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];le.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#t(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#t(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="

    An error occurred:

    "+c(n.message+"",!0)+"
    ";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const ae=new oe;function ce(e,t){return ae.parse(e,t)}ce.options=ce.setOptions=function(e){return ae.setOptions(e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.getDefaults=t,ce.defaults=e.defaults,ce.use=function(...e){return ae.use(...e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.walkTokens=function(e,t){return ae.walkTokens(e,t)},ce.parseInline=ae.parseInline,ce.Parser=ie,ce.parser=ie.parse,ce.Renderer=se,ce.TextRenderer=re,ce.Lexer=ne,ce.lexer=ne.lex,ce.Tokenizer=w,ce.Hooks=le,ce.parse=ce;const he=ce.options,pe=ce.setOptions,ue=ce.use,ke=ce.walkTokens,ge=ce.parseInline,fe=ce,de=ie.parse,xe=ne.lex;e.Hooks=le,e.Lexer=ne,e.Marked=oe,e.Parser=ie,e.Renderer=se,e.TextRenderer=re,e.Tokenizer=w,e.getDefaults=t,e.lexer=xe,e.marked=ce,e.options=he,e.parse=fe,e.parseInline=ge,e.parser=de,e.setOptions=pe,e.use=ue,e.walkTokens=ke})); diff --git a/plugins/Wzdhehe/mcode-webui/public/styles/main.css b/plugins/Wzdhehe/mcode-webui/public/styles/main.css new file mode 100644 index 0000000..8cf24f0 --- /dev/null +++ b/plugins/Wzdhehe/mcode-webui/public/styles/main.css @@ -0,0 +1,2866 @@ +/* ============================================================ + 主题变量 — v3 "Ink & Paper"(墨与纸) + 纯黑白灰单色配色:中性表面 + 白/黑 accent + 器物感细节。 + 语义色降饱和(success/warning 灰阶,danger 保留哑红用于报错)。 + --on-accent: accent 背景上的反色文字(深色主题=墨黑,浅色主题=纸白)。 + ============================================================ */ +/* v0.5.bh: 首次加载无 data-theme 时跟随系统 — 避免 light 闪一下 */ +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #0b0b0c; + --bg-elevated: #141416; + --bg-sidebar: #101012; + --bg-hover: #1c1c1f; + --bg-active: #26262a; + --bg-input: #131315; + --text: #ececee; + --text-secondary: #a2a2a8; + --text-tertiary: #6d6d74; + --border: #26262a; + --border-light: #1d1d20; + --accent: #f4f4f5; + --accent-hover: #ffffff; + --accent-bg: rgba(244, 244, 245, 0.10); + --accent-text: #e4e4e7; + --on-accent: #101012; + --success: #9d9da3; + --warning: #c8c8cd; + --danger: #cc6b5c; + --status-on: #3fbf7f; /* v3: 功能性"开启"状态绿 (LAN 图标等), 单色主题下唯一保留的语义绿 */ + --shadow-sm: 0 1px 2px rgba(0,0,0,0.35); + --shadow-md: 0 4px 10px rgba(0,0,0,0.42); + --shadow-lg: 0 12px 32px rgba(0,0,0,0.55); + --user-accent: #f4f4f5; + /* v2 新增 */ + --accent-glow: rgba(244, 244, 245, 0.12); + --hairline: rgba(236, 236, 238, 0.08); + --font-mono: ui-monospace, "Cascadia Code", Consolas, "SFMono-Regular", Menlo, monospace; + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; + } +} +:root[data-theme="light"] { + --bg: #fafafa; + --bg-elevated: #ffffff; + --bg-sidebar: #f4f4f5; + --bg-hover: #ededee; + --bg-active: #e2e2e4; + --bg-input: #ffffff; + --text: #1a1a1c; + --text-secondary: #5f5f66; + --text-tertiary: #98989e; + --border: #e2e2e4; + --border-light: #ededee; + --accent: #17171a; + --accent-hover: #000000; + --accent-bg: #ededee; + --accent-text: #2a2a2e; + --on-accent: #ffffff; + --success: #75757c; + --warning: #4f4f56; + --danger: #bf5645; + --status-on: #1e9e5a; /* v3: 功能性"开启"状态绿 */ + --shadow-sm: 0 1px 2px rgba(0,0,0,0.05); + --shadow: 0 4px 14px rgba(0,0,0,0.09); + --shadow-lg: 0 14px 38px rgba(0,0,0,0.14); + --user-accent: #17171a; + /* v2 新增 */ + --accent-glow: rgba(23, 23, 26, 0.10); + --hairline: rgba(26, 26, 28, 0.08); + --font-mono: ui-monospace, "Cascadia Code", Consolas, "SFMono-Regular", Menlo, monospace; + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; +} +:root[data-theme="dark"] { + --bg: #0b0b0c; + --bg-elevated: #141416; + --bg-sidebar: #101012; + --bg-hover: #1c1c1f; + --bg-active: #26262a; + --bg-input: #131315; + --text: #ececee; + --text-secondary: #a2a2a8; + --text-tertiary: #6d6d74; + --border: #26262a; + --border-light: #1d1d20; + --accent: #f4f4f5; + --accent-hover: #ffffff; + --accent-bg: rgba(244, 244, 245, 0.10); + --accent-text: #e4e4e7; + --on-accent: #101012; + --success: #9d9da3; + --warning: #c8c8cd; + --danger: #cc6b5c; + --status-on: #3fbf7f; /* v3: 功能性"开启"状态绿 (LAN 图标等), 单色主题下唯一保留的语义绿 */ + --shadow-sm: 0 1px 2px rgba(0,0,0,0.35); + --shadow: 0 4px 14px rgba(0,0,0,0.45); + --shadow-lg: 0 14px 38px rgba(0,0,0,0.55); + --user-accent: #f4f4f5; + /* v2 新增 */ + --accent-glow: rgba(244, 244, 245, 0.12); + --hairline: rgba(236, 236, 238, 0.08); + --font-mono: ui-monospace, "Cascadia Code", Consolas, "SFMono-Regular", Menlo, monospace; + --radius-sm: 6px; + --radius-md: 10px; + --radius-lg: 14px; +} + +/* ============================================================ + Reset + ============================================================ */ +*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } +html, body { height: 100%; overflow: hidden; } +body { + font-family: "Segoe UI Variable Text", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; + font-size: 14px; + line-height: 1.55; + color: var(--text); + background: + radial-gradient(1200px 500px at 70% -10%, var(--accent-glow), transparent 60%), + var(--bg); + background-attachment: fixed; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + transition: background 0.25s, color 0.2s; +} +button { font: inherit; color: inherit; background: none; border: none; cursor: pointer; padding: 0; text-align: left; } +button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: var(--radius-sm); } +input, textarea { font: inherit; color: inherit; } +input:focus, textarea:focus { outline: none; } +a { color: var(--accent); text-decoration: none; } +::selection { background: var(--accent-bg); color: var(--accent-text); } +::-webkit-scrollbar { width: 6px; height: 6px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px; } +::-webkit-scrollbar-thumb:hover { background: var(--text-tertiary); } +[hidden] { display: none !important; } + +/* ============================================================ + App layout + ============================================================ */ +.app { + display: grid; + grid-template-rows: auto 1fr; + height: 100vh; + position: relative; +} +.topbar { + height: 44px; + border-bottom: 1px solid var(--border); + background: var(--bg-elevated); + display: flex; + align-items: center; + padding: 0 16px; + gap: 12px; + z-index: 10; +} +.topbar-brand { + display: flex; + align-items: center; + gap: 8px; + font-weight: 600; + font-size: 15px; +} +.topbar-logo { + width: 24px; height: 24px; + display: block; + flex-shrink: 0; + cursor: pointer; /* v0.5.bx-15: 双击可重置 ask_user 弹窗 */ + border-radius: 6px; + transition: opacity 0.15s, transform 0.15s; +} +.topbar-logo:hover { opacity: 0.85; } +.topbar-logo:active { transform: scale(0.95); } + border-radius: 6px; + overflow: hidden; +} +.topbar-version { + font-size: 11px; + color: var(--text-tertiary); + background: var(--bg-hover); + padding: 2px 6px; + border-radius: 4px; + margin-left: -2px; +} +/* v0.5.bx-37: BETA 标识 — v3 单色化: 跟随 accent (premium.css 有皮肤层覆盖) */ +.topbar-beta { + font-size: 10px; + font-weight: 700; + color: var(--on-accent); + background: var(--accent); + padding: 2px 6px; + border-radius: 4px; + letter-spacing: 0.5px; + margin-left: 2px; + user-select: none; +} +.topbar-status { + margin-left: auto; + display: flex; + gap: 8px; + font-size: 12px; + color: var(--text-secondary); +} +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + background: var(--bg-hover); + border-radius: 999px; + font-size: 12px; + color: var(--text-secondary); +} +/* v0.5.bp: 局域网访问链接 chip — 用
    渲染所以继承 cursor:pointer + 去掉下划线;hover 加背景色表示可点 */ +a.chip-lan-link { + text-decoration: none; + cursor: pointer; + color: var(--accent); + border: 1px solid color-mix(in srgb, var(--accent) 30%, transparent); + transition: background-color 0.15s, border-color 0.15s; +} +a.chip-lan-link:hover { + background: color-mix(in srgb, var(--accent) 12%, var(--bg-hover)); + border-color: color-mix(in srgb, var(--accent) 60%, transparent); +} +/* v0.5.bx-37: 强制刷新按钮 — 手机/平板浏览器 hard refresh 麻烦, 一键绕过 HTTP cache */ +button.chip-force-reload { + cursor: pointer; + color: var(--text-secondary); + border: 1px solid var(--border); + background: var(--bg-sidebar); + font: inherit; + display: inline-flex; + align-items: center; + gap: 4px; + padding: 3px 8px; + border-radius: 12px; + font-size: 11px; + transition: all 0.15s; +} +button.chip-force-reload:hover { + background: var(--bg-hover); + border-color: var(--accent); + color: var(--accent); +} +button.chip-force-reload:disabled { + opacity: 0.5; + cursor: wait; +} +button.chip-force-reload.loading svg { + animation: force-reload-spin 0.8s linear infinite; +} +button.chip-force-reload .icon { + width: 12px; + height: 12px; + flex-shrink: 0; +} +@keyframes force-reload-spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} +a.chip-lan-link .icon { + width: 12px; + height: 12px; + flex-shrink: 0; +} +.chip-dot { + width: 6px; height: 6px; border-radius: 50%; + background: var(--text-tertiary); +} +.chip[data-status="running"] .chip-dot { background: var(--accent); animation: pulse 1.5s infinite; } +.chip[data-status="loading"] .chip-dot { background: var(--warning); animation: pulse 1s infinite; } +.chip[data-status="completed"] .chip-dot { background: var(--success); } +.chip[data-status="error"] .chip-dot { background: var(--danger); } +.chip[data-status="offline"] .chip-dot { background: var(--text-tertiary); } +@keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.4; } +} + +/* v0.5.al: chip-workspace — 顶栏可点击切换工作区(用