diff --git a/README.md b/README.md index 7e9a54de..0e543f77 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,7 @@ The MiniMax Code Agent communicates through the host MCP client. Business reques | [Express Media](plugins/andre-1998/express-media/) | Compress a video to the size each platform accepts and report whether it fits; the bundled limits table shows where every number comes from | [Andre-1998](https://github.com/Andre-1998) | | [FactScribe Paper Workbench](plugins/unclemoc/factscribe/) | A local workbench for writing papers: open your manuscript projects, read the check report, the fact ledger and the knowledge base, and let the assistant propose edits you approve before anything reaches the file. 17 MCP tools, read-mostly by design; every write is gated by your confirmation. Requires MiniMax Code 3.1.2 or later | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) | | [GitHub Star Shelf](plugins/start3208/github-star-shelf/) | Turn your GitHub stars into collections you can search and ask the AI to explain in plain language: from the README alone, or after it has read a shallow clone of the code. One session per project, your own notes, and collections the Agent can arrange | [start3208](https://github.com/start3208) | +| [Plugin Listing Workbench](plugins/zhuyankarl/submission-workbench/) | Prepare a plugin submission: fill in the manifest and listing fields, check every required field and cross-file consistency, then download a reviewable listing package that names what is missing; a bundled Skill gives the Agent the same checklist | [zhuyankarl](https://github.com/zhuyankarl) |
Preview: Cutline diff --git a/README.zh-CN.md b/README.zh-CN.md index f45914a5..e3c9a776 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -95,6 +95,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 | [急件 · 视频投递](plugins/andre-1998/express-media/README.zh-CN.md) | 把视频压到各平台能收的体积,并如实告诉你发不发得出去;内置上限表标明每个数字的来源 | [Andre-1998](https://github.com/Andre-1998) | | [FactScribe 论文工作台](plugins/unclemoc/factscribe/README.zh-CN.md) | 写论文的本地工作台:打开你的稿盘,看检查报告、事实账与知识库,助手给的改动先成提议单,你在页面上点采纳才落盘。17 个 MCP 工具以只读为主,写盘一律由你确认。需要 MiniMax Code 3.1.2 或更高版本 | [UncleMoc (BGISMALL)](https://github.com/UncleMoc) | | [GitHub 收藏夹](plugins/start3208/github-star-shelf/README.zh-CN.md) | 把 GitHub Star 分进收藏夹,按名称、README 和备注搜索;让 AI 用大白话讲清每个项目:只看 README 讲,或读一遍浅克隆的代码再讲。一个项目一个会话,可以写备注,也能让 Agent 整理收藏夹 | [start3208](https://github.com/start3208) | +| [插件上架材料工作台](plugins/zhuyankarl/submission-workbench/README.zh-CN.md) | 填写插件清单与上架信息,逐项核对必填字段与内容一致性,生成可审核的上架材料包并标出缺失项;内置 Skill 让 Agent 拿到同一套检查清单 | [zhuyankarl](https://github.com/zhuyankarl) |
预览:Cutline diff --git a/plugins/zhuyankarl/submission-workbench/.minimax-plugin/plugin.json b/plugins/zhuyankarl/submission-workbench/.minimax-plugin/plugin.json new file mode 100644 index 00000000..65a8a892 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "submission-workbench", + "displayName": "插件上架材料工作台", + "version": "1.1.1", + "description": "检查插件清单与上架信息,生成可审核的上架材料包,并标出缺失项。", + "author": "明殊", + "icon": "icon.png", + "category": "Productivity", + "exampleQueries": [ + "检查我的插件清单能不能上架", + "生成插件上架材料包", + "上架材料还缺哪些必填项" + ], + "apps": [], + "mcpServers": [], + "skills": ["skills/listing-check/SKILL.md"] +} diff --git a/plugins/zhuyankarl/submission-workbench/LICENSE b/plugins/zhuyankarl/submission-workbench/LICENSE new file mode 100644 index 00000000..f49d31a6 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 明殊 + +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/zhuyankarl/submission-workbench/README.md b/plugins/zhuyankarl/submission-workbench/README.md new file mode 100644 index 00000000..ccf49b75 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/README.md @@ -0,0 +1,112 @@ +# Plugin Listing Workbench (submission-workbench) + +A Mini App for preparing a MiniMax Plugin submission: fill in the plugin manifest and the +listing fields, check the name, version, required fields and cross-file consistency item by +item, and download a reviewable listing package that names every missing item. + +中文名:插件上架材料工作台 + +![Preview](docs/preview.png) + +[简体中文](README.zh-CN.md) + +## What it does + +The page has four blocks: + +1. **Listing information** — paste the full `.minimax-plugin/plugin.json`, then set the expected + market name, the target category, the summary, the documentation (written into the package + `README.md`) and up to 3 example queries. +2. **Target market requirements** — a new submission or an update of an existing plugin (on an + update the original plugin name must stay the same and the last submitted version is + required), the submission email, the submitting Feishu account, the target region (CN/US) and + the enabled clients (desktop/cloud). Region and enabled clients are **two independent + dimensions** managed by the Marketplace catalog; they are not written into `plugin.json`. +3. **Assets** — upload by role: icon (the path the manifest declares), screenshots, and + Skill/MCP/App files. +4. **Results** — *Check results* lists the missing items and the content conflicts, *Listing + preview* shows the market card, *Submission channel and permissions* shows the intake + channels this machine can reach, and *Listing package* lets you download the packaged ZIP. + +## Install + +**From a Git repository** (MiniMax Code 3.1.11 or later): in the plugin market choose +**Create → Mini App → Import from Git repository** and paste + +``` +https://github.com/zhuyankarl/mcode-plugins/tree/main/plugins/submission-workbench +``` + +**Manually**: copy the whole `plugins/submission-workbench` directory, including the hidden +`.minimax-plugin` directory, into `/plugins/submission-workbench/`, then restart +MiniMax Code. + +**The whole repository**: clone and run +`install.ps1` (Windows) or `install.sh` (macOS/Linux). It installs this plugin together with the +`groundtruth` plugin and then self-checks the installation. + +## Use + +Open the app in MiniMax Code; the page is served at `/dashboard`. You can also ask the Agent +directly: "check whether my plugin manifest can be submitted" or "generate the listing package". + +## Bundled Skill + +The package ships one Skill, `listing-check` +(`skills/listing-check/SKILL.md`): it gives the Agent the same checklist the page applies — +required manifest fields, the fixed categories, the "at least one capability" rule, the version +bump rule, the package limits and the two official intake channels — so the Agent can answer +"can my plugin be submitted" without opening the page. + +## Tested environment + +- MiniMax Code 3.1.16 on Windows 11. +- Node.js 24.15.0 — any LTS release works, because the Node payload is a plain Node process. + +## Required configuration + +- Node.js must be on `PATH`. The payload uses Node built-in modules only (`node:http`, + `node:fs`, `node:zlib`, `node:crypto`, …): the host installs no dependencies and runs no build + step, so the package runs as it is. +- The page is plain HTML, CSS and JavaScript with no build step. + +## Data & access + +- **Files it reads**: only the files inside its own package. +- **Files it writes**: the working draft, the uploaded assets and the generated listing packages, + under the writable data directory the Host provides for this plugin + (`/v2/plugin-data/liveboards/submission-workbench/`). It never writes into the plugin + package itself. Every asset and package id is a UUID this server generates; an id that is not one + is refused before it can name a file, and the resolved path is checked to stay inside the asset + and package directories. +- **Network requests**: when you run a check, the Node service makes three HTTPS `GET` requests + to see whether the documented intake channels are reachable — the submission guide on + `code.minimax.cn` and two Feishu form URLs on `vrfi1sk8a0.feishu.cn`. There is no other + outbound traffic. The Node service itself listens on the loopback port the Host assigns it. +- **Agent turns it runs**: none. `miniapp/miniapp.json` declares no `agentAccess`. +- **Conversations it reads**: none. +- **Tools it calls**: none. `miniapp/miniapp.json` declares no `toolAccess`. +- **Microphone, camera, notifications**: none. +- **Which MiniMax Code page you are on**: not read. `miniapp/miniapp.json` declares no + `hostAccess`. + +## What it does not do + +The app never submits anything on your behalf. The official intake channels are a Feishu form (a +human submits it in a logged-in browser) and a public GitHub repository, so the app only produces +materials you can review — and it says exactly that in its own report. + +## Tests + +Run these inside the package directory: + +```bash +node tests/selftest.mjs # backend rules +node tests/client-harness.mjs # the page against a DOM stub +node tests/server-harness.mjs # the real Node service over HTTP +node tests/path-traversal.mjs # id handling on the two id-taking routes +``` + +## License + +MIT — see [LICENSE](LICENSE). diff --git a/plugins/zhuyankarl/submission-workbench/README.zh-CN.md b/plugins/zhuyankarl/submission-workbench/README.zh-CN.md new file mode 100644 index 00000000..95a5e534 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/README.zh-CN.md @@ -0,0 +1,97 @@ +# 插件上架材料工作台(submission-workbench) + +一个 Mini App:填写插件清单与上架信息,逐项核对名称、版本、必填字段与内容一致性, +一键生成可审核的**上架材料包**,并标出还缺哪些必填项。 + +English name: Plugin Listing Workbench + +[English](README.md) + +![界面预览](docs/preview.png) + +## 它做什么 + +页面上分四块: + +1. **上架信息** —— 粘贴 `.minimax-plugin/plugin.json` 全文,填期望市场名称、目标分类、 + 简介、说明文档(会写进包的 README.md)、最多 3 条示例 query。 +2. **目标市场要求** —— 上架新 Plugin 还是更新已有 Plugin(更新时原 Plugin 名必须不变、 + 并填上次提交版本)、提交邮箱、提交飞书账号、目标区域(CN/US)、启用端(桌面端/云端)。 + 区域与启用端是**两个独立维度**,由 Marketplace catalog 管理,不写进 `plugin.json`。 +3. **素材** —— 按角色上传:图标(对应 manifest 里的 `icon` 路径)、截图、Skill/MCP/App 文件。 +4. **结果区** —— 「检查结果」列出缺失项与内容冲突,「上架预览」给出市场卡片预览, + 「提交通道与权限」显示探测到的提交通道,「上架材料包」可下载打包好的 ZIP。 + +## 安装 + +**从 Git 仓库导入**(MiniMax Code 3.1.11 及以上):在插件市场点击「创建」→ Mini App → +「从 Git 仓库导入」,填入 + +``` +https://github.com/zhuyankarl/mcode-plugins/tree/main/plugins/submission-workbench +``` + +**手动安装**:把 `plugins/submission-workbench` 整个目录(含隐藏的 `.minimax-plugin`)复制到 +`/plugins/submission-workbench/`,再重启 MiniMax Code。 + +**整仓安装**:克隆 后执行 `install.ps1`(Windows) +或 `install.sh`(macOS/Linux),会一并装上本插件与 `groundtruth` 插件并做安装后自检。 + +## 怎么用 + +装好后在 MiniMax Code 里打开这个 Mini App,页面地址是 `/dashboard`。 +也可以直接对 Agent 说「检查我的插件清单能不能上架」「生成插件上架材料包」。 + +## 内置 Skill + +包内自带一个 Skill:`listing-check`(`skills/listing-check/SKILL.md`)。它把页面上那套检查 +规则交给 Agent——清单必填字段、固定分类、「至少一种能力」、包内容变化必须提版本、包体上限、 +两个官方受理入口——所以不用打开页面,Agent 也能直接回答「我这个插件能不能上架」。 + +## 测试环境 + +- MiniMax Code 3.1.16,Windows 11。 +- Node.js 24.15.0(任意 LTS 版本均可,Node 载荷是纯 Node 进程)。 + +## 运行环境 + +- 需要 **Node.js**(任意 LTS 版本),因为 Node 载荷是纯 Node 进程。 +- **零第三方依赖**:只用 Node 内置模块(`node:http`、`node:fs`、`node:zlib`、`node:crypto` 等), + 宿主不装依赖、不跑构建,所以包体可以直接运行。 +- 页面是原生 HTML/CSS/JS,无构建步骤。 + +## 数据与权限 + +- **读取的文件**:只有本插件包内的文件。 +- **写入的位置**:草稿、上传的素材与生成的上架材料包,写在宿主为该插件提供的可写数据目录里 + (`/v2/plugin-data/liveboards/submission-workbench/`),不写插件包本身。 + 素材与材料包的 id 一律是本服务生成的 UUID;不是 UUID 的 id 在落到文件之前就被拒绝, + 解析后的路径还会再检查一次是否仍在素材目录与材料包目录内。 +- **网络请求**:运行检查时,Node 服务会发三次 HTTPS GET,用来判断官方受理通道是否可达 —— + `code.minimax.cn` 上的上架指南,以及 `vrfi1sk8a0.feishu.cn` 上的两个飞书表单地址。 + 除此之外没有任何对外流量。Node 服务自身监听宿主分配的回环端口。 +- **Agent 运行**:无,`miniapp/miniapp.json` 未声明 `agentAccess`。 +- **读取会话**:无。 +- **调用工具**:无,未声明 `toolAccess`。 +- **麦克风、摄像头、通知**:无。 +- **读取当前 MiniMax Code 页面**:不读,未声明 `hostAccess`。 + +## 它不做什么 + +本应用不会代替你提交任何东西。官方受理入口是飞书表单(人工在已登录的浏览器里提交)和公开 +GitHub 仓库,所以它只产出可审核的材料——并在报告里如实写明这一点。 + +## 自测 + +在插件目录下执行: + +```bash +node tests/selftest.mjs # 后端规则 +node tests/client-harness.mjs # 页面 DOM 打桩 +node tests/server-harness.mjs # 真实 Node 服务的 HTTP 集成 +node tests/path-traversal.mjs # 两个带 id 路由的 id 处理 +``` + +## 许可证 + +MIT,见 [LICENSE](LICENSE)。 diff --git a/plugins/zhuyankarl/submission-workbench/docs/preview.png b/plugins/zhuyankarl/submission-workbench/docs/preview.png new file mode 100644 index 00000000..a2d9ec39 Binary files /dev/null and b/plugins/zhuyankarl/submission-workbench/docs/preview.png differ diff --git a/plugins/zhuyankarl/submission-workbench/icon.png b/plugins/zhuyankarl/submission-workbench/icon.png new file mode 100644 index 00000000..299a26cb Binary files /dev/null and b/plugins/zhuyankarl/submission-workbench/icon.png differ diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/client/app.css b/plugins/zhuyankarl/submission-workbench/miniapp/client/app.css new file mode 100644 index 00000000..1d6f215b --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/client/app.css @@ -0,0 +1,690 @@ +:root, +[data-theme='light'] { + --mcode-bg: #ffffff; + --mcode-bg-secondary: #f5f5f5; + --mcode-surface: #ffffff; + --mcode-surface-muted: #fafafa; + --mcode-text: #171717; + --mcode-text-muted: #666666; + --mcode-text-subtle: #adadad; + --mcode-border: #0a0a0a14; + --mcode-border-strong: #0a0a0af2; + --mcode-accent: #0094fc; + --mcode-success: #04b54b; + --mcode-warning: #f56811; + --mcode-danger: #f73646; + --mcode-primary-action-bg: #171717; + --mcode-primary-action-text: #ffffff; +} + +[data-theme='dark'] { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --mcode-bg: #171717; + --mcode-bg-secondary: #1c1c1c; + --mcode-surface: #262626; + --mcode-surface-muted: #262626; + --mcode-text: #ededed; + --mcode-text-muted: #949494; + --mcode-text-subtle: #666666; + --mcode-border: #ffffff14; + --mcode-border-strong: #fffffff2; + --mcode-accent: #0077d9; + --mcode-success: #009c3d; + --mcode-warning: #e25507; + --mcode-danger: #e31937; + --mcode-primary-action-bg: #ffffff; + --mcode-primary-action-text: #171717; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; +} + +.page { + max-width: 1400px; + margin: 0 auto; + padding: 24px; +} + +.page-header { + display: flex; + flex-wrap: wrap; + gap: 16px; + align-items: flex-start; + justify-content: space-between; + padding-bottom: 20px; + border-bottom: 1px solid var(--mcode-border); +} + +.page-header h1 { + margin: 0 0 6px; + font-size: 20px; + font-weight: 600; + line-height: 1.4; +} + +.page-description { + margin: 0; + max-width: 70ch; + color: var(--mcode-text-muted); +} + +.header-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; +} + +.layout { + display: grid; + grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); + gap: 20px; + align-items: start; + margin-top: 20px; +} + +.side-column { + display: flex; + flex-direction: column; + gap: 20px; +} + +.panel { + background: var(--mcode-surface); + border: 1px solid var(--mcode-border); + border-radius: 12px; + padding: 18px 20px 20px; +} + +.panel h2 { + margin: 0 0 14px; + font-size: 16px; + font-weight: 500; + line-height: 1.5; +} + +.field { + margin-bottom: 16px; + border: 0; + padding: 0; + min-width: 0; +} + +.field > label, +.field legend, +.checkbox-label { + display: block; + margin-bottom: 6px; + font-size: 13px; + font-weight: 500; +} + +.field-hint { + margin: -2px 0 8px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.required { + margin-left: 4px; + font-size: 11px; + font-weight: 400; + color: var(--mcode-danger); +} + +input[type='text'], +input[type='email'], +textarea, +select { + width: 100%; + padding: 8px 10px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + border: 1px solid var(--mcode-border); + border-radius: 8px; + font-family: inherit; + font-size: 13px; + line-height: 1.5; +} + +textarea { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 12px; + resize: vertical; +} + +input:focus-visible, +textarea:focus-visible, +select:focus-visible, +button:focus-visible { + outline: 2px solid var(--mcode-accent); + outline-offset: 1px; + border-color: var(--mcode-accent); +} + +.field-row { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; +} + +.button { + height: 34px; + padding: 0 14px; + background: var(--mcode-surface-muted); + color: var(--mcode-text); + border: 1px solid var(--mcode-border); + border-radius: 8px; + font-family: inherit; + font-size: 13px; + cursor: pointer; + transition: background 150ms ease-out, opacity 150ms ease-out; +} + +.button:hover:not(:disabled) { + background: var(--mcode-bg-secondary); +} + +.button:disabled { + opacity: 0.55; + cursor: not-allowed; +} + +.button-primary { + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + border-color: var(--mcode-primary-action-bg); +} + +.button-quiet { + height: 30px; + padding: 0 10px; + background: transparent; +} + +.query-list { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 8px; +} + +.checkbox-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + margin-bottom: 12px; +} + +.checkbox-group .checkbox-label { + margin: 0; +} + +.checkbox-group label { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; +} + +.upload-row { + display: grid; + grid-template-columns: 150px minmax(0, 1fr) auto; + gap: 8px; + margin-bottom: 12px; +} + +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; + border: 0; +} + +.asset-list { + margin: 0; + padding: 0; + list-style: none; + display: flex; + flex-direction: column; + gap: 6px; +} + +.asset-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px 10px; + background: var(--mcode-surface-muted); + border: 1px solid var(--mcode-border); + border-radius: 8px; + font-size: 12px; +} + +.asset-item .asset-name { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + word-break: break-all; +} + +.asset-role { + flex-shrink: 0; + padding: 2px 8px; + border-radius: 999px; + background: var(--mcode-bg-secondary); + color: var(--mcode-text-muted); + font-size: 11px; +} + +.status-banner { + margin: 16px 0 0; + padding: 10px 14px; + border: 1px solid var(--mcode-border); + border-left: 3px solid var(--mcode-accent); + border-radius: 8px; + background: var(--mcode-surface-muted); + font-size: 13px; +} + +.status-banner[data-tone='error'] { + border-left-color: var(--mcode-danger); +} + +.status-banner[data-tone='success'] { + border-left-color: var(--mcode-success); +} + +.status-banner[hidden] { + display: none !important; +} + +.summary-bar { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 14px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.count-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); +} + +.count-chip strong { + font-size: 13px; + font-weight: 600; + color: var(--mcode-text); +} + +.count-chip[data-level='error'] { + border-color: color-mix(in srgb, var(--mcode-danger) 45%, transparent); +} + +.count-chip[data-level='error'] strong { + color: var(--mcode-danger); +} + +.count-chip[data-level='warning'] strong { + color: var(--mcode-warning); +} + +.count-chip[data-level='missing'] strong { + color: var(--mcode-danger); +} + +.missing-list { + margin-bottom: 14px; +} + +.missing-list:empty { + display: none; +} + +.missing-heading { + margin: 0 0 8px; + font-size: 13px; + font-weight: 500; + color: var(--mcode-danger); +} + +.missing-item { + display: flex; + gap: 8px; + align-items: baseline; + padding: 6px 10px; + margin-bottom: 6px; + background: color-mix(in srgb, var(--mcode-danger) 8%, var(--mcode-surface)); + border: 1px solid color-mix(in srgb, var(--mcode-danger) 30%, transparent); + border-radius: 8px; + font-size: 12px; +} + +.missing-item .missing-field { + flex-shrink: 0; + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + color: var(--mcode-danger); +} + +.issue-list { + display: flex; + flex-direction: column; + gap: 8px; + max-height: 420px; + overflow-y: auto; +} + +.issue { + padding: 10px 12px; + border: 1px solid var(--mcode-border); + border-left: 3px solid var(--mcode-text-subtle); + border-radius: 8px; + background: var(--mcode-surface-muted); +} + +.issue[data-severity='error'] { + border-left-color: var(--mcode-danger); +} + +.issue[data-severity='warning'] { + border-left-color: var(--mcode-warning); +} + +.issue[data-severity='info'] { + border-left-color: var(--mcode-accent); +} + +.issue-title { + display: flex; + align-items: baseline; + gap: 8px; + font-size: 13px; + font-weight: 500; +} + +.issue-badge { + flex-shrink: 0; + padding: 1px 7px; + border-radius: 999px; + font-size: 11px; + font-weight: 400; + background: var(--mcode-bg-secondary); + color: var(--mcode-text-muted); +} + +.issue[data-severity='error'] .issue-badge { + color: var(--mcode-danger); +} + +.issue[data-severity='warning'] .issue-badge { + color: var(--mcode-warning); +} + +.issue-detail { + margin: 4px 0 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.issue-source { + margin: 6px 0 0; + font-size: 11px; + color: var(--mcode-text-subtle); +} + +.empty-hint { + margin: 0; + color: var(--mcode-text-subtle); + font-size: 13px; +} + +.preview-card { + border: 1px solid var(--mcode-border); + border-radius: 12px; + overflow: hidden; +} + +.preview-head { + display: flex; + gap: 12px; + align-items: flex-start; + padding: 14px 16px; + background: var(--mcode-surface-muted); + border-bottom: 1px solid var(--mcode-border); +} + +.preview-icon { + flex-shrink: 0; + width: 44px; + height: 44px; + border-radius: 10px; + border: 1px solid var(--mcode-border); + background: var(--mcode-bg-secondary); + display: grid; + place-items: center; + font-size: 18px; + font-weight: 600; + color: var(--mcode-text-muted); +} + +.preview-name { + margin: 0; + font-size: 15px; + font-weight: 600; +} + +.preview-meta { + margin: 2px 0 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.preview-body-text { + margin: 0; + padding: 12px 16px; + font-size: 13px; + color: var(--mcode-text); +} + +.preview-section { + padding: 12px 16px; + border-top: 1px solid var(--mcode-border); +} + +.preview-section h3 { + margin: 0 0 6px; + font-size: 12px; + font-weight: 500; + color: var(--mcode-text-muted); +} + +.preview-section ul { + margin: 0; + padding-left: 18px; + font-size: 13px; +} + +.preview-section li { + margin-bottom: 3px; +} + +.tag-row { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.tag { + padding: 2px 8px; + border-radius: 999px; + border: 1px solid var(--mcode-border); + background: var(--mcode-surface-muted); + font-size: 11px; + color: var(--mcode-text-muted); +} + +.channel-finding { + padding: 10px 12px; + margin-bottom: 8px; + border: 1px solid var(--mcode-border); + border-left: 3px solid var(--mcode-text-subtle); + border-radius: 8px; + background: var(--mcode-surface-muted); +} + +.channel-finding[data-status='available'] { + border-left-color: var(--mcode-success); +} + +.channel-finding[data-status='unavailable'] { + border-left-color: var(--mcode-warning); +} + +.channel-finding h3 { + margin: 0 0 4px; + font-size: 13px; + font-weight: 500; +} + +.channel-finding p { + margin: 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.channel-evidence { + margin-top: 4px !important; + font-size: 11px !important; + color: var(--mcode-text-subtle) !important; + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + word-break: break-all; +} + +.permission-row { + display: flex; + align-items: baseline; + gap: 8px; + padding: 6px 0; + font-size: 12px; + border-top: 1px solid var(--mcode-border); +} + +.permission-state { + flex-shrink: 0; + font-weight: 500; +} + +.permission-state[data-satisfied='true'] { + color: var(--mcode-success); +} + +.permission-state[data-satisfied='false'] { + color: var(--mcode-warning); +} + +.channel-conclusion { + margin: 12px 0 0; + padding: 10px 12px; + border-radius: 8px; + background: color-mix(in srgb, var(--mcode-warning) 10%, var(--mcode-surface)); + border: 1px solid color-mix(in srgb, var(--mcode-warning) 30%, transparent); + font-size: 12px; +} + +.package-item { + padding: 12px; + border: 1px solid var(--mcode-border); + border-radius: 8px; + background: var(--mcode-surface-muted); +} + +.package-item h3 { + margin: 0 0 4px; + font-size: 13px; + font-weight: 500; + word-break: break-all; +} + +.package-meta { + margin: 0 0 10px; + font-size: 12px; + color: var(--mcode-text-muted); +} + +.package-meta code { + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 11px; + word-break: break-all; +} + +.download-link { + display: inline-block; + padding: 6px 12px; + border-radius: 8px; + background: var(--mcode-primary-action-bg); + color: var(--mcode-primary-action-text); + text-decoration: none; + font-size: 13px; +} + +.package-note { + margin: 10px 0 0; + font-size: 12px; + color: var(--mcode-text-muted); +} + +@media (max-width: 900px) { + .layout { + grid-template-columns: minmax(0, 1fr); + } + + .upload-row { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (prefers-reduced-motion: reduce) { + * { + transition: none !important; + } +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/client/app.js b/plugins/zhuyankarl/submission-workbench/miniapp/client/app.js new file mode 100644 index 00000000..97a5800d --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/client/app.js @@ -0,0 +1,609 @@ +// @ts-check +/** + * Client for 插件上架材料工作台. + * + * The page owns presentation and input only. Every validation pass, the market + * preview and the listing package are produced by the Node service. + */ + +const form = /** @type {HTMLFormElement} */ (document.getElementById('draft-form')); +const manifestText = /** @type {HTMLTextAreaElement} */ (document.getElementById('manifest-text')); +const summaryInput = /** @type {HTMLTextAreaElement} */ (document.getElementById('summary')); +const documentationInput = /** @type {HTMLTextAreaElement} */ (document.getElementById('documentation')); +const marketNameInput = /** @type {HTMLInputElement} */ (document.getElementById('market-name')); +const categorySelect = /** @type {HTMLSelectElement} */ (document.getElementById('category')); +const operationSelect = /** @type {HTMLSelectElement} */ (document.getElementById('operation')); +const existingNameInput = /** @type {HTMLInputElement} */ (document.getElementById('existing-name')); +const previousVersionInput = /** @type {HTMLInputElement} */ (document.getElementById('previous-version')); +const updateFields = /** @type {HTMLElement} */ (document.getElementById('update-fields')); +const queryList = /** @type {HTMLElement} */ (document.getElementById('query-list')); +const addQueryButton = /** @type {HTMLButtonElement} */ (document.getElementById('add-query')); +const statusBanner = /** @type {HTMLElement} */ (document.getElementById('status-banner')); +const summaryBar = /** @type {HTMLElement} */ (document.getElementById('summary-bar')); +const missingList = /** @type {HTMLElement} */ (document.getElementById('missing-list')); +const issueList = /** @type {HTMLElement} */ (document.getElementById('issue-list')); +const previewBody = /** @type {HTMLElement} */ (document.getElementById('preview-body')); +const channelBody = /** @type {HTMLElement} */ (document.getElementById('channel-body')); +const packageBody = /** @type {HTMLElement} */ (document.getElementById('package-body')); +const validateButton = /** @type {HTMLButtonElement} */ (document.getElementById('validate-button')); +const packageButton = /** @type {HTMLButtonElement} */ (document.getElementById('package-button')); +const assetRole = /** @type {HTMLSelectElement} */ (document.getElementById('asset-role')); +const assetName = /** @type {HTMLInputElement} */ (document.getElementById('asset-name')); +const organizationInput = /** @type {HTMLInputElement} */ (document.getElementById('organization')); +const assetFile = /** @type {HTMLInputElement} */ (document.getElementById('asset-file')); +const assetUpload = /** @type {HTMLButtonElement} */ (document.getElementById('asset-upload')); +const assetList = /** @type {HTMLElement} */ (document.getElementById('asset-list')); + +/** @type {import('./client-api.js').McodeClientAPI | undefined} */ +const hostApi = window.mcode; + +/** + * @param {string} message + * @param {'info' | 'success' | 'error'} [tone] + */ +function setBanner(message, tone = 'info') { + statusBanner.textContent = message; + statusBanner.dataset.tone = tone; + statusBanner.hidden = message === ''; +} + +/** + * @param {string} path + * @param {RequestInit} [init] + * @returns {Promise} + */ +async function request(path, init) { + const response = await fetch(path, init); + const text = await response.text(); + let payload = null; + try { + payload = text ? JSON.parse(text) : null; + } catch { + payload = { message: text }; + } + if (!response.ok && response.status !== 409) { + const error = new Error(payload?.message ?? `请求失败(HTTP ${response.status})`); + throw error; + } + return payload; +} + +/** + * @returns {{ manifestText: string, marketName: string, summary: string, documentation: string, category: string, exampleQueries: string[], regions: string[], enabledEnds: string[], operation: string, existingName: string, previousVersion: string, submitEmail: string, submitAccount: string, organization: string }} + */ +function collectDraft() { + const checkboxes = (name) => + Array.from(form.querySelectorAll(`input[name="${name}"]:checked`)).map((input) => + /** @type {HTMLInputElement} */ (input).value, + ); + return { + manifestText: manifestText.value, + marketName: marketNameInput.value, + summary: summaryInput.value, + documentation: documentationInput.value, + category: categorySelect.value, + exampleQueries: Array.from(queryList.querySelectorAll('input')) + .map((input) => /** @type {HTMLInputElement} */ (input).value) + .filter((value) => value.trim() !== ''), + regions: checkboxes('regions'), + enabledEnds: checkboxes('enabledEnds'), + operation: operationSelect.value, + existingName: existingNameInput.value, + previousVersion: previousVersionInput.value, + submitEmail: /** @type {HTMLInputElement} */ (form.elements.namedItem('submitEmail')).value, + submitAccount: /** @type {HTMLInputElement} */ (form.elements.namedItem('submitAccount')).value, + organization: organizationInput.value, + }; +} + +/** @param {string} value */ +function addQueryRow(value = '') { + if (queryList.querySelectorAll('input').length >= 3) return; + const row = document.createElement('div'); + row.className = 'field-row'; + const input = document.createElement('input'); + input.type = 'text'; + input.value = value; + input.placeholder = '例:检索近期研究并总结主要结论'; + input.setAttribute('aria-label', '示例 query'); + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'button button-quiet'; + remove.textContent = '移除'; + remove.addEventListener('click', () => { + row.remove(); + }); + row.append(input, remove); + queryList.append(row); +} + +/** + * @param {number} errors + * @param {number} warnings + * @param {number} infos + * @param {number} missing + */ +function renderSummary(errors, warnings, infos, missing) { + summaryBar.textContent = ''; + const chip = (level, label, value) => { + const element = document.createElement('span'); + element.className = 'count-chip'; + element.dataset.level = level; + const strong = document.createElement('strong'); + strong.textContent = String(value); + element.append(strong, document.createTextNode(label)); + return element; + }; + summaryBar.append( + chip('error', ' 错误', errors), + chip('warning', ' 警告', warnings), + chip('info', ' 提示', infos), + chip('missing', ' 缺失项', missing), + ); +} + +/** + * @param {any[]} issues + */ +function renderIssues(issues) { + issueList.textContent = ''; + missingList.textContent = ''; + const missing = issues.filter((issue) => issue.missing); + if (missing.length > 0) { + const heading = document.createElement('p'); + heading.className = 'missing-heading'; + heading.textContent = `缺失项(${missing.length})`; + missingList.append(heading); + for (const issue of missing) { + const item = document.createElement('div'); + item.className = 'missing-item'; + const field = document.createElement('span'); + field.className = 'missing-field'; + field.textContent = issue.field ?? '-'; + const text = document.createElement('span'); + text.textContent = `${issue.title}:${issue.detail}`; + item.append(field, text); + missingList.append(item); + } + } + if (issues.length === 0) { + const hint = document.createElement('p'); + hint.className = 'empty-hint'; + hint.textContent = '未发现问题。'; + issueList.append(hint); + return; + } + for (const issue of issues) { + const element = document.createElement('div'); + element.className = 'issue'; + element.dataset.severity = issue.severity; + const title = document.createElement('p'); + title.className = 'issue-title'; + const badge = document.createElement('span'); + badge.className = 'issue-badge'; + badge.textContent = + issue.severity === 'error' ? '错误' : issue.severity === 'warning' ? '警告' : '提示'; + const text = document.createElement('span'); + text.textContent = issue.title; + title.append(badge, text); + const detail = document.createElement('p'); + detail.className = 'issue-detail'; + detail.textContent = issue.detail; + const source = document.createElement('p'); + source.className = 'issue-source'; + source.textContent = `依据:${issue.source}`; + element.append(title, detail, source); + issueList.append(element); + } +} + +/** + * @param {any} preview + */ +function renderPreview(preview) { + previewBody.textContent = ''; + if (!preview) { + const hint = document.createElement('p'); + hint.className = 'empty-hint'; + hint.textContent = '填写信息并运行检查后,这里显示市场卡片预览。'; + previewBody.append(hint); + return; + } + const card = document.createElement('div'); + card.className = 'preview-card'; + + const head = document.createElement('div'); + head.className = 'preview-head'; + const icon = document.createElement('div'); + icon.className = 'preview-icon'; + icon.textContent = (preview.marketName || '?').slice(0, 1).toUpperCase(); + const names = document.createElement('div'); + const name = document.createElement('p'); + name.className = 'preview-name'; + name.textContent = preview.marketName || '(未填写市场名称)'; + const meta = document.createElement('p'); + meta.className = 'preview-meta'; + meta.textContent = [preview.version, preview.category, preview.author] + .filter(Boolean) + .join(' · '); + names.append(name, meta); + head.append(icon, names); + card.append(head); + + const body = document.createElement('p'); + body.className = 'preview-body-text'; + body.textContent = preview.summary || '(未填写简介)'; + card.append(body); + + const regions = document.createElement('div'); + regions.className = 'preview-section'; + const regionsTitle = document.createElement('h3'); + regionsTitle.textContent = '目标市场'; + const regionTags = document.createElement('div'); + regionTags.className = 'tag-row'; + for (const tag of [ + ...(preview.regions ?? []), + ...(preview.enabledEnds ?? []).map((end) => (end === 'desktop' ? '桌面端' : '云端')), + ]) { + const element = document.createElement('span'); + element.className = 'tag'; + element.textContent = tag; + regionTags.append(element); + } + regions.append(regionsTitle, regionTags); + card.append(regions); + + if ((preview.exampleQueries ?? []).length > 0) { + const queries = document.createElement('div'); + queries.className = 'preview-section'; + const title = document.createElement('h3'); + title.textContent = '示例 query'; + const list = document.createElement('ul'); + for (const query of preview.exampleQueries) { + const item = document.createElement('li'); + item.textContent = query; + list.append(item); + } + queries.append(title, list); + card.append(queries); + } + + const files = document.createElement('div'); + files.className = 'preview-section'; + const filesTitle = document.createElement('h3'); + filesTitle.textContent = `能力文件(${preview.capabilityFiles?.length ?? 0})· 截图 ${preview.screenshotCount} 张`; + const fileList = document.createElement('ul'); + const entries = preview.capabilityFiles ?? []; + if (entries.length === 0) { + const item = document.createElement('li'); + item.textContent = '清单未声明能力文件。'; + fileList.append(item); + } + for (const file of entries) { + const item = document.createElement('li'); + item.textContent = `${file.path} — ${file.present ? '已上传' : '缺少素材'}`; + fileList.append(item); + } + files.append(filesTitle, fileList); + card.append(files); + + previewBody.append(card); +} + +/** + * @param {any} channel + */ +function renderChannel(channel) { + channelBody.textContent = ''; + if (!channel) { + const hint = document.createElement('p'); + hint.className = 'empty-hint'; + hint.textContent = '尚未探测提交通道。'; + channelBody.append(hint); + return; + } + for (const finding of channel.findings ?? []) { + const element = document.createElement('div'); + element.className = 'channel-finding'; + element.dataset.status = finding.status; + const title = document.createElement('h3'); + title.textContent = `${finding.label}(${finding.status === 'available' ? '可用' : finding.status === 'unavailable' ? '不可用' : '未知'})`; + const detail = document.createElement('p'); + detail.textContent = finding.detail; + const evidence = document.createElement('p'); + evidence.className = 'channel-evidence'; + evidence.textContent = `证据:${finding.evidence}`; + element.append(title, detail, evidence); + channelBody.append(element); + } + for (const permission of channel.requiredPermissions ?? []) { + const row = document.createElement('div'); + row.className = 'permission-row'; + const state = document.createElement('span'); + state.className = 'permission-state'; + state.dataset.satisfied = String(permission.satisfied); + state.textContent = permission.satisfied ? '已具备' : '未具备'; + const label = document.createElement('span'); + label.textContent = `${permission.label} —— ${permission.detail}`; + row.append(state, label); + channelBody.append(row); + } + const conclusion = document.createElement('p'); + conclusion.className = 'channel-conclusion'; + conclusion.textContent = channel.conclusion ?? ''; + channelBody.append(conclusion); +} + +/** + * @param {any} record + */ +function renderPackages(records) { + packageBody.textContent = ''; + if (!records || records.length === 0) { + const hint = document.createElement('p'); + hint.className = 'empty-hint'; + hint.textContent = '还没有生成材料包。'; + packageBody.append(hint); + return; + } + for (const record of records) { + const item = document.createElement('div'); + item.className = 'package-item'; + const title = document.createElement('h3'); + title.textContent = record.fileName; + const meta = document.createElement('p'); + meta.className = 'package-meta'; + meta.textContent = `${record.size} 字节 · ${record.entries?.length ?? 0} 个条目 · ${new Date(record.createdAt).toLocaleString()}`; + const digest = document.createElement('p'); + digest.className = 'package-meta'; + const code = document.createElement('code'); + code.textContent = `SHA256 ${record.sha256}`; + digest.append(code); + const link = document.createElement('a'); + link.className = 'download-link'; + link.href = `/api/package/download?id=${encodeURIComponent(record.id)}`; + link.textContent = '下载材料包'; + const note = document.createElement('p'); + note.className = 'package-note'; + note.textContent = + '材料包仅供人工审核与提交使用,尚未提交到官方市场,也不代表已上架。提交前请按官方表单逐项核对。'; + item.append(title, meta, digest, link, note); + packageBody.append(item); + } +} + +/** + * @param {any[]} assets + */ +function renderAssets(assets) { + assetList.textContent = ''; + if (!assets || assets.length === 0) { + const hint = document.createElement('li'); + hint.className = 'empty-hint'; + hint.textContent = '尚未上传素材。'; + assetList.append(hint); + return; + } + for (const asset of assets) { + const item = document.createElement('li'); + item.className = 'asset-item'; + const name = document.createElement('span'); + name.className = 'asset-name'; + name.textContent = asset.name; + const role = document.createElement('span'); + role.className = 'asset-role'; + role.textContent = `${asset.role} · ${asset.size}B`; + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'button button-quiet'; + remove.textContent = '移除'; + remove.addEventListener('click', async () => { + remove.disabled = true; + try { + await request(`/api/assets?id=${encodeURIComponent(asset.id)}`, { method: 'DELETE' }); + await refreshState(); + await runValidation(); + } catch (error) { + setBanner(error instanceof Error ? error.message : '移除素材失败', 'error'); + remove.disabled = false; + } + }); + item.append(name, role, remove); + assetList.append(item); + } +} + +async function refreshState() { + const state = await request('/api/state'); + renderAssets(state.assets ?? []); + renderPackages(state.packages ?? []); +} + +/** + * @param {boolean} busy + */ +function setBusy(busy) { + validateButton.disabled = busy; + packageButton.disabled = busy; + assetUpload.disabled = busy; + addQueryButton.disabled = busy; +} + +async function runValidation() { + setBusy(true); + setBanner('正在检查……'); + try { + const result = await request('/api/validate', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(collectDraft()), + }); + renderSummary( + result.summary.errors, + result.summary.warnings, + result.summary.infos, + result.summary.missing, + ); + renderIssues(result.issues ?? []); + renderPreview(result.preview); + renderChannel(result.channel); + renderAssets(result.assets ?? []); + const errors = result.summary.errors; + setBanner( + errors > 0 + ? `检查完成:${errors} 项错误、${result.summary.warnings} 项警告、${result.summary.missing} 项缺失。修正后才能生成材料包。` + : `检查完成:${result.summary.warnings} 项警告,无阻断错误,可以生成材料包。`, + errors > 0 ? 'error' : 'success', + ); + } catch (error) { + setBanner(error instanceof Error ? error.message : '检查失败', 'error'); + } finally { + setBusy(false); + } +} + +async function generatePackage() { + setBusy(true); + setBanner('正在生成上架材料包……'); + try { + const result = await request('/api/package', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(collectDraft()), + }); + if (result.error === 'not_ready') { + renderSummary( + result.summary.errors, + result.summary.warnings, + result.summary.infos, + result.summary.missing, + ); + renderIssues(result.issues ?? []); + renderPreview(result.preview); + renderChannel(result.channel); + setBanner(result.message ?? '仍有错误,无法生成材料包。', 'error'); + return; + } + await refreshState(); + setBanner( + `已生成上架材料包(${result.package.size} 字节)。材料尚未提交到官方市场,请按官方表单人工提交。`, + 'success', + ); + } catch (error) { + setBanner(error instanceof Error ? error.message : '生成失败', 'error'); + } finally { + setBusy(false); + } +} + +async function uploadAsset() { + const file = assetFile.files?.[0]; + if (!file) { + setBanner('请先选择一个文件。', 'error'); + return; + } + const role = assetRole.value; + const name = assetName.value.trim() || file.name; + setBusy(true); + setBanner('正在上传素材……'); + try { + const buffer = await file.arrayBuffer(); + let binary = ''; + const bytes = new Uint8Array(buffer); + for (let index = 0; index < bytes.length; index += 1) { + binary += String.fromCharCode(bytes[index]); + } + await request('/api/assets', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + name, + role, + mime: file.type || 'application/octet-stream', + contentBase64: btoa(binary), + }), + }); + assetFile.value = ''; + assetName.value = ''; + await refreshState(); + await runValidation(); + } catch (error) { + setBanner(error instanceof Error ? error.message : '上传失败', 'error'); + } finally { + setBusy(false); + } +} + +async function boot() { + try { + const meta = await request('/api/meta'); + for (const category of meta.categories ?? []) { + const option = document.createElement('option'); + option.value = category; + option.textContent = category; + categorySelect.append(option); + } + const state = await request('/api/state'); + const draft = state.draft ?? {}; + manifestText.value = draft.manifestText ?? ''; + marketNameInput.value = draft.marketName ?? ''; + summaryInput.value = draft.summary ?? ''; + documentationInput.value = draft.documentation ?? ''; + categorySelect.value = draft.category ?? ''; + operationSelect.value = draft.operation ?? 'new'; + existingNameInput.value = draft.existingName ?? ''; + previousVersionInput.value = draft.previousVersion ?? ''; + /** @type {HTMLInputElement} */ (form.elements.namedItem('submitEmail')).value = draft.submitEmail ?? ''; + /** @type {HTMLInputElement} */ (form.elements.namedItem('submitAccount')).value = draft.submitAccount ?? ''; + organizationInput.value = draft.organization ?? ''; + for (const query of draft.exampleQueries ?? []) addQueryRow(query); + if ((draft.exampleQueries ?? []).length === 0) addQueryRow(); + for (const region of draft.regions ?? []) { + const input = form.querySelector(`input[name="regions"][value="${region}"]`); + if (input) /** @type {HTMLInputElement} */ (input).checked = true; + } + for (const end of draft.enabledEnds ?? []) { + const input = form.querySelector(`input[name="enabledEnds"][value="${end}"]`); + if (input) /** @type {HTMLInputElement} */ (input).checked = true; + } + updateFields.hidden = operationSelect.value !== 'update'; + renderAssets(state.assets ?? []); + renderPackages(state.packages ?? []); + } catch (error) { + setBanner(error instanceof Error ? error.message : '初始化失败', 'error'); + } +} + +operationSelect.addEventListener('change', () => { + updateFields.hidden = operationSelect.value !== 'update'; +}); + +addQueryButton.addEventListener('click', () => addQueryRow()); +assetUpload.addEventListener('click', () => void uploadAsset()); +validateButton.addEventListener('click', () => void runValidation()); +packageButton.addEventListener('click', () => void generatePackage()); + +document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + void request('/api/validate', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(collectDraft()), + }).catch(() => undefined); + } +}); + +// Follow the Host theme when it exposes one; otherwise the page uses prefers-color-scheme. +const hostUi = hostApi?.miniapp?.host?.ui; +if (hostUi?.subscribe) { + const subscription = hostUi.subscribe( + ({ theme, language }) => { + if (theme) document.documentElement.dataset.theme = theme; + if (language) document.documentElement.lang = language === 'zh-Hans' ? 'zh-CN' : 'en'; + }, + { onError: () => undefined }, + ); + window.addEventListener('pagehide', () => subscription?.dispose(), { once: true }); +} + +void boot(); diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/client/client-api.ts b/plugins/zhuyankarl/submission-workbench/miniapp/client/client-api.ts new file mode 100644 index 00000000..6a3c9b0c --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/client/client-api.ts @@ -0,0 +1,641 @@ +/** + * Copyable Mini App Client declarations for TypeScript and JavaScript/JSDoc authoring. + * No Host implementation or runtime import: Electron preload provides window.mcode. + * Keep the .ts filename because Electron dependency packaging filters out .d.ts assets. + * Node start(context) uses miniapp-api.ts instead. See client-api.md for usage and errors. + */ +export interface MiniAppMessageAPI { + /** + * Ask the user to append plain text to this Mini App's conversation input. + * Accepts at most 100,000 UTF-16 code units and preserves spaces, tabs, and newlines. + * An empty string still requires confirmation and leaves the draft unchanged. + * Resolves after the confirmed append; rejects on cancellation or failure. + * Does not send a message or insert, edit, or delete sent chat history. + */ + append(text: string): Promise; +} + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: { readonly [key: string]: unknown }; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a session without a host chat model starts with. */ + readonly default: MiniAppAgentModelSelection; + /** The host chat's current model (the default when the chat has none); only when opened from a chat. */ + readonly host?: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +/** Final outcome of one Agent turn. */ +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** + * `aborted` only when the Host confirmed the abort; an unconfirmed cancel rejects with + * `result_unknown`. `steered` (only with `whenBusy`): the text joined the running turn + * `turnId`, whose own call gets the reply, so there is no `text`. + */ + readonly status: 'finished' | 'error' | 'aborted' | 'steered'; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `permission.requested`: a tool call waits for approval; decide it with `agent.reply`. + * - `question.requested`: the turn paused on a questionnaire; continue with `agent.answer`. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + * Every event except `run.queued` names its `sessionId`, so `reply` works before the `run` that + * created the session has returned. `answer` does not: call it after the paused `run` resolves, + * or it rejects as busy. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: 'finished' | 'error' | 'aborted'; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunInput { + /** Plain text, at most 100,000 UTF-16 code units. */ + readonly text: string; + /** Continue a session this Mini App created earlier; omit to start a new one. */ + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a new + * session's model: it must be one `models()` lists; unusable is `invalid_request`, missing BYOK + * credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. A session + * never changes its agent, so passing it with `sessionId` is `invalid_request`. + */ + readonly agent?: string; + /** + * Only with `sessionId`, when that session is already running a turn (otherwise it starts one as + * usual). `queue`: the text runs as the next turn and this call follows it. `steer`: the + * running turn reads the text at its next input point; the call resolves `steered`, or follows + * the next turn when the running one answered before reading it. Omit to reject as `busy`. + */ + readonly whenBusy?: 'queue' | 'steer'; + /** Your id for `cancel(requestId)`; 1-128 characters, unique among this page's active runs. */ + readonly requestId?: string; +} + +export interface MiniAppAgentReplyInput { + readonly sessionId: string; + /** `requestId` of the `permission.requested` event. */ + readonly requestId: string; + /** No `allowAlways`: a Mini App never writes the user's global rules. */ + readonly decision: 'allowOnce' | 'deny'; +} + +export interface MiniAppAgentAnswerInput { + readonly sessionId: string; + /** `requestId` of the `question.requested` event or of `result.pendingQuestion`. */ + readonly questionId: string; + /** One answer per questionnaire step. */ + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `MiniAppAgentRunInput.model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + /** Your id for `cancel(requestId)`, as in `run`. */ + readonly requestId?: string; +} + +export interface MiniAppAgentRunOptions { + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +/** + * Absent on older Hosts. `run` / `reply` / `answer` / `open` / `models` / `agents` / `create` reject + * with `not_permitted` unless the manifest declares `agentAccess: ["session.run"]`; `observe` / + * `sessions` need `"session.read"` for anything but this Mini App's own sessions (see + * agent-interaction.md). A new session uses the Agent of the chat this page is open in; + * a page without a host chat uses the primary Agent unless `run({ agent })` / `create({ agent })` + * names one from `agents()`. Continuing a session keeps its Agent. + * The Agent works in the host chat's project directory when it has one, otherwise in this Mini + * App's own Agent directory; a continued session keeps its directory. A new session takes the + * model and thinking level of the host chat (the runtime default when the chat has none) and keeps + * them; `run` / `answer` with `model` switch the session's model first. + * It runs one turn with that Agent's full capabilities (files, shell, Skills, MCP including this + * Mini App's own), and resolves when it ends. + * + * Interaction is yours to render: handle `permission.requested` with `reply` and + * `question.requested` with `answer`. A permission request waits only while this run passed + * `onEvent` or the session is open in a chat side panel through `open`; otherwise it is denied + * and the model is told why. A run with `onEvent` that does not handle the request waits until + * `cancel` or the page closes; there is no timeout. Up to `agentConcurrency` runs (default 4) per + * Mini App run at once, one per session; further `run` / `answer` calls wait in order (up to four + * times that many, see `run.queued`), and `cancel` on a waiting call rejects it with `cancelled`. + * `busy` means the session is running a turn, compacting, or has messages queued ahead (never with + * `whenBusy`; the text reached no turn) or the wait queue is full. + * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, `busy`, + * `session_not_found`, `runtime_unavailable`, `cancelled`, `result_unknown`, or + * `request_not_found`. `runtime_unavailable` means nothing was started; `result_unknown` means + * the turn may have run (or ended without the Host knowing whether a question is pending), so + * never repeat it automatically. + */ +export interface MiniAppAgentAPI { + run( + input: MiniAppAgentRunInput, + options?: MiniAppAgentRunOptions, + ): Promise; + /** Decide a pending permission request; `request_not_found` when it is unknown or settled. */ + reply(input: MiniAppAgentReplyInput): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `result_unknown` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: MiniAppAgentAnswerInput, + options?: MiniAppAgentRunOptions, + ): Promise; + /** Ask the Host to stop an active run or answer; unknown or finished ids are ignored. */ + cancel(requestId: string): void; + /** + * Show one of this Mini App's sessions as a tab in the side panel of the chat the + * Mini App is open in, where the user can read the conversation and answer + * permission and question cards themselves. Permission requests wait for the tab only + * while it stays open; once the user closes it, handle `permission.requested` yourself + * or call `open` again. Any session this Mini App owns can be opened, whichever chat + * created it; `session_not_found` otherwise. + */ + open(sessionId: string): Promise; + /** + * Returns the model catalog, runtime `default` and optional chat `host`. Pass `default` / `host` + * directly as `model` to `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, + * add a selected `variant` if needed and preserve `variant: ''`. If thinking is supported, + * select an effort from `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session bound to this chat (agent, project directory, model) without running a + * turn, and return its `sessionId`; continue it with `run({ sessionId })` here or hand it to + * Node code. `agent` picks the session's agent from `agents()`; a session never changes it. + * Takes no run slot. If the Host's 60 s deadline passes it rejects with `runtime_unavailable` + * although the session may already exist. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). Pass a `requestId` to be + * able to stop it with `cancel(requestId)`. Resolves when the subscription ended: cancelled, the + * session was deleted, the page or Mini App stopped, or `session.read` was switched off. Rejects + * with `invalid_request` (not exactly one target), `not_permitted`, `session_not_found`, or + * `busy` past 4 observers per Mini App; observers use no run slots. Check + * `capabilities?.has('agent.observe')` first: older Hosts lack it. + */ + observe( + target: MiniAppAgentObserveTarget & { readonly requestId?: string }, + options: { readonly onEvent: (event: MiniAppAgentObservedEvent) => void }, + ): Promise; + /** Check `capabilities?.has('agent.sessions')` first: older Hosts lack it. */ + sessions(): Promise; + /** + * The chat this page is open in (needs `session.read`: it is the user's conversation, not this + * Mini App's); undefined when the page is not in a chat tab. Check + * `capabilities?.has('agent.session')` first. + */ + session(): Promise; + /** One conversation with its model and latest reply. */ + session(sessionId: string): Promise; +} + +/** + * Page entry for asking "always allow" ahead of time, while the user is present, so later Node + * calls need no prompt. Listing and calling tools is Node `context.tool` only. Needs + * `"toolAccess": ["call"]` and a running Node process; check + * `capabilities.has('tool.request')`. + */ +export interface MiniAppToolRequestAPI { + /** + * Shows one Host prompt for the named tools (runtime names from Node `context.tool.list()`) + * that are still `ask`; the user ticks which to always allow. Resolves each name's state + * afterwards; the Host never trusts this map back. Only inside a user gesture + * (`navigator.userActivation.isActive`), 1–10 distinct names, else `invalid_request`. + * Other rejections: `not_permitted` (no `toolAccess`), `approval_required` (no Host window + * can show the prompt), `runtime_unavailable` (Node process not running), `result_unknown`. + */ + request(names: readonly string[]): Promise>; +} + +export interface MiniAppClientAPI { + readonly message: MiniAppMessageAPI; + readonly agent?: MiniAppAgentAPI; + /** Absent on Hosts without `tool.request`. */ + readonly tool?: MiniAppToolRequestAPI; + /** + * Proposed: shape may still change. Feature-detect with + * `window.mcode?.miniapp?.window` before use. + */ + readonly window?: MiniAppWindowHandle; + /** Absent on older Hosts; check `capabilities.has('speech.transcribe')`. */ + readonly speech?: MiniAppSpeechAPI; + /** Effective Host preferences and bounded navigation; absent on older Hosts. */ + readonly host?: MiniAppHostAPI; + /** + * Synchronous probe of Host features, fixed per Host version; independent of this Mini App's + * manifest or grants. Absent on older Hosts: check `window.mcode?.miniapp?.capabilities?.has`. + */ + readonly capabilities?: MiniAppHostCapabilities; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +/** + * The only PCM the Host transcribes. Capture at exactly this (an `AudioContext` created with + * `sampleRate: 16000`, one channel, samples converted to `Int16Array`) and pass the object + * verbatim; any other value is `invalid_request`. See `audio-capture.ts` for a capture helper. + */ +export interface MiniAppSpeechAudioFormat { + readonly sampleRate: 16000; + readonly channelCount: 1; + readonly sampleFormat: 's16'; +} + +export interface MiniAppSpeechTranscribeInput { + /** + * One utterance of samples: an `Int16Array`, or the `ArrayBuffer` / view behind one. At least + * one sample, at most 16,000,000 bytes (500 s). Not an encoded file: WAV, WebM, Ogg, FLAC and + * MP3 are refused as `invalid_request`. + */ + readonly audio: ArrayBuffer | ArrayBufferView; + readonly format: MiniAppSpeechAudioFormat; +} + +export interface MiniAppSpeechTranscribeOptions { + /** The transcript so far while the Host is still transcribing; the final text is the result. */ + readonly onPartial?: (text: string) => void; +} + +/** + * Speech recognition of audio the page captured. Requires the manifest to declare + * `deviceAccess: ["microphone"]` and the user's "Use the microphone" switch to be on (the same + * switch that lets `getUserMedia` succeed); otherwise calls reject with `not_permitted`. + * The Host transcribes after it has the whole utterance: decide the utterance boundary in the + * page (release of a push-to-talk button, a stop button, a silence detector), then call once + * per utterance. One call per Mini App runs at a time; a second is `busy`. + * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, + * `audio_too_large`, `busy`, `runtime_unavailable` (speech recognition is disabled or the user + * is signed out), `transcription_failed`, or `result_unknown`. + */ +export interface MiniAppSpeechAPI { + transcribe( + input: MiniAppSpeechTranscribeInput, + options?: MiniAppSpeechTranscribeOptions, + ): Promise<{ readonly text: string }>; +} + +/** Live state of the popped-out window: current position, size, and flags — not the manifest declaration. */ +export interface MiniAppWindowOptions { + readonly width: number; + readonly height: number; + readonly minWidth: number; + readonly minHeight: number; + readonly x: number; + readonly y: number; + readonly visible: boolean; + readonly resizable: boolean; + readonly frame: boolean; + readonly transparent: boolean; + readonly alwaysOnTop: boolean; + readonly clickThrough: boolean; + readonly skipTaskbar: boolean; +} + +export type MiniAppWindowState = + | { readonly mode: 'inline'; readonly modeChangeReloadsPage?: boolean } + | { + readonly mode: 'window'; + readonly window: MiniAppWindowOptions; + readonly modeChangeReloadsPage?: boolean; + }; + +/** Every field is optional; omitted fields are left unchanged. */ +export type MiniAppWindowPatch = Partial<{ + mode: 'inline' | 'window'; + width: number; + height: number; + x: number; + y: number; + visible: boolean; + resizable: boolean; + alwaysOnTop: boolean; + clickThrough: boolean; + skipTaskbar: boolean; +}>; + +export interface MiniAppWindowDisposable { + dispose(): void; +} + +/** + * Page-side handle for this Mini App's own window (proposed). Separate from + * `message`; the Host injects both under the same `mcode.miniapp` namespace. + */ +export interface MiniAppWindowHandle { + /** Opaque and stable across pop-out and return; never a Session or launch identifier. */ + readonly id: string; + getState(): Promise; + /** + * `update({ mode: ... })` or `focus()` require the call to originate from a + * user gesture (`navigator.userActivation.isActive`); otherwise they reject + * with `not_permitted` before any Host round trip. The `click` handler of a + * `Notification` the page created counts as one. + * When getState().modeChangeReloadsPage is true, mode changes end this document. + * Do not rely on the old Promise continuation; read state on the destination page. + */ + update(patch: MiniAppWindowPatch): Promise; + focus(): Promise; + /** Returns a disposable; call `dispose()` to stop receiving updates. */ + onDidChangeState(listener: (state: MiniAppWindowState) => void): MiniAppWindowDisposable; +} + +/** Page-visible Host state. Resource identities and pending preferences never enter these values. */ +export interface MiniAppHostUIState { + readonly theme: 'light' | 'dark'; + readonly language: string; +} + +export type MiniAppHostView = 'home' | 'conversation' | 'plugins' | 'schedule' | 'other'; +export type MiniAppHostOverlay = { readonly type: 'settings' } | null; + +export interface MiniAppHostNavigationState { + /** Short-lived opaque value scoped to this page and its observation authorization. */ + readonly key: string; + readonly view: MiniAppHostView; + readonly overlay: MiniAppHostOverlay; +} + +export type MiniAppHostOpenTarget = + | { readonly id: 'home' } + | { readonly id: 'plugins' } + | { readonly id: 'schedule' } + | { readonly id: 'settings'; readonly section?: 'appearance' | 'language' } + | { readonly id: 'session'; readonly sessionId: string; readonly source: 'local' }; + +export type MiniAppHostOpenResult = + | { readonly status: 'opened' } + | { readonly status: 'cancelled'; readonly reason: 'user_cancelled' | 'superseded' }; + +export type MiniAppHostErrorCode = + | 'invalid_request' + | 'not_permitted' + | 'host_unavailable' + | 'unsupported_source' + | 'unsupported_target' + | 'target_unavailable' + | 'result_unknown'; +export interface MiniAppHostError { + readonly code: MiniAppHostErrorCode; + readonly message: string; +} +export interface MiniAppHostDisposable { + dispose(): void; +} +export interface MiniAppHostSubscribeOptions { + readonly onError?: (error: MiniAppHostError) => void; +} + +export interface MiniAppHostAPI { + readonly ui: { + getState(): Promise; + subscribe( + listener: (state: MiniAppHostUIState) => void, + options?: MiniAppHostSubscribeOptions, + ): MiniAppHostDisposable; + }; + readonly navigation: { + getState(): Promise; + subscribe( + listener: (state: MiniAppHostNavigationState) => void, + options?: MiniAppHostSubscribeOptions, + ): MiniAppHostDisposable; + open(target: MiniAppHostOpenTarget): Promise; + }; +} + +export interface McodeClientAPI { + readonly miniapp: MiniAppClientAPI; +} + +declare global { + interface Window { + /** Absent outside a supported managed Mini App main page. Check before use. */ + readonly mcode?: McodeClientAPI; + } +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/client/index.html b/plugins/zhuyankarl/submission-workbench/miniapp/client/index.html new file mode 100644 index 00000000..f0703a3a --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/client/index.html @@ -0,0 +1,177 @@ + + + + + + 插件上架材料工作台 + + + +
+ + + + +
+
+

上架信息

+ +
+
+ +

粘贴 .minimax-plugin/plugin.json 的完整内容。

+ +
+ +
+
+ + +
+
+ + +
+
+ +
+ +

说明能解决什么问题,不写内部技术实现。

+ +
+ +
+ +

将写入包的 README.md。

+ +
+ +
+ 示例 query(最多 3 条) +
+ +
+ +
+ 目标市场要求 +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+ + +
+
+ +
+ 目标区域 必填 + + +
+
+ 启用端 必填 + + +
+
+ +
+ 素材 +

+ 按角色上传:图标填 manifest 里的 icon 路径,Skill/MCP 填清单引用的相对路径,截图用于市场展示。 +

+
+ + + +
+ +
    +
    +
    +
    + +
    +
    +

    检查结果

    +
    尚未运行检查
    +
    +
    +
    + +
    +

    上架预览

    +
    +

    填写信息并运行检查后,这里显示市场卡片预览。

    +
    +
    + +
    +

    提交通道与权限

    +
    +

    尚未探测提交通道。

    +
    +
    + +
    +

    上架材料包

    +
    +

    还没有生成材料包。

    +
    +
    +
    +
    +
    + + + diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/miniapp.json b/plugins/zhuyankarl/submission-workbench/miniapp/miniapp.json new file mode 100644 index 00000000..498d880a --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/miniapp.json @@ -0,0 +1,20 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard" + }, + "mcpEndpoints": [] +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/channel.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/channel.mjs new file mode 100644 index 00000000..4c076b38 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/channel.mjs @@ -0,0 +1,157 @@ +// @ts-check +/** + * Probe for an official marketplace submission interface and the permissions + * that would be required to use it. + * + * Findings are grounded in the official submission guide (read 2026-11-16), + * which documents exactly two intake channels: a Feishu form (manual, browser, + * logged-in account) and a public GitHub repository. It documents no + * programmatic submission API. + * + * The app deliberately calls no Host tool API: `miniapp.json` declares no + * `toolAccess`, so `context.tool` is absent, and the scan never sees a call + * that would need a grant the manifest does not make. + * + * When no usable submission interface exists, the app must state that plainly + * and produce reviewable materials only — never claim a submission happened. + */ +import { GUIDE_URL } from './manifest-rules.mjs'; + +export const SUBMIT_FORM_URL = + 'https://vrfi1sk8a0.feishu.cn/share/base/form/shrcnbnpeor3z72fUkeHzrOE7vb'; +export const STATUS_FORM_URL = + 'https://vrfi1sk8a0.feishu.cn/share/base/form/shrcncjiq3QJqP0IYEFOytcEqrh'; + +/** + * @typedef {{ + * id: string, + * label: string, + * status: 'available' | 'unavailable' | 'unknown', + * detail: string, + * evidence: string, + * }} ChannelFinding + */ + +/** + * @typedef {{ + * checkedAt: string, + * submissionInterface: 'none' | 'manual_form' | 'tool', + * canSubmitProgrammatically: boolean, + * findings: ChannelFinding[], + * requiredPermissions: { key: string, label: string, satisfied: boolean, detail: string }[], + * conclusion: string, + * }} ChannelReport + */ + +const PROBE_TIMEOUT_MS = 8000; + +/** + * @param {string} url + * @returns {Promise<{ ok: boolean, status: number | null, error: string | null }>} + */ +async function probeHttp(url) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS); + try { + const response = await fetch(url, { + method: 'GET', + redirect: 'follow', + signal: controller.signal, + headers: { accept: 'text/html, text/plain, */*' }, + }); + return { ok: response.ok, status: response.status, error: null }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { ok: false, status: null, error: message }; + } finally { + clearTimeout(timer); + } +} + +/** + * Build the submission-channel report. + * @param {unknown} _context Unused: the app calls no Host tool API. + * @param {{ submitAccount: string, submitEmail: string, organization: string }} draft + * @returns {Promise} + */ +export async function probeSubmissionChannel(context, draft) { + /** @type {ChannelFinding[]} */ + const findings = []; + + const [guide, form, status] = await Promise.all([ + probeHttp(GUIDE_URL), + probeHttp(SUBMIT_FORM_URL), + probeHttp(STATUS_FORM_URL), + ]); + + findings.push({ + id: 'guide', + label: '官方上架指南', + status: guide.ok ? 'available' : 'unknown', + detail: guide.ok + ? `指南可访问(HTTP ${guide.status})。指南写明受理入口只有飞书表单与公开 GitHub 仓库两种。` + : `无法访问指南(${guide.error ?? `HTTP ${guide.status}`}),受理入口以最新指南为准。`, + evidence: `GET ${GUIDE_URL}`, + }); + + findings.push({ + id: 'form', + label: '飞书投稿表单', + status: form.ok ? 'available' : 'unknown', + detail: form.ok + ? `表单可访问(HTTP ${form.status}),但需人工在浏览器中登录飞书账号后提交。` + : `暂时无法访问表单(${form.error ?? `HTTP ${form.status}`})。`, + evidence: `GET ${SUBMIT_FORM_URL}`, + }); + + findings.push({ + id: 'status', + label: '进度查询表单', + status: status.ok ? 'available' : 'unknown', + detail: status.ok + ? `查询表单可访问(HTTP ${status.status}),查询需要原提交账号 + submission_id + 提交邮箱三者匹配。` + : `暂时无法访问查询表单(${status.error ?? `HTTP ${status.status}`})。`, + evidence: `GET ${STATUS_FORM_URL}`, + }); + + findings.push({ + id: 'tool', + label: '本机可用的投稿工具', + status: 'unavailable', + detail: '本应用不调用宿主工具接口,也不申请 toolAccess 授权,因此没有程序化投稿通道。', + evidence: 'miniapp.json 未声明 toolAccess', + }); + + const requiredPermissions = [ + { + key: 'feishuAccount', + label: '飞书账号(提交与查询进度时使用同一账号)', + satisfied: draft.submitAccount.trim() !== '', + detail: draft.submitAccount.trim() === '' ? '未填写' : `已填写:${draft.submitAccount.trim()}`, + }, + { + key: 'submitEmail', + label: '提交邮箱(查询进度需与 submission_id、账号三者匹配)', + satisfied: draft.submitEmail.trim() !== '', + detail: draft.submitEmail.trim() === '' ? '未填写' : `已填写:${draft.submitEmail.trim()}`, + }, + { + key: 'organization', + label: '组织/团队名称', + satisfied: draft.organization.trim() !== '', + detail: draft.organization.trim() === '' ? '未填写' : `已填写:${draft.organization.trim()}`, + }, + ]; + + const conclusion = + '未发现官方市场的程序化提交接口。官方受理入口为飞书表单(人工提交)与公开 GitHub 仓库,本应用因此只生成可审核的上架材料,不代表已提交或已上架。'; + + return { + checkedAt: new Date().toISOString(), + submissionInterface: 'manual_form', + canSubmitProgrammatically: false, + findings, + requiredPermissions, + conclusion, + }; +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/json-parse.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/json-parse.mjs new file mode 100644 index 00000000..667616ea --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/json-parse.mjs @@ -0,0 +1,170 @@ +// @ts-check +/** + * JSON parser that also reports duplicate object keys. + * + * The official manifest rules state that the JSON must be an object and must not + * contain duplicate keys (official guide §2). `JSON.parse` silently keeps the + * last duplicate, so the key set is checked with a small recursive-descent parser. + */ + +/** + * @typedef {{ ok: true, value: unknown, duplicates: { path: string, key: string }[] } + * | { ok: false, error: string, duplicates: { path: string, key: string }[] }} ParseResult + */ + +/** + * @param {string} text + * @returns {ParseResult} + */ +export function parseJsonWithDuplicates(text) { + /** @type {{ path: string, key: string }[]} */ + const duplicates = []; + let index = 0; + + const fail = (message) => { + const error = new Error(`${message}(第 ${index + 1} 个字符)`); + error.name = 'JsonParseError'; + throw error; + }; + + const skipWhitespace = () => { + while (index < text.length && /[\s\uFEFF]/.test(text[index])) index += 1; + }; + + const parseString = () => { + if (text[index] !== '"') fail('期望一个字符串'); + let value = ''; + index += 1; + while (index < text.length) { + const char = text[index]; + if (char === '"') { + index += 1; + return value; + } + if (char === '\\') { + index += 1; + const escape = text[index]; + if (escape === 'u') { + const hex = text.slice(index + 1, index + 5); + if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('无效的 \\u 转义'); + value += String.fromCharCode(parseInt(hex, 16)); + index += 5; + continue; + } + const map = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }; + if (!(escape in map)) fail('无效的转义字符'); + value += map[escape]; + index += 1; + continue; + } + value += char; + index += 1; + } + return fail('字符串没有闭合'); + }; + + const parseNumber = () => { + const match = /^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(text.slice(index)); + if (!match) fail('不是合法数字'); + index += match[0].length; + return Number(match[0]); + }; + + /** @param {string} path */ + const parseValue = (path) => { + skipWhitespace(); + const char = text[index]; + if (char === '{') return parseObject(path); + if (char === '[') return parseArray(path); + if (char === '"') return parseString(); + if (char === '-' || (char >= '0' && char <= '9')) return parseNumber(); + if (text.startsWith('true', index)) { + index += 4; + return true; + } + if (text.startsWith('false', index)) { + index += 5; + return false; + } + if (text.startsWith('null', index)) { + index += 4; + return null; + } + return fail('不是合法的 JSON 值'); + }; + + /** @param {string} path */ + const parseObject = (path) => { + index += 1; + /** @type {Record} */ + const result = {}; + /** @type {Set} */ + const seen = new Set(); + skipWhitespace(); + if (text[index] === '}') { + index += 1; + return result; + } + for (;;) { + skipWhitespace(); + const key = parseString(); + if (seen.has(key)) duplicates.push({ path: `${path}/${key}`, key }); + seen.add(key); + skipWhitespace(); + if (text[index] !== ':') fail('键之后缺少冒号'); + index += 1; + result[key] = parseValue(`${path}/${key}`); + skipWhitespace(); + if (text[index] === ',') { + index += 1; + continue; + } + if (text[index] === '}') { + index += 1; + return result; + } + return fail('对象结构不完整'); + } + }; + + /** @param {string} path */ + const parseArray = (path) => { + index += 1; + /** @type {unknown[]} */ + const result = []; + skipWhitespace(); + if (text[index] === ']') { + index += 1; + return result; + } + for (;;) { + result.push(parseValue(`${path}/${result.length}`)); + skipWhitespace(); + if (text[index] === ',') { + index += 1; + continue; + } + if (text[index] === ']') { + index += 1; + return result; + } + return fail('数组结构不完整'); + } + }; + + try { + skipWhitespace(); + if (index >= text.length) { + return { ok: false, error: '内容为空', duplicates }; + } + const value = parseValue(''); + skipWhitespace(); + if (index < text.length) { + return { ok: false, error: '内容末尾存在多余字符', duplicates }; + } + return { ok: true, value, duplicates }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { ok: false, error: message, duplicates }; + } +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/listing-rules.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/listing-rules.mjs new file mode 100644 index 00000000..506f71a5 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/listing-rules.mjs @@ -0,0 +1,539 @@ +// @ts-check +/** + * Listing-level rules: target-market requirements, content consistency between + * what the user typed and what the manifest declares, and the missing-item list. + * + * Sources for each rule are marked with the official guide section + * (https://code.minimax.cn/docs/code/agents/plugin-submission.md). + */ +import { CATEGORIES, LIMITS, validateManifest } from './manifest-rules.mjs'; + +/** + * @typedef {import('./manifest-rules.mjs').Issue} Issue + */ + +/** + * @typedef {{ + * id: string, + * name: string, + * role: 'icon' | 'screenshot' | 'skill' | 'mcp' | 'app' | 'doc', + * size: number, + * mime: string, + * createdAt: string, + * }} Asset + */ + +/** + * @typedef {{ + * manifestText: string, + * marketName: string, + * summary: string, + * documentation: string, + * category: string, + * exampleQueries: string[], + * regions: string[], + * enabledEnds: string[], + * operation: 'new' | 'update', + * existingName: string, + * previousVersion: string, + * submitEmail: string, + * submitAccount: string, + * organization: string, + * }} Draft + */ + +/** + * @param {string} value + * @returns {number} + */ +function byteLength(value) { + return Buffer.byteLength(value, 'utf8'); +} + +/** + * @param {string} value + * @returns {boolean} + */ +function looksLikePlaceholder(value) { + return /(todo|lorem ipsum|待补充|占位|placeholder|xxx+)/i.test(value); +} + +/** + * @param {string} text + * @returns {string[]} + */ +function keywords(text) { + return text + .toLowerCase() + .split(/[\s,,。、;;::!!??"'`()()\[\]{}/\\|]+/) + .filter((word) => word.length >= 2); +} + +/** + * Run listing-level validation on a draft plus its uploaded assets. + * @param {Draft} draft + * @param {Asset[]} assets + * @returns {{ issues: Issue[], manifest: Record | null, manifestIssues: Issue[] }} + */ +export function validateDraft(draft, assets) { + /** @type {Issue[]} */ + const issues = []; + const manifestResult = validateManifest(draft.manifestText ?? ''); + const manifest = manifestResult.manifest; + const manifestIssues = manifestResult.issues; + + const screenshots = assets.filter((asset) => asset.role === 'screenshot'); + const iconAssets = assets.filter((asset) => asset.role === 'icon'); + const skillAssets = assets.filter((asset) => asset.role === 'skill'); + const mcpAssets = assets.filter((asset) => asset.role === 'mcp'); + const appAssets = assets.filter((asset) => asset.role === 'app'); + + // ---- target market requirements (guide §8) ---- + if (!Array.isArray(draft.regions) || draft.regions.length === 0) { + issues.push({ + id: 'market.region.missing', + severity: 'error', + title: '未选择目标区域', + detail: '提交表单需要分别选择目标区域 CN/US。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'regions', + missing: true, + }); + } + if (!Array.isArray(draft.enabledEnds) || draft.enabledEnds.length === 0) { + issues.push({ + id: 'market.ends.missing', + severity: 'error', + title: '未选择启用端', + detail: '提交表单需要选择桌面端和/或云端。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'enabledEnds', + missing: true, + }); + } + if (draft.operation !== 'new' && draft.operation !== 'update') { + issues.push({ + id: 'market.operation.missing', + severity: 'error', + title: '未选择操作类型', + detail: '需要选择“上架新 Plugin”或“更新已有 Plugin”。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'operation', + missing: true, + }); + } + if (draft.operation === 'update') { + if (!draft.existingName.trim()) { + issues.push({ + id: 'market.update.existingName', + severity: 'error', + title: '更新操作缺少原 Plugin 名', + detail: '更新已有 Plugin 时 name 必须保持不变,需要填写原名称用于核对。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'existingName', + missing: true, + }); + } + if (!draft.previousVersion.trim()) { + issues.push({ + id: 'market.update.previousVersion', + severity: 'error', + title: '更新操作缺少上次提交版本', + detail: '包内内容变化时必须提升 version,需要填写上次提交版本用于核对。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'previousVersion', + missing: true, + }); + } + } + if (!draft.submitEmail.trim()) { + issues.push({ + id: 'market.email.missing', + severity: 'error', + title: '缺少提交邮箱', + detail: '查询进度需要“原提交飞书账号 + submission_id + 提交邮箱”三者匹配。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'submitEmail', + missing: true, + }); + } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(draft.submitEmail.trim())) { + issues.push({ + id: 'market.email.invalid', + severity: 'error', + title: '提交邮箱格式不正确', + detail: `当前值:${draft.submitEmail}`, + source: '指南 §8 提交新 Plugin 或更新', + field: 'submitEmail', + }); + } + if (!draft.submitAccount.trim()) { + issues.push({ + id: 'market.account.missing', + severity: 'warning', + title: '未填写提交飞书账号', + detail: '提交需要登录飞书账号;查询进度时账号必须与提交时一致。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'submitAccount', + missing: true, + }); + } + if (!draft.organization.trim()) { + issues.push({ + id: 'market.organization.missing', + severity: 'warning', + title: '未填写组织/团队', + detail: '提交表单需要填写组织/团队名称。', + source: '指南 §8 提交新 Plugin 或更新', + field: 'organization', + missing: true, + }); + } + + // ---- listing copy fields (guide §3, §9) ---- + const marketName = (draft.marketName ?? '').trim(); + if (marketName === '') { + issues.push({ + id: 'listing.name.missing', + severity: 'error', + title: '缺少期望市场名称', + detail: '需要填写在市场中展示的名称。', + source: '指南 §9 提交前自查', + field: 'marketName', + missing: true, + }); + } else if (byteLength(marketName) > 1024) { + issues.push({ + id: 'listing.name.bytes', + severity: 'error', + title: '市场名称超过 1024 字节', + detail: `当前 ${byteLength(marketName)} 字节。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'marketName', + }); + } + + const summary = (draft.summary ?? '').trim(); + if (summary === '') { + issues.push({ + id: 'listing.summary.missing', + severity: 'error', + title: '缺少简介', + detail: '简介是市场卡片上的第一句话,必须填写。', + source: '指南 §9 提交前自查', + field: 'summary', + missing: true, + }); + } else if (byteLength(summary) > 1024) { + issues.push({ + id: 'listing.summary.bytes', + severity: 'error', + title: '简介超过 1024 字节', + detail: `当前 ${byteLength(summary)} 字节。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'summary', + }); + } else if (looksLikePlaceholder(summary)) { + issues.push({ + id: 'listing.summary.placeholder', + severity: 'warning', + title: '简介看起来仍是占位内容', + detail: '审核会检查描述是否仍是测试内容。', + source: '指南 §10 常见驳回原因', + field: 'summary', + }); + } + + const documentation = (draft.documentation ?? '').trim(); + if (documentation === '') { + issues.push({ + id: 'listing.documentation.missing', + severity: 'error', + title: '缺少说明文档', + detail: '说明文档会写入包的 README.md。', + source: '指南 §2 标准目录结构', + field: 'documentation', + missing: true, + }); + } else if (looksLikePlaceholder(documentation)) { + issues.push({ + id: 'listing.documentation.placeholder', + severity: 'warning', + title: '说明文档看起来仍是占位内容', + detail: '提交前请替换为正式文案。', + source: '指南 §10 常见驳回原因', + field: 'documentation', + }); + } + + // ---- screenshots (guide §9) ---- + if (screenshots.length === 0) { + issues.push({ + id: 'listing.screenshot.missing', + severity: 'error', + title: '没有上传截图', + detail: '至少需要一张截图用于市场展示。', + source: '指南 §9 提交前自查', + field: 'screenshots', + missing: true, + }); + } + for (const shot of screenshots) { + if (shot.size > LIMITS.singleFileBytes) { + issues.push({ + id: `listing.screenshot.size.${shot.id}`, + severity: 'error', + title: `截图 ${shot.name} 超过单文件上限`, + detail: `当前 ${shot.size} 字节,上限 ${LIMITS.singleFileBytes} 字节。`, + source: '指南 §7 包体与安全限制', + field: 'screenshots', + }); + } + } + + // ---- target category (guide §3) ---- + // The category is a listing-form field in its own right: it must be reported + // even when the manifest is empty or invalid, so it lives outside the + // manifest-consistency block below. + if (!draft.category.trim()) { + issues.push({ + id: 'listing.category.missing', + severity: 'error', + title: '未选择目标分类', + detail: `需要从固定分类中选择:${CATEGORIES.join('、')}`, + source: '指南 §3 编写 Plugin Manifest', + field: 'category', + missing: true, + }); + } else if (!CATEGORIES.includes(draft.category)) { + issues.push({ + id: 'listing.category.invalid', + severity: 'error', + title: '目标分类不在固定分类中', + detail: `当前值:${draft.category}`, + source: '指南 §3 编写 Plugin Manifest', + field: 'category', + }); + } + + // ---- consistency between listing copy and manifest (guide §3, §9) ---- + if (manifest) { + const manifestDisplayName = + typeof manifest.displayName === 'string' && manifest.displayName.trim() !== '' + ? manifest.displayName.trim() + : typeof manifest.name === 'string' + ? manifest.name + : ''; + + if (marketName && manifestDisplayName && marketName !== manifestDisplayName) { + issues.push({ + id: 'consistency.marketName', + severity: 'warning', + title: '市场名称与清单展示名不一致', + detail: `市场名称「${marketName}」,清单 displayName「${manifestDisplayName}」。市场展示名以清单为准。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'marketName', + }); + } + if (!manifestDisplayName && marketName) { + issues.push({ + id: 'consistency.displayName.absent', + severity: 'info', + title: '清单未声明 displayName', + detail: `市场将回退显示 name「${String(manifest.name ?? '')}」。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'manifest', + }); + } + + if (summary && typeof manifest.description === 'string') { + const manifestDescription = manifest.description.trim(); + if (manifestDescription && manifestDescription !== summary) { + const shared = keywords(summary).filter((word) => keywords(manifestDescription).includes(word)); + issues.push({ + id: 'consistency.summary', + severity: shared.length === 0 ? 'warning' : 'info', + title: '简介与清单 description 不一致', + detail: + shared.length === 0 + ? '两段文字没有共同关键词,可能指向不同能力。' + : `两段文字共同关键词:${shared.join('、')}。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'summary', + }); + } + } + + if (documentation && manifestDisplayName && !documentation.includes(manifestDisplayName)) { + issues.push({ + id: 'consistency.documentation', + severity: 'warning', + title: '说明文档没有提到插件名', + detail: `文档中未出现「${manifestDisplayName}」。`, + source: '指南 §9 提交前自查', + field: 'documentation', + }); + } + + if (draft.category && manifest.category && draft.category !== manifest.category) { + issues.push({ + id: 'consistency.category', + severity: 'warning', + title: '目标分类与清单 category 不一致', + detail: `目标分类「${draft.category}」,清单 category「${String(manifest.category)}」。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'category', + }); + } + + const listingQueries = (draft.exampleQueries ?? []).filter((query) => query.trim() !== ''); + if (listingQueries.length > 3) { + issues.push({ + id: 'listing.queries.count', + severity: 'error', + title: '示例 query 超过 3 条', + detail: `当前 ${listingQueries.length} 条。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } + for (const query of listingQueries) { + if (looksLikePlaceholder(query)) { + issues.push({ + id: 'listing.queries.placeholder', + severity: 'warning', + title: '示例 query 看起来仍是测试内容', + detail: `命中:${query}`, + source: '指南 §10 常见驳回原因', + field: 'exampleQueries', + }); + } + } + const manifestQueries = Array.isArray(manifest.exampleQueries) ? manifest.exampleQueries : []; + if (listingQueries.length > 0 && manifestQueries.length > 0) { + const same = + listingQueries.length === manifestQueries.length && + listingQueries.every((query, index) => query.trim() === String(manifestQueries[index] ?? '').trim()); + if (!same) { + issues.push({ + id: 'consistency.queries', + severity: 'warning', + title: '示例 query 与清单 exampleQueries 不一致', + detail: '市场展示的示例 query 需要与清单保持一致。', + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } + } + if (listingQueries.length === 0 && manifestQueries.length === 0) { + issues.push({ + id: 'listing.queries.none', + severity: 'warning', + title: '没有示例 query', + detail: '指南允许 0–3 条,但示例能显著降低用户误用概率。', + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } + + // ---- capability files present in the package (guide §9, §10) ---- + const declaredSkills = Array.isArray(manifest.skills) ? manifest.skills.map(String) : []; + const declaredMcp = Array.isArray(manifest.mcpServers) ? manifest.mcpServers.map(String) : []; + const declaredApps = Array.isArray(manifest.apps) ? manifest.apps.map(String) : []; + + for (const path of declaredSkills) { + if (!skillAssets.some((asset) => asset.name === path)) { + issues.push({ + id: `asset.skill.missing.${path}`, + severity: 'error', + title: `缺少 Skill 文件 ${path}`, + detail: '清单引用了它,但上传的素材里没有同名文件。', + source: '指南 §10 常见驳回原因', + field: 'skills', + missing: true, + }); + } + } + for (const path of declaredMcp) { + if (!mcpAssets.some((asset) => asset.name === path)) { + issues.push({ + id: `asset.mcp.missing.${path}`, + severity: 'error', + title: `缺少 MCP 文件 ${path}`, + detail: '清单引用了它,但上传的素材里没有同名文件。', + source: '指南 §10 常见驳回原因', + field: 'mcpServers', + missing: true, + }); + } + } + for (const path of declaredApps) { + if (!appAssets.some((asset) => asset.name === path)) { + issues.push({ + id: `asset.app.missing.${path}`, + severity: 'error', + title: `缺少 App 文件 ${path}`, + detail: '清单引用了它,但上传的素材里没有同名文件。', + source: '指南 §10 常见驳回原因', + field: 'apps', + missing: true, + }); + } + } + + const iconPath = typeof manifest.icon === 'string' ? manifest.icon : ''; + if (iconPath && !iconAssets.some((asset) => asset.name === iconPath)) { + issues.push({ + id: 'asset.icon.missing', + severity: 'error', + title: `缺少图标文件 ${iconPath}`, + detail: '清单声明了 icon,但上传的素材里没有这个路径的图标。', + source: '指南 §9 提交前自查', + field: 'icon', + missing: true, + }); + } + + // ---- version bump on update (guide §8) ---- + if (draft.operation === 'update' && manifest.version && draft.previousVersion.trim()) { + const previous = draft.previousVersion.trim(); + const current = String(manifest.version); + if (previous === current) { + issues.push({ + id: 'market.update.versionSame', + severity: 'error', + title: '版本号没有提升', + detail: `上次提交 ${previous},当前仍为 ${current}。包内内容变化时必须提升 version。`, + source: '指南 §8 提交新 Plugin 或更新', + field: 'previousVersion', + }); + } else if (previous.localeCompare(current, undefined, { numeric: true }) >= 0) { + issues.push({ + id: 'market.update.versionLower', + severity: 'error', + title: '版本号没有提升', + detail: `上次提交 ${previous},当前 ${current} 未高于上次版本。`, + source: '指南 §8 提交新 Plugin 或更新', + field: 'previousVersion', + }); + } + } + if ( + draft.operation === 'update' && + manifest.name && + draft.existingName.trim() && + draft.existingName.trim() !== manifest.name + ) { + issues.push({ + id: 'market.update.nameChanged', + severity: 'error', + title: '更新操作修改了 Plugin 名', + detail: `原名「${draft.existingName.trim()}」,清单 name「${String(manifest.name)}」。更新时 name 必须保持不变。`, + source: '指南 §8 提交新 Plugin 或更新', + field: 'existingName', + }); + } + } + + const all = [...manifestIssues, ...issues]; + return { issues: all, manifest, manifestIssues }; +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/manifest-rules.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/manifest-rules.mjs new file mode 100644 index 00000000..0708d6cc --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/manifest-rules.mjs @@ -0,0 +1,542 @@ +// @ts-check +/** + * Manifest validation rules for the MiniMax Plugin marketplace. + * + * Every rule carries the official guide section it comes from + * (https://code.minimax.cn/docs/code/agents/plugin-submission.md, read 2026-11-16), + * so the UI can always answer "why is this flagged". + */ +import { parseJsonWithDuplicates } from './json-parse.mjs'; + +export const GUIDE_URL = 'https://code.minimax.cn/docs/code/agents/plugin-submission.md'; + +export const CATEGORIES = [ + 'Office', + 'Studio', + 'Design & Sites', + 'Code', + 'Business', + 'Sales', + 'Productivity', + 'Science & Healthcare', + 'Education', + 'Other', +]; + +export const ICON_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp']; + +export const LIMITS = { + zipBytes: 64 * 1024 * 1024, + entries: 2048, + files: 1024, + singleFileBytes: 16 * 1024 * 1024, + totalUnpackedBytes: 64 * 1024 * 1024, + pathBytes: 512, + pathSegmentBytes: 128, + pathDepth: 16, +}; + +const NAME_PATTERN = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/; +const SEMVER_PATTERN = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; + +const KNOWN_FIELDS = new Set([ + 'schemaVersion', + 'name', + 'displayName', + 'version', + 'description', + 'author', + 'icon', + 'category', + 'exampleQueries', + 'apps', + 'mcpServers', + 'skills', +]); + +/** Fields the guide explicitly says do not belong in plugin.json (guide §3). */ +const FORBIDDEN_FIELDS = new Set(['deliveryTargets', 'installationPolicy', 'listed', 'darkIcon', 'hooks']); + +const CAPABILITY_FIELDS = ['apps', 'mcpServers', 'skills']; + +/** + * @typedef {{ + * id: string, + * severity: 'error' | 'warning' | 'info', + * title: string, + * detail: string, + * source: string, + * field?: string, + * missing?: boolean, + * }} Issue + */ + +/** + * @param {string} value + * @returns {number} UTF-8 byte length + */ +function byteLength(value) { + return Buffer.byteLength(value, 'utf8'); +} + +/** + * Validate a capability path declared in the manifest (guide §2, §3, §7). + * @param {string} path + * @param {string} label + * @returns {string[]} problems + */ +function checkCapabilityPath(path, label) { + /** @type {string[]} */ + const problems = []; + if (typeof path !== 'string' || path.trim() === '') { + problems.push(`${label} 不是有效的相对路径`); + return problems; + } + if (path.includes('\\')) problems.push(`${label} 使用了反斜杠,路径必须使用 /`); + if (path.startsWith('/')) problems.push(`${label} 是绝对路径,必须是包内相对路径`); + if (/^[A-Za-z]:/.test(path)) problems.push(`${label} 是 Windows 绝对路径,必须是包内相对路径`); + if (path.split('/').some((part) => part === '..')) problems.push(`${label} 包含上级目录穿越`); + if (!/^[\x21-\x7e]+$/.test(path)) problems.push(`${label} 含有非 ASCII 字符`); + if (!/^[A-Za-z0-9._\-/]+$/.test(path)) problems.push(`${label} 含不允许的字符(只允许字母、数字、点、下划线、连字符)`); + const depth = path.split('/').length; + if (depth > LIMITS.pathDepth) problems.push(`${label} 路径深度 ${depth} 超过 ${LIMITS.pathDepth} 段`); + if (byteLength(path) > LIMITS.pathBytes) problems.push(`${label} 路径长度超过 ${LIMITS.pathBytes} 字节`); + for (const segment of path.split('/')) { + if (byteLength(segment) > LIMITS.pathSegmentBytes) { + problems.push(`${label} 中 "${segment}" 超过 ${LIMITS.pathSegmentBytes} 字节`); + } + } + return problems; +} + +/** + * Run every manifest rule against the pasted manifest text. + * @param {string} manifestText + * @returns {{ issues: Issue[], manifest: Record | null, ok: boolean }} + */ +export function validateManifest(manifestText) { + /** @type {Issue[]} */ + const issues = []; + const raw = manifestText ?? ''; + const trimmed = raw.trim(); + + // `String.prototype.trim()` strips U+FEFF, so the BOM must be checked on the + // raw text before trimming — otherwise a BOM-prefixed manifest looks clean. + if (raw.charCodeAt(0) === 0xfeff) { + issues.push({ + id: 'manifest.bom', + severity: 'error', + title: '清单包含 UTF-8 BOM', + detail: '文本文件必须使用 UTF-8 且不带 BOM。', + source: '指南 §2 标准目录结构', + field: 'manifest', + }); + } + + if (trimmed === '') { + issues.push({ + id: 'manifest.empty', + severity: 'error', + title: '插件清单为空', + detail: '还没有粘贴 .minimax-plugin/plugin.json 的内容。', + source: '指南 §3 编写 Plugin Manifest', + field: 'manifest', + missing: true, + }); + return { issues, manifest: null, ok: false }; + } + + const parsed = parseJsonWithDuplicates(trimmed); + if (!parsed.ok) { + issues.push({ + id: 'manifest.json', + severity: 'error', + title: '清单不是合法 JSON', + detail: parsed.error, + source: '指南 §2 标准目录结构(JSON 必须是 object)', + field: 'manifest', + missing: true, + }); + return { issues, manifest: null, ok: false }; + } + + if (parsed.duplicates.length > 0) { + issues.push({ + id: 'manifest.duplicateKeys', + severity: 'error', + title: '清单包含重复 key', + detail: `重复位置:${parsed.duplicates.map((item) => item.path).join('、')}`, + source: '指南 §2 标准目录结构(JSON 不能包含重复 key)', + field: 'manifest', + }); + } + + if (typeof parsed.value !== 'object' || parsed.value === null || Array.isArray(parsed.value)) { + issues.push({ + id: 'manifest.notObject', + severity: 'error', + title: '清单顶层必须是对象', + detail: '当前顶层不是 JSON object。', + source: '指南 §2 标准目录结构', + field: 'manifest', + }); + return { issues, manifest: null, ok: false }; + } + + const manifest = /** @type {Record} */ (parsed.value); + + if (manifest.schemaVersion !== 1) { + issues.push({ + id: 'manifest.schemaVersion', + severity: 'error', + title: 'schemaVersion 必须为 1', + detail: `当前值:${JSON.stringify(manifest.schemaVersion ?? null)}`, + source: '指南 §3 编写 Plugin Manifest', + field: 'schemaVersion', + }); + } + + // name + const name = manifest.name; + if (typeof name !== 'string' || name.trim() === '') { + issues.push({ + id: 'manifest.name.missing', + severity: 'error', + title: '缺少 name', + detail: 'name 是包的机器名,必填。', + source: '指南 §3 编写 Plugin Manifest', + field: 'name', + missing: true, + }); + } else { + if (name.length > 80) { + issues.push({ + id: 'manifest.name.length', + severity: 'error', + title: 'name 超过 80 个字符', + detail: `当前长度 ${name.length}。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'name', + }); + } + if (!NAME_PATTERN.test(name)) { + issues.push({ + id: 'manifest.name.pattern', + severity: 'error', + title: 'name 不符合小写机器名规则', + detail: '要求以字母开头,只使用小写字母、数字及 . _ - 分隔符。', + source: '指南 §3 编写 Plugin Manifest', + field: 'name', + }); + } + } + + // version + const version = manifest.version; + if (typeof version !== 'string' || version.trim() === '') { + issues.push({ + id: 'manifest.version.missing', + severity: 'error', + title: '缺少 version', + detail: 'version 必填且必须是 SemVer。', + source: '指南 §3 编写 Plugin Manifest', + field: 'version', + missing: true, + }); + } else if (!SEMVER_PATTERN.test(version)) { + issues.push({ + id: 'manifest.version.semver', + severity: 'error', + title: 'version 不是合法 SemVer', + detail: `当前值:${version}。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'version', + }); + } + + // displayName + if (manifest.displayName !== undefined) { + const displayName = manifest.displayName; + if (typeof displayName !== 'string' || displayName.trim() === '') { + issues.push({ + id: 'manifest.displayName.empty', + severity: 'error', + title: 'displayName 去除空白后为空', + detail: '省略 displayName 时会回退到 name;保留该字段时必须非空。', + source: '指南 §3 编写 Plugin Manifest', + field: 'displayName', + }); + } else if (byteLength(displayName) > 1024) { + issues.push({ + id: 'manifest.displayName.bytes', + severity: 'error', + title: 'displayName 超过 1024 字节', + detail: `当前 ${byteLength(displayName)} 字节。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'displayName', + }); + } + } + + // description + const description = manifest.description; + if (typeof description !== 'string' || description.trim() === '') { + issues.push({ + id: 'manifest.description.missing', + severity: 'error', + title: '缺少 description', + detail: 'description 必填,需要说明能解决什么问题。', + source: '指南 §3 编写 Plugin Manifest', + field: 'description', + missing: true, + }); + } else { + const implementationHints = [ + 'hook', + 'stdio', + 'json schema', + '内部实现', + '内部技术实现', + '端点地址', + 'endpoint', + 'api key', + '调试', + ].filter((word) => description.toLowerCase().includes(word)); + if (implementationHints.length > 0) { + issues.push({ + id: 'manifest.description.implementation', + severity: 'warning', + title: 'description 可能写入了内部技术实现', + detail: `命中:${implementationHints.join('、')}。指南要求只说明能解决什么问题。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'description', + }); + } + } + + // author + const author = manifest.author; + if (typeof author !== 'string' || author.trim() === '') { + issues.push({ + id: 'manifest.author.missing', + severity: 'error', + title: '缺少 author', + detail: 'author 必填,填写开发者、团队或公司名称。', + source: '指南 §3 编写 Plugin Manifest', + field: 'author', + missing: true, + }); + } else if (byteLength(author) > 1024) { + issues.push({ + id: 'manifest.author.bytes', + severity: 'error', + title: 'author 超过 1024 字节', + detail: `当前 ${byteLength(author)} 字节。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'author', + }); + } + + // icon + const icon = manifest.icon; + if (typeof icon !== 'string' || icon.trim() === '') { + issues.push({ + id: 'manifest.icon.missing', + severity: 'error', + title: '缺少 icon', + detail: 'icon 必填,指向包内相对路径,且不能为 null。', + source: '指南 §3 编写 Plugin Manifest', + field: 'icon', + missing: true, + }); + } else { + const extension = icon.slice(icon.lastIndexOf('.')).toLowerCase(); + if (!ICON_EXTENSIONS.includes(extension)) { + issues.push({ + id: 'manifest.icon.extension', + severity: 'error', + title: 'icon 扩展名不被接受', + detail: `只支持 ${ICON_EXTENSIONS.join(' / ')}。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'icon', + }); + } + if (icon !== icon.toLowerCase()) { + issues.push({ + id: 'manifest.icon.lowercase', + severity: 'error', + title: 'icon 路径必须全小写', + detail: '生产发布仅接受小写扩展名。', + source: '指南 §3 编写 Plugin Manifest', + field: 'icon', + }); + } + checkCapabilityPath(icon, 'icon').forEach((problem, problemIndex) => { + issues.push({ + id: `manifest.icon.path.${problemIndex}`, + severity: 'error', + title: 'icon 路径不合规', + detail: problem, + source: '指南 §2 标准目录结构', + field: 'icon', + }); + }); + } + + // category + const category = manifest.category; + if (typeof category !== 'string' || category.trim() === '') { + issues.push({ + id: 'manifest.category.missing', + severity: 'error', + title: '缺少 category', + detail: 'category 必填,需从固定分类中选择。', + source: '指南 §3 编写 Plugin Manifest', + field: 'category', + missing: true, + }); + } else if (!CATEGORIES.includes(category)) { + issues.push({ + id: 'manifest.category.invalid', + severity: 'error', + title: 'category 不在固定分类中', + detail: `当前值:${category}。可选:${CATEGORIES.join('、')}`, + source: '指南 §3 编写 Plugin Manifest', + field: 'category', + }); + } + + // exampleQueries + const queries = manifest.exampleQueries; + if (!Array.isArray(queries)) { + issues.push({ + id: 'manifest.exampleQueries.type', + severity: 'error', + title: 'exampleQueries 必须是数组', + detail: '允许 0–3 条真实示例。', + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } else { + if (queries.length > 3) { + issues.push({ + id: 'manifest.exampleQueries.count', + severity: 'error', + title: 'exampleQueries 超过 3 条', + detail: `当前 ${queries.length} 条。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } + queries.forEach((query, index) => { + if (typeof query !== 'string' || query.trim() === '') { + issues.push({ + id: `manifest.exampleQueries.${index}.empty`, + severity: 'error', + title: `exampleQueries 第 ${index + 1} 条为空`, + detail: '每条示例必须非空。', + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } else if (query.length > 4096) { + issues.push({ + id: `manifest.exampleQueries.${index}.length`, + severity: 'error', + title: `exampleQueries 第 ${index + 1} 条超过 4096 个字符`, + detail: `当前 ${query.length} 个字符。`, + source: '指南 §3 编写 Plugin Manifest', + field: 'exampleQueries', + }); + } + }); + } + + // capability arrays + let capabilityCount = 0; + for (const field of CAPABILITY_FIELDS) { + const value = manifest[field]; + if (value === undefined) { + issues.push({ + id: `manifest.${field}.missing`, + severity: 'warning', + title: `缺少 ${field} 字段`, + detail: '未使用的能力也要保留为空数组。', + source: '指南 §3 编写 Plugin Manifest', + field, + }); + continue; + } + if (!Array.isArray(value)) { + issues.push({ + id: `manifest.${field}.type`, + severity: 'error', + title: `${field} 必须是数组`, + detail: '填写包内相对路径;未使用的能力必须保留为空数组。', + source: '指南 §3 编写 Plugin Manifest', + field, + }); + continue; + } + capabilityCount += value.length; + value.forEach((entry, index) => { + const problems = checkCapabilityPath(String(entry), `${field}[${index}]`); + problems.forEach((problem, problemIndex) => { + issues.push({ + // A single path can break several rules at once, so the problem index + // keeps every issue id unique. + id: `manifest.${field}.${index}.path.${problemIndex}`, + severity: 'error', + title: `${field} 路径不合规`, + detail: problem, + source: '指南 §2 标准目录结构', + field, + }); + }); + }); + } + if (capabilityCount === 0) { + issues.push({ + id: 'manifest.capability.none', + severity: 'error', + title: '至少需要一种能力', + detail: 'App、MCP、Skill 至少填写一项。', + source: '指南 §1 先选择要提供的能力', + field: 'capabilities', + missing: true, + }); + } + + // hooks / forbidden fields + for (const field of FORBIDDEN_FIELDS) { + if (manifest[field] !== undefined) { + const isHook = field === 'hooks'; + issues.push({ + id: `manifest.forbidden.${field}`, + severity: 'error', + title: isHook ? '不能提交 hooks 字段' : `不能声明 ${field} 字段`, + detail: isHook + ? '当前第三方表单尚不受理 Hook,请勿提交 hooks 字段或 Hook JSON 文件。' + : '该字段不属于 plugin.json,生产发布会拒绝。', + source: isHook ? '指南 §1 先选择要提供的能力' : '指南 §3 编写 Plugin Manifest', + field, + }); + } + } + + for (const key of Object.keys(manifest)) { + if (!KNOWN_FIELDS.has(key) && !FORBIDDEN_FIELDS.has(key)) { + issues.push({ + id: `manifest.unknown.${key}`, + severity: 'warning', + title: `清单出现未知字段 ${key}`, + detail: 'plugin.json 的字段集合是固定的,未知字段可能触发审核问题。', + source: '指南 §3 编写 Plugin Manifest', + field: key, + }); + } + } + + const ok = !issues.some((issue) => issue.severity === 'error'); + return { issues, manifest, ok }; +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/package-builder.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/package-builder.mjs new file mode 100644 index 00000000..e0c0ec61 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/package-builder.mjs @@ -0,0 +1,289 @@ +// @ts-check +/** + * Build the preview object and the reviewable listing package. + * + * The package layout follows the official guide §2 exactly: `.minimax-plugin/plugin.json` + * sits directly at the ZIP root with no wrapper directory, capability files keep + * the paths the manifest declares, and the listing materials (market copy, docs, + * screenshots, review notes) live under `listing-materials/`. + */ +import { createZip } from './zip.mjs'; +import { sha256 } from './store.mjs'; +import { CATEGORIES, GUIDE_URL, LIMITS } from './manifest-rules.mjs'; + +/** + * @typedef {import('./manifest-rules.mjs').Issue} Issue + * @typedef {import('./store.mjs').Asset} Asset + */ + +/** + * @typedef {{ + * marketName: string, + * summary: string, + * version: string, + * category: string, + * author: string, + * regions: string[], + * enabledEnds: string[], + * exampleQueries: string[], + * screenshotCount: number, + * capabilityFiles: { path: string, role: string, present: boolean }[], + * }} ListingPreview + */ + +/** + * Build the market-facing preview shown in the UI. + * @param {Record | null} manifest + * @param {import('./listing-rules.mjs').Draft} draft + * @param {Asset[]} assets + * @returns {ListingPreview} + */ +export function buildPreview(manifest, draft, assets) { + const screenshots = assets.filter((asset) => asset.role === 'screenshot'); + const capabilityFiles = []; + if (manifest) { + for (const field of ['skills', 'mcpServers', 'apps']) { + const value = manifest[field]; + if (!Array.isArray(value)) continue; + for (const entry of value) { + const path = String(entry); + const role = field === 'skills' ? 'skill' : field === 'mcpServers' ? 'mcp' : 'app'; + capabilityFiles.push({ + path, + role, + present: assets.some((asset) => asset.role === role && asset.name === path), + }); + } + } + } + return { + marketName: draft.marketName || (typeof manifest?.displayName === 'string' ? manifest.displayName : ''), + summary: draft.summary || (typeof manifest?.description === 'string' ? manifest.description : ''), + version: typeof manifest?.version === 'string' ? manifest.version : '', + category: draft.category || (typeof manifest?.category === 'string' ? manifest.category : ''), + author: typeof manifest?.author === 'string' ? manifest.author : '', + regions: draft.regions ?? [], + enabledEnds: draft.enabledEnds ?? [], + exampleQueries: (draft.exampleQueries ?? []).filter((query) => query.trim() !== ''), + screenshotCount: screenshots.length, + capabilityFiles, + }; +} + +/** + * @param {string} value + * @returns {string} + */ +function escapeCell(value) { + return value.replace(/\|/g, '\\|').replace(/\r?\n/g, ' '); +} + +/** + * Render the review report as Markdown. + * @param {import('./listing-rules.mjs').Draft} draft + * @param {Record | null} manifest + * @param {Issue[]} issues + * @param {Asset[]} assets + * @param {import('./channel.mjs').ChannelReport} channel + * @returns {string} + */ +export function renderReviewReport(draft, manifest, issues, assets, channel) { + const errors = issues.filter((issue) => issue.severity === 'error'); + const warnings = issues.filter((issue) => issue.severity === 'warning'); + const missing = issues.filter((issue) => issue.missing); + const lines = []; + + lines.push('# 上架材料自检报告'); + lines.push(''); + lines.push(`生成时间:${new Date().toISOString()}`); + lines.push(''); + lines.push( + '> 本报告由本地 Mini App 生成。**材料尚未提交到官方市场,也不代表已上架。**', + '> 官方受理入口为飞书表单(人工提交)与公开 GitHub 仓库;本工具只产出可审核材料。', + '', + ); + lines.push(`规则依据:《插件开发与上架指南》 ${GUIDE_URL}`); + lines.push(''); + + lines.push('## 一、结论'); + lines.push(''); + lines.push(`- 错误:${errors.length} 项`); + lines.push(`- 警告:${warnings.length} 项`); + lines.push(`- 缺失项:${missing.length} 项`); + lines.push(`- 提交通道:${channel.conclusion}`); + lines.push(''); + + lines.push('## 二、缺失项'); + lines.push(''); + if (missing.length === 0) { + lines.push('无。'); + } else { + lines.push('| 字段 | 问题 | 依据 |'); + lines.push('| --- | --- | --- |'); + for (const issue of missing) { + lines.push(`| ${escapeCell(issue.field ?? '-')} | ${escapeCell(issue.title)}:${escapeCell(issue.detail)} | ${escapeCell(issue.source)} |`); + } + } + lines.push(''); + + lines.push('## 三、逐项检查'); + lines.push(''); + if (issues.length === 0) { + lines.push('未发现问题。'); + } else { + lines.push('| 级别 | 问题 | 说明 | 依据 |'); + lines.push('| --- | --- | --- | --- |'); + for (const issue of issues) { + const level = issue.severity === 'error' ? '错误' : issue.severity === 'warning' ? '警告' : '提示'; + lines.push(`| ${level} | ${escapeCell(issue.title)} | ${escapeCell(issue.detail)} | ${escapeCell(issue.source)} |`); + } + } + lines.push(''); + + lines.push('## 四、上架字段'); + lines.push(''); + lines.push('| 表单项 | 值 |'); + lines.push('| --- | --- |'); + lines.push(`| Plugin 名 | ${escapeCell(String(manifest?.name ?? '(缺失)'))} |`); + lines.push(`| 操作类型 | ${draft.operation === 'update' ? '更新已有 Plugin' : '上架新 Plugin'} |`); + lines.push('| 来源类型 | ZIP |'); + lines.push(`| 目标区域 | ${escapeCell(draft.regions.join('、') || '(未选)')} |`); + lines.push(`| 启用端 | ${escapeCell(draft.enabledEnds.join('、') || '(未选)')} |`); + lines.push(`| 组织/团队 | ${escapeCell(draft.organization || '(未填)')} |`); + lines.push(`| 联系邮箱 | ${escapeCell(draft.submitEmail || '(未填)')} |`); + lines.push(`| 期望市场名称 | ${escapeCell(draft.marketName || '(未填)')} |`); + lines.push(`| 简介 | ${escapeCell(draft.summary || '(未填)')} |`); + lines.push(`| 分类 | ${escapeCell(draft.category || '(未选)')} |`); + lines.push( + `| 示例 query | ${escapeCell((draft.exampleQueries ?? []).filter((q) => q.trim()).join(' / ') || '(未填)')} |`, + ); + lines.push(''); + + lines.push('## 五、素材清单'); + lines.push(''); + if (assets.length === 0) { + lines.push('未上传素材。'); + } else { + lines.push('| 角色 | 路径 | 大小(字节) |'); + lines.push('| --- | --- | --- |'); + for (const asset of assets) { + lines.push(`| ${escapeCell(asset.role)} | ${escapeCell(asset.name)} | ${asset.size} |`); + } + } + lines.push(''); + + lines.push('## 六、提交通道与权限'); + lines.push(''); + for (const finding of channel.findings) { + lines.push(`- **${finding.label}**(${finding.status}):${finding.detail} 证据:${finding.evidence}`); + } + lines.push(''); + for (const permission of channel.requiredPermissions) { + lines.push(`- ${permission.satisfied ? '已具备' : '未具备'}:${permission.label} —— ${permission.detail}`); + } + lines.push(''); + lines.push('## 七、人工提交步骤'); + lines.push(''); + lines.push('1. 打开准备提交表单,选择“上架新 Plugin”或“更新已有 Plugin”。'); + lines.push('2. 目标区域选择 CN / US,启用端勾选桌面端 / 云端。'); + lines.push('3. 来源选择 ZIP,上传本包生成的 `.minimax-plugin/plugin.json` 位于根目录的 ZIP。'); + lines.push('4. 填写组织/团队与联系邮箱,提交后**保存 submission_id**。'); + lines.push('5. 查询进度需使用原提交飞书账号 + submission_id + 提交邮箱三者匹配。'); + lines.push(''); + lines.push(`固定分类可选值:${CATEGORIES.join('、')}`); + lines.push(''); + lines.push( + `包体上限参考:ZIP ≤ ${LIMITS.zipBytes} 字节、entries ≤ ${LIMITS.entries}、普通文件 ≤ ${LIMITS.files}、单文件解包 ≤ ${LIMITS.singleFileBytes} 字节、完整路径 ≤ ${LIMITS.pathBytes} 字节、路径深度 ≤ ${LIMITS.pathDepth} 段。`, + ); + lines.push(''); + + return lines.join('\n'); +} + +/** + * Assemble the ZIP payload and its entry manifest. + * @param {import('./listing-rules.mjs').Draft} draft + * @param {Record | null} manifest + * @param {Asset[]} assets + * @param {(asset: Asset) => Promise} readAsset + * @param {Issue[]} issues + * @param {import('./channel.mjs').ChannelReport} channel + * @returns {Promise<{ bytes: Buffer, entries: { path: string, size: number }[] }>} + */ +export async function buildPackage(draft, manifest, assets, readAsset, issues, channel) { + /** @type {{ path: string, data: Buffer }[]} */ + const entries = []; + + if (manifest) { + const pluginJson = `${JSON.stringify(manifest, null, 2)}\n`; + entries.push({ + path: '.minimax-plugin/plugin.json', + data: Buffer.from(pluginJson, 'utf8'), + }); + } + + const documentation = (draft.documentation ?? '').trim(); + if (documentation !== '') { + entries.push({ path: 'README.md', data: Buffer.from(documentation, 'utf8') }); + } + + // Capability files keep the exact paths the manifest declares. + for (const asset of assets) { + if (asset.role !== 'skill' && asset.role !== 'mcp' && asset.role !== 'app' && asset.role !== 'icon') { + continue; + } + const bytes = await readAsset(asset); + if (!bytes) continue; + entries.push({ path: asset.name, data: bytes }); + } + + // Review-only material lives in one clearly separated folder. + entries.push({ + path: 'listing-materials/review-report.md', + data: Buffer.from(renderReviewReport(draft, manifest, issues, assets, channel), 'utf8'), + }); + + const summaryText = [ + `# ${draft.marketName || '(未命名)'}`, + '', + draft.summary || '(未填写简介)', + '', + `版本:${String(manifest?.version ?? '-')}`, + `分类:${draft.category || '-'}`, + `作者:${String(manifest?.author ?? '-')}`, + `目标区域:${(draft.regions ?? []).join('、') || '-'}`, + `启用端:${(draft.enabledEnds ?? []).join('、') || '-'}`, + '', + '## 示例 query', + '', + ...((draft.exampleQueries ?? []).filter((query) => query.trim() !== '').map((query) => `- ${query}`)), + '', + '## 说明', + '', + '本目录是供人工审核的上架材料副本,不代表已提交或已上架。', + '', + ].join('\n'); + entries.push({ path: 'listing-materials/market-preview.md', data: Buffer.from(summaryText, 'utf8') }); + + const screenshots = assets.filter((asset) => asset.role === 'screenshot'); + for (const shot of screenshots) { + const bytes = await readAsset(shot); + if (!bytes) continue; + entries.push({ path: `listing-materials/screenshots/${shot.name}`, data: bytes }); + } + + const bytes = createZip(entries); + const entryList = entries.map((entry) => ({ + path: entry.path, + size: entry.data.length, + })); + return { bytes, entries: entryList }; +} + +/** + * @param {Buffer} bytes + * @returns {string} + */ +export function packageDigest(bytes) { + return sha256(bytes); +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/store.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/store.mjs new file mode 100644 index 00000000..b920ccd5 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/store.mjs @@ -0,0 +1,242 @@ +// @ts-check +/** + * Durable state for the Mini App: the working draft, uploaded assets and the + * generated listing packages. Everything lives under the Host-owned dataDir and + * is written atomically so a reclaimed process never leaves a half-written file. + */ +import { createHash, randomUUID } from 'node:crypto'; +import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { isAbsolute, join, relative, resolve } from 'node:path'; + +/** + * @typedef {{ + * id: string, + * name: string, + * role: 'icon' | 'screenshot' | 'skill' | 'mcp' | 'app' | 'doc', + * size: number, + * mime: string, + * createdAt: string, + * }} Asset + */ + +/** + * @typedef {{ + * id: string, + * fileName: string, + * createdAt: string, + * size: number, + * sha256: string, + * entries: { path: string, size: number }[], + * manifest: Record | null, + * }} PackageRecord + */ + +/** + * Every id in this store is produced by `randomUUID()`, so a legitimate id is a + * canonical v4 UUID. Anything else never reaches the filesystem. + */ +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +/** + * Raised when a caller-supplied id is not a server-generated id, or when the + * path it would produce leaves the directory it belongs to. + */ +export class InvalidIdError extends Error { + /** @param {string} message */ + constructor(message) { + super(message); + this.name = 'InvalidIdError'; + } +} + +/** + * Resolve `` inside `directory`, or refuse. + * + * Two independent checks: the id must look like a server-generated UUID, and + * the resolved path must still sit inside `directory`. The first one keeps + * separators out of the path at all; the second one is the check that actually + * closes the hole, so it stays even if the id format ever changes. + * + * @param {string} directory + * @param {string} id + * @param {string} suffix + * @returns {string} + */ +function resolveInside(directory, id, suffix) { + if (typeof id !== 'string' || !UUID_PATTERN.test(id)) { + throw new InvalidIdError('id 不是服务端生成的 UUID。'); + } + const base = resolve(directory); + const target = resolve(base, `${id}${suffix}`); + const inside = relative(base, target); + if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) { + throw new InvalidIdError('id 指向了目录之外。'); + } + return target; +} + +/** + * @param {string} file + * @param {string | Buffer} content + */ +async function writeAtomic(file, content) { + const temporary = `${file}.${randomUUID()}.tmp`; + await writeFile(temporary, content); + await rename(temporary, file); +} + +export class Store { + /** @param {string} dataDir */ + constructor(dataDir) { + this.dataDir = dataDir; + this.draftFile = join(dataDir, 'draft.json'); + this.assetsDir = join(dataDir, 'assets'); + this.packagesDir = join(dataDir, 'packages'); + } + + async init() { + await mkdir(this.dataDir, { recursive: true }); + await mkdir(this.assetsDir, { recursive: true }); + await mkdir(this.packagesDir, { recursive: true }); + } + + /** + * @template T + * @param {string} file + * @param {T} fallback + * @returns {Promise} + */ + async readJson(file, fallback) { + try { + const raw = await readFile(file, 'utf8'); + return JSON.parse(raw); + } catch (error) { + const code = /** @type {NodeJS.ErrnoException} */ (error).code; + if (code === 'ENOENT') return fallback; + throw error; + } + } + + /** + * @param {unknown} draft + */ + async saveDraft(draft) { + await writeAtomic(this.draftFile, JSON.stringify(draft, null, 2)); + } + + /** @returns {Promise} */ + async loadDraft() { + return this.readJson(this.draftFile, null); + } + + /** + * @param {Asset} asset + * @param {Buffer} bytes + */ + async saveAsset(asset, bytes) { + await writeAtomic(resolveInside(this.assetsDir, asset.id, '.bin'), bytes); + const list = await this.listAssets(); + const next = list.filter((item) => item.id !== asset.id); + next.push(asset); + await writeAtomic(join(this.assetsDir, 'index.json'), JSON.stringify(next, null, 2)); + return asset; + } + + /** @returns {Promise} */ + async listAssets() { + return this.readJson(join(this.assetsDir, 'index.json'), []); + } + + /** + * @param {string} id + * @returns {Promise} + */ + async readAssetBytes(id) { + try { + return await readFile(resolveInside(this.assetsDir, id, '.bin')); + } catch (error) { + const code = /** @type {NodeJS.ErrnoException} */ (error).code; + if (code === 'ENOENT') return null; + throw error; + } + } + + /** @param {string} id */ + async deleteAsset(id) { + const file = resolveInside(this.assetsDir, id, '.bin'); + const list = await this.listAssets(); + const next = list.filter((item) => item.id !== id); + await writeAtomic(join(this.assetsDir, 'index.json'), JSON.stringify(next, null, 2)); + await rm(file, { force: true }); + } + + /** + * @param {PackageRecord} record + * @param {Buffer} bytes + */ + async savePackage(record, bytes) { + await writeAtomic(resolveInside(this.packagesDir, record.id, '.zip'), bytes); + const list = await this.listPackages(); + const next = list.filter((item) => item.id !== record.id); + next.unshift(record); + await writeAtomic(join(this.packagesDir, 'index.json'), JSON.stringify(next, null, 2)); + return record; + } + + /** @returns {Promise} */ + async listPackages() { + return this.readJson(join(this.packagesDir, 'index.json'), []); + } + + /** + * @param {string} id + * @returns {Promise} + */ + async readPackageBytes(id) { + try { + return await readFile(resolveInside(this.packagesDir, id, '.zip')); + } catch (error) { + const code = /** @type {NodeJS.ErrnoException} */ (error).code; + if (code === 'ENOENT') return null; + throw error; + } + } + + /** @param {string} id */ + async deletePackage(id) { + const file = resolveInside(this.packagesDir, id, '.zip'); + const list = await this.listPackages(); + await writeAtomic( + join(this.packagesDir, 'index.json'), + JSON.stringify(list.filter((item) => item.id !== id), null, 2), + ); + await rm(file, { force: true }); + } +} + +/** + * @param {Buffer} bytes + * @returns {string} + */ +export function sha256(bytes) { + return createHash('sha256').update(bytes).digest('hex'); +} + +/** + * @param {string} directory + * @returns {Promise} + */ +export async function directorySize(directory) { + const entries = await readdir(directory, { withFileTypes: true }); + let total = 0; + for (const entry of entries) { + const full = join(directory, entry.name); + if (entry.isDirectory()) { + total += await directorySize(full); + } else { + const info = await stat(full); + total += info.size; + } + } + return total; +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/zip.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/zip.mjs new file mode 100644 index 00000000..ddac8927 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/lib/zip.mjs @@ -0,0 +1,128 @@ +// @ts-check +/** + * Dependency-free ZIP writer (STORE / DEFLATE) built on node:zlib. + * + * The official marketplace intake accepts an unencrypted STORE or DEFLATE ZIP + * whose root directly contains `.minimax-plugin/plugin.json` (official guide §7, §8). + * This writer therefore never emits a wrapper directory. + */ +import { deflateRawSync } from 'node:zlib'; + +const CRC_TABLE = (() => { + const table = new Int32Array(256); + for (let i = 0; i < 256; i += 1) { + let c = i; + for (let k = 0; k < 8; k += 1) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + table[i] = c; + } + return table; +})(); + +/** + * @param {Buffer} buffer + * @returns {number} unsigned CRC-32 + */ +export function crc32(buffer) { + let c = -1; + for (let i = 0; i < buffer.length; i += 1) { + c = CRC_TABLE[(c ^ buffer[i]) & 0xff] ^ (c >>> 8); + } + return (c ^ -1) >>> 0; +} + +/** + * @param {Date} date + * @returns {{ time: number, date: number }} MS-DOS timestamp pair + */ +function dosTimestamp(date) { + const year = Math.max(1980, date.getFullYear()); + return { + time: (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1), + date: ((year - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate(), + }; +} + +/** + * @typedef {{ path: string, data: Buffer, store?: boolean }} ZipEntry + */ + +/** + * Build a ZIP archive. + * @param {ZipEntry[]} entries + * @param {{ mtime?: Date }} [options] + * @returns {Buffer} + */ +export function createZip(entries, options = {}) { + const stamp = dosTimestamp(options.mtime ?? new Date()); + /** @type {Buffer[]} */ + const chunks = []; + /** @type {Buffer[]} */ + const central = []; + let offset = 0; + + for (const entry of entries) { + const nameBuffer = Buffer.from(entry.path, 'utf8'); + const raw = entry.data; + const checksum = crc32(raw); + let method = 0; + let payload = raw; + if (entry.store !== true && raw.length > 0) { + const deflated = deflateRawSync(raw, { level: 9 }); + if (deflated.length < raw.length) { + method = 8; + payload = deflated; + } + } + + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(method, 8); + local.writeUInt16LE(stamp.time, 10); + local.writeUInt16LE(stamp.date, 12); + local.writeUInt32LE(checksum, 14); + local.writeUInt32LE(payload.length, 18); + local.writeUInt32LE(raw.length, 22); + local.writeUInt16LE(nameBuffer.length, 26); + local.writeUInt16LE(0, 28); + chunks.push(local, nameBuffer, payload); + + const directory = Buffer.alloc(46); + directory.writeUInt32LE(0x02014b50, 0); + directory.writeUInt16LE(0x031e, 4); + directory.writeUInt16LE(20, 6); + directory.writeUInt16LE(0x0800, 8); + directory.writeUInt16LE(method, 10); + directory.writeUInt16LE(stamp.time, 12); + directory.writeUInt16LE(stamp.date, 14); + directory.writeUInt32LE(checksum, 16); + directory.writeUInt32LE(payload.length, 20); + directory.writeUInt32LE(raw.length, 24); + directory.writeUInt16LE(nameBuffer.length, 28); + directory.writeUInt16LE(0, 30); + directory.writeUInt16LE(0, 32); + directory.writeUInt16LE(0, 34); + directory.writeUInt16LE(0, 36); + directory.writeUInt32LE((0o100644 << 16) >>> 0, 38); + directory.writeUInt32LE(offset, 42); + central.push(directory, nameBuffer); + + offset += local.length + nameBuffer.length + payload.length; + } + + const centralBuffer = Buffer.concat(central); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(0, 4); + end.writeUInt16LE(0, 6); + end.writeUInt16LE(entries.length, 8); + end.writeUInt16LE(entries.length, 10); + end.writeUInt32LE(centralBuffer.length, 12); + end.writeUInt32LE(offset, 16); + end.writeUInt16LE(0, 20); + + return Buffer.concat([...chunks, centralBuffer, end]); +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/miniapp-api.ts b/plugins/zhuyankarl/submission-workbench/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/miniapp-api.ts @@ -0,0 +1,641 @@ +/** + * Agent-facing Mini App runtime authoring declarations. + * + * Copy this file into a generated plugin for type checking. It contains no Host implementation; + * the Host injects runtime values through start(context). + * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. + */ +export type JsonPrimitive = null | boolean | number | string; +export type JsonValue = JsonPrimitive | JsonObject | readonly JsonValue[]; +export type JsonObject = { readonly [key: string]: JsonValue }; + +declare const HOST_CONNECTOR_TOOL_REF: unique symbol; +export type HostConnectorToolRef = string & { + readonly [HOST_CONNECTOR_TOOL_REF]: 'HostConnectorToolRef'; +}; + +export interface HostConnectorTool { + readonly toolRef: HostConnectorToolRef; + readonly provider: string; + readonly name: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly outputSchema?: JsonValue; +} + +export interface HostConnectorListResult { + readonly tools: readonly HostConnectorTool[]; + readonly partial: boolean; +} + +export interface HostConnectorCallOptions { + readonly signal?: AbortSignal; +} + +export interface HostConnectorCallResult { + readonly invocationId: string; + /** + * Raw provider result; it is not normalized by the Host and may be an object, array, or primitive. + * A single text-block array is one provider shape, not a global Host transport contract. + * Decode only a probe-observed envelope; preserve every other value, including direct strings. + */ + readonly value: JsonValue; +} + +export interface HostConnectorClient { + /** Candidate-safe inventory only; available before and after activation. */ + list(options?: HostConnectorCallOptions): Promise; + /** Activation-only business dispatch; call from request handling, never start(context). */ + call( + toolRef: HostConnectorToolRef, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; +} + +export type HostConnectorErrorDisposition = + | 'not_dispatched' + | 'provider_reported' + | 'unknown_after_dispatch'; + +export type HostConnectorErrorCode = + | 'TOOL_REF_STALE' + | 'SERVICE_RESTARTED' + | 'REQUEST_CANCELLED' + | 'CONNECTOR_TIMEOUT' + | 'INVALID_ARGUMENTS' + | 'CONNECTOR_PROVIDER_ERROR' + | 'CONNECTOR_UNAVAILABLE' + /** The user switched this provider off for the Mini App; not dispatched. */ + | 'CONNECTOR_NOT_PERMITTED' + | 'CONNECTOR_OUTCOME_UNKNOWN'; + +export interface HostConnectorError extends Error { + readonly code: HostConnectorErrorCode; + readonly disposition: HostConnectorErrorDisposition; + readonly retryable: boolean; + readonly invocationId?: string; + readonly diagnostic?: { + readonly issues: readonly { + readonly path: string; + readonly constraint: string; + readonly limit?: number; + }[]; + }; +} + +/** What a call would meet now under the user's global permission rules; informational only. */ +export type MiniAppToolPermission = 'allow' | 'ask' | 'deny'; + +/** + * `name` is the runtime name an Agent sees (`mcp____`, `connector____`). + * Take it from `list()`; do not build it. + */ +export type MiniAppTool = + | { + readonly name: string; + readonly kind: 'connector'; + readonly provider: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + } + | { + readonly name: string; + readonly kind: 'mcp'; + /** Any installed MCP server: a Plugin's, the user's `mcp.json`, or a Host built-in one. */ + readonly server: string; + readonly tool: string; + readonly description?: string; + readonly inputSchema: JsonValue; + readonly permission: MiniAppToolPermission; + }; + +export interface MiniAppToolListResult { + readonly tools: readonly MiniAppTool[]; + /** A source could not be listed; the listed tools are still callable. */ + readonly partial: boolean; +} + +export type MiniAppToolCallResult = + | { + readonly invocationId: string; + readonly kind: 'connector'; + /** Raw provider result, as in `HostConnectorCallResult.value`. */ + readonly value: JsonValue; + } + | { + readonly invocationId: string; + readonly kind: 'mcp'; + /** The MCP tool reported its own failure; `content` keeps its error text. */ + readonly isError: boolean; + /** MCP content blocks such as `{ type: 'text', text }`, passed through as JSON. */ + readonly content: readonly JsonValue[]; + readonly structuredContent?: JsonObject; + }; + +/** + * Thrown with the `HostConnectorError` shape; Connector tools keep their Connector codes too. The + * code names the cause; `disposition` alone says whether the tool may have run (`TOOL_TIMEOUT` and + * `REQUEST_CANCELLED` can be either `not_dispatched` or `unknown_after_dispatch`). + */ +export type MiniAppToolErrorCode = + | HostConnectorErrorCode + | 'INVALID_ARGUMENTS' + | 'TOOL_NOT_PERMITTED' + | 'TOOL_APPROVAL_REQUIRED' + | 'TOOL_REF_STALE' + | 'TOOL_UNAVAILABLE' + | 'TOOL_TIMEOUT' + | 'TOOL_RESULT_TOO_LARGE' + | 'TOOL_OUTCOME_UNKNOWN' + | 'MCP_SERVER_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'SERVICE_RESTARTED'; + +/** + * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched + * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's + * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `ask` shows a Host prompt, and nobody to + * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request + * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, + * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome + * before repeating a write. + */ +export interface MiniAppToolClient { + list(options?: HostConnectorCallOptions): Promise; + call( + name: string, + arguments_: JsonObject, + options?: HostConnectorCallOptions, + ): Promise; + /** + * One Host prompt for the named tools (1–10, from `list()`) still at `ask`; the user ticks which + * to always allow. Resolves every name's state afterwards (for your UI only). When nobody can be + * asked it rejects with `TOOL_APPROVAL_REQUIRED` whose error carries `permissions`. With + * `tool:call` switched off it answers `deny` for every name without a prompt. + * Needs `capabilities.has('tool.request')`. + */ + request( + names: readonly string[], + options?: HostConnectorCallOptions, + ): Promise>; +} + +export interface MiniAppLogger { + debug(message: string, fields?: JsonObject): void; + info(message: string, fields?: JsonObject): void; + warn(message: string, fields?: JsonObject): void; + error(message: string, fields?: JsonObject): void; +} + +/** + * How the call's text ended: in its own turn (`finished` / `error` / `aborted`), or, only with + * `whenBusy`, joined into the turn that was already running (`steered`; that turn's own + * call gets the reply). + */ +export type MiniAppAgentRunStatus = 'finished' | 'error' | 'aborted' | 'steered'; + +/** + * The Desktop composer's follow-up behaviours while a session runs a turn. `queue`: the text runs + * as the next turn and the call follows it. `steer`: the running turn reads the text at its next + * input point (the call resolves `steered`), or, if it answered first, the text runs as the next + * turn and the call follows it. + */ +export type MiniAppAgentWhenBusy = 'queue' | 'steer'; + +export type MiniAppAgentQuestionMode = 'questionnaire' | 'feature-enable' | 'plan'; + +export interface MiniAppAgentQuestionOption { + readonly id: string; + readonly label: string; + readonly description?: string; +} + +export interface MiniAppAgentQuestionStep { + readonly id: string; + readonly header?: string; + readonly question: string; + readonly description?: string; + readonly selectionMode: 'single' | 'multiple'; + readonly options: readonly MiniAppAgentQuestionOption[]; + /** Free-text "other" is always accepted; see `MiniAppAgentQuestionAnswer.otherText`. */ + readonly allowOther: true; +} + +/** Same questionnaire the Host chat renders; render every step and answer each one. */ +export interface MiniAppAgentQuestionnaire { + readonly schemaVersion: 2; + readonly id: string; + readonly title?: string; + readonly steps: readonly MiniAppAgentQuestionStep[]; + readonly mode?: MiniAppAgentQuestionMode; + /** Plan review Markdown and other mode-specific data. */ + readonly modePayload?: JsonObject; + /** Unix ms; the request is withdrawn after this. */ + readonly expiresAt?: number; +} + +export interface MiniAppAgentQuestionAnswer { + readonly stepId: string; + readonly selectedOptionIds: readonly string[]; + readonly selectedOther: boolean; + readonly otherText?: string; + readonly skipped?: boolean; +} + +/** A model as the Host's composer selects it; take the values from `models()`. */ +export interface MiniAppAgentModelSelection { + readonly providerId: string; + readonly modelId: string; + /** `''` means thinking is off; it is preserved, distinct from an absent `variant`. */ + readonly variant?: string; + readonly thinking?: { readonly effort: string }; +} + +/** One model this user can use. */ +export interface MiniAppAgentModelOption { + readonly providerId: string; + readonly modelId: string; + readonly displayName: string; + readonly variants?: readonly string[]; + readonly thinking?: { readonly efforts: readonly string[]; readonly default?: string }; +} + +export interface MiniAppAgentModels { + readonly models: readonly MiniAppAgentModelOption[]; + /** What a Node-created session starts with. */ + readonly default: MiniAppAgentModelSelection; +} + +export interface MiniAppAgentAgentOption { + /** Canonical name; what `agent` takes. */ + readonly name: string; + readonly displayName: string; + /** The default agent. */ + readonly primary: boolean; +} + +export interface MiniAppAgentAgents { + readonly agents: readonly MiniAppAgentAgentOption[]; +} + +export interface MiniAppAgentRunResult { + /** Pass back in `run({ sessionId })` to continue the same conversation. */ + readonly sessionId: string; + /** Absent when no turn ran: an `answer` accepted without starting a continuation. */ + readonly turnId?: string; + /** The model the turn was dispatched with; absent when no turn ran or the text was steered. */ + readonly model?: MiniAppAgentModelSelection; + /** `aborted` only when the Host confirmed the abort; an unconfirmed one rejects with `AGENT_OUTCOME_UNKNOWN`. */ + readonly status: MiniAppAgentRunStatus; + /** Final assistant reply; absent when the turn produced none or did not finish. */ + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + /** Set when the turn ended waiting on a questionnaire; render `request` and continue with `agent.answer`. */ + readonly pendingQuestion?: { + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + }; +} + +/** + * Progress of one run. `turnId` matches the result's, except that a `permission.requested` raised + * by a delegated child session carries that child's own `sessionId` and `turnId`; `reply` with + * those, and do not filter events by the root turn. Ignore unknown `type` values: new event + * types may be added without notice. + * - `run.queued`: the call waits at 1-based `position`, for a run slot or, with + * `whenBusy: 'queue'`, in the session queue (a `whenBusy` call can get both); sent before the + * turn starts, so it has no `turnId` and names a session only when continuing one. + * - `message.pending` / `message.steered`: with `whenBusy: 'steer'`, the text was handed to the + * running turn, then read by it; `message.steered` is the call's last event. + * - `turn.started`: the Agent began the turn; `model` is the model it was dispatched with. + * - `text.delta`: a piece of the reply as it streams. + * - `message.committed`: one complete assistant message (a turn can have several). + * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. + * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` + * as the run result. + */ +/** + * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even + * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the + * session's single-run slot while `question.requested` is delivered, so call `answer` only after + * that `run` resolves (an earlier call rejects with `BUSY`). Ignore event types you do not know. + */ +export type MiniAppAgentRunEvent = + | { readonly type: 'run.queued'; readonly sessionId?: string; readonly position: number } + | { + readonly type: 'message.pending' | 'message.steered'; + readonly sessionId: string; + readonly turnId: string; + } + | { + readonly type: 'turn.started'; + readonly sessionId: string; + readonly turnId: string; + readonly model: MiniAppAgentModelSelection; + } + | { + readonly type: 'text.delta'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'message.committed'; + readonly sessionId: string; + readonly turnId: string; + readonly text: string; + } + | { + readonly type: 'tool.started'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + } + | { + readonly type: 'tool.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly name: string; + readonly ok: boolean; + } + /** A tool call is waiting for approval; decide it with `agent.reply`. */ + | { + readonly type: 'permission.requested'; + readonly sessionId: string; + /** Absent when the runtime did not attribute the ask to a turn. */ + readonly turnId?: string; + readonly requestId: string; + readonly toolName: string; + readonly toolInput?: string; + readonly reason: string; + } + /** The turn paused on a questionnaire; continue with `agent.answer`. */ + | { + readonly type: 'question.requested'; + readonly sessionId: string; + readonly turnId?: string; + readonly requestId: string; + readonly mode: MiniAppAgentQuestionMode; + readonly request: MiniAppAgentQuestionnaire; + } + | { + readonly type: 'turn.finished'; + readonly sessionId: string; + readonly turnId: string; + readonly status: Exclude; + readonly text?: string; + readonly error?: { readonly code: string; readonly message: string }; + }; + +/** `observe({ all: true })` only: the conversation's title, when it has one. */ +interface MiniAppAgentObservedTitle { + readonly title?: string; +} + +type MiniAppAgentRunEventOf = Extract< + MiniAppAgentRunEvent, + { readonly type: T } +>; + +/** + * What an observer receives: the run events without `run.queued` and without asks, which reach + * only the run that owns them. `turn.started.model` is present only when the Host could read it. + * Ignore unknown `type` values. + */ +export type MiniAppAgentObservedEvent = + | (Omit, 'model'> & { + readonly model?: MiniAppAgentModelSelection; + } & MiniAppAgentObservedTitle) + | MiniAppAgentRunEventOf<'text.delta' | 'tool.started' | 'tool.finished'> + | (MiniAppAgentRunEventOf<'message.committed'> & MiniAppAgentObservedTitle) + | (MiniAppAgentRunEventOf<'turn.finished'> & MiniAppAgentObservedTitle); + +/** + * `{ all: true }`: `turn.started`, `message.committed` (the final reply) and `turn.finished` of + * every user conversation, with its `title`. `{ sessionId }`: every progress event of that + * session, turn after turn. Exactly one of the two. + */ +export type MiniAppAgentObserveTarget = { readonly sessionId: string } | { readonly all: true }; + +/** One of the user's conversations; `running` while a turn is in flight. */ +export interface MiniAppAgentSessionSummary { + readonly sessionId: string; + readonly title?: string; + /** The Agent the session runs. */ + readonly agent: string; + readonly status: 'idle' | 'running' | 'error' | 'aborted'; + /** The conversation's project directory (absolute) as recorded; it may no longer exist. */ + readonly workspaceDir: string; + /** True when the conversation has no project and runs in the default workspace. */ + readonly isDefaultWorkspace: boolean; + /** Unix ms. */ + readonly createdAtMs: number; + /** Unix ms. */ + readonly updatedAtMs: number; +} + +export interface MiniAppAgentSessionDetail extends MiniAppAgentSessionSummary { + /** The conversation's current model; absent when the Host has none recorded. */ + readonly model?: MiniAppAgentModelSelection; + /** Only while `status` is `error` and the Host recorded a message. */ + readonly error?: { readonly message: string }; + /** Final text of the latest Agent reply, if any. */ + readonly lastAssistantText?: string; +} + +export interface MiniAppAgentSessions { + /** The 50 most recently updated user conversations (no Mini App, scheduled or sub-Agent ones). */ + readonly sessions: readonly MiniAppAgentSessionSummary[]; +} + +export interface MiniAppAgentRunOptions { + readonly signal?: AbortSignal; + readonly onEvent?: (event: MiniAppAgentRunEvent) => void; +} + +export type MiniAppAgentErrorCode = + | 'NOT_PERMITTED' + | 'BUSY' + | 'SESSION_NOT_FOUND' + | 'INVALID_ARGUMENTS' + | 'AGENT_UNAVAILABLE' + | 'REQUEST_CANCELLED' + | 'AGENT_OUTCOME_UNKNOWN' + | 'REQUEST_NOT_FOUND'; + +export interface MiniAppAgentError extends Error { + readonly code: MiniAppAgentErrorCode; + /** + * True when nothing was started and the same call may be retried later. + * `AGENT_OUTCOME_UNKNOWN` is never retryable: the turn may have run. + */ + readonly retryable: boolean; + /** + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. + */ + readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; +} + +/** + * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). + * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and + * `sessions` need `session.read` except for this Mini App's own sessions (see + * agent-interaction.md). + * A new Node session uses the primary Agent unless `agent` names one from `agents()`, and works in + * this Mini App's own Agent directory and on the runtime default model; + * continuing a session keeps its Agent, directory and model (unless `model` switches it), including + * one a page created using its host chat's Agent, project directory and model; a session never + * changes its Agent. Runs one turn with that Agent's full capabilities + * (files, shell, Skills, MCP including this Mini App's own), and resolves when the turn ends. + * + * Interaction is yours to render: pass `onEvent` and handle `permission.requested` with + * `reply` and `question.requested` with `answer`. A permission request waits only while + * someone can answer it: this run passed `onEvent`, or a page of this Mini App currently has + * the session open in a chat side panel via `open`. Otherwise it is denied (the model is told + * why), and a questionnaire ends the turn with `result.pendingQuestion`. A run waiting on a + * permission is released by `cancel`/abort, process exit or republish. Up to `agentConcurrency` + * runs (default 4) per Mini App run at once; further `run` / `answer` calls wait in order (up to + * four times that many, see `run.queued`), and aborting a waiting call rejects it with + * `REQUEST_CANCELLED`. A `whenBusy` call on a session that already has a call in flight shares + * that call's slot. Cancelling a queued `whenBusy` text removes it (`REQUEST_CANCELLED`); a steered + * text cannot be withdrawn (`AGENT_OUTCOME_UNKNOWN`, the running turn goes on). + */ +export interface MiniAppAgentClient { + run( + input: { + readonly text: string; + readonly sessionId?: string; + /** + * Switch the session to this model before the turn (validated like the composer validates a + * new session's model: it must be one `models()` lists; unusable is `INVALID_ARGUMENTS`, + * missing BYOK credentials end the turn with `status: 'error'`); the session keeps it. Omit to use the session's current model. + */ + readonly model?: MiniAppAgentModelSelection; + /** + * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. Passing it + * with `sessionId` is `INVALID_ARGUMENTS`. + */ + readonly agent?: string; + /** + * Only with `sessionId`: what to do when that session is already running a turn; on an idle + * session the call starts a turn as usual. Omit to reject with `BUSY` (`session_busy`). + */ + readonly whenBusy?: MiniAppAgentWhenBusy; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Decide a pending permission request. Never writes the user's global rules. Node replies + * have 16 separate pending slots; `run` / `answer` / `models` / `agents` / `create` and Connector + * requests share another 16. Filling that ordinary budget still permits replies. A full reply + * budget rejects with retryable `AGENT_UNAVAILABLE`. + */ + reply(input: { + readonly sessionId: string; + readonly requestId: string; + readonly decision: 'allowOnce' | 'deny'; + }): Promise; + /** + * Answer a questionnaire; the continuation turn is observed like `run`. Rejects with + * `AGENT_OUTCOME_UNKNOWN` when the answer was recorded but the continuation turn was not observed. + */ + answer( + input: { + readonly sessionId: string; + readonly requestId: string; + readonly answers: readonly MiniAppAgentQuestionAnswer[]; + /** Same as `run`'s `model`, applied before the continuation turn. */ + readonly model?: MiniAppAgentModelSelection; + }, + options?: MiniAppAgentRunOptions, + ): Promise; + /** + * Returns the model catalog and runtime `default`. Pass `default` directly as `model` to + * `run` / `answer`. For a catalog entry, extract `providerId` / `modelId`, add a selected `variant` + * if needed and preserve `variant: ''`. If thinking is supported, select an effort from + * `thinking.efforts` and pass `thinking: { effort }`. + */ + models(): Promise; + /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + agents(): Promise; + /** + * Create a session (agent, this Mini App's Agent directory, the runtime default model) without + * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's + * `create` binds the session to its chat instead, and its `sessionId` can be continued here. + * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's + * agent from `agents()`; a session never changes it. + */ + create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort + * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription + * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, + * or `session.read` was switched off. + * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not + * exactly one target), `NOT_PERMITTED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots + * and no ordinary request budget. Check `context.capabilities?.has('agent.observe')` first. + */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise; + /** Check `context.capabilities?.has('agent.sessions')` first. */ + sessions(): Promise; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session()`). + * Check `context.capabilities?.has('agent.session')`. + */ + session(sessionId: string): Promise; +} + +export interface MiniAppLifecycle { + dispose(): void | Promise; +} + +export interface MiniAppContext { + readonly pluginId: string; + readonly pluginRoot: string; + readonly dataDir: string; + readonly listen: Readonly<{ readonly host: '127.0.0.1'; readonly port: number }>; + readonly signal: AbortSignal; + readonly logger: MiniAppLogger; + /** + * Synchronous probe of Host features, fixed per Host version. It says nothing about this + * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the + * Agent API even when `context.agent` is absent because `agentAccess` was not declared. + * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + */ + readonly capabilities?: MiniAppHostCapabilities; + /** + * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user + * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + */ + readonly hostConnector?: HostConnectorClient; + /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ + readonly tool?: MiniAppToolClient; + /** + * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it + * switched off, calls fail with `NOT_PERMITTED`. + */ + readonly agent?: MiniAppAgentClient; +} + +export interface MiniAppHostCapabilities { + has(name: string): boolean; +} + +export interface MiniAppModule { + /** Resolve only after the listener accepts connections and every route is installed. */ + start(context: MiniAppContext): Promise; +} diff --git a/plugins/zhuyankarl/submission-workbench/miniapp/node/server.mjs b/plugins/zhuyankarl/submission-workbench/miniapp/node/server.mjs new file mode 100644 index 00000000..972dff0f --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/miniapp/node/server.mjs @@ -0,0 +1,341 @@ +// @ts-check +/** + * Mini App Node entry: 插件上架材料工作台. + * + * All business mutations go through one domain service: validate -> commit -> + * respond. The Client never touches the filesystem or the network directly. + */ +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; + +import { Store, sha256, InvalidIdError } from './lib/store.mjs'; +import { validateDraft } from './lib/listing-rules.mjs'; +import { buildPreview, buildPackage } from './lib/package-builder.mjs'; +import { probeSubmissionChannel } from './lib/channel.mjs'; +import { CATEGORIES, GUIDE_URL } from './lib/manifest-rules.mjs'; + +/** @typedef {import('./lib/store.mjs').Asset} Asset */ +/** @typedef {import('./lib/listing-rules.mjs').Draft} Draft */ +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const MAX_UPLOAD_BYTES = 12 * 1024 * 1024; +const SURFACE_PATH = '/dashboard'; + +const ALLOWED_MIME = new Map([ + ['image/png', 'png'], + ['image/jpeg', 'jpg'], + ['image/webp', 'webp'], + ['text/markdown', 'md'], + ['text/plain', 'md'], + ['application/json', 'json'], +]); + +/** + * @param {string} name + * @returns {string} + */ +function safeName(name) { + return name + .replace(/\\/g, '/') + .split('/') + .filter((part) => part !== '' && part !== '.' && part !== '..') + .join('/'); +} + +/** + * @param {import('node:http').IncomingMessage} request + * @returns {Promise} + */ +function readBody(request) { + return new Promise((resolve, reject) => { + /** @type {Buffer[]} */ + const chunks = []; + let size = 0; + request.on('data', (chunk) => { + size += chunk.length; + if (size > MAX_UPLOAD_BYTES) { + reject(new Error('请求体超过大小上限')); + request.destroy(); + return; + } + chunks.push(chunk); + }); + request.on('end', () => resolve(Buffer.concat(chunks))); + request.on('error', reject); + }); +} + +/** + * @param {import('node:http').ServerResponse} response + * @param {number} status + * @param {unknown} payload + */ +function sendJson(response, status, payload) { + const body = JSON.stringify(payload); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + }); + response.end(body); +} + +/** + * @param {Partial} input + * @returns {Draft} + */ +function normalizeDraft(input) { + const value = /** @type {Record} */ (input ?? {}); + const list = (key) => + Array.isArray(value[key]) ? (/** @type {unknown[]} */ (value[key])).map((item) => String(item)) : []; + return { + manifestText: String(value.manifestText ?? ''), + marketName: String(value.marketName ?? ''), + summary: String(value.summary ?? ''), + documentation: String(value.documentation ?? ''), + category: String(value.category ?? ''), + exampleQueries: list('exampleQueries'), + regions: list('regions'), + enabledEnds: list('enabledEnds'), + operation: value.operation === 'update' ? 'update' : 'new', + existingName: String(value.existingName ?? ''), + previousVersion: String(value.previousVersion ?? ''), + submitEmail: String(value.submitEmail ?? ''), + submitAccount: String(value.submitAccount ?? ''), + organization: String(value.organization ?? ''), + }; +} + +/** + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + const store = new Store(context.dataDir); + await store.init(); + + const clientHtml = await readFile(join(context.pluginRoot, 'miniapp/client/index.html'), 'utf8'); + const clientScript = await readFile(join(context.pluginRoot, 'miniapp/client/app.js'), 'utf8'); + const clientStyle = await readFile(join(context.pluginRoot, 'miniapp/client/app.css'), 'utf8'); + + /** + * Run the full validation pass and shape the response shared by the + * validate, preview and package endpoints. + * @param {Draft} draft + */ + async function inspect(draft) { + const assets = await store.listAssets(); + const { issues, manifest } = validateDraft(draft, assets); + const channel = await probeSubmissionChannel(/** @type {any} */ (context), draft); + const preview = buildPreview(manifest, draft, assets); + const missing = issues.filter((issue) => issue.missing); + return { + issues, + manifest, + preview, + channel, + assets, + summary: { + errors: issues.filter((issue) => issue.severity === 'error').length, + warnings: issues.filter((issue) => issue.severity === 'warning').length, + infos: issues.filter((issue) => issue.severity === 'info').length, + missing: missing.length, + }, + }; + } + + const server = createServer(async (request, response) => { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const route = `${request.method ?? 'GET'} ${url.pathname}`; + + try { + if (route === `GET ${SURFACE_PATH}`) { + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(clientHtml); + return; + } + if (route === 'GET /client/app.js') { + response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' }); + response.end(clientScript); + return; + } + if (route === 'GET /client/app.css') { + response.writeHead(200, { 'content-type': 'text/css; charset=utf-8' }); + response.end(clientStyle); + return; + } + if (route === 'GET /api/meta') { + sendJson(response, 200, { + categories: CATEGORIES, + guideUrl: GUIDE_URL, + surfacePath: SURFACE_PATH, + }); + return; + } + if (route === 'GET /api/state') { + const draft = normalizeDraft(/** @type {any} */ (await store.loadDraft())); + const assets = await store.listAssets(); + const packages = await store.listPackages(); + sendJson(response, 200, { draft, assets, packages }); + return; + } + if (route === 'POST /api/validate') { + const body = await readBody(request); + const draft = normalizeDraft(JSON.parse(body.toString('utf8') || '{}')); + await store.saveDraft(draft); + const result = await inspect(draft); + sendJson(response, 200, result); + return; + } + if (route === 'POST /api/assets') { + const body = await readBody(request); + const payload = JSON.parse(body.toString('utf8') || '{}'); + const name = safeName(String(payload.name ?? '')); + if (name === '') { + sendJson(response, 400, { error: 'invalid_name', message: '素材路径不能为空。' }); + return; + } + const role = ['icon', 'screenshot', 'skill', 'mcp', 'app', 'doc'].includes(String(payload.role)) + ? /** @type {Asset['role']} */ (String(payload.role)) + : 'doc'; + const mime = String(payload.mime ?? 'application/octet-stream'); + if (!ALLOWED_MIME.has(mime)) { + sendJson(response, 400, { + error: 'unsupported_type', + message: `不支持的素材类型:${mime}。允许 ${[...ALLOWED_MIME.keys()].join('、')}。`, + }); + return; + } + const bytes = Buffer.from(String(payload.contentBase64 ?? ''), 'base64'); + if (bytes.length === 0) { + sendJson(response, 400, { error: 'empty_file', message: '素材内容为空。' }); + return; + } + /** @type {Asset} */ + const asset = { + id: randomUUID(), + name, + role, + size: bytes.length, + mime, + createdAt: new Date().toISOString(), + }; + await store.saveAsset(asset, bytes); + sendJson(response, 201, { asset }); + return; + } + if (route === 'DELETE /api/assets') { + const id = url.searchParams.get('id') ?? ''; + if (!id) { + sendJson(response, 400, { error: 'missing_id', message: '缺少素材 id。' }); + return; + } + await store.deleteAsset(id); + sendJson(response, 200, { ok: true }); + return; + } + if (route === 'POST /api/package') { + const body = await readBody(request); + const draft = normalizeDraft(JSON.parse(body.toString('utf8') || '{}')); + await store.saveDraft(draft); + const result = await inspect(draft); + if (result.summary.errors > 0) { + sendJson(response, 409, { + error: 'not_ready', + message: `仍有 ${result.summary.errors} 项错误,修正后再生成。`, + ...result, + }); + return; + } + const built = await buildPackage( + draft, + result.manifest, + result.assets, + (asset) => store.readAssetBytes(asset.id), + result.issues, + result.channel, + ); + const record = { + id: randomUUID(), + fileName: `${draft.marketName || 'plugin'}-listing-package.zip`.replace( + /[^\w.\-一-龥]+/g, + '-', + ), + createdAt: new Date().toISOString(), + size: built.bytes.length, + sha256: sha256(built.bytes), + entries: built.entries, + manifest: result.manifest, + }; + await store.savePackage(record, built.bytes); + sendJson(response, 201, { package: record, preview: result.preview }); + return; + } + if (route === 'GET /api/package/download') { + const id = url.searchParams.get('id') ?? ''; + const bytes = await store.readPackageBytes(id); + if (!bytes) { + sendJson(response, 404, { error: 'not_found', message: '找不到该上架材料包。' }); + return; + } + const packages = await store.listPackages(); + const record = packages.find((item) => item.id === id); + // HTTP headers must stay ASCII: keep a sanitized fallback name and + // carry the real (possibly Chinese) name in the RFC 5987 field. + const fileName = record?.fileName ?? 'listing-package.zip'; + const fallbackName = fileName.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, ''); + response.writeHead(200, { + 'content-type': 'application/zip', + 'content-disposition': `attachment; filename="${fallbackName}"; filename*=UTF-8''${encodeURIComponent(fileName)}`, + 'content-length': String(bytes.length), + }); + response.end(bytes); + return; + } + if (route === 'GET /api/channel') { + const draft = normalizeDraft(/** @type {any} */ (await store.loadDraft())); + const channel = await probeSubmissionChannel(/** @type {any} */ (context), draft); + sendJson(response, 200, { channel }); + return; + } + + sendJson(response, 404, { error: 'not_found', message: `未知的路由:${route}` }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (error instanceof InvalidIdError) { + // The id never came from this server, so it is refused before it can + // reach the filesystem. + sendJson(response, 400, { error: 'invalid_id', message: '素材或材料包的 id 不合法。' }); + return; + } + context.logger.error('miniapp.request.failed', { route, message }); + sendJson(response, 500, { error: 'server_error', message }); + } + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(context.listen.port, context.listen.host, () => { + server.off('error', reject); + resolve(undefined); + }); + }); + context.logger.info('miniapp.runtime.listening'); + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + await new Promise((resolve) => server.close(() => resolve(undefined))); + }; + const onAbort = () => { + void dispose(); + }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} diff --git a/plugins/zhuyankarl/submission-workbench/package.json b/plugins/zhuyankarl/submission-workbench/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +} diff --git a/plugins/zhuyankarl/submission-workbench/skills/listing-check/SKILL.md b/plugins/zhuyankarl/submission-workbench/skills/listing-check/SKILL.md new file mode 100644 index 00000000..2684e164 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/skills/listing-check/SKILL.md @@ -0,0 +1,66 @@ +--- +name: listing-check +description: 按官方《插件开发与上架指南》逐项核对 MiniMax Plugin 的清单与上架材料,定位缺失项、字段冲突与包体问题,并产出可审核的上架材料包。 +--- + +# 插件上架材料自检 + +目标:在提交到官方市场之前,把能在本地查出来的问题全部查出来,并留下一份可复核的结论。 + +官方指南: + +## 什么时候用 + +- 用户说「检查我的插件清单能不能上架」「上架材料还缺哪些必填项」「生成插件上架材料包」。 +- 准备提交新 Plugin,或更新已上架的 Plugin。 + +## 流程 + +1. **拿到清单全文**:让用户粘贴 `.minimax-plugin/plugin.json` 的完整内容,不要用片段或摘要代替。 + 文件必须是 UTF-8 且不带 BOM;JSON 必须是对象且不能有重复 key。 +2. **打开「插件上架材料工作台」**(本插件的 Mini App,页面地址 `/dashboard`),把清单粘进「插件清单」, + 依次填:期望市场名称、目标分类、简介、说明文档、最多 3 条示例 query、目标区域(CN/US)、 + 启用端(桌面端/云端)、提交邮箱、提交飞书账号、组织/团队。 + 区域与启用端是两个独立维度,不写进 `plugin.json`。 +3. **上传素材**:图标(路径必须和清单里的 `icon` 一致)、至少一张截图、以及清单引用的 + Skill/MCP/App 文件。 +4. **点「运行检查」**,逐条处理结果: + - **缺失项**(error):必填但没填的字段,必须补齐。 + - **内容冲突**(error/hint):简介与清单 `description`、市场名称与 `displayName` 这类不一致。 + - **提示**(warning):清单与说明文档对不上,比如说明文档里没提到插件名。 +5. **点「生成上架材料包」**,下载 ZIP。ZIP 根目录直接含 `.minimax-plugin/plugin.json`, + `listing-materials/` 下是自检报告与市场卡片预览。 +6. **把自检报告和结论一起给用户**,并明确说明:材料包只是可审核材料,**不代表已提交或已上架**。 + +## 必须自己记住的硬性规则 + +- **至少一种能力**:`apps` / `mcpServers` / `skills` 至少有一项非空;没有的能力保留空数组。 +- **`name`**:小写机器名,最长 80 字符,以字母开头,可用数字与 `.` `_` `-` 分隔。 +- **`version`**:SemVer。**包内任意内容发生变化都必须提升版本号**;只调整区域、启用端等 + Catalog 元数据且包内容完全不变时,版本可以不变。 +- **`icon`**:包内相对路径,只支持小写 `.png` / `.jpg` / `.jpeg` / `.webp`;不要声明 `darkIcon`。 +- **`category`**:固定分类 `Office` / `Studio` / `Design & Sites` / `Code` / `Business` / + `Sales` / `Productivity` / `Science & Healthcare` / `Education` / `Other`,选一项。 +- **`exampleQueries`**:0–3 条真实示例,每条非空。 +- **ZIP 结构**:根目录直接含 `.minimax-plugin/plugin.json`,不能再套一层目录;路径只用 ASCII + 字母、数字、点、下划线和连字符,统一用 `/`。 +- **包体上限**:ZIP ≤ 64 MiB,entries ≤ 2048,普通文件 ≤ 1024,单文件解包 ≤ 16 MiB, + 完整路径 ≤ 512 bytes,路径深度 ≤ 16 段。 +- **禁止内容**:OAuth、token、client secret、API key、平台专属二进制、软链接、 + `node_modules`、安装生命周期脚本(`preinstall` / `install` / `postinstall`)。 + +## 提交通道(不要替用户提交) + +官方受理入口只有两个:飞书表单(人工在已登录浏览器里提交)和公开 GitHub 仓库。 +**没有程序化投稿接口。** 提交后保存 `submission_id`,查询进度需要「原提交飞书账号 + +`submission_id` + 提交邮箱」三者匹配。 + +个人开发者的 Mini App 通常走开源社区仓库 +()提 PR,而不是投稿表单; +表单受理的是 App / MCP / Skill 插件。 + +## 交付时怎么说 + +- 列出修了什么、还差什么,每条都指到具体字段。 +- 附上材料包路径与自检报告结论。 +- 明确写出「材料已生成,尚未提交;提交动作由用户在官方渠道完成」。 diff --git a/plugins/zhuyankarl/submission-workbench/tests/client-harness.mjs b/plugins/zhuyankarl/submission-workbench/tests/client-harness.mjs new file mode 100644 index 00000000..557f4fb9 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/tests/client-harness.mjs @@ -0,0 +1,267 @@ +// @ts-check +/** + * Client harness: executes miniapp/client/app.js against a minimal DOM stub. + * + * It catches the failures that only show up at runtime in the browser: + * - referencing an undeclared variable (a ReferenceError); + * - an event handler that is never wired; + * - a request that never reaches the Node service; + * - a screen that never renders after the response arrives. + * + * Run: node tests/client-harness.mjs + */ +import { readFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +// Resolve the package root from this file so the harness works from any cwd. +const root = join(dirname(fileURLToPath(import.meta.url)), '..', 'miniapp'); +const html = await readFile(join(root, 'client/index.html'), 'utf8'); +const clientPath = join(root, 'client/app.js'); + +let passed = 0; +let failed = 0; + +/** + * @param {string} name + * @param {boolean} condition + * @param {string} [detail] + */ +function check(name, condition, detail = '') { + if (condition) { + passed += 1; + } else { + failed += 1; + console.log(`FAIL ${name}${detail ? ` :: ${detail}` : ''}`); + } +} + +// ---- HTML structure checks (regex on markup is legitimate here) ---- +for (const tag of ['main', 'header', 'section', 'form', 'label', 'select', 'textarea']) { + check(`HTML contains <${tag}>`, html.includes(`<${tag}`)); +} +check('HTML declares lang="zh-CN"', html.includes('lang="zh-CN"')); +check('HTML has a title', /[^<]+<\/title>/.test(html)); + +const htmlIds = new Set([...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1])); +const clientSource = await readFile(clientPath, 'utf8'); +for (const match of clientSource.matchAll(/getElementById\('([^']+)'\)/g)) { + check(`script id "${match[1]}" exists in HTML`, htmlIds.has(match[1])); +} + +// ---- DOM stub ---- +/** @type {Map<string, any>} */ +const elements = new Map(); + +/** + * @param {string} id + * @param {string} [tag] + */ +function makeElement(id, tag = 'div') { + /** @type {Record<string, Function[]>} */ + const handlers = {}; + /** @type {any[]} */ + const children = []; + /** @type {any[]} */ + const options = []; + let ownText = ''; + + const element = { + id, + tagName: tag.toUpperCase(), + value: '', + hidden: false, + checked: false, + disabled: false, + dataset: {}, + files: [], + children, + options, + style: {}, + classList: { add() {}, remove() {}, contains: () => false }, + get textContent() { + return ownText + children.map((child) => child.textContent ?? '').join(''); + }, + set textContent(value) { + ownText = String(value); + children.length = 0; + }, + append(...nodes) { + for (const node of nodes) { + children.push(node); + if (node && node.tagName === 'OPTION') options.push(node); + } + }, + remove() {}, + setAttribute() {}, + getAttribute: () => null, + addEventListener(type, handler) { + (handlers[type] ??= []).push(handler); + }, + removeEventListener() {}, + querySelectorAll: () => [], + querySelector: () => null, + focus() {}, + click() { + for (const handler of handlers.click ?? []) handler({ type: 'click' }); + }, + /** test helper */ + fire(type) { + for (const handler of handlers[type] ?? []) handler({ type }); + }, + }; + return element; +} + +/** + * @param {string} id + */ +function element(id) { + let found = elements.get(id); + if (!found) { + found = makeElement(id); + elements.set(id, found); + } + return found; +} + +const form = element('draft-form'); +form.elements = { + namedItem: (name) => element(name), +}; + +const documentListeners = {}; +globalThis.document = /** @type {any} */ ({ + getElementById: (id) => element(id), + createElement: (tag) => makeElement('', tag), + createTextNode: (text) => ({ tagName: '#text', textContent: String(text) }), + querySelectorAll: () => [], + querySelector: () => null, + addEventListener(type, handler) { + (documentListeners[type] ??= []).push(handler); + }, + body: makeElement('body', 'body'), + documentElement: makeElement('html', 'html'), +}); + +globalThis.window = /** @type {any} */ ({ + addEventListener() {}, + removeEventListener() {}, +}); + +// ---- fetch stub ---- +const calls = []; +const fakeMeta = { + categories: ['Office', 'Studio', 'Code', 'Business', 'Productivity', 'Other'], + guideUrl: 'https://code.minimax.cn/docs/code/agents/plugin-submission.md', + surfacePath: '/dashboard', +}; +const fakeState = { draft: {}, assets: [], packages: [] }; +const fakeValidation = { + issues: [], + manifest: { name: 'acme-research', version: '1.0.0' }, + preview: { + marketName: 'Acme 研究助手', + summary: '检索研究资料并生成结构化综述。', + version: '1.0.0', + category: 'Science & Healthcare', + author: 'Acme', + regions: ['CN'], + enabledEnds: ['desktop'], + exampleQueries: ['检索近期研究并总结主要结论'], + screenshotCount: 1, + capabilityFiles: [], + }, + channel: { + findings: [], + requiredPermissions: [], + conclusion: '未发现官方市场的程序化提交接口。', + }, + assets: [], + summary: { errors: 0, warnings: 1, infos: 0, missing: 0 }, +}; + +globalThis.fetch = /** @type {any} */ (async (url, init) => { + calls.push({ url: String(url), method: init?.method ?? 'GET' }); + const payload = String(url).endsWith('/api/meta') + ? fakeMeta + : String(url).endsWith('/api/state') + ? fakeState + : fakeValidation; + return { + ok: true, + status: 200, + text: async () => JSON.stringify(payload), + }; +}); + +let importError = null; +try { + await import(pathToFileURL(clientPath).href); +} catch (error) { + importError = error; +} +check('client module evaluates without a ReferenceError', importError === null, String(importError)); + +await new Promise((resolve) => setTimeout(resolve, 50)); + +check('boot requested /api/meta', calls.some((call) => call.url.endsWith('/api/meta'))); +check('boot requested /api/state', calls.some((call) => call.url.endsWith('/api/state'))); +check( + 'category select was populated from /api/meta', + element('category').options.length === fakeMeta.categories.length, + `options=${element('category').options.length}`, +); + +// ---- the primary action must actually call the Node service ---- +element('manifest-text').value = '{"schemaVersion":1,"name":"acme-research"}'; +element('market-name').value = 'Acme 研究助手'; +element('category').value = 'Science & Healthcare'; +element('summary').value = '检索研究资料并生成结构化综述。'; +element('documentation').value = '# Acme 研究助手\n\n正式说明文档。'; +element('submit-email').value = 'a@example.com'; +element('submit-account').value = '宋昊'; +element('organization').value = 'Acme'; + +const before = calls.length; +element('validate-button').fire('click'); +await new Promise((resolve) => setTimeout(resolve, 50)); + +check( + 'clicking 运行检查 posts to /api/validate', + calls.slice(before).some((call) => call.url.endsWith('/api/validate') && call.method === 'POST'), + JSON.stringify(calls.slice(before)), +); +check( + 'no ReferenceError surfaced in the status banner', + !element('status-banner').textContent.includes('is not defined'), + element('status-banner').textContent, +); +check( + 'check results rendered into the summary bar', + element('summary-bar').textContent.includes('错误'), + element('summary-bar').textContent, +); +check( + 'market preview rendered', + element('preview-body').textContent.includes('Acme 研究助手'), + element('preview-body').textContent.slice(0, 120), +); +check( + 'channel conclusion rendered', + element('channel-body').textContent.includes('未发现官方市场的程序化提交接口'), + element('channel-body').textContent.slice(0, 120), +); + +// ---- the package action must reach the Node service too ---- +const beforePackage = calls.length; +element('package-button').fire('click'); +await new Promise((resolve) => setTimeout(resolve, 50)); +check( + 'clicking 生成上架材料包 posts to /api/package', + calls.slice(beforePackage).some((call) => call.url.endsWith('/api/package') && call.method === 'POST'), + JSON.stringify(calls.slice(beforePackage)), +); + +console.log(`\n${passed} passed, ${failed} failed`); +if (failed > 0) process.exitCode = 1; diff --git a/plugins/zhuyankarl/submission-workbench/tests/path-traversal.mjs b/plugins/zhuyankarl/submission-workbench/tests/path-traversal.mjs new file mode 100644 index 00000000..1b9006f3 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/tests/path-traversal.mjs @@ -0,0 +1,249 @@ +// @ts-check +/** + * Regression harness for the path-traversal fix on the id-taking routes. + * + * Every id this store hands out is a server-generated UUID, so an id that does + * not look like one is refused before it can name a file. The harness proves + * that for the two routes that take an id from the query string + * (`DELETE /api/assets` and `GET /api/package/download`), and it proves the + * matching happy path still works. + * + * A canary file sits one level above the data directory, exactly where the + * reported exploit reached. Every traversal attempt must leave it untouched. + * + * Run: node tests/path-traversal.mjs + */ +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { randomUUID } from 'node:crypto'; + +import { start } from '../miniapp/node/server.mjs'; +import { Store, InvalidIdError } from '../miniapp/node/lib/store.mjs'; + +let passed = 0; +let failed = 0; + +/** + * @param {string} name + * @param {boolean} condition + * @param {string} [detail] + */ +function check(name, condition, detail = '') { + if (condition) { + passed += 1; + } else { + failed += 1; + console.log(`FAIL ${name}${detail ? ` :: ${detail}` : ''}`); + } +} + +/** + * @returns {Promise<number>} + */ +function freePort() { + return new Promise((resolve, reject) => { + const server = createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + const port = typeof address === 'object' && address ? address.port : 0; + server.close(() => resolve(port)); + }); + }); +} + +/** + * Ids that must never reach the filesystem. Each one names the canary through + * the asset (`.bin`) or the package (`.zip`) suffix. + */ +const TRAVERSAL_IDS = [ + '../../canary', + '..\\..\\canary', + '....//....//canary', + '../assets/../../canary', + '..%2F..%2Fcanary', + '%2e%2e%2f%2e%2e%2fcanary', + '../../canary/../canary', + '/etc/passwd', + 'C:\\Windows\\System32\\config\\SAM', + 'not-a-uuid', + '00000000-0000-4000-8000-000000000000/../../canary', + '00000000-0000-4000-8000-000000000000.bin', + `${randomUUID()}\x00../../canary`, +]; + +const root = await mkdtemp(join(tmpdir(), 'miniapp-traversal-')); +// The data directory is one level below the canary, so `../canary` from the +// assets directory is the canary itself. +const dataDir = join(root, 'data'); +const canaryBin = join(root, 'canary.bin'); +const canaryZip = join(root, 'canary.zip'); +const canaryBytes = Buffer.from('canary-must-survive', 'utf8'); + +await mkdir(dataDir, { recursive: true }); +await writeFile(canaryBin, canaryBytes); +await writeFile(canaryZip, canaryBytes); + +const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); +const port = await freePort(); +const controller = new AbortController(); + +const lifecycle = await start({ + pluginId: 'test', + pluginRoot, + dataDir, + listen: { host: '127.0.0.1', port }, + signal: controller.signal, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + capabilities: { has: () => false }, +}); + +const base = `http://127.0.0.1:${port}`; + +/** + * @param {string} file + * @returns {Promise<boolean>} + */ +async function exists(file) { + try { + await readFile(file); + return true; + } catch { + return false; + } +} + +/** + * @param {string} file + * @returns {Promise<boolean>} + */ +async function canaryIntact(file) { + try { + const bytes = await readFile(file); + return bytes.equals(canaryBytes); + } catch { + return false; + } +} + +try { + // ---- store level: the ids never reach the filesystem ---- + const store = new Store(dataDir); + await store.init(); + + for (const id of TRAVERSAL_IDS) { + const label = JSON.stringify(id); + + let deleteError; + try { + await store.deleteAsset(id); + } catch (error) { + deleteError = error; + } + check(`deleteAsset refuses ${label}`, deleteError instanceof InvalidIdError, String(deleteError)); + check(`deleteAsset left the canary alone for ${label}`, await canaryIntact(canaryBin)); + + let readError; + try { + await store.readPackageBytes(id); + } catch (error) { + readError = error; + } + check(`readPackageBytes refuses ${label}`, readError instanceof InvalidIdError, String(readError)); + check(`readPackageBytes left the canary alone for ${label}`, await canaryIntact(canaryZip)); + + let assetReadError; + try { + await store.readAssetBytes(id); + } catch (error) { + assetReadError = error; + } + check(`readAssetBytes refuses ${label}`, assetReadError instanceof InvalidIdError, String(assetReadError)); + check(`readAssetBytes left the canary alone for ${label}`, await canaryIntact(canaryBin)); + + let packageDeleteError; + try { + await store.deletePackage(id); + } catch (error) { + packageDeleteError = error; + } + check(`deletePackage refuses ${label}`, packageDeleteError instanceof InvalidIdError, String(packageDeleteError)); + check(`deletePackage left the canary alone for ${label}`, await canaryIntact(canaryZip)); + } + + // ---- HTTP level: the routes answer 400 and never serve the canary ---- + for (const id of TRAVERSAL_IDS) { + const label = JSON.stringify(id); + + const deletion = await fetch(`${base}/api/assets?id=${encodeURIComponent(id)}`, { + method: 'DELETE', + }); + check(`DELETE /api/assets answers 400 for ${label}`, deletion.status === 400, `status=${deletion.status}`); + check(`DELETE /api/assets left the canary alone for ${label}`, await canaryIntact(canaryBin)); + + const download = await fetch(`${base}/api/package/download?id=${encodeURIComponent(id)}`); + check(`GET /api/package/download answers 400 for ${label}`, download.status === 400, `status=${download.status}`); + const body = Buffer.from(await download.arrayBuffer()); + check( + `GET /api/package/download never served the canary for ${label}`, + !body.equals(canaryBytes), + body.toString('utf8').slice(0, 80), + ); + check(`GET /api/package/download left the canary alone for ${label}`, await canaryIntact(canaryZip)); + } + + // ---- the happy path still works with a real server-generated id ---- + const assetId = randomUUID(); + await store.saveAsset( + { + id: assetId, + name: 'icon.png', + role: 'icon', + size: 3, + mime: 'image/png', + createdAt: new Date().toISOString(), + }, + Buffer.from('png', 'utf8'), + ); + const assetFile = join(dataDir, 'assets', `${assetId}.bin`); + check('the saved asset is on disk', await exists(assetFile)); + + const validDelete = await fetch(`${base}/api/assets?id=${encodeURIComponent(assetId)}`, { + method: 'DELETE', + }); + check('DELETE /api/assets accepts a real id', validDelete.status === 200, `status=${validDelete.status}`); + check('DELETE /api/assets removed the file', (await exists(assetFile)) === false); + + const packageId = randomUUID(); + const packageBytes = Buffer.from('PK-not-really-a-zip', 'utf8'); + await store.savePackage( + { + id: packageId, + fileName: 'listing-package.zip', + createdAt: new Date().toISOString(), + size: packageBytes.length, + sha256: 'x', + entries: [], + manifest: null, + }, + packageBytes, + ); + + const validDownload = await fetch(`${base}/api/package/download?id=${encodeURIComponent(packageId)}`); + check('GET /api/package/download accepts a real id', validDownload.status === 200, `status=${validDownload.status}`); + const downloaded = Buffer.from(await validDownload.arrayBuffer()); + check('the downloaded bytes are the stored bytes', downloaded.equals(packageBytes)); + + // ---- an id that is well-formed but unknown is a 404, not a 400 ---- + const unknown = await fetch(`${base}/api/package/download?id=${randomUUID()}`); + check('an unknown but valid id answers 404', unknown.status === 404, `status=${unknown.status}`); +} finally { + await lifecycle.dispose(); + await rm(root, { recursive: true, force: true }); +} + +console.log(`\n${passed} passed, ${failed} failed`); +if (failed > 0) process.exitCode = 1; diff --git a/plugins/zhuyankarl/submission-workbench/tests/selftest.mjs b/plugins/zhuyankarl/submission-workbench/tests/selftest.mjs new file mode 100644 index 00000000..09d38b55 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/tests/selftest.mjs @@ -0,0 +1,447 @@ +// @ts-check +/** + * Local test harness for the Mini App backend logic. + * Run: node tests/selftest.mjs + */ +import { validateManifest } from '../miniapp/node/lib/manifest-rules.mjs'; +import { validateDraft } from '../miniapp/node/lib/listing-rules.mjs'; +import { buildPackage } from '../miniapp/node/lib/package-builder.mjs'; +import { createZip } from '../miniapp/node/lib/zip.mjs'; +import { parseJsonWithDuplicates } from '../miniapp/node/lib/json-parse.mjs'; +import { inflateRawSync } from 'node:zlib'; + +let passed = 0; +let failed = 0; + +/** + * @param {string} name + * @param {boolean} condition + * @param {string} [detail] + */ +function check(name, condition, detail = '') { + if (condition) { + passed += 1; + } else { + failed += 1; + console.log(`FAIL ${name}${detail ? ` :: ${detail}` : ''}`); + } +} + +const VALID_MANIFEST = JSON.stringify( + { + schemaVersion: 1, + name: 'acme-research', + displayName: 'Acme 研究助手', + version: '1.0.0', + description: '检索研究资料并生成结构化综述。', + author: 'Acme', + icon: 'icon.png', + category: 'Science & Healthcare', + exampleQueries: ['检索近期研究并总结主要结论'], + apps: [], + mcpServers: [], + skills: ['skills/literature-review/SKILL.md'], + }, + null, + 2, +); + +// ---- manifest rules ---- +{ + const result = validateManifest(VALID_MANIFEST); + check('valid manifest has no errors', result.ok, JSON.stringify(result.issues)); + check('valid manifest parses', result.manifest?.name === 'acme-research'); +} + +{ + const result = validateManifest(''); + check( + 'empty manifest is an error + missing', + result.issues.some((i) => i.severity === 'error' && i.missing), + ); +} + +{ + const result = validateManifest('{ "schemaVersion": 1, "name": "a", "name": "b" }'); + check( + 'duplicate keys detected', + result.issues.some((i) => i.id === 'manifest.duplicateKeys'), + JSON.stringify(result.issues.map((i) => i.id)), + ); +} + +{ + // A UTF-8 BOM survives in the raw text but `String.prototype.trim()` strips it, + // so the BOM rule must inspect the raw input. + const result = validateManifest(`${VALID_MANIFEST}`); + check( + 'UTF-8 BOM detected', + result.issues.some((i) => i.id === 'manifest.bom'), + JSON.stringify(result.issues.map((i) => i.id)), + ); + check('BOM manifest is not accepted', result.ok === false); +} + +{ + // One path can break several rules; every issue must keep a unique id. + const result = validateManifest( + JSON.stringify({ + schemaVersion: 1, + name: 'ok-name', + version: '1.0.0', + skills: ['skills/中文 目录/SKILL.md'], + }), + ); + const ids = result.issues.map((i) => i.id); + check('issue ids stay unique', new Set(ids).size === ids.length, JSON.stringify(ids)); +} + +{ + const result = validateManifest('{ "schemaVersion": 1, "name": "Bad_Name" }'); + check( + 'invalid name pattern detected', + result.issues.some((i) => i.id === 'manifest.name.pattern'), + ); +} + +{ + const result = validateManifest('{ "schemaVersion": 1, "name": "ok-name", "version": "1.0" }'); + check( + 'invalid semver detected', + result.issues.some((i) => i.id === 'manifest.version.semver'), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "category": "Nope" }', + ); + check( + 'invalid category detected', + result.issues.some((i) => i.id === 'manifest.category.invalid'), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "hooks": {} }', + ); + check( + 'hooks field rejected', + result.issues.some((i) => i.id === 'manifest.forbidden.hooks'), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "darkIcon": "d.png" }', + ); + check( + 'darkIcon rejected', + result.issues.some((i) => i.id === 'manifest.forbidden.darkIcon'), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "skills": ["../escape/SKILL.md"] }', + ); + check( + 'path traversal detected', + result.issues.some((i) => i.id.startsWith('manifest.skills.0.path.')), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "icon": "icon.PNG" }', + ); + check( + 'uppercase icon extension detected', + result.issues.some((i) => i.id === 'manifest.icon.lowercase'), + ); +} + +{ + const result = validateManifest( + '{ "schemaVersion": 1, "name": "ok-name", "version": "1.0.0", "exampleQueries": ["a","b","c","d"] }', + ); + check( + 'more than 3 example queries detected', + result.issues.some((i) => i.id === 'manifest.exampleQueries.count'), + ); +} + +// ---- json parser ---- +{ + const result = parseJsonWithDuplicates('{"a":1,"a":2,"b":{"c":1,"c":2}}'); + check('parser reports 2 duplicates', result.ok && result.duplicates.length === 2); +} +{ + const result = parseJsonWithDuplicates('{"a":1,'); + check('parser reports invalid json', !result.ok); +} +{ + const result = parseJsonWithDuplicates('{"a":"\\u00e9"}'); + check('parser handles unicode escapes', result.ok && result.value.a === 'é'); +} + +// ---- listing rules ---- +const baseDraft = { + manifestText: VALID_MANIFEST, + marketName: 'Acme 研究助手', + summary: '检索研究资料并生成结构化综述。', + documentation: '# Acme 研究助手\n\n这是正式说明文档。', + category: 'Science & Healthcare', + exampleQueries: ['检索近期研究并总结主要结论'], + regions: ['CN'], + enabledEnds: ['desktop'], + operation: 'new', + existingName: '', + previousVersion: '', + submitEmail: 'a@example.com', + submitAccount: '宋昊', + organization: 'Acme', +}; + +const assets = [ + { + id: 'a1', + name: 'icon.png', + role: 'icon', + size: 1024, + mime: 'image/png', + createdAt: '2026-11-16T00:00:00.000Z', + }, + { + id: 'a2', + name: 'skills/literature-review/SKILL.md', + role: 'skill', + size: 512, + mime: 'text/markdown', + createdAt: '2026-11-16T00:00:00.000Z', + }, + { + id: 'a3', + name: 'shot-01.png', + role: 'screenshot', + size: 2048, + mime: 'image/png', + createdAt: '2026-11-16T00:00:00.000Z', + }, +]; + +{ + const result = validateDraft(baseDraft, assets); + check( + 'complete draft has no errors', + result.issues.filter((i) => i.severity === 'error').length === 0, + JSON.stringify(result.issues.filter((i) => i.severity === 'error').map((i) => i.id)), + ); +} + +{ + const result = validateDraft({ ...baseDraft, manifestText: '', category: '' }, assets); + check( + 'missing manifest is flagged as missing', + result.issues.some((i) => i.missing && i.field === 'manifest'), + ); + // The category is a listing-form field: it must be reported even when the + // manifest is missing, otherwise the user never learns the form is incomplete. + check( + 'missing category is flagged even without a manifest', + result.issues.some((i) => i.id === 'listing.category.missing' && i.missing), + JSON.stringify(result.issues.map((i) => i.id)), + ); +} + +{ + const result = validateDraft({ ...baseDraft, screenshots: undefined }, assets.filter((a) => a.role !== 'screenshot')); + check( + 'missing screenshot flagged', + result.issues.some((i) => i.id === 'listing.screenshot.missing'), + ); +} + +{ + const result = validateDraft({ ...baseDraft, regions: [] }, assets); + check('missing region flagged', result.issues.some((i) => i.id === 'market.region.missing')); +} + +{ + const result = validateDraft({ ...baseDraft, summary: '完全不同的另一段话' }, assets); + check( + 'summary mismatch flagged', + result.issues.some((i) => i.id === 'consistency.summary'), + ); +} + +{ + const result = validateDraft({ ...baseDraft, marketName: '另一个名字' }, assets); + check( + 'market name mismatch flagged', + result.issues.some((i) => i.id === 'consistency.marketName'), + ); +} + +{ + const result = validateDraft( + { ...baseDraft, operation: 'update', existingName: 'acme-research', previousVersion: '1.0.0' }, + assets, + ); + check( + 'unchanged version on update flagged', + result.issues.some((i) => i.id === 'market.update.versionSame'), + ); +} + +{ + const result = validateDraft( + { ...baseDraft, operation: 'update', existingName: 'other-name', previousVersion: '0.9.0' }, + assets, + ); + check( + 'renamed plugin on update flagged', + result.issues.some((i) => i.id === 'market.update.nameChanged'), + ); +} + +{ + const result = validateDraft({ ...baseDraft, submitEmail: 'not-an-email' }, assets); + check('invalid email flagged', result.issues.some((i) => i.id === 'market.email.invalid')); +} + +{ + const result = validateDraft(baseDraft, assets.filter((a) => a.role !== 'icon')); + check( + 'missing icon asset flagged', + result.issues.some((i) => i.id === 'asset.icon.missing'), + ); +} + +// ---- zip writer ---- +{ + const zip = createZip([ + { path: 'a.txt', data: Buffer.from('hello world hello world hello world', 'utf8') }, + { path: 'dir/b.bin', data: Buffer.from([1, 2, 3, 4, 5]) }, + ]); + check('zip has PK signature', zip.readUInt32LE(0) === 0x04034b50); + check('zip ends with EOCD', zip.readUInt32LE(zip.length - 22) === 0x06054b50); + check('zip is non-trivial', zip.length > 100); +} + +// ---- package builder ---- +{ + const channel = { + checkedAt: '2026-11-16T00:00:00.000Z', + submissionInterface: 'manual_form', + canSubmitProgrammatically: false, + findings: [], + requiredPermissions: [], + conclusion: '仅生成可审核材料', + }; + const result = validateDraft(baseDraft, assets); + const built = await buildPackage( + baseDraft, + result.manifest, + assets, + async (asset) => (asset.role === 'icon' ? Buffer.from('PNG') : Buffer.from('# doc')), + result.issues, + channel, + ); + const paths = built.entries.map((entry) => entry.path); + check( + 'plugin.json sits at ZIP root', + paths.includes('.minimax-plugin/plugin.json'), + JSON.stringify(paths), + ); + check( + 'no wrapper directory', + !paths.some((path) => path.split('/')[0] === 'acme-research'), + JSON.stringify(paths), + ); + check('README included', paths.includes('README.md')); + check('skill file included', paths.includes('skills/literature-review/SKILL.md')); + check('review report included', paths.includes('listing-materials/review-report.md')); + check('market preview included', paths.includes('listing-materials/market-preview.md')); + check('zip bytes produced', built.bytes.length > 200); + + // Read the archive back with an independent minimal reader to prove the + // generated ZIP really carries the expected entries. + const readZipEntries = (zip) => { + const endOffset = zip.length - 22; + const total = zip.readUInt16LE(endOffset + 10); + let offset = zip.readUInt32LE(endOffset + 16); + const found = []; + for (let index = 0; index < total; index += 1) { + const nameLength = zip.readUInt16LE(offset + 28); + const extraLength = zip.readUInt16LE(offset + 30); + const commentLength = zip.readUInt16LE(offset + 32); + const localOffset = zip.readUInt32LE(offset + 42); + const name = zip.slice(offset + 46, offset + 46 + nameLength).toString('utf8'); + const localNameLength = zip.readUInt16LE(localOffset + 26); + const localExtraLength = zip.readUInt16LE(localOffset + 28); + const method = zip.readUInt16LE(localOffset + 8); + const compressedSize = zip.readUInt32LE(localOffset + 18); + const dataStart = localOffset + 30 + localNameLength + localExtraLength; + const payload = zip.slice(dataStart, dataStart + compressedSize); + found.push({ + name, + method, + text: + method === 0 + ? payload.toString('utf8') + : method === 8 + ? inflateRawSync(payload).toString('utf8') + : null, + }); + offset += 46 + nameLength + extraLength + commentLength; + } + return found; + }; + + const zipEntries = readZipEntries(built.bytes); + const zipNames = zipEntries.map((entry) => entry.name); + check( + 'zip really contains .minimax-plugin/plugin.json at root', + zipNames.includes('.minimax-plugin/plugin.json'), + JSON.stringify(zipNames), + ); + check( + 'zip has no wrapper directory', + !zipNames.some((name) => name.split('/')[0] === 'acme-research'), + JSON.stringify(zipNames), + ); + check( + 'zip contains README.md', + zipNames.includes('README.md'), + ); + check( + 'zip contains the review report', + zipNames.includes('listing-materials/review-report.md'), + ); + check( + 'zip contains the market preview', + zipNames.includes('listing-materials/market-preview.md'), + ); + check( + 'zip contains the skill file', + zipNames.includes('skills/literature-review/SKILL.md'), + ); + const reportEntry = zipEntries.find((entry) => entry.name === 'listing-materials/review-report.md'); + const pluginEntry = zipEntries.find((entry) => entry.name === '.minimax-plugin/plugin.json'); + const reportText = reportEntry?.text ?? ''; + check('review report states the package is not submitted', reportText.includes('尚未提交')); + check('review report cites the official guide', reportText.includes('plugin-submission.md')); + check( + 'plugin.json in the zip is valid JSON with the right name', + Boolean(pluginEntry) && JSON.parse(pluginEntry.text ?? '{}').name === 'acme-research', + ); + check( + 'stored (uncompressed) entries are method 0 and readable', + zipEntries.filter((entry) => entry.method === 0).length >= 0, + ); +} + +console.log(`\n${passed} passed, ${failed} failed`); +if (failed > 0) process.exitCode = 1; diff --git a/plugins/zhuyankarl/submission-workbench/tests/server-harness.mjs b/plugins/zhuyankarl/submission-workbench/tests/server-harness.mjs new file mode 100644 index 00000000..22e93363 --- /dev/null +++ b/plugins/zhuyankarl/submission-workbench/tests/server-harness.mjs @@ -0,0 +1,246 @@ +// @ts-check +/** + * Server integration harness: starts the real Node service on an ephemeral + * port and drives it over HTTP exactly like the Client does. + * + * It covers the path the DOM harness cannot: real HTTP headers, the asset + * upload route, package generation and the download route. + * + * Run: node tests/server-harness.mjs + */ +import { mkdtemp, rm } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { inflateRawSync } from 'node:zlib'; + +import { start } from '../miniapp/node/server.mjs'; + +let passed = 0; +let failed = 0; + +/** + * @param {string} name + * @param {boolean} condition + * @param {string} [detail] + */ +function check(name, condition, detail = '') { + if (condition) { + passed += 1; + } else { + failed += 1; + console.log(`FAIL ${name}${detail ? ` :: ${detail}` : ''}`); + } +} + +/** + * @returns {Promise<number>} + */ +function freePort() { + return new Promise((resolve, reject) => { + const server = createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + const port = typeof address === 'object' && address ? address.port : 0; + server.close(() => resolve(port)); + }); + }); +} + +const dataDir = await mkdtemp(join(tmpdir(), 'miniapp-listing-')); +// Resolve the package root from this file so the harness works from any cwd. +const pluginRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); +const port = await freePort(); +const controller = new AbortController(); + +const lifecycle = await start({ + pluginId: 'test', + pluginRoot, + dataDir, + listen: { host: '127.0.0.1', port }, + signal: controller.signal, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + capabilities: { has: () => false }, +}); + +const base = `http://127.0.0.1:${port}`; + +try { + // ---- meta ---- + const meta = await (await fetch(`${base}/api/meta`)).json(); + check('meta lists the official categories', (meta.categories ?? []).length === 10, JSON.stringify(meta.categories)); + + // ---- validate an incomplete draft ---- + const emptyDraft = { + manifestText: '', + marketName: '', + summary: '', + documentation: '', + category: '', + exampleQueries: [], + regions: [], + enabledEnds: [], + operation: 'new', + existingName: '', + previousVersion: '', + submitEmail: '', + submitAccount: '', + organization: '', + }; + const emptyResult = await (await fetch(`${base}/api/validate`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(emptyDraft), + })).json(); + check('empty draft reports missing items', (emptyResult.summary?.missing ?? 0) > 0, JSON.stringify(emptyResult.summary)); + check('empty draft has errors', (emptyResult.summary?.errors ?? 0) > 0); + + // ---- upload assets ---- + const manifest = { + schemaVersion: 1, + name: 'acme-research', + displayName: 'Acme 研究助手', + version: '1.0.0', + description: '检索研究资料并生成结构化综述。', + author: 'Acme', + icon: 'icon.png', + category: 'Science & Healthcare', + exampleQueries: ['检索近期研究并总结主要结论'], + apps: [], + mcpServers: [], + skills: ['skills/literature-review/SKILL.md'], + }; + const png = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64', + ); + const uploads = [ + { name: 'icon.png', role: 'icon', mime: 'image/png', contentBase64: png.toString('base64') }, + { name: 'screenshot-01.png', role: 'screenshot', mime: 'image/png', contentBase64: png.toString('base64') }, + { + name: 'skills/literature-review/SKILL.md', + role: 'skill', + mime: 'text/markdown', + contentBase64: Buffer.from('---\nname: literature-review\ndescription: 综述。\n---\n', 'utf8').toString('base64'), + }, + ]; + for (const upload of uploads) { + const response = await fetch(`${base}/api/assets`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(upload), + }); + check(`upload ${upload.name} accepted`, response.status === 201, `status=${response.status}`); + } + + // ---- package generation ---- + const draft = { + ...emptyDraft, + manifestText: JSON.stringify(manifest, null, 2), + marketName: 'Acme 研究助手', + summary: '检索研究资料并生成结构化综述。', + documentation: '# Acme 研究助手\n\n正式说明文档。', + category: 'Science & Healthcare', + exampleQueries: ['检索近期研究并总结主要结论'], + regions: ['CN'], + enabledEnds: ['desktop', 'cloud'], + submitEmail: '545965171@qq.com', + submitAccount: '宋昊', + organization: 'Acme', + }; + const packageResponse = await fetch(`${base}/api/package`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(draft), + }); + check('package generated', packageResponse.status === 201, `status=${packageResponse.status}`); + const packagePayload = await packageResponse.json(); + const record = packagePayload.package; + check('package has an id', typeof record?.id === 'string'); + check('package has a sha256', /^[0-9a-f]{64}$/.test(record?.sha256 ?? ''), record?.sha256); + check('package lists 7 entries', record?.entries?.length === 7, JSON.stringify(record?.entries?.map((e) => e.path))); + + // ---- download route (the route that broke on non-ASCII file names) ---- + const download = await fetch(`${base}/api/package/download?id=${encodeURIComponent(record.id)}`); + check('download returns 200', download.status === 200, `status=${download.status}`); + check('download is application/zip', download.headers.get('content-type') === 'application/zip', download.headers.get('content-type')); + const disposition = download.headers.get('content-disposition') ?? ''; + check( + 'content-disposition is ASCII-safe', + /^[^\u0080-\uFFFF]*$/.test(disposition), + disposition, + ); + check( + 'content-disposition carries the UTF-8 file name', + disposition.includes("filename*=UTF-8''"), + disposition, + ); + const bytes = Buffer.from(await download.arrayBuffer()); + check('downloaded size matches the record', bytes.length === record.size, `${bytes.length} vs ${record.size}`); + check('downloaded bytes match the sha256', (await import('node:crypto')).createHash('sha256').update(bytes).digest('hex') === record.sha256); + + // ---- parse the downloaded archive independently ---- + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let eocd = -1; + for (let i = bytes.length - 22; i >= 0; i -= 1) { + if (view.getUint32(i, true) === 0x06054b50) { + eocd = i; + break; + } + } + check('EOCD record found', eocd >= 0); + const total = view.getUint16(eocd + 10, true); + let offset = view.getUint32(eocd + 16, true); + /** @type {any[]} */ + const entries = []; + for (let i = 0; i < total; i += 1) { + const nameLength = view.getUint16(offset + 28, true); + const extraLength = view.getUint16(offset + 30, true); + const commentLength = view.getUint16(offset + 32, true); + const method = view.getUint16(offset + 10, true); + const localOffset = view.getUint32(offset + 42, true); + const localNameLength = view.getUint16(localOffset + 26, true); + const localExtraLength = view.getUint16(localOffset + 28, true); + const compressedSize = view.getUint32(localOffset + 18, true); + const dataStart = localOffset + 30 + localNameLength + localExtraLength; + const payload = bytes.subarray(dataStart, dataStart + compressedSize); + entries.push({ + name: bytes.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'), + method, + text: method === 0 ? payload.toString('utf8') : inflateRawSync(payload).toString('utf8'), + }); + offset += 46 + nameLength + extraLength + commentLength; + } + const names = entries.map((entry) => entry.name); + check('plugin.json sits at the ZIP root', names.includes('.minimax-plugin/plugin.json'), JSON.stringify(names)); + check('no wrapper directory', !names.some((name) => name.split('/')[0] === 'acme-research'), JSON.stringify(names)); + check('README included', names.includes('README.md')); + check('icon included', names.includes('icon.png')); + check('skill included', names.includes('skills/literature-review/SKILL.md')); + check('review report included', names.includes('listing-materials/review-report.md')); + check('market preview included', names.includes('listing-materials/market-preview.md')); + check('screenshot included', names.includes('listing-materials/screenshots/screenshot-01.png'), JSON.stringify(names)); + const pluginEntry = entries.find((entry) => entry.name === '.minimax-plugin/plugin.json'); + check('plugin.json in the zip parses and matches', JSON.parse(pluginEntry?.text ?? '{}').name === 'acme-research'); + const reportEntry = entries.find((entry) => entry.name === 'listing-materials/review-report.md'); + check('report states the package is not submitted', (reportEntry?.text ?? '').includes('尚未提交')); + check('report cites the official guide', (reportEntry?.text ?? '').includes('plugin-submission.md')); + + // ---- state survived and is readable ---- + const state = await (await fetch(`${base}/api/state`)).json(); + check('state keeps the draft', state.draft?.marketName === 'Acme 研究助手', JSON.stringify(state.draft?.marketName)); + check('state keeps the assets', (state.assets ?? []).length === 3, String((state.assets ?? []).length)); + check('state keeps the generated package', (state.packages ?? []).length >= 1); + + // ---- unknown route ---- + const missing = await fetch(`${base}/api/nope`); + check('unknown route returns 404', missing.status === 404, `status=${missing.status}`); +} finally { + await lifecycle.dispose(); + await rm(dataDir, { recursive: true, force: true }); +} + +console.log(`\n${passed} passed, ${failed} failed`); +if (failed > 0) process.exitCode = 1;