From d2c5c6fc2a9b0f7d110cd3e5e0e6f1f1d980c6af Mon Sep 17 00:00:00 2001 From: TLK1973 Date: Mon, 30 Nov 2026 09:44:53 +0000 Subject: [PATCH] Add tlk1973-gear-measurement-selector Mini App --- README.md | 433 +++++------ README.zh-CN.md | 433 +++++------ .../.minimax-plugin/plugin.json | 18 + .../tlk1973-gear-measurement-selector/LICENSE | 21 + .../README.md | 112 +++ .../icon.png | Bin 0 -> 1574 bytes .../miniapp/client/app.css | 217 ++++++ .../miniapp/client/app.js | 612 +++++++++++++++ .../miniapp/client/index.html | 266 +++++++ .../miniapp/miniapp.json | 32 + .../miniapp/node/devices.mjs | 704 ++++++++++++++++++ .../miniapp/node/engine.mjs | 613 +++++++++++++++ .../miniapp/node/export.mjs | 213 ++++++ .../miniapp/node/miniapp-api.ts | 641 ++++++++++++++++ .../miniapp/node/refresh.mjs | 134 ++++ .../miniapp/node/server.mjs | 346 +++++++++ .../miniapp/node/store.mjs | 71 ++ .../package.json | 6 + 18 files changed, 4440 insertions(+), 432 deletions(-) create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/.minimax-plugin/plugin.json create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/LICENSE create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/README.md create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/icon.png create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.css create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.js create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/index.html create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/miniapp.json create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/devices.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/engine.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/export.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/miniapp-api.ts create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/refresh.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/server.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/store.mjs create mode 100644 plugins/tlk1973/tlk1973-gear-measurement-selector/package.json diff --git a/README.md b/README.md index 86551113..b81ecf70 100644 --- a/README.md +++ b/README.md @@ -1,216 +1,217 @@ -# MiniMax Code MiniApps - -English | [简体中文](README.zh-CN.md) - -The official community repository for **MiniApps built for the MiniMax Code desktop app**. Discover useful tools, playful experiments, and apps you can make your own. - -[Product vision](#pursuing-human-in-the-loop-toward-agent-os) · [Architecture](#architecture) · [Explore MiniApps](#miniapps) · [Get started](#getting-started) · [Contribute](CONTRIBUTING.md) · [Report an issue](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) - -## About - -This repository is open to the community: anyone can contribute a MiniApp plugin by opening a pull request. MiniApps are interactive apps packaged as MiniMax Plugins. This repository brings together complete, self-contained plugin packages contributed by developers, with source files and usage instructions alongside each app. - -Packages are organized by author under `plugins///`. You can download an app, install it manually in MiniMax Code, and use its source as a starting point for your own work. - -## Pursuing Human in the Loop, Toward Agent OS - -We believe the Agent is evolving into the next-generation operating system (OS). In this paradigm shift, plugins are no longer mere feature extensions: plugins are software, and plugins are apps (MiniApps). - -At the same time, real productivity in every industry remains rooted in highly specialized work environments. A conversational interface (Chat UI) alone cannot replace the precise control and rich views of professional tools. Professional workflows of the future should not ask users to leave their workbench to accommodate AI. Instead, professional environments and AI should evolve in deep symbiosis, with AI internalized as a foundational, atomic capability available on demand—like power and water, compute, and storage. By building professional-grade MiniApps that grow on top of the Agent OS, we aim to connect the specialized interfaces of vertical domains with the AI-native compute beneath them, and to reshape how every industry works. - -> *CadQuery Viewer case: one prompt asks the Agent for a 3D model of the MiniMax octopus, and you point at what to change right on the model.* The Agent looks up the official mascot for reference, writes a parametric CadQuery script, runs and fixes it, and the build appears in the Viewer on the right. To change something, click the spot on the model (here, the mouth), type "make the mouth red", and send it to the conversation—the Agent gets the exact part and coordinates, and the Viewer switches to the new version once it is done. - -![CadQuery Viewer case study: the Agent builds a MiniMax octopus model, then recolours the mouth the user marked on the model](plugins/hanzijie/cq-viewer/docs/case-study.gif) - -**MiniApp's product stance: keep people involved in collaboration and decisions (Human-in-the-Loop).** - -We respect every industry, every profession, and the expertise people build over time. AI should be your smartest executor—amplifying your capabilities rather than pretending to have professional judgment on your behalf. MiniApps reconnect the part of the process that is too often split apart: turning work from something that can be refined into something that can be delivered. - -Our aim is to provide every industry with its own **professional IDE framework**: a place where AI can work while people can review, edit, and confirm at any point. - -We want users to be able to: - -- **Connect capabilities:** Reliably connect and use open-source MCP servers and first-party plugins, bringing data and actions into a professional workflow. -- **Build an interface:** Create a workspace that fits the way each industry actually works. -- **Collaborate at any time:** Make an Agent an always-available, dependable work assistant. And, of course, use it for anything else that is interesting or useful. - -In the way of working we envision, a lawyer would not submit an AI-written pleading directly to a court; an analyst would not make an investment decision directly from an AI-generated opinion; and an operator would not launch an AI-generated campaign unchanged. - -Instead, they would ask AI to research background, organize material, prepare a first draft, improve the expression, and find omissions—then return to their professional workspace to **review, edit, confirm, and let AI continue.** - -## Architecture - -MiniApps run inside the MiniMax Code desktop host through four cooperating layers: - -- **Host management:** The host provides Electron page hosting, runtime services, plugin installation and publishing, Node process lifecycle, readiness and instance management, and permissions and credentials. It provides control across the stack while business logic remains owned by each plugin. -- **Presentation layer (Chromium / Chrome engine):** The MiniApp page renders HTML, CSS, and JavaScript for filters, tables, charts, and interactive views. Host credentials stay out of the page. -- **Application layer (Node.js):** The Node process owns data aggregation, transformation and processing, business rules, and persistence. Page APIs and Agent tools reuse the same business services. Node can also provide a managed MCP service for the host MCP client. -- **Capabilities and data access:** Plugins can use available Host Connector access, optional plugin-spawned CLI child processes, and the planned unified tool entry for authorized Connector or MCP access to external services, MCP services, local tools, and local data. - -The MiniMax Code Agent communicates through the host MCP client. Business requests and page data move between the presentation and application layers, while Agent calls and results are mediated by the host. This keeps credentials and control in the host, and keeps domain logic and persistence in the plugin. - -![MiniApp technical architecture](docs/architecture/miniapp-technical-architecture-en.png) - -*English architecture diagram: MiniMax Code Desktop Host, presentation, application, and capabilities/data access layers.* - -## MiniApps - -| MiniApp | What it does | Author | -| --- | --- | --- | -| [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | -| [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | -| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | One dashboard page for live weather, A-share and gold, silver, crude oil and Bitcoin quotes, and six switchable news columns, with precious metals always shown in CNY per gram | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | -| [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | -| [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | -| [Dynamic Workflow Console](plugins/stevenjj33/workflow-console/) | Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export | [stevenjj33](https://github.com/stevenjj33) | -| [MiniMax Photo](plugins/webguhui/minimax-photo/) | Layered image editing with an in-app AI assistant, local recovery and programmatic editing tools | [WebGuHui](https://github.com/WebGuHui) | -| [MMX Octopus](plugins/antianqi/mmx-octopus/) | A desktop companion that mirrors what your Agent is doing, chats with you in her own session, and can be driven by the Agent through four MCP tools | [antianqi](https://github.com/antianqi) | -| [Cutline](plugins/klarkxy/cutline/) | Browser-based video editor: timeline cuts, captions, motion graphics, grading and export, cut from chat by the Agent | [klarkxy](https://github.com/klarkxy) | -| [MiniMax Video](plugins/webguhui/minimax-video/) | Local video editing with captions, a host Agent assistant, reviewable timeline edits, and MP4/MP3 export | [WebGuHui](https://github.com/WebGuHui) | -| [AI Office](plugins/cristinamadureira353-svg/ai-office/) | Manage five model-powered employees in a pixel office: client tasks, chats, breaks, meetings and quota-aware offline states; uses your own API keys | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | -| [Token Usage Board](plugins/amszuidas/mcode-token-usage-board/) | Explore local Token usage by date, model, and session, including input, output, and cache usage | [amszuidas](https://github.com/amszuidas) | -| [Token Usage Board](plugins/yanhy2000/mcode-usage-monitor/) | Watch local Token usage, output speed, and cache hit rate in near real time; filter by time range, model, and session | [yanhy2000](https://github.com/yanhy2000) | -| [Model Manager](plugins/ocoomber/openrouter-model-manager/) | Browse, search, and enable/disable models in your `~/.minimax/config.yaml` with instant save, bulk actions, one-click undo, and automatic backups | [ocoomber](https://github.com/ocoomber) | -| [Self-drive Route Planner](plugins/hanzijie/self-drive-route-planner/) | **Official plugin** for planning driving routes with place search, route alternatives, demo mode, and Xiaohongshu 3:4 itinerary cards | [HanZijie](https://github.com/HanZijie) | -| [Git Commit Tree](plugins/microbiosis/git-tree/) | Inspect a local Git repo's commit history with a swim-lane graph, branches/tags, commit detail, and per-file change stats; persisted filter preferences and optional auto-refresh | [Microbiosis](https://github.com/Microbiosis) | -| [Pomodoro Sit Reminder](plugins/1602winxp/pomodoro-sit-timer/) | A Pomodoro timer that only counts: an in-page sit reminder and sound when a segment ends, with no timer lock and no enforced rest length; reminders from a single file or a folder in sequence or shuffled, with single-track loop and loudness matching | [1602WinXP](https://github.com/1602WinXP) | -| [灵签易占 / Chinese Divination](plugins/weekbin/chinese-divination/) | Cast hexagrams with the Plum Blossom method (time, number, three-coin, or daily), read the result through the classical body/use rules, and browse all sixty-four hexagrams with a ganzhi almanac | [weekbin](https://github.com/weekbin) | -| [Session Trajectory](plugins/avatasia/mmc-trajectory/) | Browse a conversation's model trajectory: messages, reasoning, tool calls and results, Token usage, and per-turn timing | [avatasia](https://github.com/avatasia) | -| [CadQuery Viewer](plugins/hanzijie/cq-viewer/) | Opened in a conversation, lists the STL / STEP models in that conversation's folder (STEP keeps assembly part names, colours, and real CAD edges) and orbits around whatever point you press on; watch models pushed from CadQuery scripts, and mark positions on the model to send to the conversation in one click; one more click has a background Agent render the current view's white model into a finished product image with MiniMax image generation, following your own description; MCP tools let the AI add model folders and open models, and a CadQuery parametric-design skill is bundled | [HanZijie](https://github.com/HanZijie) · [flowful-ai](https://github.com/flowful-ai) | -| [MiniMax Bot](plugins/minimax-ai/minimax-bot/) | **Official plugin** that turns MiniMax Code into an always-on team of Bots: a Chief Bot builds the team, group chats hand work between members with `@` mentions, and every Bot has its own memory, scheduled tasks, and usage stats. Requires MiniMax Code 3.1.2 or later | [MiniMax-AI](https://github.com/MiniMax-AI) | -| [心屿 / Xinyu Island](plugins/yujiachen-y/xinyu-daily/) | A cozy daily-mood island that plays like an indie game: an inspiration card shaped by your answers, mood stickers, a joy jar, a decision slot machine, a Book of Answers, and 20 hidden secrets guarded by a grumpy crab. Optionally, Xiaoyu writes you a daily letter and chats with you using your model. Requires MiniMax Code 3.1.2 or later | [yujiachen-y](https://github.com/yujiachen-y) | -| [MoMo Collab](plugins/amszuidas/momo-collab/) | A project steward that turns stray thoughts, screenshots, and links into ideas, writes clear ideas up as tasks, runs each task in its own Agent session with a full handoff, checks the result against your done criteria, and tracks everything on a board. Requires MiniMax Code 3.1.2 or later | [amszuidas](https://github.com/amszuidas) | -| [Anatomy Gallery](plugins/zch0227/anatomy-gallery/) | A gallery for interactive isometric figures made with the anatomy skill: hang them in rooms you organize, view light and dark editions full screen, keep every version, and have an Agent create or edit figures from the gallery with a per-run process log. The anatomy skill is bundled. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | -| [仓库透视 / Repo X-Ray](plugins/yujiachen-y/repo-xray/) | Understand a codebase from its Git history: a code map you can drill into, hotspots and bug magnets, high-risk files, owners and knowledge loss, commit rhythm and firefighting, and the tech stack. Works with GitHub, GitLab, and local repositories; analysis runs on your machine | [yujiachen-y](https://github.com/yujiachen-y) | -| [OpenViking Mini Studio](plugins/openviking/mini-studio/) | Browse and search your OpenViking context read-only, preview it, and add selected URIs or content to the chat | OpenViking | -| [Disk Insight](plugins/zch0227/disk-insight/) | See where disk space went on macOS and Windows with a sunburst space map, find junk files sorted into three safety tiers, large and duplicate files, and how much code repositories and Git worktrees take; ask an Agent about any item, and permanently delete what you select after a confirmation that lists every item. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | -| [A/时差保安 / Timezone Guard](plugins/liuchen19960902/timezone-guard/) | Check the other side's local time before you message: the target city's clock turns into a green "now is fine", yellow "keep it short", or red "go to sleep" verdict. Requires MiniMax Code 3.1.2 or later | [FineCat](https://github.com/LiuChen19960902) | -| [AI Node Canvas](plugins/antianqi/ai-node-canvas/) | An infinite-canvas node graph for MiniMax Code: wire text, image, video and audio runs into a graph, let each result flow downstream, cut a clip on a timeline, split a soundtrack off a video, and run media tools on any result | [antianqi](https://github.com/antianqi) | -| [An-bot-team](plugins/antianqi/an-bot-team/) | Today's bot is one person wearing several masks, taking turns with you. An-bot-team gives you a team instead: members with different skills and temperaments, each guarding one field, and they can argue about the same question from different angles | [antianqi](https://github.com/antianqi) | -| [Agent Flow](plugins/huixin615/agent-flow/) | Import this plugin's Hook event file to inspect native task calls and sub-agent lifecycles, with exact task-to-child links when IDs are available. Choose a recorded chat or the latest imported record; no Host session files are opened. Requires MiniMax Code 3.1.4 or later | [Huixin615](https://github.com/Huixin615) | -| [蹬王之王 · Expiry Guardian](plugins/hylouis233/expiry-guardian/) | Track credit and reset-card expiry from a local ledger you maintain, and get a "spend the card or let the credits burn first" recommendation with the reasoning spelled out | [Hylouis](https://github.com/Hylouis233) | -| [MiniMax Pet](plugins/minimax-ai/minimax-pet/) | A lightweight companion with appearance, task and settings tabs, visible-session activity, answer-needed reminders, Markdown-rendered replies, a one-click jump to a task's conversation (3.1.11 or later) and a transparent desktop pet. Requires MiniMax Code 3.1.6 or later | [MiniMax](https://github.com/MiniMax-AI) | -| [MCP OAuth Console](plugins/microbiosis/mcp-oauth-console/) | Sign in to MCP servers that require OAuth: device-code or authorization-code + PKCE flow, the `Authorization` header written into the MCP configuration, and an opt-in refresh before expiry | [Microbiosis](https://github.com/Microbiosis) | -| [本机大盘 · Local Market Board](plugins/jzlikewei/kurumi-monitor/) | Watch your own machine as a stock terminal: CPU, GPU, temperature, memory, disk, network and every running process become listed stocks with live candlesticks, moving averages, a watchlist, a leaderboard and a trade tape, on macOS and Windows. Requires minimax Code 3.1.2 or later | [jzlikewei](https://github.com/jzlikewei) | -| [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) | -| [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | -| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) | -| [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) | -| [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) | - -
-Preview: Weekly Planner - -![Weekly Planner showing the weekly progress panel and one day's task list with synthetic data](plugins/alanhean/weekly-planner/docs/preview.png) - -The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/alanhean/weekly-planner/README.md) for installation, data access, and compatibility notes. - -
- -
-Preview: Cutline - -![Cutline editor with synthetic media, titles and a multi-track timeline](plugins/klarkxy/cutline/docs/editor-en.png) - -![Cutline export dialog with range, preset, video and audio settings](plugins/klarkxy/cutline/docs/export-en.png) - -The preview uses a synthetic project. See the [Cutline README](plugins/klarkxy/cutline/README.md) for installation, editing, export and data-access details. - -
- -
-Preview: Token Usage Board - -![Token Usage Board showing usage trends with synthetic data](plugins/amszuidas/mcode-token-usage-board/docs/preview.png) - -The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/amszuidas/mcode-token-usage-board/README.md) for data access, counting rules, and compatibility notes. - -
- -
-Preview: Token Usage Board (mcode-usage-monitor) - -![Token Usage Board showing usage trends with synthetic data](plugins/yanhy2000/mcode-usage-monitor/docs/preview.png) - -The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/yanhy2000/mcode-usage-monitor/README.md) for data access, counting rules, and compatibility notes. - -
- -
-Preview: Git Commit Tree - -![Git Commit Tree showing a swim-lane commit graph with synthetic data](plugins/microbiosis/git-tree/docs/preview.jpg) - -The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/microbiosis/git-tree/README.md) for repository discovery, layout algorithm attribution, and compatibility notes. - -
- -## Getting started - -### Requirements - -Use a MiniMax Code desktop version that supports MiniApps. Check the app's README for tested client versions, operating systems, configuration, and known limitations. Compatibility is documented per app. Apps that use newer capabilities need a newer client, and older versions cannot install them: running Agent tasks or opening in their own window needs MiniMax Code 3.1.2 or later; reading your conversations, calling your installed tools, or using the microphone needs 3.1.6 or later; using the camera or showing system notifications needs 3.1.9 or later; following which MiniMax Code page you are on needs 3.1.11 or later. From 3.1.6 you can switch off each permission an app declares, one by one, in its plugin details. - -### 1. Download - -Select **Code → Download ZIP** on this repository and extract the archive, or clone it: - -```sh -git clone https://github.com/MiniMax-AI/MiniMax-Code-MiniApps.git -``` - -Find the app you want under `plugins//` and read its README, including which local files or network services it accesses. - -### 2. Install - -Copy the **entire plugin directory**, including the hidden `.minimax-plugin` directory, into `/plugins/`. - -By default, `` is the `.minimax` directory in your home folder (`~/.minimax`), so plugins go in `~/.minimax/plugins/`. If you have configured a different data directory, use that directory instead. - -For Token Usage Board: - -```text -Repository: plugins/amszuidas/mcode-token-usage-board/ -Install to: /plugins/mcode-token-usage-board/ -``` - -The installed manifest must be at: - -```text -/plugins/mcode-token-usage-board/.minimax-plugin/plugin.json -``` - -The author directory (`amszuidas/`) only groups contributions in the repository. Copy the plugin directory directly into the client's `plugins/` directory, without that extra author level. - -From MiniMax Code 3.1.11 you can import an app instead of copying it: on the Plugins page, choose **Create**, then **Import from a Git repository** under Mini App, and paste the URL of the plugin directory, for example `https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/amszuidas/mcode-token-usage-board`. The client downloads the whole repository (about 160 MiB) and gives up after five minutes, so on a slow connection install manually instead. Earlier clients cannot import from this repository because it is larger than their 128 MiB limit. - -### 3. Open - -Restart MiniMax Code, confirm that the plugin is recognized and enabled, and open the MiniApp following its README. For Token Usage Board, ask the Agent to open “Token 用量看板”. - -To update an app, close it and exit MiniMax Code, then replace its complete plugin directory. Keep any backup outside `plugins/` and follow the app's instructions for preserving its data. To uninstall, close the app and exit the client before removing its plugin directory; separately stored app data may remain. - -## Contributing - -Tools, games, visualizations, and small experiments are all welcome. To share a MiniApp: - -1. Fork the repository, copy `examples/hello-miniapp/` to `plugins///`, and build your app there. The package rules are in [`docs/`](docs/package-contract.md); AI coding agents read [`AGENTS.md`](AGENTS.md) automatically. -2. Include a README, a license, and any required runtime files. Document setup, data access, and what you have tested. -3. Add the app to the tables in both root READMEs, run `npm run check`, and open a pull request. - -Use a lowercase GitHub username for the author directory. The plugin directory name must match `.minimax-plugin/plugin.json` → `name`, and **plugin IDs must be unique across the repository**, since the author directory is not part of the installed path. - -See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contribution guide. - -## Questions and feedback - -Use [GitHub Issues](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) to report a problem or suggest an app or improvement. For an app issue, include its ID and version, your MiniMax Code version, operating system, steps to reproduce, and the expected and actual behavior. Remove credentials and private session content from logs and screenshots. - -To ask for a runtime capability that MiniApps do not have yet, such as a new `context` API or window behaviour, comment on the pinned [capability wishlist](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues/9) instead of opening a new issue. - -## License - -This repository is licensed under the [MIT License](LICENSE). Individual MiniApps are governed by the licenses included in their own directories. +# MiniMax Code MiniApps + +English | [简体中文](README.zh-CN.md) + +The official community repository for **MiniApps built for the MiniMax Code desktop app**. Discover useful tools, playful experiments, and apps you can make your own. + +[Product vision](#pursuing-human-in-the-loop-toward-agent-os) · [Architecture](#architecture) · [Explore MiniApps](#miniapps) · [Get started](#getting-started) · [Contribute](CONTRIBUTING.md) · [Report an issue](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) + +## About + +This repository is open to the community: anyone can contribute a MiniApp plugin by opening a pull request. MiniApps are interactive apps packaged as MiniMax Plugins. This repository brings together complete, self-contained plugin packages contributed by developers, with source files and usage instructions alongside each app. + +Packages are organized by author under `plugins///`. You can download an app, install it manually in MiniMax Code, and use its source as a starting point for your own work. + +## Pursuing Human in the Loop, Toward Agent OS + +We believe the Agent is evolving into the next-generation operating system (OS). In this paradigm shift, plugins are no longer mere feature extensions: plugins are software, and plugins are apps (MiniApps). + +At the same time, real productivity in every industry remains rooted in highly specialized work environments. A conversational interface (Chat UI) alone cannot replace the precise control and rich views of professional tools. Professional workflows of the future should not ask users to leave their workbench to accommodate AI. Instead, professional environments and AI should evolve in deep symbiosis, with AI internalized as a foundational, atomic capability available on demand—like power and water, compute, and storage. By building professional-grade MiniApps that grow on top of the Agent OS, we aim to connect the specialized interfaces of vertical domains with the AI-native compute beneath them, and to reshape how every industry works. + +> *CadQuery Viewer case: one prompt asks the Agent for a 3D model of the MiniMax octopus, and you point at what to change right on the model.* The Agent looks up the official mascot for reference, writes a parametric CadQuery script, runs and fixes it, and the build appears in the Viewer on the right. To change something, click the spot on the model (here, the mouth), type "make the mouth red", and send it to the conversation—the Agent gets the exact part and coordinates, and the Viewer switches to the new version once it is done. + +![CadQuery Viewer case study: the Agent builds a MiniMax octopus model, then recolours the mouth the user marked on the model](plugins/hanzijie/cq-viewer/docs/case-study.gif) + +**MiniApp's product stance: keep people involved in collaboration and decisions (Human-in-the-Loop).** + +We respect every industry, every profession, and the expertise people build over time. AI should be your smartest executor—amplifying your capabilities rather than pretending to have professional judgment on your behalf. MiniApps reconnect the part of the process that is too often split apart: turning work from something that can be refined into something that can be delivered. + +Our aim is to provide every industry with its own **professional IDE framework**: a place where AI can work while people can review, edit, and confirm at any point. + +We want users to be able to: + +- **Connect capabilities:** Reliably connect and use open-source MCP servers and first-party plugins, bringing data and actions into a professional workflow. +- **Build an interface:** Create a workspace that fits the way each industry actually works. +- **Collaborate at any time:** Make an Agent an always-available, dependable work assistant. And, of course, use it for anything else that is interesting or useful. + +In the way of working we envision, a lawyer would not submit an AI-written pleading directly to a court; an analyst would not make an investment decision directly from an AI-generated opinion; and an operator would not launch an AI-generated campaign unchanged. + +Instead, they would ask AI to research background, organize material, prepare a first draft, improve the expression, and find omissions—then return to their professional workspace to **review, edit, confirm, and let AI continue.** + +## Architecture + +MiniApps run inside the MiniMax Code desktop host through four cooperating layers: + +- **Host management:** The host provides Electron page hosting, runtime services, plugin installation and publishing, Node process lifecycle, readiness and instance management, and permissions and credentials. It provides control across the stack while business logic remains owned by each plugin. +- **Presentation layer (Chromium / Chrome engine):** The MiniApp page renders HTML, CSS, and JavaScript for filters, tables, charts, and interactive views. Host credentials stay out of the page. +- **Application layer (Node.js):** The Node process owns data aggregation, transformation and processing, business rules, and persistence. Page APIs and Agent tools reuse the same business services. Node can also provide a managed MCP service for the host MCP client. +- **Capabilities and data access:** Plugins can use available Host Connector access, optional plugin-spawned CLI child processes, and the planned unified tool entry for authorized Connector or MCP access to external services, MCP services, local tools, and local data. + +The MiniMax Code Agent communicates through the host MCP client. Business requests and page data move between the presentation and application layers, while Agent calls and results are mediated by the host. This keeps credentials and control in the host, and keeps domain logic and persistence in the plugin. + +![MiniApp technical architecture](docs/architecture/miniapp-technical-architecture-en.png) + +*English architecture diagram: MiniMax Code Desktop Host, presentation, application, and capabilities/data access layers.* + +## MiniApps + +| MiniApp | What it does | Author | +| --- | --- | --- | +| [Gear Measurement Scheme Selector](plugins/tlk1973/tlk1973-gear-measurement-selector/) | Selects contact and non-contact gear measurement machines from workpiece, accuracy, space, environment and budget constraints, with a filterable comparison table, a ranked recommendation, site/environment/auxiliary configuration lists and a shareable export | [TLK1973](https://github.com/TLK1973) | +| [Postman Lite](plugins/ssugarr/postman-lite/) | A lightweight local API request tool: build requests, send them through a local proxy that sidesteps browser CORS limits, and inspect responses, with collections kept as plain JSON | [ssugarr](https://github.com/ssugarr) | +| [Weekly Planner](plugins/alanhean/weekly-planner/) | A local weekly planner: add tasks with a date and a priority, review them day by day, tick them off, and track the week's completion rate | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | One dashboard page for live weather, A-share and gold, silver, crude oil and Bitcoin quotes, and six switchable news columns, with precious metals always shown in CNY per gram | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | +| [DeepSeek Chat Migration](plugins/danielwalnut/deepseek-chat-migration/) | Preview official DeepSeek web exports locally, restore branches and attachments, and import selected conversations as native MiniMax Code sessions with a bundled importer | [DanielWalnut](https://github.com/DanielWalnut) | +| [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | Run OpenFilm inside MiniMax Code with the desktop interface: Studio editor, chat column and local agents, with a web-Studio fallback | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | +| [Dynamic Workflow Console](plugins/stevenjj33/workflow-console/) | Run and supervise MiniMax Code dynamic workflows from one page: live status, a stage-and-dependency flow graph, per-node output, approval and control, templates, and report export | [stevenjj33](https://github.com/stevenjj33) | +| [MiniMax Photo](plugins/webguhui/minimax-photo/) | Layered image editing with an in-app AI assistant, local recovery and programmatic editing tools | [WebGuHui](https://github.com/WebGuHui) | +| [MMX Octopus](plugins/antianqi/mmx-octopus/) | A desktop companion that mirrors what your Agent is doing, chats with you in her own session, and can be driven by the Agent through four MCP tools | [antianqi](https://github.com/antianqi) | +| [Cutline](plugins/klarkxy/cutline/) | Browser-based video editor: timeline cuts, captions, motion graphics, grading and export, cut from chat by the Agent | [klarkxy](https://github.com/klarkxy) | +| [MiniMax Video](plugins/webguhui/minimax-video/) | Local video editing with captions, a host Agent assistant, reviewable timeline edits, and MP4/MP3 export | [WebGuHui](https://github.com/WebGuHui) | +| [AI Office](plugins/cristinamadureira353-svg/ai-office/) | Manage five model-powered employees in a pixel office: client tasks, chats, breaks, meetings and quota-aware offline states; uses your own API keys | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | +| [Token Usage Board](plugins/amszuidas/mcode-token-usage-board/) | Explore local Token usage by date, model, and session, including input, output, and cache usage | [amszuidas](https://github.com/amszuidas) | +| [Token Usage Board](plugins/yanhy2000/mcode-usage-monitor/) | Watch local Token usage, output speed, and cache hit rate in near real time; filter by time range, model, and session | [yanhy2000](https://github.com/yanhy2000) | +| [Model Manager](plugins/ocoomber/openrouter-model-manager/) | Browse, search, and enable/disable models in your `~/.minimax/config.yaml` with instant save, bulk actions, one-click undo, and automatic backups | [ocoomber](https://github.com/ocoomber) | +| [Self-drive Route Planner](plugins/hanzijie/self-drive-route-planner/) | **Official plugin** for planning driving routes with place search, route alternatives, demo mode, and Xiaohongshu 3:4 itinerary cards | [HanZijie](https://github.com/HanZijie) | +| [Git Commit Tree](plugins/microbiosis/git-tree/) | Inspect a local Git repo's commit history with a swim-lane graph, branches/tags, commit detail, and per-file change stats; persisted filter preferences and optional auto-refresh | [Microbiosis](https://github.com/Microbiosis) | +| [Pomodoro Sit Reminder](plugins/1602winxp/pomodoro-sit-timer/) | A Pomodoro timer that only counts: an in-page sit reminder and sound when a segment ends, with no timer lock and no enforced rest length; reminders from a single file or a folder in sequence or shuffled, with single-track loop and loudness matching | [1602WinXP](https://github.com/1602WinXP) | +| [灵签易占 / Chinese Divination](plugins/weekbin/chinese-divination/) | Cast hexagrams with the Plum Blossom method (time, number, three-coin, or daily), read the result through the classical body/use rules, and browse all sixty-four hexagrams with a ganzhi almanac | [weekbin](https://github.com/weekbin) | +| [Session Trajectory](plugins/avatasia/mmc-trajectory/) | Browse a conversation's model trajectory: messages, reasoning, tool calls and results, Token usage, and per-turn timing | [avatasia](https://github.com/avatasia) | +| [CadQuery Viewer](plugins/hanzijie/cq-viewer/) | Opened in a conversation, lists the STL / STEP models in that conversation's folder (STEP keeps assembly part names, colours, and real CAD edges) and orbits around whatever point you press on; watch models pushed from CadQuery scripts, and mark positions on the model to send to the conversation in one click; one more click has a background Agent render the current view's white model into a finished product image with MiniMax image generation, following your own description; MCP tools let the AI add model folders and open models, and a CadQuery parametric-design skill is bundled | [HanZijie](https://github.com/HanZijie) · [flowful-ai](https://github.com/flowful-ai) | +| [MiniMax Bot](plugins/minimax-ai/minimax-bot/) | **Official plugin** that turns MiniMax Code into an always-on team of Bots: a Chief Bot builds the team, group chats hand work between members with `@` mentions, and every Bot has its own memory, scheduled tasks, and usage stats. Requires MiniMax Code 3.1.2 or later | [MiniMax-AI](https://github.com/MiniMax-AI) | +| [心屿 / Xinyu Island](plugins/yujiachen-y/xinyu-daily/) | A cozy daily-mood island that plays like an indie game: an inspiration card shaped by your answers, mood stickers, a joy jar, a decision slot machine, a Book of Answers, and 20 hidden secrets guarded by a grumpy crab. Optionally, Xiaoyu writes you a daily letter and chats with you using your model. Requires MiniMax Code 3.1.2 or later | [yujiachen-y](https://github.com/yujiachen-y) | +| [MoMo Collab](plugins/amszuidas/momo-collab/) | A project steward that turns stray thoughts, screenshots, and links into ideas, writes clear ideas up as tasks, runs each task in its own Agent session with a full handoff, checks the result against your done criteria, and tracks everything on a board. Requires MiniMax Code 3.1.2 or later | [amszuidas](https://github.com/amszuidas) | +| [Anatomy Gallery](plugins/zch0227/anatomy-gallery/) | A gallery for interactive isometric figures made with the anatomy skill: hang them in rooms you organize, view light and dark editions full screen, keep every version, and have an Agent create or edit figures from the gallery with a per-run process log. The anatomy skill is bundled. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | +| [仓库透视 / Repo X-Ray](plugins/yujiachen-y/repo-xray/) | Understand a codebase from its Git history: a code map you can drill into, hotspots and bug magnets, high-risk files, owners and knowledge loss, commit rhythm and firefighting, and the tech stack. Works with GitHub, GitLab, and local repositories; analysis runs on your machine | [yujiachen-y](https://github.com/yujiachen-y) | +| [OpenViking Mini Studio](plugins/openviking/mini-studio/) | Browse and search your OpenViking context read-only, preview it, and add selected URIs or content to the chat | OpenViking | +| [Disk Insight](plugins/zch0227/disk-insight/) | See where disk space went on macOS and Windows with a sunburst space map, find junk files sorted into three safety tiers, large and duplicate files, and how much code repositories and Git worktrees take; ask an Agent about any item, and permanently delete what you select after a confirmation that lists every item. Requires MiniMax Code 3.1.2 or later | [zch0227](https://github.com/zch0227) | +| [A/时差保安 / Timezone Guard](plugins/liuchen19960902/timezone-guard/) | Check the other side's local time before you message: the target city's clock turns into a green "now is fine", yellow "keep it short", or red "go to sleep" verdict. Requires MiniMax Code 3.1.2 or later | [FineCat](https://github.com/LiuChen19960902) | +| [AI Node Canvas](plugins/antianqi/ai-node-canvas/) | An infinite-canvas node graph for MiniMax Code: wire text, image, video and audio runs into a graph, let each result flow downstream, cut a clip on a timeline, split a soundtrack off a video, and run media tools on any result | [antianqi](https://github.com/antianqi) | +| [An-bot-team](plugins/antianqi/an-bot-team/) | Today's bot is one person wearing several masks, taking turns with you. An-bot-team gives you a team instead: members with different skills and temperaments, each guarding one field, and they can argue about the same question from different angles | [antianqi](https://github.com/antianqi) | +| [Agent Flow](plugins/huixin615/agent-flow/) | Import this plugin's Hook event file to inspect native task calls and sub-agent lifecycles, with exact task-to-child links when IDs are available. Choose a recorded chat or the latest imported record; no Host session files are opened. Requires MiniMax Code 3.1.4 or later | [Huixin615](https://github.com/Huixin615) | +| [蹬王之王 · Expiry Guardian](plugins/hylouis233/expiry-guardian/) | Track credit and reset-card expiry from a local ledger you maintain, and get a "spend the card or let the credits burn first" recommendation with the reasoning spelled out | [Hylouis](https://github.com/Hylouis233) | +| [MiniMax Pet](plugins/minimax-ai/minimax-pet/) | A lightweight companion with appearance, task and settings tabs, visible-session activity, answer-needed reminders, Markdown-rendered replies, a one-click jump to a task's conversation (3.1.11 or later) and a transparent desktop pet. Requires MiniMax Code 3.1.6 or later | [MiniMax](https://github.com/MiniMax-AI) | +| [MCP OAuth Console](plugins/microbiosis/mcp-oauth-console/) | Sign in to MCP servers that require OAuth: device-code or authorization-code + PKCE flow, the `Authorization` header written into the MCP configuration, and an opt-in refresh before expiry | [Microbiosis](https://github.com/Microbiosis) | +| [本机大盘 · Local Market Board](plugins/jzlikewei/kurumi-monitor/) | Watch your own machine as a stock terminal: CPU, GPU, temperature, memory, disk, network and every running process become listed stocks with live candlesticks, moving averages, a watchlist, a leaderboard and a trade tape, on macOS and Windows. Requires minimax Code 3.1.2 or later | [jzlikewei](https://github.com/jzlikewei) | +| [Quota Bottle](plugins/7723qqq/quota-bottle/) | An octopus-shaped glass bottle that floats on your desktop and shows the remaining Token Plan quota from a login you configure yourself, with the liquid level and opacity following the remaining share, and a device-code login plus an opt-in local token-usage estimate as fallbacks | [7723qqq](https://github.com/7723qqq) | +| [Site QA](plugins/lonelyguy-se1/site-qa/) | Check local HTML/robots/sitemap for SEO and accessibility gaps, then ask the agent to fix them (Mini App + skill/CLI). Requires MiniMax Code 3.1.6 or later | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | +| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/) | Turn one sentence into verified 4K images: it plans the shot list, searches for reference images, generates, reviews each image by looking at it, corrects colour cast, runs a bounded fix loop and delivers the result with an acceptance report; multi-image runs generate a character sheet first so the same subject stays the same subject. Needs an H3-Image endpoint and key you configure yourself. Requires MiniMax Code 3.1.6 or later | [liddalidd](https://github.com/liddalidd) | +| [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) | +| [WeChat Article Studio](plugins/xiaobinger/wechat-mp-article-studio/) | Plan a WeChat Official Account article: cover and illustration slots rendered as real images, a duplication check against your previous piece, versioned drafts with publish states, and paste-ready inline-styled HTML. Publishing stays blocked until account authorisation, material access and a publish interface are confirmed; with no interface connected it only ever saves a draft. Requires MiniMax Code 3.1.6 or later | [xiaobinger](https://github.com/xiaobinger) | + +
+Preview: Weekly Planner + +![Weekly Planner showing the weekly progress panel and one day's task list with synthetic data](plugins/alanhean/weekly-planner/docs/preview.png) + +The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/alanhean/weekly-planner/README.md) for installation, data access, and compatibility notes. + +
+ +
+Preview: Cutline + +![Cutline editor with synthetic media, titles and a multi-track timeline](plugins/klarkxy/cutline/docs/editor-en.png) + +![Cutline export dialog with range, preset, video and audio settings](plugins/klarkxy/cutline/docs/export-en.png) + +The preview uses a synthetic project. See the [Cutline README](plugins/klarkxy/cutline/README.md) for installation, editing, export and data-access details. + +
+ +
+Preview: Token Usage Board + +![Token Usage Board showing usage trends with synthetic data](plugins/amszuidas/mcode-token-usage-board/docs/preview.png) + +The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/amszuidas/mcode-token-usage-board/README.md) for data access, counting rules, and compatibility notes. + +
+ +
+Preview: Token Usage Board (mcode-usage-monitor) + +![Token Usage Board showing usage trends with synthetic data](plugins/yanhy2000/mcode-usage-monitor/docs/preview.png) + +The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/yanhy2000/mcode-usage-monitor/README.md) for data access, counting rules, and compatibility notes. + +
+ +
+Preview: Git Commit Tree + +![Git Commit Tree showing a swim-lane commit graph with synthetic data](plugins/microbiosis/git-tree/docs/preview.jpg) + +The preview uses synthetic data. The app interface is currently in Chinese. See its [README](plugins/microbiosis/git-tree/README.md) for repository discovery, layout algorithm attribution, and compatibility notes. + +
+ +## Getting started + +### Requirements + +Use a MiniMax Code desktop version that supports MiniApps. Check the app's README for tested client versions, operating systems, configuration, and known limitations. Compatibility is documented per app. Apps that use newer capabilities need a newer client, and older versions cannot install them: running Agent tasks or opening in their own window needs MiniMax Code 3.1.2 or later; reading your conversations, calling your installed tools, or using the microphone needs 3.1.6 or later; using the camera or showing system notifications needs 3.1.9 or later; following which MiniMax Code page you are on needs 3.1.11 or later. From 3.1.6 you can switch off each permission an app declares, one by one, in its plugin details. + +### 1. Download + +Select **Code → Download ZIP** on this repository and extract the archive, or clone it: + +```sh +git clone https://github.com/MiniMax-AI/MiniMax-Code-MiniApps.git +``` + +Find the app you want under `plugins//` and read its README, including which local files or network services it accesses. + +### 2. Install + +Copy the **entire plugin directory**, including the hidden `.minimax-plugin` directory, into `/plugins/`. + +By default, `` is the `.minimax` directory in your home folder (`~/.minimax`), so plugins go in `~/.minimax/plugins/`. If you have configured a different data directory, use that directory instead. + +For Token Usage Board: + +```text +Repository: plugins/amszuidas/mcode-token-usage-board/ +Install to: /plugins/mcode-token-usage-board/ +``` + +The installed manifest must be at: + +```text +/plugins/mcode-token-usage-board/.minimax-plugin/plugin.json +``` + +The author directory (`amszuidas/`) only groups contributions in the repository. Copy the plugin directory directly into the client's `plugins/` directory, without that extra author level. + +From MiniMax Code 3.1.11 you can import an app instead of copying it: on the Plugins page, choose **Create**, then **Import from a Git repository** under Mini App, and paste the URL of the plugin directory, for example `https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/amszuidas/mcode-token-usage-board`. The client downloads the whole repository (about 160 MiB) and gives up after five minutes, so on a slow connection install manually instead. Earlier clients cannot import from this repository because it is larger than their 128 MiB limit. + +### 3. Open + +Restart MiniMax Code, confirm that the plugin is recognized and enabled, and open the MiniApp following its README. For Token Usage Board, ask the Agent to open “Token 用量看板”. + +To update an app, close it and exit MiniMax Code, then replace its complete plugin directory. Keep any backup outside `plugins/` and follow the app's instructions for preserving its data. To uninstall, close the app and exit the client before removing its plugin directory; separately stored app data may remain. + +## Contributing + +Tools, games, visualizations, and small experiments are all welcome. To share a MiniApp: + +1. Fork the repository, copy `examples/hello-miniapp/` to `plugins///`, and build your app there. The package rules are in [`docs/`](docs/package-contract.md); AI coding agents read [`AGENTS.md`](AGENTS.md) automatically. +2. Include a README, a license, and any required runtime files. Document setup, data access, and what you have tested. +3. Add the app to the tables in both root READMEs, run `npm run check`, and open a pull request. + +Use a lowercase GitHub username for the author directory. The plugin directory name must match `.minimax-plugin/plugin.json` → `name`, and **plugin IDs must be unique across the repository**, since the author directory is not part of the installed path. + +See [CONTRIBUTING.md](CONTRIBUTING.md) for the full contribution guide. + +## Questions and feedback + +Use [GitHub Issues](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) to report a problem or suggest an app or improvement. For an app issue, include its ID and version, your MiniMax Code version, operating system, steps to reproduce, and the expected and actual behavior. Remove credentials and private session content from logs and screenshots. + +To ask for a runtime capability that MiniApps do not have yet, such as a new `context` API or window behaviour, comment on the pinned [capability wishlist](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues/9) instead of opening a new issue. + +## License + +This repository is licensed under the [MIT License](LICENSE). Individual MiniApps are governed by the licenses included in their own directories. diff --git a/README.zh-CN.md b/README.zh-CN.md index 3178b68a..bf86804f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,216 +1,217 @@ -# MiniMax Code MiniApps - -[English](README.md) | 简体中文 - -**MiniMax Code 桌面端 MiniApp 官方社区仓库**。发现实用工具、有趣的小应用,也可以在这些作品的基础上制作自己的 MiniApp。 - -[产品理念](#产品理念) · [架构](#架构) · [浏览作品](#miniapps) · [开始使用](#开始使用) · [贡献作品](CONTRIBUTING.zh-CN.md) · [反馈问题](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) - -## 关于本仓库 - -本仓库面向开源社区开放:任何开发者都可以通过 Pull Request 贡献自己的 MiniApp 插件。MiniApp 是以 MiniMax Plugin 形式承载的交互式应用。本仓库收录开发者贡献的完整插件包,每个作品都包含独立使用所需的文件、源码和说明。 - -作品按作者存放在 `plugins///` 下。你可以下载后手动安装到 MiniMax Code,也可以参考源码开发自己的作品。 - -## 追求 Human in the Loop,迈向 Agent OS - -我们相信,Agent 正在演进为下一代操作系统(OS)。在这一范式转移下,插件不再只是简单的功能扩展,插件即软件,插件即 App(MiniApp)。 - -与此同时,各行各业的真实生产力依然扎根于高度专业化的工作环境中。单纯的“对话式交互(Chat UI)”无法替代专业工具的精准控制与复杂视图。未来的专业工作流,不应是让用户离开工作台去迁就 AI,而是让专业工作环境与 AI 深度共生——将 AI 内化为像水电、计算、存储一样可随时调用的底层原子能力。通过构建生长在 Agent OS 之上的专业级 MiniApps,我们致力于连接垂直领域的专业交互界面与底层的 AI 原生算力,重塑各行各业的工作方式。 - -> *CadQuery Viewer 案例:一句话让 Agent 生成 MiniMax 小章鱼的 3D 模型,想改哪里就直接在模型上指出来。* Agent 先查官方形象作参考,再编写 CadQuery 参数化脚本、自己运行并修正问题,构建结果直接显示在右侧的 Viewer 里。要改的时候,在模型上点一下标出位置(比如嘴巴),写一句“嘴巴染成红色”发回对话——Agent 拿到准确的零件和坐标,改完后 Viewer 自动换成新版本。 - -![CadQuery Viewer 案例:Agent 生成 MiniMax 小章鱼模型,用户在模型上标注嘴巴并让 Agent 改成红色](plugins/hanzijie/cq-viewer/docs/case-study.gif) - -**MiniApp 的产品立场:让人始终参与协作与决策(Human-in-the-Loop)。** - -我们尊重每一个行业、每一种职业,也尊重每个人长期积累的专业能力。AI 应该成为你最聪明的执行者,放大你的能力,而不是替你假装拥有专业能力。MiniApp 想做的,就是把从打磨到交付这一被切碎的过程重新接起来。 - -所以,我们希望通过 MiniApp,为每个行业提供一个属于自己的**专业 IDE 框架**——一个既能让 AI 在其中工作,也能让人随时审核、修改、确认的地方。 - -**在这里,用户可以:** - -- **接入能力:** 稳定接入并使用各类开源 MCP 和第一方插件,将数据与操作接入自己的专业工作流。 -- **构建界面:** 构建自己的工作界面,让每个行业拥有真正适合自己的工作台。 -- **随时协作:** 让 Agent 成为随时可用、值得信赖的工作助手。当然,你也可以让它做任何有意思的事情! - -在我们设想的工作方式里,律师不会把 AI 写的诉状直接提交给法院;分析师不会直接依据 AI 生成的观点作出投资决策;运营人员也不会把 AI 生成的活动方案原封不动地上线。 - -但他们会让 AI 帮自己研究背景、整理材料、完成初稿、完善表达、发现遗漏,然后回到自己的专业工作台中,**审阅、修改、确认,再让 AI 继续推进。** - -## 架构 - -MiniApp 运行在 MiniMax Code 桌面宿主中,由四个相互配合的层组成: - -- **宿主管理层:** 宿主提供 Electron 页面承载、运行时服务、插件安装与发布、Node 进程生命周期、就绪与实例管理,以及权限与凭证管理。宿主控制贯穿各层,但业务逻辑仍由插件负责。 -- **展示层(Chromium / Chrome 引擎):** MiniApp 页面使用 HTML、CSS 和 JavaScript 实现筛选、表格、图表与交互式渲染;宿主凭证不会交给页面。 -- **应用层(Node.js):** Node 进程负责数据聚合、转换与深度加工、业务规则和持久化。页面接口与 Agent 工具复用同一套业务服务;Node 还可以为宿主 MCP 客户端提供受管理的 MCP 服务。 -- **能力与数据接入层:** 插件可以使用现有的 Host Connector 能力、可选的插件子进程 CLI,以及规划中的统一工具入口,在获得授权后访问 Connector 或 MCP,连接外部业务服务、MCP 服务、本地工具与本地数据。 - -MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求与页面数据在展示层和应用层之间流转,Agent 的调用与结果由宿主进行中介和管理。这样既能让凭证与控制权留在宿主,也能让领域逻辑与持久化留在插件中。 - -![MiniApp 技术架构图](docs/architecture/miniapp-technical-architecture.png) - -*中文版架构图:MiniMax Code 桌面宿主、展示层、应用层,以及能力与数据接入层。* - -## MiniApps - -| MiniApp | 功能 | 作者 | -| --- | --- | --- | -| [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | -| [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | -| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | 一个看板页同时看实时天气、A 股与黄金白银原油比特币行情、六个可切换的新闻栏目,贵金属统一按人民币每克显示 | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | -| [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | -| [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | -| [动态工作流控制台](plugins/stevenjj33/workflow-console/README.zh-CN.md) | 在一个页面里运行并盯住 MiniMax Code 动态工作流:实时状态、按阶段与依赖画出的流程图、节点输出、审核与控制、模板与报告导出 | [stevenjj33](https://github.com/stevenjj33) | -| [MiniMax Photo](plugins/webguhui/minimax-photo/) | 图层图片编辑、应用内 AI 助手、本地恢复与程序化编辑工具 | [WebGuHui](https://github.com/WebGuHui) | -| [MMX 章鱼娘](plugins/antianqi/mmx-octopus/) | 桌面上的小章鱼:跟着 Agent 的状态换表情、用自己的会话跟你聊天,也能被 Agent 用 4 个 MCP 工具指挥 | [antianqi](https://github.com/antianqi) | -| [Cutline](plugins/klarkxy/cutline/) | 浏览器里的视频剪辑台:时间线剪切、字幕、动效、调色与导出,聊天里一句话就能剪片 | [klarkxy](https://github.com/klarkxy) | -| [MiniMax Video](plugins/webguhui/minimax-video/) | 本地视频剪辑、字幕、宿主 Agent 助手、可预览的时间线修改与 MP4/MP3 导出 | [WebGuHui](https://github.com/WebGuHui) | -| [AI 事务所](plugins/cristinamadureira353-svg/ai-office/README.zh-CN.md) | 五位真实模型员工的像素事务所:接单、聊天、休息和开会,额度耗尽时角色暂停;使用玩家自己的 API Key | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | -| [Token 用量看板](plugins/amszuidas/mcode-token-usage-board/README.zh-CN.md) | 按时间、模型和会话查看本机 Token 用量,包含输入、输出和缓存用量 | [amszuidas](https://github.com/amszuidas) | -| [Token 用量看板](plugins/yanhy2000/mcode-usage-monitor/README.zh-CN.md) | 近实时查看本机 Token 用量、输出速度与缓存命中率,可按时间范围、模型和会话筛选 | [yanhy2000](https://github.com/yanhy2000) | -| [模型管理器](plugins/ocoomber/openrouter-model-manager/README.zh-CN.md) | 浏览、搜索并启用/停用 `~/.minimax/config.yaml` 中的模型,支持即时保存、批量操作、一键撤销和自动备份 | [ocoomber](https://github.com/ocoomber) | -| [自驾规划](plugins/hanzijie/self-drive-route-planner/README.zh-CN.md) | 【官方插件】规划自驾路线、地点搜索、候选算路与小红书 3:4 行程图;支持演示模式 | [HanZijie](https://github.com/HanZijie) | -| [Git 提交树](plugins/microbiosis/git-tree/README.zh-CN.md) | 查看本机 Git 仓库的提交历史:泳道提交图、分支/标签、提交详情与文件改动统计,支持筛选偏好持久化与可选自动刷新 | [Microbiosis](https://github.com/Microbiosis) | -| [番茄钟 · 久坐提醒](plugins/1602winxp/pomodoro-sit-timer/README.zh-CN.md) | 只计时的番茄钟:工作段结束在页面内弹出久坐提醒并响铃,不锁状态、不限制休息时长;提醒音支持单文件或文件夹、顺序/随机播放、单曲循环与响度匹配 | [1602WinXP](https://github.com/1602WinXP) | -| [灵签易占](plugins/weekbin/chinese-divination/README.zh-CN.md) | 梅花易数起卦与解卦:时间、数字、铜钱摇卦、每日一卦四法起卦,按体用生克断吉凶,另备六十四卦全文与干支历法 | [weekbin](https://github.com/weekbin) | -| [会话轨迹](plugins/avatasia/mmc-trajectory/README.zh-CN.md) | 按轮次浏览一段会话的模型轨迹:消息流、思考过程、工具调用与结果、token 用量与每轮耗时 | [avatasia](https://github.com/avatasia) | -| [CadQuery Viewer](plugins/hanzijie/cq-viewer/README.zh-CN.md) | 在对话里打开时列出对话所在文件夹里的 STL / STEP(保留装配零件名称、颜色和真实边线),按住哪里就绕哪里旋转;显示 CadQuery 脚本推送的模型,在模型上标注位置后一键发给 AI;再点一下,后台 Agent 用 MiniMax 图像生成把当前视角的白模渲染成成品图,可补充自己的描述;AI 可通过 MCP 工具添加模型文件夹、打开模型,并内置 CadQuery 参数化建模 skill | [HanZijie](https://github.com/HanZijie) · [flowful-ai](https://github.com/flowful-ai) | -| [MiniMax Bot](plugins/minimax-ai/minimax-bot/) | 【官方插件】把 MiniMax Code 变成常驻的 Bot 团队:总管 Bot 帮你组建团队,群聊里用 `@` 在成员之间交接工作,每个 Bot 有自己的记忆、定时任务和用量统计;需要 MiniMax Code 3.1.2 或更高版本(说明文档为英文) | [MiniMax-AI](https://github.com/MiniMax-AI) | -| [心屿](plugins/yujiachen-y/xinyu-daily/README.zh-CN.md) | 像独立小游戏的每日心情小岛:由你的回答决定的今日灵感卡、心情贴纸、小确幸罐子、纠结老虎机、答案之书,还有坏脾气螃蟹藏起来的 20 个秘密;可选开启小屿陪伴,借用你的模型每天写信、陪你聊天。需要 MiniMax Code 3.1.2 或更高版本 | [yujiachen-y](https://github.com/yujiachen-y) | -| [协作 · MoMo](plugins/amszuidas/momo-collab/README.zh-CN.md) | 项目管家 MoMo:把随手的想法、截图和链接攒成想法,写清后变成任务,派 Agent 会话带着完整背景去执行,按验收标准核对结果后交你审核,进展在看板上一眼可见。需要 MiniMax Code 3.1.2 或更高版本 | [amszuidas](https://github.com/amszuidas) | -| [Anatomy 画廊](plugins/zch0227/anatomy-gallery/README.zh-CN.md) | 集中展示 anatomy 技能做出的交互式等距图解:按自建展区挂墙,全屏查看明暗两版,保留全部历史版本;在画廊里让 Agent 新建或修改作品,每次运行都有过程记录。自带 anatomy 技能。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | -| [仓库透视](plugins/yujiachen-y/repo-xray/README.zh-CN.md) | 从 Git 历史看懂一个代码仓库:可逐层下钻的代码地图、热点与 Bug 磁铁、高风险文件、负责人与知识流失、提交节奏与救火记录、技术栈;支持 GitHub、GitLab 和本机仓库,全部在本机分析 | [yujiachen-y](https://github.com/yujiachen-y) | -| [OpenViking Mini Studio](plugins/openviking/mini-studio/) | 只读浏览和搜索 OpenViking 上下文、预览内容,并把选中的 URI 或内容加入对话 | OpenViking | -| [磁盘透视](plugins/zch0227/disk-insight/README.zh-CN.md) | 查看 macOS 和 Windows 的磁盘空间去向:旭日图空间地图,按三档风险分类的垃圾文件,大文件和重复文件,代码仓库和 Git worktree 的占用;任何条目都可以问 Agent,选中的条目在确认框里逐一列出,确认后直接永久删除。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | -| [A/时差保安](plugins/liuchen19960902/timezone-guard/README.zh-CN.md) | 发消息前先看对方那边几点:按对方城市当地时间给出「现在可以聊 / 短聊就好 / 先睡,别发」三档判定。需要 MiniMax Code 3.1.2 或更高版本 | [FineCat](https://github.com/LiuChen19960902) | -| [AI 节点画布](plugins/antianqi/ai-node-canvas/README.zh-CN.md) | MiniMax Code 里的无限画布节点图:把文本、图片、视频、音频的生成接成一张图,结果顺着连线往下传;能在时间轴上剪片段、把视频里的声音分离出来,任何一张结果都能直接做二次处理 | [antianqi](https://github.com/antianqi) | -| [An-bot-team 团队](plugins/antianqi/an-bot-team/) | 现在的 bot 像一个人轮流带着几个面具跟你聊天;An-bot-team 给你一支真正各有能力、各有性格的团队,还能围坐一起从不同角度讨论同一个问题 | [antianqi](https://github.com/antianqi) | -| [Agent 协作透视](plugins/huixin615/agent-flow/README.zh-CN.md) | 手动导入插件 Hook 记录,查看原生 task 调用与子 Agent 运行区间;有明确 ID 时关联父子任务。可选择记录会话或一键查看最近导入的记录,不读取宿主会话文件。需要 MiniMax Code 3.1.4 或更高版本 | [Huixin615](https://github.com/Huixin615) | -| [蹬王之王](plugins/hylouis233/expiry-guardian/README.md) | 看你自己维护的本地账本,算出「该用卡还是该留积分」,并把理由说清楚 | [Hylouis](https://github.com/Hylouis233) | -| [MiniMax Pet](plugins/minimax-ai/minimax-pet/README.zh-CN.md) | 提供外观/任务/设置、可见会话状态、需要回答提醒、按 Markdown 渲染的回复、一键打开任务对话(3.1.11 起)和透明桌宠;需要 MiniMax Code 3.1.6 或更高版本 | [MiniMax](https://github.com/MiniMax-AI) | -| [MCP OAuth 令牌台](plugins/microbiosis/mcp-oauth-console/README.zh-CN.md) | 给需要 OAuth 的 MCP 服务器完成登录:设备码或授权码 + PKCE 流程,把 `Authorization` 头写入 MCP 配置,并可选择在到期前自动续期 | [Microbiosis](https://github.com/Microbiosis) | -| [本机大盘](plugins/jzlikewei/kurumi-monitor/README.zh-CN.md) | 把本机当成行情终端来看:CPU、GPU、温度、内存、磁盘、网络与每个运行中的进程都是一只个股,实时 K 线、均线、自选行情、主力动向与逐笔成交,支持 macOS 与 Windows。需要 minimax Code 3.1.2 或更高版本 | [jzlikewei](https://github.com/jzlikewei) | -| [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) | -| [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | -| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) | -| [急件 · 视频投递](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) | -| [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) | - -
-预览:周计划 - -![周计划,使用合成数据展示本周进度面板与当天的任务列表](plugins/alanhean/weekly-planner/docs/preview.png) - -预览使用合成数据。应用界面目前为中文。安装、数据访问与兼容性说明见其 [README](plugins/alanhean/weekly-planner/README.zh-CN.md)。 - -
- -
-预览:Cutline - -![Cutline 编辑器,使用合成素材展示标题与多轨时间线](plugins/klarkxy/cutline/docs/editor-zh-CN.png) - -![Cutline 导出面板,展示范围、预设、视频与音频设置](plugins/klarkxy/cutline/docs/export-zh-CN.png) - -预览使用合成工程。安装、剪辑、导出和数据访问说明见 [Cutline README](plugins/klarkxy/cutline/README.zh-CN.md)。 - -
- -
-预览:Token 用量看板 - -![Token 用量看板,使用合成数据展示用量趋势](plugins/amszuidas/mcode-token-usage-board/docs/preview.png) - -预览使用合成数据,应用界面目前为中文。数据访问范围、统计口径和兼容性说明见作品 [README](plugins/amszuidas/mcode-token-usage-board/README.zh-CN.md)。 - -
- -
-预览:Token 用量看板(mcode-usage-monitor) - -![Token 用量看板,使用合成数据展示用量趋势](plugins/yanhy2000/mcode-usage-monitor/docs/preview.png) - -预览使用合成数据,应用界面目前为中文。数据访问范围、统计口径和兼容性说明见作品 [README](plugins/yanhy2000/mcode-usage-monitor/README.zh-CN.md)。 - -
- -
-预览:Git 提交树 - -![Git 提交树,使用合成数据展示泳道提交图](plugins/microbiosis/git-tree/docs/preview.jpg) - -预览使用合成数据,应用界面目前为中文。仓库发现规则、泳道算法来源与兼容性说明见作品 [README](plugins/microbiosis/git-tree/README.zh-CN.md)。 - -
- -## 开始使用 - -### 使用要求 - -需要支持 MiniApp 的 MiniMax Code 桌面端版本。各作品的 README 会说明已验证的客户端版本、操作系统、所需配置和已知限制,兼容性以具体作品为准。使用较新能力的作品需要较新的客户端,旧版本无法安装:运行 Agent 任务、在独立窗口中打开需要 MiniMax Code 3.1.2 或更高版本;读取你的会话、调用你已安装的工具或使用麦克风需要 3.1.6 或更高版本;使用摄像头或发送系统通知需要 3.1.9 或更高版本;读取你当前所在的 MiniMax Code 页面需要 3.1.11 或更高版本。从 3.1.6 起,你可以在每个作品的插件详情里逐项关闭它声明的权限。 - -### 1. 下载 - -点击仓库页面的 **Code → Download ZIP** 并解压,或 clone 仓库: - -```sh -git clone https://github.com/MiniMax-AI/MiniMax-Code-MiniApps.git -``` - -在 `plugins//` 下找到想用的作品,阅读其 README,了解它会访问哪些本地文件或网络服务。 - -### 2. 安装 - -将**完整插件目录**复制到 `/plugins/`,保留 `.minimax-plugin` 隐藏目录。 - -`` 默认为用户主目录下的 `.minimax`,即 `~/.minimax`,因此默认安装目录为 `~/.minimax/plugins/`。如果你配置了其他数据目录,请使用实际配置的路径。 - -以 Token 用量看板为例: - -```text -仓库中:plugins/amszuidas/mcode-token-usage-board/ -安装到:/plugins/mcode-token-usage-board/ -``` - -安装后的插件清单应位于: - -```text -/plugins/mcode-token-usage-board/.minimax-plugin/plugin.json -``` - -作者目录(`amszuidas/`)只用于仓库归类。复制到客户端时,将插件目录直接放入 `plugins/`,不要多套一层作者目录。 - -从 MiniMax Code 3.1.11 起,也可以不复制文件、直接导入:在插件页点击 **创建**,在 Mini App 下选择 **从 Git 仓库导入**,粘贴插件目录的链接,例如 `https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/amszuidas/mcode-token-usage-board`。客户端会下载整个仓库(约 160 MiB),5 分钟内没下完就会放弃,网络较慢时请改用手动安装。更早的版本无法从本仓库导入,因为仓库已超过它们 128 MiB 的上限。 - -### 3. 打开 - -重新启动 MiniMax Code,确认插件已被识别并启用,再按作品 README 打开 MiniApp。例如,你可以请 Agent 打开“Token 用量看板”。 - -更新时先关闭 MiniApp 并退出客户端,再替换完整插件目录。备份放在 `plugins/` 之外,数据保留方式按作品说明处理。卸载时同样先关闭应用并退出客户端,再移除对应插件目录;单独保存的应用数据可能仍会保留。 - -## 贡献作品 - -欢迎分享工具、游戏、可视化应用和小实验。提交作品只需: - -1. Fork 仓库,把 `examples/hello-miniapp/` 复制到 `plugins/<你的-github-username>//`,在此基础上开发。插件包规则见 [`docs/`](docs/package-contract.md)(英文);AI 编码助手会自动读取 [`AGENTS.md`](AGENTS.md)。 -2. 附上 README、许可证和运行所需文件,说明配置方式、数据访问范围与验证情况。 -3. 在根目录的中英文 README 作品表格中增加一行,运行 `npm run check`,然后提交 Pull Request。 - -作者目录使用小写 GitHub username。插件目录名必须与 `.minimax-plugin/plugin.json` 中的 `name` 一致,且**插件 ID 在整个仓库中唯一**,因为安装路径不包含作者目录。 - -完整说明见[贡献指南](CONTRIBUTING.zh-CN.md)。 - -## 问题与建议 - -欢迎通过 [GitHub Issues](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) 反馈问题、分享作品想法或提出改进建议。反馈插件问题时,请提供插件 ID 和版本、MiniMax Code 版本、操作系统、复现步骤,以及预期和实际结果。日志和截图请移除凭据及私人会话内容。 - -如果你希望 MiniApp 获得目前还不具备的运行时能力(例如新的 `context` API 或窗口行为),请直接在置顶的[能力愿望单](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues/9)下评论,不必另开 issue。 - -## 许可证 - -本仓库采用 [MIT License](LICENSE)。各 MiniApp 以其目录中附带的许可证为准。 +# MiniMax Code MiniApps + +[English](README.md) | 简体中文 + +**MiniMax Code 桌面端 MiniApp 官方社区仓库**。发现实用工具、有趣的小应用,也可以在这些作品的基础上制作自己的 MiniApp。 + +[产品理念](#产品理念) · [架构](#架构) · [浏览作品](#miniapps) · [开始使用](#开始使用) · [贡献作品](CONTRIBUTING.zh-CN.md) · [反馈问题](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) + +## 关于本仓库 + +本仓库面向开源社区开放:任何开发者都可以通过 Pull Request 贡献自己的 MiniApp 插件。MiniApp 是以 MiniMax Plugin 形式承载的交互式应用。本仓库收录开发者贡献的完整插件包,每个作品都包含独立使用所需的文件、源码和说明。 + +作品按作者存放在 `plugins///` 下。你可以下载后手动安装到 MiniMax Code,也可以参考源码开发自己的作品。 + +## 追求 Human in the Loop,迈向 Agent OS + +我们相信,Agent 正在演进为下一代操作系统(OS)。在这一范式转移下,插件不再只是简单的功能扩展,插件即软件,插件即 App(MiniApp)。 + +与此同时,各行各业的真实生产力依然扎根于高度专业化的工作环境中。单纯的“对话式交互(Chat UI)”无法替代专业工具的精准控制与复杂视图。未来的专业工作流,不应是让用户离开工作台去迁就 AI,而是让专业工作环境与 AI 深度共生——将 AI 内化为像水电、计算、存储一样可随时调用的底层原子能力。通过构建生长在 Agent OS 之上的专业级 MiniApps,我们致力于连接垂直领域的专业交互界面与底层的 AI 原生算力,重塑各行各业的工作方式。 + +> *CadQuery Viewer 案例:一句话让 Agent 生成 MiniMax 小章鱼的 3D 模型,想改哪里就直接在模型上指出来。* Agent 先查官方形象作参考,再编写 CadQuery 参数化脚本、自己运行并修正问题,构建结果直接显示在右侧的 Viewer 里。要改的时候,在模型上点一下标出位置(比如嘴巴),写一句“嘴巴染成红色”发回对话——Agent 拿到准确的零件和坐标,改完后 Viewer 自动换成新版本。 + +![CadQuery Viewer 案例:Agent 生成 MiniMax 小章鱼模型,用户在模型上标注嘴巴并让 Agent 改成红色](plugins/hanzijie/cq-viewer/docs/case-study.gif) + +**MiniApp 的产品立场:让人始终参与协作与决策(Human-in-the-Loop)。** + +我们尊重每一个行业、每一种职业,也尊重每个人长期积累的专业能力。AI 应该成为你最聪明的执行者,放大你的能力,而不是替你假装拥有专业能力。MiniApp 想做的,就是把从打磨到交付这一被切碎的过程重新接起来。 + +所以,我们希望通过 MiniApp,为每个行业提供一个属于自己的**专业 IDE 框架**——一个既能让 AI 在其中工作,也能让人随时审核、修改、确认的地方。 + +**在这里,用户可以:** + +- **接入能力:** 稳定接入并使用各类开源 MCP 和第一方插件,将数据与操作接入自己的专业工作流。 +- **构建界面:** 构建自己的工作界面,让每个行业拥有真正适合自己的工作台。 +- **随时协作:** 让 Agent 成为随时可用、值得信赖的工作助手。当然,你也可以让它做任何有意思的事情! + +在我们设想的工作方式里,律师不会把 AI 写的诉状直接提交给法院;分析师不会直接依据 AI 生成的观点作出投资决策;运营人员也不会把 AI 生成的活动方案原封不动地上线。 + +但他们会让 AI 帮自己研究背景、整理材料、完成初稿、完善表达、发现遗漏,然后回到自己的专业工作台中,**审阅、修改、确认,再让 AI 继续推进。** + +## 架构 + +MiniApp 运行在 MiniMax Code 桌面宿主中,由四个相互配合的层组成: + +- **宿主管理层:** 宿主提供 Electron 页面承载、运行时服务、插件安装与发布、Node 进程生命周期、就绪与实例管理,以及权限与凭证管理。宿主控制贯穿各层,但业务逻辑仍由插件负责。 +- **展示层(Chromium / Chrome 引擎):** MiniApp 页面使用 HTML、CSS 和 JavaScript 实现筛选、表格、图表与交互式渲染;宿主凭证不会交给页面。 +- **应用层(Node.js):** Node 进程负责数据聚合、转换与深度加工、业务规则和持久化。页面接口与 Agent 工具复用同一套业务服务;Node 还可以为宿主 MCP 客户端提供受管理的 MCP 服务。 +- **能力与数据接入层:** 插件可以使用现有的 Host Connector 能力、可选的插件子进程 CLI,以及规划中的统一工具入口,在获得授权后访问 Connector 或 MCP,连接外部业务服务、MCP 服务、本地工具与本地数据。 + +MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求与页面数据在展示层和应用层之间流转,Agent 的调用与结果由宿主进行中介和管理。这样既能让凭证与控制权留在宿主,也能让领域逻辑与持久化留在插件中。 + +![MiniApp 技术架构图](docs/architecture/miniapp-technical-architecture.png) + +*中文版架构图:MiniMax Code 桌面宿主、展示层、应用层,以及能力与数据接入层。* + +## MiniApps + +| MiniApp | 功能 | 作者 | +| --- | --- | --- | +| [齿轮测量方案选型工具](plugins/tlk1973/tlk1973-gear-measurement-selector/) | 按测量对象、目标精度、场地、环境与预算约束筛选接触式与非接触式齿轮测量设备,输出可筛选对比表、方案建议、场地/环境/辅助设备配置清单与可分享导出 | [TLK1973](https://github.com/TLK1973) | +| [Postman Lite](plugins/ssugarr/postman-lite/README.zh-CN.md) | 轻量的本地 API 请求工具:构建请求、通过本地代理转发(绕过浏览器 CORS 限制)、查看响应,集合以纯 JSON 保存 | [ssugarr](https://github.com/ssugarr) | +| [周计划](plugins/alanhean/weekly-planner/README.zh-CN.md) | 本地周计划:手动录入任务、日期与优先级,按天查看安排,勾选完成并跟踪本周完成率 | [Alanhean](https://github.com/Alanhean) | +| [天气 · 新闻看板](plugins/lixiangroir-ideal/weather-news-board/) | 一个看板页同时看实时天气、A 股与黄金白银原油比特币行情、六个可切换的新闻栏目,贵金属统一按人民币每克显示 | [lixiangroir-Ideal](https://github.com/lixiangroir-Ideal) | +| [DeepSeek 会话迁移](plugins/danielwalnut/deepseek-chat-migration/README_ZH.md) | 在本机预览 DeepSeek 网页版官方导出包,恢复分支和附件,并用自带的导入脚本把选中对话导入成 MiniMax Code 原生会话 | [DanielWalnut](https://github.com/DanielWalnut) | +| [OpenFilm](plugins/cristinamadureira353-svg/openfilm/) | 把 OpenFilm 装进 MiniMax Code:桌面版界面(Studio 编辑器 + 聊天栏 + 本地 agent),桌面模式不可用时回落网页版 | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | +| [动态工作流控制台](plugins/stevenjj33/workflow-console/README.zh-CN.md) | 在一个页面里运行并盯住 MiniMax Code 动态工作流:实时状态、按阶段与依赖画出的流程图、节点输出、审核与控制、模板与报告导出 | [stevenjj33](https://github.com/stevenjj33) | +| [MiniMax Photo](plugins/webguhui/minimax-photo/) | 图层图片编辑、应用内 AI 助手、本地恢复与程序化编辑工具 | [WebGuHui](https://github.com/WebGuHui) | +| [MMX 章鱼娘](plugins/antianqi/mmx-octopus/) | 桌面上的小章鱼:跟着 Agent 的状态换表情、用自己的会话跟你聊天,也能被 Agent 用 4 个 MCP 工具指挥 | [antianqi](https://github.com/antianqi) | +| [Cutline](plugins/klarkxy/cutline/) | 浏览器里的视频剪辑台:时间线剪切、字幕、动效、调色与导出,聊天里一句话就能剪片 | [klarkxy](https://github.com/klarkxy) | +| [MiniMax Video](plugins/webguhui/minimax-video/) | 本地视频剪辑、字幕、宿主 Agent 助手、可预览的时间线修改与 MP4/MP3 导出 | [WebGuHui](https://github.com/WebGuHui) | +| [AI 事务所](plugins/cristinamadureira353-svg/ai-office/README.zh-CN.md) | 五位真实模型员工的像素事务所:接单、聊天、休息和开会,额度耗尽时角色暂停;使用玩家自己的 API Key | [最爱双皮奶](https://github.com/cristinamadureira353-svg) | +| [Token 用量看板](plugins/amszuidas/mcode-token-usage-board/README.zh-CN.md) | 按时间、模型和会话查看本机 Token 用量,包含输入、输出和缓存用量 | [amszuidas](https://github.com/amszuidas) | +| [Token 用量看板](plugins/yanhy2000/mcode-usage-monitor/README.zh-CN.md) | 近实时查看本机 Token 用量、输出速度与缓存命中率,可按时间范围、模型和会话筛选 | [yanhy2000](https://github.com/yanhy2000) | +| [模型管理器](plugins/ocoomber/openrouter-model-manager/README.zh-CN.md) | 浏览、搜索并启用/停用 `~/.minimax/config.yaml` 中的模型,支持即时保存、批量操作、一键撤销和自动备份 | [ocoomber](https://github.com/ocoomber) | +| [自驾规划](plugins/hanzijie/self-drive-route-planner/README.zh-CN.md) | 【官方插件】规划自驾路线、地点搜索、候选算路与小红书 3:4 行程图;支持演示模式 | [HanZijie](https://github.com/HanZijie) | +| [Git 提交树](plugins/microbiosis/git-tree/README.zh-CN.md) | 查看本机 Git 仓库的提交历史:泳道提交图、分支/标签、提交详情与文件改动统计,支持筛选偏好持久化与可选自动刷新 | [Microbiosis](https://github.com/Microbiosis) | +| [番茄钟 · 久坐提醒](plugins/1602winxp/pomodoro-sit-timer/README.zh-CN.md) | 只计时的番茄钟:工作段结束在页面内弹出久坐提醒并响铃,不锁状态、不限制休息时长;提醒音支持单文件或文件夹、顺序/随机播放、单曲循环与响度匹配 | [1602WinXP](https://github.com/1602WinXP) | +| [灵签易占](plugins/weekbin/chinese-divination/README.zh-CN.md) | 梅花易数起卦与解卦:时间、数字、铜钱摇卦、每日一卦四法起卦,按体用生克断吉凶,另备六十四卦全文与干支历法 | [weekbin](https://github.com/weekbin) | +| [会话轨迹](plugins/avatasia/mmc-trajectory/README.zh-CN.md) | 按轮次浏览一段会话的模型轨迹:消息流、思考过程、工具调用与结果、token 用量与每轮耗时 | [avatasia](https://github.com/avatasia) | +| [CadQuery Viewer](plugins/hanzijie/cq-viewer/README.zh-CN.md) | 在对话里打开时列出对话所在文件夹里的 STL / STEP(保留装配零件名称、颜色和真实边线),按住哪里就绕哪里旋转;显示 CadQuery 脚本推送的模型,在模型上标注位置后一键发给 AI;再点一下,后台 Agent 用 MiniMax 图像生成把当前视角的白模渲染成成品图,可补充自己的描述;AI 可通过 MCP 工具添加模型文件夹、打开模型,并内置 CadQuery 参数化建模 skill | [HanZijie](https://github.com/HanZijie) · [flowful-ai](https://github.com/flowful-ai) | +| [MiniMax Bot](plugins/minimax-ai/minimax-bot/) | 【官方插件】把 MiniMax Code 变成常驻的 Bot 团队:总管 Bot 帮你组建团队,群聊里用 `@` 在成员之间交接工作,每个 Bot 有自己的记忆、定时任务和用量统计;需要 MiniMax Code 3.1.2 或更高版本(说明文档为英文) | [MiniMax-AI](https://github.com/MiniMax-AI) | +| [心屿](plugins/yujiachen-y/xinyu-daily/README.zh-CN.md) | 像独立小游戏的每日心情小岛:由你的回答决定的今日灵感卡、心情贴纸、小确幸罐子、纠结老虎机、答案之书,还有坏脾气螃蟹藏起来的 20 个秘密;可选开启小屿陪伴,借用你的模型每天写信、陪你聊天。需要 MiniMax Code 3.1.2 或更高版本 | [yujiachen-y](https://github.com/yujiachen-y) | +| [协作 · MoMo](plugins/amszuidas/momo-collab/README.zh-CN.md) | 项目管家 MoMo:把随手的想法、截图和链接攒成想法,写清后变成任务,派 Agent 会话带着完整背景去执行,按验收标准核对结果后交你审核,进展在看板上一眼可见。需要 MiniMax Code 3.1.2 或更高版本 | [amszuidas](https://github.com/amszuidas) | +| [Anatomy 画廊](plugins/zch0227/anatomy-gallery/README.zh-CN.md) | 集中展示 anatomy 技能做出的交互式等距图解:按自建展区挂墙,全屏查看明暗两版,保留全部历史版本;在画廊里让 Agent 新建或修改作品,每次运行都有过程记录。自带 anatomy 技能。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | +| [仓库透视](plugins/yujiachen-y/repo-xray/README.zh-CN.md) | 从 Git 历史看懂一个代码仓库:可逐层下钻的代码地图、热点与 Bug 磁铁、高风险文件、负责人与知识流失、提交节奏与救火记录、技术栈;支持 GitHub、GitLab 和本机仓库,全部在本机分析 | [yujiachen-y](https://github.com/yujiachen-y) | +| [OpenViking Mini Studio](plugins/openviking/mini-studio/) | 只读浏览和搜索 OpenViking 上下文、预览内容,并把选中的 URI 或内容加入对话 | OpenViking | +| [磁盘透视](plugins/zch0227/disk-insight/README.zh-CN.md) | 查看 macOS 和 Windows 的磁盘空间去向:旭日图空间地图,按三档风险分类的垃圾文件,大文件和重复文件,代码仓库和 Git worktree 的占用;任何条目都可以问 Agent,选中的条目在确认框里逐一列出,确认后直接永久删除。需要 MiniMax Code 3.1.2 或更高版本 | [zch0227](https://github.com/zch0227) | +| [A/时差保安](plugins/liuchen19960902/timezone-guard/README.zh-CN.md) | 发消息前先看对方那边几点:按对方城市当地时间给出「现在可以聊 / 短聊就好 / 先睡,别发」三档判定。需要 MiniMax Code 3.1.2 或更高版本 | [FineCat](https://github.com/LiuChen19960902) | +| [AI 节点画布](plugins/antianqi/ai-node-canvas/README.zh-CN.md) | MiniMax Code 里的无限画布节点图:把文本、图片、视频、音频的生成接成一张图,结果顺着连线往下传;能在时间轴上剪片段、把视频里的声音分离出来,任何一张结果都能直接做二次处理 | [antianqi](https://github.com/antianqi) | +| [An-bot-team 团队](plugins/antianqi/an-bot-team/) | 现在的 bot 像一个人轮流带着几个面具跟你聊天;An-bot-team 给你一支真正各有能力、各有性格的团队,还能围坐一起从不同角度讨论同一个问题 | [antianqi](https://github.com/antianqi) | +| [Agent 协作透视](plugins/huixin615/agent-flow/README.zh-CN.md) | 手动导入插件 Hook 记录,查看原生 task 调用与子 Agent 运行区间;有明确 ID 时关联父子任务。可选择记录会话或一键查看最近导入的记录,不读取宿主会话文件。需要 MiniMax Code 3.1.4 或更高版本 | [Huixin615](https://github.com/Huixin615) | +| [蹬王之王](plugins/hylouis233/expiry-guardian/README.md) | 看你自己维护的本地账本,算出「该用卡还是该留积分」,并把理由说清楚 | [Hylouis](https://github.com/Hylouis233) | +| [MiniMax Pet](plugins/minimax-ai/minimax-pet/README.zh-CN.md) | 提供外观/任务/设置、可见会话状态、需要回答提醒、按 Markdown 渲染的回复、一键打开任务对话(3.1.11 起)和透明桌宠;需要 MiniMax Code 3.1.6 或更高版本 | [MiniMax](https://github.com/MiniMax-AI) | +| [MCP OAuth 令牌台](plugins/microbiosis/mcp-oauth-console/README.zh-CN.md) | 给需要 OAuth 的 MCP 服务器完成登录:设备码或授权码 + PKCE 流程,把 `Authorization` 头写入 MCP 配置,并可选择在到期前自动续期 | [Microbiosis](https://github.com/Microbiosis) | +| [本机大盘](plugins/jzlikewei/kurumi-monitor/README.zh-CN.md) | 把本机当成行情终端来看:CPU、GPU、温度、内存、磁盘、网络与每个运行中的进程都是一只个股,实时 K 线、均线、自选行情、主力动向与逐笔成交,支持 macOS 与 Windows。需要 minimax Code 3.1.2 或更高版本 | [jzlikewei](https://github.com/jzlikewei) | +| [额度瓶](plugins/7723qqq/quota-bottle/README.zh-CN.md) | 一只悬浮在桌面上的章鱼形玻璃瓶,用你自己配置的登录读取 Token Plan 剩余额度;液面与透明度按剩余占比走,拿不到实时额度时回退到设备码登录或手填总额与可选的本机本月用量 | [7723qqq](https://github.com/7723qqq) | +| [Site QA](plugins/lonelyguy-se1/site-qa/) | 检查本地 HTML/robots/sitemap 的 SEO / 无障碍问题,再让 Agent 修复(Mini App + skill/CLI)。需要 MiniMax Code 3.1.6 或更高版本(说明文档为英文) | [LonelyGuySE1](https://github.com/LonelyGuy-SE1) | +| [H3-Image-Executor](plugins/liddalidd/h3-image-executor/README.zh-CN.md) | 把一句话需求跑成经过校验的 4K 图片:规划分镜、检索参考图、生成、看图评审、色偏校正、有限次修正,最后交付图片和验收报告;多图任务会先生成角色设定图锁定主体外观。需要自备 H3-Image 接口地址和 Key。需要 MiniMax Code 3.1.6 或更高版本 | [liddalidd](https://github.com/liddalidd) | +| [急件 · 视频投递](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) | +| [公众号图文工作台](plugins/xiaobinger/wechat-mp-article-studio/README.zh-CN.md) | 输入主题、正文、封面与插图需求,选一个视觉风格,产出封面与插图方案、与上一篇的查重结论、带版本和发布状态的草稿箱,以及可以直接粘贴进公众号的内联样式 HTML;发布前必须确认账号授权、素材范围与可用发布接口,没接接口时只存草稿。需要 MiniMax Code 3.1.6 或更高版本 | [xiaobinger](https://github.com/xiaobinger) | + +
+预览:周计划 + +![周计划,使用合成数据展示本周进度面板与当天的任务列表](plugins/alanhean/weekly-planner/docs/preview.png) + +预览使用合成数据。应用界面目前为中文。安装、数据访问与兼容性说明见其 [README](plugins/alanhean/weekly-planner/README.zh-CN.md)。 + +
+ +
+预览:Cutline + +![Cutline 编辑器,使用合成素材展示标题与多轨时间线](plugins/klarkxy/cutline/docs/editor-zh-CN.png) + +![Cutline 导出面板,展示范围、预设、视频与音频设置](plugins/klarkxy/cutline/docs/export-zh-CN.png) + +预览使用合成工程。安装、剪辑、导出和数据访问说明见 [Cutline README](plugins/klarkxy/cutline/README.zh-CN.md)。 + +
+ +
+预览:Token 用量看板 + +![Token 用量看板,使用合成数据展示用量趋势](plugins/amszuidas/mcode-token-usage-board/docs/preview.png) + +预览使用合成数据,应用界面目前为中文。数据访问范围、统计口径和兼容性说明见作品 [README](plugins/amszuidas/mcode-token-usage-board/README.zh-CN.md)。 + +
+ +
+预览:Token 用量看板(mcode-usage-monitor) + +![Token 用量看板,使用合成数据展示用量趋势](plugins/yanhy2000/mcode-usage-monitor/docs/preview.png) + +预览使用合成数据,应用界面目前为中文。数据访问范围、统计口径和兼容性说明见作品 [README](plugins/yanhy2000/mcode-usage-monitor/README.zh-CN.md)。 + +
+ +
+预览:Git 提交树 + +![Git 提交树,使用合成数据展示泳道提交图](plugins/microbiosis/git-tree/docs/preview.jpg) + +预览使用合成数据,应用界面目前为中文。仓库发现规则、泳道算法来源与兼容性说明见作品 [README](plugins/microbiosis/git-tree/README.zh-CN.md)。 + +
+ +## 开始使用 + +### 使用要求 + +需要支持 MiniApp 的 MiniMax Code 桌面端版本。各作品的 README 会说明已验证的客户端版本、操作系统、所需配置和已知限制,兼容性以具体作品为准。使用较新能力的作品需要较新的客户端,旧版本无法安装:运行 Agent 任务、在独立窗口中打开需要 MiniMax Code 3.1.2 或更高版本;读取你的会话、调用你已安装的工具或使用麦克风需要 3.1.6 或更高版本;使用摄像头或发送系统通知需要 3.1.9 或更高版本;读取你当前所在的 MiniMax Code 页面需要 3.1.11 或更高版本。从 3.1.6 起,你可以在每个作品的插件详情里逐项关闭它声明的权限。 + +### 1. 下载 + +点击仓库页面的 **Code → Download ZIP** 并解压,或 clone 仓库: + +```sh +git clone https://github.com/MiniMax-AI/MiniMax-Code-MiniApps.git +``` + +在 `plugins//` 下找到想用的作品,阅读其 README,了解它会访问哪些本地文件或网络服务。 + +### 2. 安装 + +将**完整插件目录**复制到 `/plugins/`,保留 `.minimax-plugin` 隐藏目录。 + +`` 默认为用户主目录下的 `.minimax`,即 `~/.minimax`,因此默认安装目录为 `~/.minimax/plugins/`。如果你配置了其他数据目录,请使用实际配置的路径。 + +以 Token 用量看板为例: + +```text +仓库中:plugins/amszuidas/mcode-token-usage-board/ +安装到:/plugins/mcode-token-usage-board/ +``` + +安装后的插件清单应位于: + +```text +/plugins/mcode-token-usage-board/.minimax-plugin/plugin.json +``` + +作者目录(`amszuidas/`)只用于仓库归类。复制到客户端时,将插件目录直接放入 `plugins/`,不要多套一层作者目录。 + +从 MiniMax Code 3.1.11 起,也可以不复制文件、直接导入:在插件页点击 **创建**,在 Mini App 下选择 **从 Git 仓库导入**,粘贴插件目录的链接,例如 `https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/tree/main/plugins/amszuidas/mcode-token-usage-board`。客户端会下载整个仓库(约 160 MiB),5 分钟内没下完就会放弃,网络较慢时请改用手动安装。更早的版本无法从本仓库导入,因为仓库已超过它们 128 MiB 的上限。 + +### 3. 打开 + +重新启动 MiniMax Code,确认插件已被识别并启用,再按作品 README 打开 MiniApp。例如,你可以请 Agent 打开“Token 用量看板”。 + +更新时先关闭 MiniApp 并退出客户端,再替换完整插件目录。备份放在 `plugins/` 之外,数据保留方式按作品说明处理。卸载时同样先关闭应用并退出客户端,再移除对应插件目录;单独保存的应用数据可能仍会保留。 + +## 贡献作品 + +欢迎分享工具、游戏、可视化应用和小实验。提交作品只需: + +1. Fork 仓库,把 `examples/hello-miniapp/` 复制到 `plugins/<你的-github-username>//`,在此基础上开发。插件包规则见 [`docs/`](docs/package-contract.md)(英文);AI 编码助手会自动读取 [`AGENTS.md`](AGENTS.md)。 +2. 附上 README、许可证和运行所需文件,说明配置方式、数据访问范围与验证情况。 +3. 在根目录的中英文 README 作品表格中增加一行,运行 `npm run check`,然后提交 Pull Request。 + +作者目录使用小写 GitHub username。插件目录名必须与 `.minimax-plugin/plugin.json` 中的 `name` 一致,且**插件 ID 在整个仓库中唯一**,因为安装路径不包含作者目录。 + +完整说明见[贡献指南](CONTRIBUTING.zh-CN.md)。 + +## 问题与建议 + +欢迎通过 [GitHub Issues](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues) 反馈问题、分享作品想法或提出改进建议。反馈插件问题时,请提供插件 ID 和版本、MiniMax Code 版本、操作系统、复现步骤,以及预期和实际结果。日志和截图请移除凭据及私人会话内容。 + +如果你希望 MiniApp 获得目前还不具备的运行时能力(例如新的 `context` API 或窗口行为),请直接在置顶的[能力愿望单](https://github.com/MiniMax-AI/MiniMax-Code-MiniApps/issues/9)下评论,不必另开 issue。 + +## 许可证 + +本仓库采用 [MIT License](LICENSE)。各 MiniApp 以其目录中附带的许可证为准。 diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/.minimax-plugin/plugin.json b/plugins/tlk1973/tlk1973-gear-measurement-selector/.minimax-plugin/plugin.json new file mode 100644 index 00000000..31e5f382 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/.minimax-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "schemaVersion": 1, + "name": "tlk1973-gear-measurement-selector", + "displayName": "Gear Measurement Scheme Selector", + "version": "1.0.0", + "description": "Selects contact and non-contact gear measurement equipment: records workpiece, accuracy, space, environment and budget constraints, then produces a filterable comparison table, a ranked recommendation, site/environment/auxiliary configuration lists, and a shareable HTML or Markdown comparison sheet.", + "author": "TLK1973", + "icon": "icon.png", + "category": "Business", + "exampleQueries": [ + "Open the gear measurement scheme selector", + "Enter an aerospace gear accuracy and space constraint and generate a selection recommendation", + "Export the gear measurement equipment comparison table" + ], + "apps": [], + "mcpServers": [], + "skills": [] +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/LICENSE b/plugins/tlk1973/tlk1973-gear-measurement-selector/LICENSE new file mode 100644 index 00000000..284eeb48 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 TLK1973 + +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/tlk1973/tlk1973-gear-measurement-selector/README.md b/plugins/tlk1973/tlk1973-gear-measurement-selector/README.md new file mode 100644 index 00000000..ada88324 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/README.md @@ -0,0 +1,112 @@ +# Gear Measurement Scheme Selector + +A Mini App that turns a gear-measurement requirement into a defensible equipment shortlist. +Record the workpiece, the target tolerance, the laboratory space, the environment and the budget; +the app scores every candidate machine against hard constraints and soft criteria, then writes a +main device recommendation, a set of complementary device roles, and site, environment and +auxiliary-equipment configuration lists. + +The included library covers 15 machines across contact, optical, hybrid, X-ray CT and laser +confocal measurement principles, with each numeric value carrying an evidence grade and an explicit +"not yet verified" marker where a first-party source was not available. + +## What it does + +- **Requirement capture** — workpiece class, module, outer diameter, face width, target tolerance, + annual volume, judgement type, laboratory space, environment conditions, budget ceiling and the + acceptance criteria you must require from the vendor. +- **Filterable comparison table** — search by brand, model or use case; filter by role (main-device + candidate, complementary device, excluded), measurement principle and evidence grade; sort by any + score column. +- **Two decision modes** — accuracy-first (accuracy 0.50 / stability 0.25 / fit 0.15 / cost 0.10) + and stability-first (accuracy 0.30 / stability 0.40 / fit 0.20 / cost 0.10). The active weights + are printed under the table so the ranking is reproducible. +- **Hard-constraint gating** — coverage, space, environment and measurement-principle compatibility + are gates, not weights. A machine that cannot legally make the requested judgement is reported as + a mismatch instead of being quietly ranked lower. +- **Main device plus complementary roles** — a machine that cannot judge but can measure waviness, + screen at line rate, inspect internals or profile a cutting edge is routed to that role rather + than discarded. +- **Configuration lists** — site works, environment controls and auxiliary equipment, each item + stating its basis (which device attribute or requirement produced it). +- **Shareable output** — export the current comparison, recommendation and configuration lists as a + standalone HTML document or a Markdown file that leaves the app entirely. +- **Optional online refresh** — fetch the vendor's current product page and show the specification + snippets found. The built-in verified library is never overwritten, and a failed fetch keeps the + built-in value and says so. + +## How to install and open it + +1. Copy this package into the MiniMax Code plugin directory, or publish it as a local Mini App + package. +2. Open MiniMax Code and select the "Gear Measurement Scheme Selector" Mini App from the plugin + panel, or ask the Agent to open it. +3. Fill in the requirement form on the left, then press **Generate recommendation**. + +The Mini App runs entirely on the local machine. No account, API key or external service is +required for the core workflow. + +## Tested environment + +- MiniMax Code 3.1.2 or later — this package declares `surface.window`, which requires that + version. Tested on MiniMax Code desktop, Windows 10 (10.0.19045) x64, Electron managed Browser + surface. +- Node.js v24.15.0. +- Client acceptance exercised in the opened Mini App page: + - Initial render of the comparison table with all 15 devices, 7 satisfying the hard constraints, + 7 routed to complementary roles and 1 excluded. + - Role, principle and evidence-grade filters; text search; column sorting. + - Switching between the accuracy-first and stability-first decision modes. + - The recommendation, configuration-list and saved-scheme tabs, including the empty state. + - Saving a scheme, reloading the page and confirming the scheme persisted, then deleting it. + - HTML and Markdown export, both containing the device table and the data-provenance notice. + - The online refresh action against real vendor pages, including a candidate that fails and falls + back to the built-in value. + - Console errors and failed/4xx/5xx network requests: none. +- The comparison table is wide by design and scrolls inside its own container; the page itself does + not scroll horizontally. + +## Data & access + +- **Files read**: none outside the plugin package. The Node entry reads only its own + `miniapp/client/` files to serve the page. +- **Files written**: durable state under the Host-provided `context.dataDir` only + (`selection-state.json`, written atomically through a temporary file and rename). Saved schemes + and refresh timestamps live there. Nothing is written to the workspace package at runtime. +- **Network hosts**: the optional refresh action contacts vendor web pages only — Klingelnberg, + Gleason, Mahr, ZEISS, Marposs, DWFritz, Starrett, Nikon, Lasertec, Creaform and Hali. The URLs are + listed in `miniapp/node/devices.mjs`. No other outbound request is made, and no data is uploaded. +- **Spawned processes**: none. +- **Agent turns**: none. The app runs no Agent turns and declares no `agentAccess`. +- **Conversations read**: none. The app declares no `session.read`. +- **Tools called**: none. The app declares no `toolAccess`. +- **Microphone, camera, notifications**: not used. +- **Host navigation read**: not used. +- **Connector providers**: none declared; the app does not use any Host Connector. +- **Declared access in `miniapp/miniapp.json`**: `surface.window` only (window size for the + pop-out window). No other access is declared, and none is used. + +## Accuracy and data provenance + +The built-in library separates what is verified from what is not: + +| Grade | Meaning | +| --- | --- | +| A | First-party vendor page fetched during authoring | +| B | Authoritative secondary source, or a certification announcement carried by several outlets | +| C | Distributor or reseller page repeating vendor claims | +| D | Inference, or a vendor claim not independently confirmed | + +Every device entry shows its evidence grade in the table. Values marked as unverified are shown as +such rather than replaced with an estimate. Prices are reported as "not yet verified" because these +machines are sold on quotation and no public price source exists. + +Two limits are stated in the app itself and repeated in every export: a published MPE is a maximum +permissible error under ISO 10360-2, not the measurement uncertainty required by ISO 14253-1; and +the ISO gear inspection standards do not define an optical method, so an optical system's authority +to make a final conformity decision has to come from an enterprise specification or customer +acceptance. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/icon.png b/plugins/tlk1973/tlk1973-gear-measurement-selector/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..299a26cbf5c1427dffa9cd575cf721307d570765 GIT binary patch literal 1574 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrV7=|>;uumf=gr;N9Fb5F_7BDH zN*t40jx3m@A#jD`h{82~A;W#9hIKB=6V;QM-fp_!Iw3Du_^7z>7spdwD|5UT=(0U- z4vcs42{>&0A!&-l#UFng7Vv9zUfN`Qd~;|s@7+uz9O)JMQ;7Q z+VlNc*1f)P;(=w;neIK@5%Dq?bm#T^{r{9*@ia!gnj^~T2}4Q1*Th_Vu`>}GpIDCO z#4fN@Vt4rd)BClU(Q~fW#@QT3`o97jTK?xMOo;EM)AkEGZ>^la!>4}Tg|#orV!ID- z4G8cmi29Kul*I@Nov(+hUWIHbj*XAkN|#&6e?ev6^ZSxvcK?~yFA_-*H<;a0#(2g^ zzl72KdH~l2CW&?ibaY*)m{GcGsq4HCVQW8`+3MMAA9>%$$6x1gcEXjIh6=|UTHH*2 zPm^w)+0I})`*&FN5&Nu1Y+r6yc*L8(Sa9m$yrfKZ#~fa1&NHPdC8Y+RdyG?WF};29 zt~O0_E62oyX%mAzpJu)CiI9%EV`HT-k0aLM2a{@p^XrK&uP*%0esO=1w)UU=+zCGMvNmy= z|6P>ouW5@p2v)su`cxCfV?$ymt*7pfdX*%ncOdCuPzej4`!;F|NW(R z>9S1?D}6X`#NYh7GVkf}bgjz@`%TThovQS5e3ma}8>P8_foSNz|MS*u5I(ouy{)ZH zDAVlt_qYF?TCQcTsM{ODK6ko9)iJH7$x{Rh??u)A%=k6?)3WE!yQWM!akgaN_W!DX z-#&jmHN3X`^}*WR`-q(SpO3zY`t01fRdCqjHPcc83_B1GbPU2zNIsfpf)(T$7XRi5-O#h75#2n`^6HJMF!qC&lGw+h(&G*h? zk*k_rMVov+YqaeSTOYYZzjSt0F6+COd#ca&eqZ;_rtH&`lb%gyI!#lfHFBb5N}kls z$lZDCNY^>py$dH>z2A9YX;J*2GNpMejVH=I&vYJ{xB2|{X>r$mYq=dibJoiERAfK) zQ9W)K_T5@<--_8kB%7Wkzk0OuD!*pi4Mquhsb5FS-xaZWR zZ|9tq^y-Rf{wEFBD;u8QSW~|%f9dnxxlsofN1ZNZ>HPit!>su-YkBth3z|N4bh|s- zYxS08(KkMRy%ipDKxc+#k7En7+RrklI~Sdmo1bg6`PiN0n#CTy2vIV@izrM+Ju?Ht m|NpbhtN4MXJsYT)XJ&Z(ZtAoneFio_5e83JKbLh*2~7YK=FPVN literal 0 HcmV?d00001 diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.css b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.css new file mode 100644 index 00000000..ae46de66 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.css @@ -0,0 +1,217 @@ +:root { + --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; + --radius-card: 12px; + --radius-ctl: 8px; +} + +@media (prefers-color-scheme: dark) { + :root { + --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; } +[hidden] { display: none !important; } + +body { + margin: 0; + background: var(--mcode-bg); + color: var(--mcode-text); + font-family: ui-sans-serif, -apple-system, system-ui, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.6; +} + +.page { max-width: 1400px; margin: 0 auto; padding: 24px; } + +.page-head { + display: flex; align-items: flex-start; justify-content: space-between; + gap: 16px; flex-wrap: wrap; margin-bottom: 20px; +} +.page-head h1 { font-size: 18px; line-height: 28px; font-weight: 600; margin: 0 0 4px; } +.page-head p { margin: 0; color: var(--mcode-text-muted); font-size: 13px; max-width: 760px; } +.head-actions { display: flex; gap: 8px; flex-wrap: wrap; } + +button { + font: inherit; height: 34px; padding: 0 14px; border-radius: var(--radius-ctl); + border: 1px solid var(--mcode-border); background: var(--mcode-surface-muted); + color: var(--mcode-text); cursor: pointer; transition: background 150ms ease-out, border-color 150ms ease-out; + display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; +} +button:hover:not(:disabled) { border-color: var(--mcode-border-strong); } +button:focus-visible { outline: 2px solid var(--mcode-accent); outline-offset: 2px; } +button:disabled { opacity: 0.5; cursor: not-allowed; } +button.primary { background: var(--mcode-primary-action-bg); color: var(--mcode-primary-action-text); border-color: transparent; } +button.link { background: transparent; border-color: transparent; color: var(--mcode-accent); padding: 0 6px; } +button.small { height: 28px; padding: 0 10px; font-size: 12px; } + +.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--mcode-border); margin-bottom: 20px; } +.tab { + border: none; background: transparent; height: 38px; padding: 0 14px; + border-radius: 0; border-bottom: 2px solid transparent; color: var(--mcode-text-muted); +} +.tab[aria-selected="true"] { color: var(--mcode-text); border-bottom-color: var(--mcode-text); font-weight: 500; } + +.layout { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: 20px; align-items: start; } +.layout > * { min-width: 0; } +@media (max-width: 1080px) { .layout { grid-template-columns: minmax(0, 1fr); } } + +.card { + background: var(--mcode-surface); border: 1px solid var(--mcode-border); + border-radius: var(--radius-card); padding: 16px; margin-bottom: 16px; +} +.card > h2 { font-size: 16px; line-height: 24px; font-weight: 500; margin: 0 0 12px; } +.card > h3 { font-size: 14px; font-weight: 600; margin: 16px 0 8px; } + +fieldset { border: none; margin: 0 0 16px; padding: 0; } +legend { font-size: 12px; color: var(--mcode-text-muted); padding: 0 0 8px; font-weight: 500; } + +.field { margin-bottom: 10px; } +.field label { display: block; font-size: 12px; color: var(--mcode-text-muted); margin-bottom: 4px; } +.field input, .field select { + width: 100%; height: 36px; padding: 0 10px; font: inherit; + border: 1px solid var(--mcode-border); border-radius: var(--radius-ctl); + background: var(--mcode-surface); color: var(--mcode-text); +} +.field input:focus, .field select:focus { + outline: none; border-color: var(--mcode-accent); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--mcode-accent) 22%, transparent); +} +.field .unit { font-size: 11px; color: var(--mcode-text-subtle); margin-left: 4px; } +.grid2 { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px; } +.hint { font-size: 11px; color: var(--mcode-text-subtle); margin: 4px 0 0; } + +.check { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; font-size: 13px; } +.check input { width: 15px; height: 15px; accent-color: var(--mcode-accent); } + +.segmented { display: inline-flex; background: var(--mcode-surface-muted); border: 1px solid var(--mcode-border); border-radius: var(--radius-ctl); padding: 2px; } +.segmented button { border: none; background: transparent; height: 28px; font-size: 12px; color: var(--mcode-text-muted); } +.segmented button[aria-pressed="true"] { background: var(--mcode-surface); color: var(--mcode-text); font-weight: 500; box-shadow: 0 1px 2px rgb(10 10 10 / 8%); } + +.toolbar { display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end; margin-bottom: 12px; } +.toolbar .field { margin: 0; min-width: 130px; } +.toolbar .grow { flex: 1 1 180px; min-width: 0; } +.toolbar .field select, .toolbar .field input { min-width: 0; } + +.table-wrap { overflow-x: auto; border: 1px solid var(--mcode-border); border-radius: var(--radius-card); background: var(--mcode-surface); } +table { width: 100%; border-collapse: collapse; font-size: 13px; } +th, td { text-align: left; padding: 9px 11px; border-bottom: 1px solid var(--mcode-border); vertical-align: top; } +th { background: var(--mcode-surface-muted); font-weight: 600; font-size: 12px; color: var(--mcode-text-muted); white-space: nowrap; position: sticky; top: 0; z-index: 1; } +tbody tr:last-child td { border-bottom: none; } +tbody tr:hover { background: var(--mcode-surface-muted); } +td.num { text-align: right; font-variant-numeric: tabular-nums; } +td .dev-name { font-weight: 500; } +td .dev-model { color: var(--mcode-text-muted); font-size: 12px; } +.sortable { cursor: pointer; user-select: none; } +.sortable:hover { color: var(--mcode-text); } + +.badge { + display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; + border: 1px solid var(--mcode-border-strong); margin-right: 4px; white-space: nowrap; +} +.badge.ok { color: var(--mcode-success); border-color: var(--mcode-success); } +.badge.warn { color: var(--mcode-warning); border-color: var(--mcode-warning); } +.badge.info { color: var(--mcode-accent); border-color: var(--mcode-accent); } +.badge.muted { color: var(--mcode-text-subtle); } + +.kpi-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; margin-bottom: 16px; } +.kpi { background: var(--mcode-surface); border: 1px solid var(--mcode-border); border-radius: var(--radius-card); padding: 14px 16px; } +.kpi .k { font-size: 12px; color: var(--mcode-text-muted); } +.kpi .v { font-size: 24px; font-weight: 600; line-height: 1.3; margin-top: 2px; } +.kpi .v small { font-size: 13px; font-weight: 400; color: var(--mcode-text-muted); } + +.notice { border: 1px solid var(--mcode-border); border-left: 3px solid var(--mcode-accent); background: var(--mcode-surface-muted); border-radius: var(--radius-ctl); padding: 10px 12px; font-size: 12px; color: var(--mcode-text-muted); margin-bottom: 14px; } +.notice.warn { border-left-color: var(--mcode-warning); } +.notice.err { border-left-color: var(--mcode-danger); } +.notice.ok { border-left-color: var(--mcode-success); } + +.rec { border: 1px solid var(--mcode-border); border-radius: var(--radius-card); padding: 16px; background: var(--mcode-surface); margin-bottom: 12px; } +.rec h3 { margin: 0 0 4px; font-size: 15px; font-weight: 600; } +.rec .role { color: var(--mcode-text-muted); font-size: 12px; margin-bottom: 10px; } +.rec ul { margin: 6px 0 0; padding-left: 18px; font-size: 12px; color: var(--mcode-text-muted); } +.rec li { margin: 3px 0; } + +.cfg-item { display: grid; grid-template-columns: 190px 1fr; gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--mcode-border); } +.cfg-item:last-child { border-bottom: none; } +.cfg-item .k { font-weight: 500; font-size: 13px; } +.cfg-item .s { font-size: 13px; } +.cfg-item .b { font-size: 11px; color: var(--mcode-text-subtle); margin-top: 3px; } + +.status { font-size: 12px; color: var(--mcode-text-muted); } +.status.error { color: var(--mcode-danger); } +.status.ok { color: var(--mcode-success); } + +.empty { text-align: center; padding: 48px 20px; color: var(--mcode-text-muted); } +.empty svg { color: var(--mcode-text-subtle); margin-bottom: 10px; } + +.saved-item { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 9px 0; border-bottom: 1px solid var(--mcode-border); } +.saved-item:last-child { border-bottom: none; } +.saved-item .meta { font-size: 12px; color: var(--mcode-text-muted); } + +.dialog-backdrop { + position: fixed; inset: 0; background: rgb(0 0 0 / 42%); + display: flex; align-items: center; justify-content: center; padding: 24px; z-index: 50; +} +.dialog { + background: var(--mcode-surface); border: 1px solid var(--mcode-border); + border-radius: var(--radius-card); padding: 20px; max-width: 620px; width: 100%; + max-height: 82vh; overflow: auto; box-shadow: 0 0 20px rgb(10 10 10 / 18%); +} +.dialog h2 { font-size: 16px; margin: 0 0 12px; font-weight: 500; } +.dialog pre { + background: var(--mcode-surface-muted); border: 1px solid var(--mcode-border); border-radius: var(--radius-ctl); + padding: 12px; font-size: 12px; overflow: auto; max-height: 42vh; + font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; word-break: break-word; +} +.dialog-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; } + +.toast { + position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); + background: var(--mcode-primary-action-bg); color: var(--mcode-primary-action-text); + padding: 10px 18px; border-radius: 999px; font-size: 13px; z-index: 60; + box-shadow: 0 0 20px rgb(10 10 10 / 18%); +} + +.spinner { + width: 14px; height: 14px; border: 2px solid var(--mcode-border-strong); + border-top-color: var(--mcode-accent); border-radius: 50%; + animation: spin 700ms linear infinite; display: inline-block; +} +@keyframes spin { to { transform: rotate(360deg); } } +@media (prefers-reduced-motion: reduce) { + * { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } +} + +@media (max-width: 768px) { + .page { padding: 16px; } + .grid2 { grid-template-columns: 1fr; } + .cfg-item { grid-template-columns: 1fr; gap: 4px; } +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.js b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.js new file mode 100644 index 00000000..0eb14a2a --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/app.js @@ -0,0 +1,612 @@ +'use strict'; + +(function () { + const state = { + boot: null, + requirement: null, + mode: 'accuracy', + result: null, + sort: { key: 'composite', dir: 'desc' }, + filters: { q: '', role: 'all', method: 'all', grade: 'all' }, + saved: [], + }; + + const $ = (id) => document.getElementById(id); + const esc = (v) => { + if (v === null || v === undefined) return ''; + return String(v) + .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + }; + const numOr = (v, fb) => { + const n = Number(v); + return Number.isFinite(n) && v !== '' && v !== null ? n : fb; + }; + + function toast(message, kind) { + const root = $('toast-root'); + root.innerHTML = ''; + const el = document.createElement('div'); + el.className = 'toast'; + el.textContent = message; + if (kind === 'error') el.style.background = 'var(--mcode-danger)'; + if (kind === 'ok') el.style.background = 'var(--mcode-success)'; + root.appendChild(el); + setTimeout(() => { if (root.contains(el)) root.removeChild(el); }, 3200); + } + + function setStatus(el, message, kind) { + el.className = 'status' + (kind ? ' ' + kind : ''); + el.textContent = message; + } + + function showDialog(title, bodyHtml, actions) { + const root = $('dialog-root'); + root.innerHTML = ''; + const backdrop = document.createElement('div'); + backdrop.className = 'dialog-backdrop'; + const dialog = document.createElement('div'); + dialog.className = 'dialog'; + dialog.setAttribute('role', 'dialog'); + dialog.setAttribute('aria-modal', 'true'); + dialog.setAttribute('aria-label', title); + const h = document.createElement('h2'); + h.textContent = title; + dialog.appendChild(h); + const body = document.createElement('div'); + body.innerHTML = bodyHtml; + dialog.appendChild(body); + const bar = document.createElement('div'); + bar.className = 'dialog-actions'; + for (const a of actions) { + const b = document.createElement('button'); + b.type = 'button'; + b.textContent = a.label; + if (a.primary) b.className = 'primary'; + b.addEventListener('click', () => { + if (a.onClick) a.onClick(); + if (a.keepOpen !== true) closeDialog(); + }); + bar.appendChild(b); + } + dialog.appendChild(bar); + backdrop.appendChild(dialog); + root.appendChild(backdrop); + backdrop.addEventListener('click', (e) => { if (e.target === backdrop) closeDialog(); }); + const onKey = (e) => { if (e.key === 'Escape') { closeDialog(); document.removeEventListener('keydown', onKey); } }; + document.addEventListener('keydown', onKey); + const focusable = dialog.querySelector('button'); + if (focusable) focusable.focus(); + dialog.dataset.restoreFocus = '1'; + } + function closeDialog() { + const root = $('dialog-root'); + root.innerHTML = ''; + } + + async function api(path, options) { + const res = await fetch(path, Object.assign({ headers: { 'content-type': 'application/json' } }, options || {})); + let data = null; + try { data = await res.json(); } catch (e) { data = { error: 'bad_response' }; } + if (!res.ok) { + throw new Error((data && data.message) || ('请求失败(HTTP ' + res.status + ')')); + } + return data; + } + + function fillForm(req) { + $('f-project').value = req.projectName || ''; + $('f-gear').value = req.gearClass || ''; + $('f-judgement').value = req.judgementType; + $('f-module').value = req.moduleMm; + $('f-diameter').value = req.diameterMm; + $('f-face').value = req.faceWidthMm; + $('f-tolerance').value = req.toleranceUm; + $('f-volume').value = req.annualVolume; + $('f-final').checked = !!req.needsFinalAcceptance; + $('f-len').value = req.space.lengthM; + $('f-wid').value = req.space.widthM; + $('f-hei').value = req.space.heightM; + $('f-load').value = req.space.loadKg; + $('f-power').value = req.space.powerKw; + $('f-door').value = req.space.doorWidthMm; + $('f-temp').value = req.environment.tempC; + $('f-stab').value = req.environment.tempStabilityK; + $('f-hum').value = req.environment.humidityPct; + $('f-vib').value = req.environment.vibration; + $('f-clean').value = req.environment.cleanliness; + $('f-budget').value = req.budget.amount; + $('a-mpe').checked = !!req.acceptance.mpeRequired; + $('a-trace').checked = !!req.acceptance.requireTraceability; + $('a-grr').checked = !!req.acceptance.requireGrR; + $('a-cal').checked = !!req.acceptance.requireThirdPartyCalibration; + $('a-notes').value = req.acceptance.notes || ''; + const methods = req.methods || []; + document.querySelectorAll('input[name="method"]').forEach((cb) => { + cb.checked = methods.includes(cb.value); + }); + updateJudgementHint(); + } + + function readForm() { + const methods = Array.from(document.querySelectorAll('input[name="method"]:checked')).map((cb) => cb.value); + return { + projectName: $('f-project').value.trim(), + gearClass: $('f-gear').value.trim(), + judgementType: $('f-judgement').value, + moduleMm: numOr($('f-module').value, null), + diameterMm: numOr($('f-diameter').value, null), + faceWidthMm: numOr($('f-face').value, null), + toleranceUm: numOr($('f-tolerance').value, null), + annualVolume: numOr($('f-volume').value, null), + needsFinalAcceptance: $('f-final').checked, + methods: methods.length ? methods : ['contact', 'non-contact', 'hybrid'], + space: { + lengthM: numOr($('f-len').value, null), + widthM: numOr($('f-wid').value, null), + heightM: numOr($('f-hei').value, null), + loadKg: numOr($('f-load').value, null), + powerKw: numOr($('f-power').value, null), + doorWidthMm: numOr($('f-door').value, null), + }, + environment: { + tempC: numOr($('f-temp').value, null), + tempStabilityK: numOr($('f-stab').value, null), + humidityPct: numOr($('f-hum').value, null), + vibration: $('f-vib').value, + cleanliness: $('f-clean').value.trim(), + }, + budget: { amount: numOr($('f-budget').value, null), currency: 'CNY', includesInstallation: true }, + acceptance: { + mpeRequired: $('a-mpe').checked, + uncertaintyRatio: 0.1, + requireTraceability: $('a-trace').checked, + requireGrR: $('a-grr').checked, + requireThirdPartyCalibration: $('a-cal').checked, + notes: $('a-notes').value.trim(), + }, + }; + } + + function updateJudgementHint() { + const jt = state.boot && state.boot.judgementTypes[$('f-judgement').value]; + $('judgement-hint').textContent = jt ? jt.note : ''; + } + + function roleOf(row) { + if (row.eligible) return 'primary'; + if (row.complementary) return 'complementary'; + return 'excluded'; + } + + function visibleRows() { + if (!state.result) return []; + const f = state.filters; + const q = f.q.trim().toLowerCase(); + let rows = state.result.ranked.filter((r) => { + if (f.role !== 'all' && roleOf(r) !== f.role) return false; + if (f.method !== 'all' && r.method !== f.method) return false; + if (f.grade === 'verified' && !r.verifiedFlag) return false; + if (f.grade === 'pending' && r.pendingVerification === 0) return false; + if (q) { + const hay = [r.brand, r.model, r.name, r.role, r.methodLabel, + (r.scenarios || []).join(' '), (r.features || []).join(' ')].join(' ').toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }); + const key = state.sort.key; + const dir = state.sort.dir === 'asc' ? 1 : -1; + const val = (r) => { + if (key === 'name') return r.brand + ' ' + r.model; + if (key === 'method') return r.method; + if (key === 'composite') return r.composite; + return r.scores[key].score; + }; + rows = rows.slice().sort((a, b) => { + const va = val(a); const vb = val(b); + if (typeof va === 'string') return va.localeCompare(vb, 'zh-CN') * dir; + return (va - vb) * dir; + }); + return rows; + } + + function renderCompare() { + const body = $('compare-body'); + const rows = visibleRows(); + body.innerHTML = ''; + if (!rows.length) { + const tr = document.createElement('tr'); + const td = document.createElement('td'); + td.colSpan = 11; + td.innerHTML = '

没有符合当前筛选条件的设备。

请放宽角色、原理或证据等级筛选。

'; + tr.appendChild(td); + body.appendChild(tr); + $('compare-count').textContent = '显示 0 / 共 ' + (state.result ? state.result.ranked.length : 0) + ' 台'; + return; + } + for (const r of rows) { + const tr = document.createElement('tr'); + const role = roleOf(r); + const roleBadge = role === 'primary' + ? '主设备候选' + : (role === 'complementary' ? '配套设备' : '不满足约束'); + const gradeBadge = r.verifiedFlag + ? 'A/B 级' + : '待核实'; + const stability = (r.scores.stability.notes || []).slice(0, 3).map(esc).join(';'); + const scenarios = (r.scenarios || []).slice(0, 2).map(esc).join(';'); + const limits = (r.limits || []).slice(0, 1).map(esc).join(';'); + const failures = r.hardFailures.length + ? '
' + r.hardFailures.map(esc).join(';') + '
' + : ''; + const evidence = r.evidence.map((e) => + '
' + esc(e.grade) + ' ' + esc(e.source.slice(0, 60)) + '
' + ).join(''); + tr.innerHTML = + '
' + esc(r.brand) + ' ' + esc(r.model) + '
' + + '
' + esc(r.name) + '
' + roleBadge + '' + + '' + esc(r.methodLabel) + '
' + esc(r.role) + '
' + + '' + esc(r.standard || '待核实') + '
' + esc(r.uncertaintyNote || '') + '
' + + '' + esc(r.scores.accuracy.score) + '' + + '' + esc(r.scores.stability.score) + '' + + '' + esc(r.scores.fit.score) + '' + + '' + esc(r.scores.cost.score) + '' + + '' + esc(r.composite) + '' + + '' + stability + '
' + esc((r.features || [])[0] || '') + '
' + + '' + scenarios + (limits ? '
限制:' + limits + '
' : '') + '' + + '' + gradeBadge + failures + evidence + ''; + body.appendChild(tr); + } + const total = state.result ? state.result.ranked.length : 0; + $('compare-count').textContent = '显示 ' + rows.length + ' / 共 ' + total + ' 台' + + ' | 决策模式:' + state.result.mode.label + + '(精度 ' + state.result.mode.weights.accuracy + ' / 稳定性 ' + state.result.mode.weights.stability + + ' / 适配 ' + state.result.mode.weights.fit + ' / 成本 ' + state.result.mode.weights.cost + ')'; + } + + function renderRecommend() { + const kpis = $('rec-kpis'); + const body = $('rec-body'); + kpis.innerHTML = ''; + body.innerHTML = ''; + if (!state.result) { + body.innerHTML = '

尚未生成方案建议。

'; + return; + } + const s = state.result.summary; + const items = [ + ['推荐主设备', s.topName || '无', s.topScore !== null ? '综合分 ' + s.topScore : ''], + ['主设备候选', s.eligible + ' 台', '满足全部硬约束'], + ['配套设备', s.complementary + ' 台', '承担其他任务角色'], + ['候选设备池', s.total + ' 台', '含 ' + s.excluded + ' 台不满足约束'], + ]; + for (const [k, v, sub] of items) { + const d = document.createElement('div'); + d.className = 'kpi'; + d.innerHTML = '
' + esc(k) + '
' + esc(v) + (sub ? ' ' + esc(sub) + '' : '') + '
'; + kpis.appendChild(d); + } + + const cfg = state.result.configuration; + if (!cfg) { + body.innerHTML = '

当前需求下没有满足全部硬约束的设备。

' + + '

可放宽空间、预算或判定类型,或换用更宽松的目标允差。

'; + return; + } + + const primary = state.result.ranked.find((r) => r.id === cfg.primary.id); + const rec = document.createElement('div'); + rec.className = 'rec'; + let html = '

' + esc(cfg.primary.name) + '

' + esc(cfg.primary.role) + ' | 综合分 ' + + esc(primary ? primary.composite : '—') + ' | 模式 ' + esc(state.result.mode.label) + '
'; + if (primary) { + html += '
    '; + for (const n of primary.scores.accuracy.notes) html += '
  • 精度:' + esc(n) + '
  • '; + for (const n of primary.scores.stability.notes.slice(0, 3)) html += '
  • 稳定性:' + esc(n) + '
  • '; + for (const n of primary.scores.fit.notes.slice(0, 2)) html += '
  • 适配:' + esc(n) + '
  • '; + html += '
'; + } + rec.innerHTML = html; + body.appendChild(rec); + + if (cfg.alternates.length) { + const alt = document.createElement('div'); + alt.className = 'rec'; + alt.innerHTML = '

备选主设备

    ' + + cfg.alternates.map((a) => '
  • ' + esc(a.name) + '(综合分 ' + esc(a.composite) + ')— ' + esc(a.role) + '
  • ').join('') + + '
'; + body.appendChild(alt); + } + + if (cfg.complementary.length) { + const comp = document.createElement('div'); + comp.className = 'rec'; + comp.innerHTML = '

配套设备角色

    ' + + cfg.complementary.map((c) => '
  • ' + esc(c.name) + ' — 可承担:' + esc(c.serves) + + (c.warnings && c.warnings.length ? '
    约束提示:' + esc(c.warnings.join(';')) + '
    ' : '') + '
  • ').join('') + + '
'; + body.appendChild(comp); + } + + if (cfg.incompatible.length) { + const inc = document.createElement('div'); + inc.className = 'rec'; + inc.innerHTML = '

不满足硬约束

    ' + + cfg.incompatible.map((c) => '
  • ' + esc(c.name) + '
    ' + esc(c.reasons.join(';')) + '
  • ').join('') + + '
'; + body.appendChild(inc); + } + + const warn = document.createElement('div'); + warn.className = 'notice warn'; + warn.innerHTML = '结论口径:标称 MPE 为 ISO 10360-2 长度测量最大允许误差,不等同于 ISO 14253-1 要求的判定不确定度;' + + 'ISO 齿轮检测标准尚未定义光学方法,光学方案的最终判定权须由企业规范或客户认可取得。价格一律待核实(厂商询价制)。' + + '本表为选型辅助,最终结论须以实际配置的校准、比对与 GR&R 报告为准。'; + body.appendChild(warn); + } + + function renderConfig() { + const body = $('config-body'); + body.innerHTML = ''; + const cfg = state.result && state.result.configuration; + if (!cfg) { + body.innerHTML = '

尚未生成配置清单。

'; + return; + } + const section = (title, items, note) => { + const card = document.createElement('div'); + card.className = 'card'; + let h = '

' + esc(title) + '

'; + if (note) h += '

' + esc(note) + '

'; + h += items.map((i) => + '
' + esc(i.item) + (i.required ? ' 必备' : ' 建议') + '
' + + '
' + esc(i.spec) + '
依据:' + esc(i.basis) + '
' + ).join(''); + card.innerHTML = h; + body.appendChild(card); + }; + section('主设备', [{ + item: cfg.primary.name, + spec: cfg.primary.role, + basis: '按 ' + state.result.mode.label + ' 模式综合评分排序,满足全部硬约束', + required: true, + }], null); + section('场地配置清单', cfg.site, '据设备外形尺寸、承重与安装要求推导;标注「待核实」者需向厂商索取三维包络。'); + section('环境配置清单', cfg.environment, '据设备标定温度区间与测量原理推导。'); + section('辅助设备与验收要求', cfg.aux, '按你勾选的验收指标生成;光学方案额外要求多边形化误差与点间距数据。'); + } + + function renderSaved() { + const body = $('saved-body'); + body.innerHTML = ''; + if (!state.saved.length) { + body.innerHTML = '

尚未保存任何方案。

在「方案建议」页保存当前需求后,会出现在这里。

'; + return; + } + for (const r of state.saved) { + const div = document.createElement('div'); + div.className = 'saved-item'; + const req = r.requirement || {}; + div.innerHTML = '
' + esc(req.projectName || '未命名方案') + '
' + + '
' + esc(req.gearClass || '') + ' · ' + esc(req.diameterMm || '—') + ' mm / ' + + esc(req.toleranceUm || '—') + ' µm · 模式 ' + esc(r.mode || 'accuracy') + '
'; + const bar = document.createElement('div'); + bar.className = 'head-actions'; + const load = document.createElement('button'); + load.className = 'small'; + load.type = 'button'; + load.textContent = '载入'; + load.addEventListener('click', () => { + state.requirement = JSON.parse(JSON.stringify(req)); + state.mode = r.mode || 'accuracy'; + fillForm(state.requirement); + updateModeButtons(); + analyze(); + toast('已载入方案', 'ok'); + }); + const del = document.createElement('button'); + del.className = 'small'; + del.type = 'button'; + del.textContent = '删除'; + del.addEventListener('click', async () => { + try { + await api('/api/requirements/' + encodeURIComponent(r.id), { method: 'DELETE' }); + await loadSaved(); + toast('已删除', 'ok'); + } catch (e) { + toast('删除失败:' + e.message, 'error'); + } + }); + bar.appendChild(load); + bar.appendChild(del); + div.appendChild(bar); + body.appendChild(div); + } + } + + function updateModeButtons() { + $('mode-accuracy').setAttribute('aria-pressed', String(state.mode === 'accuracy')); + $('mode-stability').setAttribute('aria-pressed', String(state.mode === 'stability')); + } + + async function analyze() { + const status = $('compare-status'); + setStatus(status, '正在计算方案…'); + const btn = $('btn-analyze'); + btn.disabled = true; + try { + const data = await api('/api/analyze', { + method: 'POST', + body: JSON.stringify({ requirement: state.requirement || readForm(), mode: state.mode }), + }); + state.requirement = data.requirement; + state.result = data.result; + setStatus(status, '已更新:' + data.result.summary.total + ' 台候选,' + + data.result.summary.eligible + ' 台满足硬约束,' + + data.result.summary.complementary + ' 台作为配套。', 'ok'); + renderCompare(); + renderRecommend(); + renderConfig(); + } catch (e) { + setStatus(status, '计算失败:' + e.message, 'error'); + } finally { + btn.disabled = false; + } + } + + async function loadSaved() { + try { + const data = await api('/api/requirements'); + state.saved = data.requirements || []; + renderSaved(); + } catch (e) { + state.saved = []; + renderSaved(); + } + } + + async function doExport(format) { + try { + const data = await api('/api/export', { + method: 'POST', + body: JSON.stringify({ requirement: state.requirement || readForm(), mode: state.mode, format }), + }); + const blob = new Blob([data.content], { type: data.mime }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = data.filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + setTimeout(() => URL.revokeObjectURL(url), 4000); + toast('已导出 ' + data.filename, 'ok'); + } catch (e) { + toast('导出失败:' + e.message, 'error'); + } + } + + async function doRefresh() { + const btn = $('btn-refresh'); + btn.disabled = true; + const original = btn.innerHTML; + btn.innerHTML = ' 正在抓取…'; + try { + const ids = (state.result ? state.result.ranked : []).slice(0, 3).map((r) => r.id); + if (!ids.length) throw new Error('尚无设备可刷新'); + const data = await api('/api/refresh', { method: 'POST', body: JSON.stringify({ deviceIds: ids }) }); + let html = '

在线刷新为可选辅助,内置核实库的值不会被覆盖。以下为抓取到的页面片段,请人工比对。

'; + for (const r of data.results) { + html += '

' + esc(r.deviceId) + '

'; + if (r.ok) { + html += '

' + esc(r.note) + '

'; + if (r.hits && r.hits.length) { + html += '
' + esc(r.hits.join('\n')) + '
'; + } + } else { + html += '

' + esc(r.reason) + '

'; + for (const a of (r.attempts || [])) { + html += '

' + esc(a.url) + ' — ' + esc(a.error || ('HTTP ' + a.status)) + '

'; + } + } + } + showDialog('在线刷新结果', html, [{ label: '关闭', primary: true }]); + toast('刷新完成', 'ok'); + } catch (e) { + toast('刷新失败:' + e.message, 'error'); + } finally { + btn.disabled = false; + btn.innerHTML = original; + } + } + + function switchTab(name) { + const map = { compare: 'tab-compare', recommend: 'tab-recommend', config: 'tab-config', saved: 'tab-saved' }; + const panels = { compare: 'panel-compare', recommend: 'panel-recommend', config: 'panel-config', saved: 'panel-saved' }; + for (const key of Object.keys(map)) { + const isActive = key === name; + $(map[key]).setAttribute('aria-selected', String(isActive)); + $(panels[key]).hidden = !isActive; + } + } + + function bind() { + $('req-form').addEventListener('submit', (e) => { + e.preventDefault(); + state.requirement = readForm(); + analyze(); + }); + $('btn-reset').addEventListener('click', () => { + state.requirement = JSON.parse(JSON.stringify(state.boot.defaultRequirement)); + fillForm(state.requirement); + analyze(); + toast('已恢复缺省值', 'ok'); + }); + $('f-judgement').addEventListener('change', updateJudgementHint); + $('mode-accuracy').addEventListener('click', () => { + state.mode = 'accuracy'; updateModeButtons(); analyze(); + }); + $('mode-stability').addEventListener('click', () => { + state.mode = 'stability'; updateModeButtons(); analyze(); + }); + $('q-search').addEventListener('input', (e) => { state.filters.q = e.target.value; renderCompare(); }); + $('f-filter-role').addEventListener('change', (e) => { state.filters.role = e.target.value; renderCompare(); }); + $('f-filter-method').addEventListener('change', (e) => { state.filters.method = e.target.value; renderCompare(); }); + $('f-filter-grade').addEventListener('change', (e) => { state.filters.grade = e.target.value; renderCompare(); }); + document.querySelectorAll('th.sortable').forEach((th) => { + th.addEventListener('click', () => { + const key = th.dataset.sort; + if (state.sort.key === key) state.sort.dir = state.sort.dir === 'desc' ? 'asc' : 'desc'; + else { state.sort.key = key; state.sort.dir = key === 'name' || key === 'method' ? 'asc' : 'desc'; } + renderCompare(); + }); + }); + $('btn-export-html').addEventListener('click', () => doExport('html')); + $('btn-export-md').addEventListener('click', () => doExport('markdown')); + $('btn-refresh').addEventListener('click', doRefresh); + ['tab-compare', 'tab-recommend', 'tab-config', 'tab-saved'].forEach((id) => { + $(id).addEventListener('click', () => { + switchTab(id.replace('tab-', '')); + if (id === 'tab-saved') loadSaved(); + }); + }); + } + + async function init() { + const globalStatus = $('global-status'); + try { + const boot = await api('/api/bootstrap'); + state.boot = boot; + state.saved = boot.storedRequirements || []; + const sel = $('f-judgement'); + sel.innerHTML = ''; + for (const key of Object.keys(boot.judgementTypes)) { + const jt = boot.judgementTypes[key]; + const opt = document.createElement('option'); + opt.value = key; + opt.textContent = jt.label; + sel.appendChild(opt); + } + state.requirement = JSON.parse(JSON.stringify(boot.defaultRequirement)); + fillForm(state.requirement); + bind(); + renderSaved(); + await analyze(); + if (boot.stateError) { + globalStatus.className = 'notice err'; + globalStatus.textContent = boot.stateError; + } else { + globalStatus.className = 'notice'; + globalStatus.innerHTML = '数据口径:内置核实库共 ' + boot.devices.length + + ' 台候选设备,证据分级 A=原厂一手页面、B=权威二手、C=经销商转述、D=推断或待核实;' + + '抓取时间 ' + esc(boot.evidenceRetrievedAt) + '。价格一律为待核实(厂商询价制,无公开报价源)。' + + '「在线刷新规格」为可选辅助,失败时自动保留内置数据。'; + } + } catch (e) { + globalStatus.className = 'notice err'; + globalStatus.textContent = '初始化失败:' + e.message; + } + } + + init(); +})(); diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/index.html b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/index.html new file mode 100644 index 00000000..ad796bf6 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/client/index.html @@ -0,0 +1,266 @@ + + + + + + Gear Measurement Scheme Selector + + + +
+
+
+

齿轮测量方案选型工具

+

录入测量对象、目标精度、场地、环境与预算约束,系统统一整理标称精度、稳定性、技术特点与适用场景,对接触式与非接触式候选设备生成可筛选对比表,并输出主设备、场地、环境与辅助设备配置清单。

+
+
+ + + +
+
+ +
正在载入设备库…
+ + + +
+ + +
+
+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
+
+
+ +
+ +
+ + + + + + + + + + + + + + + + + + +
齿轮测量候选设备对比表
设备测量原理标称精度与标准精度分稳定性分适配分成本分综合分稳定性与技术特点适用场景与限制证据
+
+

+
+ + + + + + +
+
+
+ +
+
+ + + diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/miniapp.json b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/miniapp.json new file mode 100644 index 00000000..6146b4a9 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/miniapp.json @@ -0,0 +1,32 @@ +{ + "schemaVersion": 1, + "artifacts": { + "client": [ + "./miniapp/client" + ], + "node": [ + "./miniapp/node" + ] + }, + "runtime": { + "kind": "process", + "entry": "./miniapp/node/server.mjs", + "lifecycle": "on-demand" + }, + "surface": { + "path": "/dashboard", + "window": { + "width": 1280, + "height": 860, + "minWidth": 720, + "minHeight": 560, + "resizable": true, + "frame": true, + "transparent": false, + "alwaysOnTop": false, + "skipTaskbar": false, + "clickThrough": false + } + }, + "mcpEndpoints": [] +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/devices.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/devices.mjs new file mode 100644 index 00000000..041a09e9 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/devices.mjs @@ -0,0 +1,704 @@ +'use strict'; + +/** + * Built-in verified device library for gear-measurement solution selection. + * + * Evidence grades (following the project meta-rules): + * A = first-party vendor page/spec sheet fetched during authoring + * B = secondary authoritative source (trade press carrying a vendor statement, or a + * certification announcement carried by several outlets) + * C = distributor/reseller page repeating vendor claims + * D = inference, historical task context, or vendor claim not yet independently confirmed + * + * Every numeric field that is not A/B graded must be treated as "待核实" by the UI. + * No price is published: all entries carry price.status = '待核实' with an inquiry path. + */ + +const EVIDENCE_RETRIEVED_AT = '2026-11-30'; + +function ev(grade, source, note) { + return { grade, source, note: note || null, retrievedAt: EVIDENCE_RETRIEVED_AT }; +} + +const DEVICES = [ + { + id: 'klingelnberg-p40', + capabilities: ['iso1328-final', 'process-screening'], + brand: 'Klingelnberg', + model: 'P 40', + name: 'Klingelnberg P 40 精密测量中心', + method: 'hybrid', + methodLabel: '混合式(触测 + 光学传感器 Optoscan)', + role: '实验室计量级判定 · 产线前道筛查', + accuracy: { + mpeBase: 1.8, + mpeLenCoef: 1 / 450, + mpeForm: '1.8 µm + L/450 mm', + mpeCondition: 'ISO 10360-2 (2010),18–22 °C;15–35 °C 时为 1.8 µm + L/250 mm', + standard: 'VDI/VDE 2612 sheet 6 · Group A', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, + roundnessUm: 0.3, + axialRunoutUm: 1.5, + uncertaintyNote: 'MPE_E0 为 ISO 10360-2 长度测量最大允许误差,非完整不确定度;' + + '总不确定度需按具体配置由 PTB/DAkkS 报告确认。', + }, + stability: { + tempCompensated: true, + tempRangeC: [15, 35], + tempGradient: '参考温度梯度 0.5 K/h;2 K/d;2 K/m(15–35 °C 时 2 K/h;12 K/d)', + base: '气浮', + thermalDriftNote: '内置温度补偿,产线可用性高;15–35 °C 区间内 MPE 线性项变差。', + }, + coverage: { + maxDiaMm: 400, maxHeightMm: 700, moduleMin: 0.3, moduleMax: 20, + maxWeightKg: null, maxLengthMm: 1000, + }, + env: { + tempMinC: 15, tempMaxC: 35, vibrationLimitMms: 0.1, + cleanliness: '计量间(防尘)', humidityPct: null, + }, + space: { + lengthMm: 2015, widthMm: 2505, heightMm: 2200, weightKg: null, powerKw: null, + foundation: '建议独立隔振基础 + 恒温室', doorClearanceMm: null, + }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制,无公开报价。' }, + cycleTime: '自动化测量中心(节拍待厂商确认)', + features: [ + '全自动 CNC 数控,一次装夹完成坐标、形状、齿形与粗糙度测量', + '触测针与 Optoscan 光学传感器可切换,光学模式减少 70 mm Z 向行程', + '模块范围 0.30–20 mm,覆盖齿轮、蜗杆/蜗轮、锥齿轮、滚刀与剃齿刀', + 'X 轴 ±115 mm,Z 轴 550 (700) mm,中心距 5–800 (50–1000) mm', + ], + scenarios: [ + '航空/汽车齿轮 ISO 1328-1、AGMA 2001 最终判定', + '齿轮刀具(滚刀、剃齿刀)齿形测量', + '量产前道过程筛查与工艺闭环', + ], + limits: [ + '非手持/非在线结构光方案,不适合 100% 高速全检', + '光学部分仍非计量级齿形判定源', + ], + evidence: [ + ev('A', 'https://klingelnberg.com/en/industry-solutions/aviation/detail-page?product=150', + '原厂产品页,含完整 MPE_E0、VDI/VDE 2612 分组、行程与尺寸表'), + ], + }, + { + id: 'klingelnberg-p26', + capabilities: ['iso1328-final', 'process-screening'], + brand: 'Klingelnberg', + model: 'P 26', + name: 'Klingelnberg P 26 精密测量中心', + method: 'hybrid', + methodLabel: '混合式(触测 + 光学)', + role: '实验室计量级判定(较小工件)', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, + mpeCondition: null, + standard: '待核实', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '未取得原厂可核对的 MPE 表,精度指标待厂商提供。', + }, + stability: { + tempCompensated: true, tempRangeC: null, tempGradient: null, + base: '气浮', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: 260, maxHeightMm: null, moduleMin: 0.3, moduleMax: 20, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: ['P 40 同系列紧凑机型,覆盖更小工件直径', '触测与光学双模式'], + scenarios: ['中小直径齿轮的计量级判定与过程筛查'], + limits: ['各项精度与空间参数待核实后才能进入正式比选'], + evidence: [ + ev('D', '历史任务上下文', '型号与覆盖直径来自历史研究结论,原厂页面本次抓取返回 500,参数未复核'), + ], + }, + { + id: 'gleason-175gms-nano', + capabilities: ['iso1328-final', 'process-screening'], + brand: 'Gleason', + model: '175GMS nano', + name: 'Gleason 175GMS nano 齿轮计量系统', + method: 'contact', + methodLabel: '接触式(3D 扫描探头 + 触测)', + role: '精密计量级判定 · 研发与小型齿轮箱', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '待核实(厂商宣称形状测量重复性超 VDI/VDE 2612,待索取等级证明)', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '原厂页未公布 MPE_E0;"nano 级亚微米"为厂商表述,须索取 MPE 报告与等级证明后方可量化。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, + base: '待核实', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: 175, maxHeightMm: 480, moduleMin: 0.4, moduleMax: 6.35, + maxWeightKg: null, maxLengthMm: 480, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: [ + '高精 3D 扫描探头配样式库(stylus calibration library),可选自动换针并 "calibrate all probes"', + '集成粗糙度测量,评价遵循 DIN / ISO / ANSI 常用参数', + '具备 CMM 坐标测量能力,可做齿轮 + 通用几何一体化检测', + '工作站含环境温湿度监控与 QR 条码读取', + ], + scenarios: [ + '小型齿轮箱与人形机器人减速器齿轮检测', + '齿轮刀具与轴类齿轮复合检测', + ], + limits: ['工件直径上限 175 mm,大件齿轮需另选机型', 'MPE 未公布前不可直接用于 ISO 1328-1 判定承诺'], + evidence: [ + ev('B', 'https://www.gleason.com/en/products/metrology/metrology-systems/analytical-inspection-and-cmm/175gms-nano-precise-gear-measurement-for-humanoid-robotics-and-small-gearboxes', + '原厂产品页,确认模数 0.4–6.35 mm、工件长 480 mm、直径 175 mm、3D 扫描探头与粗糙度能力'), + ev('B', 'https://www.gleason.com/fr/facts-and-news/news-room/nano-level-gear-inspection-goes-smaller', + '原厂新闻室:"nano 级亚微米" 表述,未给出量化 MPE'), + ], + }, + { + id: 'mahr-gmx-275w', + capabilities: ['iso1328-final', 'process-screening'], + brand: 'Mahr', + model: 'MarGear GMX 275 W', + name: 'Mahr MarGear GMX 275 W 齿轮测量中心', + method: 'contact', + methodLabel: '接触式(3D 扫描传感器 + 直接驱动 C 轴)', + role: '计量级判定 · 齿轮与齿轮刀具通用', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, + mpeCondition: '20 °C ± 2 °C', + standard: 'VDI/VDE 2612/2613 组 1 · 精度等级 I', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: 0.11, + uncertaintyNote: '厂商公布轴向跳动偏差 ≤ 0.11 µm + 0.0008 µm/mm(测量半径);' + + '未公布 MPE_E0 全量程表,齿形/齿向不确定度待索取。', + }, + stability: { + tempCompensated: null, tempRangeC: [18, 22], tempGradient: null, + base: '待核实', thermalDriftNote: '精度等级 I 以 20 ± 2 °C 为条件,环境超出需温度补偿或重标定。', + }, + coverage: { + maxDiaMm: 275, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: 18, tempMaxC: 22, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { + lengthMm: 1520, widthMm: 621, heightMm: 1920, weightKg: null, powerKw: null, + foundation: null, doorClearanceMm: null, + }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: [ + '最高外径 275 mm,齿轮与齿轮加工刀具精密全自动测试', + '高精 3D 扫描传感器 + 直接驱动 C 轴,兼顾精度与效率', + '偏差直接评估并自动生成机器误差校正', + '同一台设备完成齿轮测量与形状测量', + ], + scenarios: ['通用齿轮与齿轮刀具制造', 'ISO 1328-1 齿形齿向判定', '齿轮刀具刃口与磨削分析'], + limits: ['精度等级以 20 ± 2 °C 为条件,需恒温环境配合'], + evidence: [ + ev('C', 'http://m.forth-tech.com/detail-3418445.html', + '经销商产品页,列出 VDI/VDE 2612/2613 组 1 等级 I、轴向跳动 0.11 µm + 0.0008 µm/mm、外径 275 mm 与外形尺寸'), + ], + }, + { + id: 'mahr-gmx-400', + capabilities: ['iso1328-final', 'process-screening'], + brand: 'Mahr', + model: 'MarGear GMX 400', + name: 'Mahr MarGear GMX 400 齿轮测量中心', + method: 'contact', + methodLabel: '接触式(3D 扫描传感器)', + role: '计量级判定(较大直径)', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '待核实', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '未取得可核对的原厂规格表。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, base: '待核实', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: 400, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: ['GMX 系列较大直径机型'], + scenarios: ['较大直径齿轮的计量级判定'], + limits: ['全部关键参数待核实'], + evidence: [ + ev('D', '历史任务上下文', '仅确认存在该型号,参数未取得'), + ], + }, + { + id: 'zeiss-prismo-verity-gearpro', + capabilities: ['iso1328-final'], + brand: 'ZEISS', + model: 'PRISMO verity + GEAR PRO', + name: 'ZEISS PRISMO verity + GEAR PRO 计量方案', + method: 'contact', + methodLabel: '接触式(CMM 路线 + 齿轮算法选件)', + role: '实验室可溯源最终判定', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, + mpeCondition: null, + standard: 'ISO 1328-1 / AGMA 2001 报告', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: 'GEAR PRO 评定偏差 ≤ ±0.1 µm(软件口径,PTB 认证);' + + '整机长度测量误差 0.7 + L/400 µm 属历史来源,精度上限由所配 CMM 决定,须索取整机 MPE 报告。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, + base: '待核实(随所配 CMM 机型)', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: 18, tempMaxC: 22, vibrationLimitMms: null, cleanliness: '计量间', humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '软件与 CMM 组合报价,需分别询价。' }, + cycleTime: null, + features: [ + 'CMM 路线,实验室量值可溯源,契合 AS9102 FAIR 记录要求', + 'GEAR PRO 为 CALYPSO 的齿轮选件,2024 年 GEAR PRO 7.2 获 PTB 认证', + '已发表与齿轮测量专机、ATOS Q 的标准几何量与波纹度对照研究', + ], + scenarios: ['航空齿轮最终合格判定与量值溯源', '客户/法规要求可溯源报告的验收场合'], + limits: ['精度上限由所配 CMM 机型决定,不能单独用软件指标承诺', '节拍显著慢于光学与激光方案'], + evidence: [ + ev('B', 'https://www.antpedia.com/news/wx_article/1008824.html', + '行业媒体转载:2024 年 ZEISS GEAR PRO 7.2 获 PTB 认证'), + ev('D', '历史任务上下文', '长度测量误差 0.7 + L/400 µm 与 PTB 证书号来自历史研究,本次未复核'), + ], + }, + { + id: 'zeiss-atos-q-scanbox', + capabilities: ['waviness-nvh', 'process-screening'], + brand: 'ZEISS', + model: 'ATOS Q + ScanBox 4105', + name: 'ZEISS ATOS Q / ScanBox 4105 光学三维测量系统', + method: 'non-contact', + methodLabel: '非接触式(蓝光条纹投影全场点云)', + role: '全齿面波纹度与拓扑 · 数字化 · NVH 归因', + accuracy: { + mpeBase: 5.0, mpeLenCoef: 0, + mpeForm: '单幅扫描精度可达 0.005 mm(典型 0.01–0.02 mm)', + mpeCondition: '随测量体积、镜头组与标定状态变化', + standard: '不适用(ISO 齿轮检测标准尚未定义光学方法)', + metrology: 'process', + measurableToleranceUm: [5, 20], + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '该 5 µm 为单幅扫描精度而非 MPE_E0;点间距 0.03–0.15 mm 决定齿顶齿根多边形化误差,' + + '齿形齿向与触测的系统性差异可达数微米。不得用于 ISO 1328-1 最终判定。', + }, + stability: { + tempCompensated: false, tempRangeC: null, tempGradient: null, + base: '传感器固定于三脚架 / 桌面 / ScanBox', + thermalDriftNote: '温漂影响点云配准,需环境温控;无内置温度补偿的公开证据。', + }, + coverage: { + maxDiaMm: 500, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: 100, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: '防尘、避免强光直射', humidityPct: null }, + space: { + lengthMm: null, widthMm: null, heightMm: null, weightKg: 4, powerKw: null, + foundation: 'ScanBox 4105 独立工位,地面平整', doorClearanceMm: null, + }, + price: { value: null, currency: 'CNY', status: '待核实', note: '经销商报价,机型配置差异大。' }, + cycleTime: '单幅扫描约 0.2 s;ScanBox 自动化节拍待核实', + features: [ + '8M / 12M 两个版本,单次扫描最多捕捉 2 × 1200 万或 2 × 800 万坐标点', + '测量体积 50 / 100 / 170 / 270 / 350 / 500 mm³,测量面积 100×70 – 500×370 mm²', + '点间距 12M 版 0.03–0.12 mm、8M 版 0.04–0.15 mm;工作距离 490 mm;主机约 4 kg', + '蓝光均衡器实现高速条纹投影,三重扫描原理适应反光与凹陷表面', + 'ScanBox 4105 可下探至 80×60×60 mm³ 测量体积,扫描过程监控与自动纠错', + 'ZEISS INSPECT 覆盖扫描、检测与报告全流程', + ], + scenarios: [ + '全齿面波纹度、拓扑与 NVH 关联分析', + '磨损数字孪生、数字化与逆向工程', + '齿轮泵等零件的触测/光学对照研究', + ], + limits: [ + 'ISO 齿轮检测标准尚未定义光学方法,最终判定权须由企业规范或客户认可取得', + '齿顶齿根多边形化误差系统性存在,不可通过平均消除', + ], + evidence: [ + ev('C', 'https://www.instrument.com.cn/netshow/sh121019/c677341.htm', + '经销商技术页,列出 8M/12M 点数、测量体积、点间距 0.03–0.15 mm、工作距离 490 mm、约 4 kg 与单幅 0.005 mm'), + ev('B', 'https://www.zebicon.com/en/metrology-systems/automated-3d-scanners/atos-scanbox-series-4', + 'ScanBox 4105 自动化系统与 80×60×60 mm³ 最小测量体积'), + ], + }, + { + id: 'marposs-m62', + capabilities: ['process-screening'], + brand: 'Marposs', + model: 'M62 Laser Profiler', + name: 'Marposs M62 Laser Profiler 齿轮检测系统', + method: 'non-contact', + methodLabel: '非接触式(激光三角测量轮廓)', + role: '产线 100% 筛查 · 齿形齿向轮廓与修形量', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用(未公布 MPE)', + metrology: 'process', + measurableToleranceUm: [5, 10], + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '厂商口径"可测公差 5–10 µm"指可分辨的公差带,不等同于测量不确定度;' + + '未公布 MPE_E0,不得用于最终判定。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, + base: '在线工位支架', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: 300, maxHeightMm: 40, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: '产线工位', doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: '约 40 秒/件', + features: [ + '激光三角测量,投影激光线一次采集整条 Z-X 轮廓,旋转 360° 后重建三维', + '可测特性:Ca 齿向修形量、fhα 齿形倾斜偏差、Ffα 齿形总偏差、Cβ、fhβ、Ffβ', + '兼容 Marposs 电子测量显示单元(如 E9066 工业计算机)', + '可接 Gear AddOn 与 QuickSPC 做统计过程控制', + ], + scenarios: [ + '齿轮 100% 高速筛查与 SPC 反馈', + '磨齿/滚齿工艺的过程能力监控', + '偶数齿与奇数齿、直齿与斜齿', + ], + limits: ['未公布 MPE_E0,精度不可直接对标计量级', '高度上限 40 mm,超长工件需另选机型'], + evidence: [ + ev('B', 'https://ctemag.com?p=101861/', + '行业媒体刊载厂商发布:Ø30–300 mm、高 15–40 mm、约 40 s 节拍、可测公差 5–10 µm 与可测特性清单'), + ev('B', 'https://www.mfgnewsweb.com/archives/4/63927/Quality-Control-mar23/ad_info.aspx', + '行业媒体对同一发布内容的独立报道,可交叉印证'), + ], + }, + { + id: 'dwfritz-zerotouch', + capabilities: ['process-screening'], + brand: 'DWFritz', + model: 'ZeroTouch Gear Metrology System', + name: 'DWFritz ZeroTouch 齿轮计量系统', + method: 'non-contact', + methodLabel: '非接触式(三维光学 3D referencing)', + role: '近线/在线 100% 齿面全检 · 表面缺陷检出', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用(未公布 MPE)', + metrology: 'process', + measurableToleranceUm: [5, 10], + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '厂商公布可测公差 5–10 µm、最小缺陷 50 µm;未公布 MPE_E0,' + + '不得用于 ISO 1328-1 最终判定。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, + base: '在线工位', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: 300, maxHeightMm: 40, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: '产线工位', doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: '典型约 30 秒/件', + features: [ + '对外径最大 300 mm、高度最大 40 mm 的齿轮做 100% 非接触检测', + '典型节拍约 30 秒/件,采集稠密精密点云', + '对整个参考表面做 3D referencing,采集数百万数据点,可弱化局部表面缺陷与粗糙度影响', + '最小可检出表面缺陷 50 µm', + ], + scenarios: ['近线与在线 100% 齿面检验', '磨削/铣削后实时反馈上游工艺、减少废品'], + limits: ['未公布 MPE_E0', '高度上限 40 mm', '非计量级判定源'], + evidence: [ + ev('A', 'https://www.zerotouchmetrology.com/en/products/zerotouch-gear-metrology-system', + '原厂产品页:外径 ≤300 mm、高 ≤40 mm、典型节拍约 30 s、公差 5–10 µm、最小缺陷 50 µm、3D referencing 与数百万点'), + ], + }, + { + id: 'starrett-kmr-m3', + capabilities: ['process-screening'], + brand: 'Starrett', + model: 'KMR M3 + MetLogix M3 Gear Module', + name: 'Starrett 视觉测量机 KMR M3(MetLogix M3 齿轮模块)', + method: 'non-contact', + methodLabel: '非接触式(视觉边缘检测,可选触测)', + role: '直齿常规尺寸量与形状量快速评价', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用', + metrology: 'process', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '厂商未公布针对齿轮齿形的 MPE 或不确定度;' + + '视觉法对表面反光、装夹与照明条件敏感,须以标准件比对确认。', + }, + stability: { + tempCompensated: false, tempRangeC: null, tempGradient: null, + base: '常规', thermalDriftNote: '视觉法不依赖温度补偿,对振动与照明更敏感。', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: [ + '单件采集超过 10,000 点', + 'Standard / Master 标准宏降低人为差异与培训成本', + '无接触损伤,可全齿面成像归档追溯', + '支持 DFX 导入与 CAD 比对', + ], + scenarios: ['直齿齿轮齿宽、φ 角、直径公差与形状快速评价', '高批量与跨班次一致性管控'], + limits: ['以直齿应用为主,斜齿/内齿适配性待核实', '对反光、装夹与光学条件敏感'], + evidence: [ + ev('C', 'https://www.optimaxonline.com?p=5810/', + '经销商页:KMR M3 视场测量、图像处理与 DFX 导入能力'), + ev('D', '历史任务上下文', '>10,000 点与 Standard/Master 宏来自历史研究,未在原厂页复核'), + ], + }, + { + id: 'mahr-marshaft-3d', + capabilities: ['process-screening', 'waviness-nvh'], + brand: 'Mahr', + model: 'MarShaft Scope 600/850 plus 3D', + name: 'Mahr MarShaft Scope 600/850 plus 3D 轴与齿轮光学测量系统', + method: 'hybrid', + methodLabel: '混合式(光学 + 触测)', + role: '轴类与齿轮的三维形位评价', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用', + metrology: 'process', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '待核实。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, base: '待核实', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: ['同一系统兼顾轴类与齿轮', 'MarWin 软件环境与 Marposs 生态一致'], + scenarios: ['传动系统零件族(轴 + 齿轮)统一形位评价'], + limits: ['面向轴类为主,非齿轮专用计量中心', '齿轮为附加能力'], + evidence: [ + ev('D', '历史任务上下文', '型号与技术路线来自历史研究,原厂页本次抓取返回 403'), + ], + }, + { + id: 'nikon-ct', + capabilities: ['internal-structure', 'iso1328-final'], + brand: 'Nikon Metrology', + model: 'XT H 225 / XR-100 系列', + name: 'Nikon Metrology X-ray CT 计量系统', + method: 'non-contact', + methodLabel: '非接触式(X 射线 CT,绝对尺度)', + role: '内齿、花键与内部缺陷 · 热处理变形', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '待核实', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: 'CT 为绝对尺度测量,无需参考样件;具体精度与工件尺寸强相关,待厂商提供数据。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, + base: '屏蔽间独立机位', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: '射线屏蔽间', humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: '屏蔽间 + 吊装通道', doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制,机房改造费用另计。' }, + cycleTime: null, + features: [ + '绝对尺度 CT,无需参考样件、不破坏样件即可测内部几何', + '可测内齿、花键、孔隙、热处理变形与增材齿轮内部结构', + '已有量产应用案例(BorgWarner 涡轮增压器等)', + ], + scenarios: ['内齿轮与花键的内部几何检测', '增材件孔隙与热处理变形分析'], + limits: ['分辨率与工件尺寸相关', '需射线屏蔽、辐射安全许可与专用机房'], + evidence: [ + ev('B', 'https://industry.nikon.com/zh-cn/news/new-x-ray-ct-system-has-unique-combination-of-five-innovative-features-taking-usability-and-uptime-to-the-next-level/', + '原厂发布 XT H 225 ST 2x 微焦点 CT 系统;精度数据未在该页给出'), + ev('D', '历史任务上下文', 'MCT225 / XT H / XR-100 型号族与绝对尺度特性来自历史研究'), + ], + }, + { + id: 'lasertec-hybrid', + capabilities: ['tool-metrology'], + brand: 'Lasertec', + model: 'HYBRID 系列', + name: 'Lasertec HYBRID 激光共聚焦显微镜', + method: 'non-contact', + methodLabel: '非接触式(激光共聚焦)', + role: '齿轮刀具刃口与齿面微观形貌', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用(微观形貌)', + metrology: 'process', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '垂直分辨率 0.05 nm 级为纵向分辨率指标,非整齿轮几何不确定度。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, base: '防振台', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: '洁净台面', humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: '防振台', doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: ['激光共聚焦,垂直分辨率 0.05 nm 级', '滚刀、插齿刀、强力车齿刀刃口与齿面粗糙度'], + scenarios: ['齿轮刀具刃口轮廓与齿面微观形貌', '磨削烧伤与表面完整性分析'], + limits: ['视场小,不能替代整齿轮几何测量'], + evidence: [ + ev('D', '历史任务上下文', '来自历史研究,原厂页未复核'), + ], + }, + { + id: 'creaform-goscan', + capabilities: ['process-screening'], + brand: 'Creaform (AMETEK)', + model: 'Go!SCAN SPARK / HandySCAN', + name: 'Creaform 手持结构光扫描系统', + method: 'non-contact', + methodLabel: '非接触式(手持结构光)', + role: '数字化 · 逆向工程 · 磨损与毛刺检查', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '不适用', + metrology: 'process', + measurableToleranceUm: null, + repeatabilityUm: null, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '计量级扫描仪,但非齿轮几何量具,精度不足以判定齿形。', + }, + stability: { + tempCompensated: false, tempRangeC: null, tempGradient: null, base: '手持', thermalDriftNote: '手持操作引入姿态与遮挡误差。', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制。' }, + cycleTime: null, + features: ['航空领域应用成熟', '便携,可现场使用,不接触表面'], + scenarios: ['数字化与逆向工程', '装配验证、磨损与毛刺检查'], + limits: ['不是齿轮几何量具,精度不足以判定齿形'], + evidence: [ + ev('D', '历史任务上下文', '来自历史研究,原厂页本次抓取返回 404'), + ], + }, + { + id: 'cn-hq-3920', + capabilities: ['iso1328-final', 'process-screening'], + brand: '哈量', + model: '3920', + name: '哈量 3920 齿轮测量中心(国产替代)', + method: 'contact', + methodLabel: '接触式', + role: '国产低成本计量级候选', + accuracy: { + mpeBase: null, mpeLenCoef: null, mpeForm: null, mpeCondition: null, + standard: '待核实', + metrology: 'metrology', + measurableToleranceUm: null, + repeatabilityUm: 1.0, roundnessUm: null, axialRunoutUm: null, + uncertaintyNote: '厂商口径:齿形齿向示值误差 2 µm、重复精度 1 µm;' + + '未取得第三方或校准机构证明,须先与现役进口机做量值比对再放量。', + }, + stability: { + tempCompensated: null, tempRangeC: null, tempGradient: null, base: '待核实', thermalDriftNote: '待核实', + }, + coverage: { + maxDiaMm: null, maxHeightMm: null, moduleMin: null, moduleMax: null, + maxWeightKg: null, maxLengthMm: null, + }, + env: { tempMinC: null, tempMaxC: null, vibrationLimitMms: null, cleanliness: null, humidityPct: null }, + space: { lengthMm: null, widthMm: null, heightMm: null, weightKg: null, powerKw: null, foundation: null, doorClearanceMm: null }, + price: { value: null, currency: 'CNY', status: '待核实', note: '厂商询价制,通常显著低于进口机型(推断,待询价核实)。' }, + cycleTime: null, + features: ['国产化备选,成本通常更低(推断)'], + scenarios: ['国产化降本路线'], + limits: ['全部关键参数待核实', '需与现役设备做量值比对与 GR&R 后方可承担判定任务'], + evidence: [ + ev('D', '历史任务上下文', '秦川等同系列厂商口径,本次未复核'), + ], + }, +]; + +/** Static candidate vendor pages used by the optional online refresh. Deep links drift, so refresh + * treats a 404/403 as "not refreshable" and keeps the built-in value. */ +const REFRESH_SOURCES = { + 'klingelnberg-p40': ['https://klingelnberg.com/en/industry-solutions/aviation/detail-page?product=150'], + 'klingelnberg-p26': ['https://klingelnberg.com/en/industry-solutions/aviation/detail-page?product=149'], + 'gleason-175gms-nano': [ + 'https://www.gleason.com/en/products/metrology/metrology-systems/analytical-inspection-and-cmm/175gms-nano-precise-gear-measurement-for-humanoid-robotics-and-small-gearboxes', + ], + 'mahr-gmx-275w': ['http://m.forth-tech.com/detail-3418445.html'], + 'mahr-gmx-400': ['https://www.mahr.com/en/products/gear-measuring-machines/'], + 'zeiss-atos-q-scanbox': [ + 'https://www.zebicon.com/en/metrology-systems/automated-3d-scanners/atos-scanbox-series-4', + 'https://www.zeiss.com/microscopy/en/products/3d-metrology/atos.html', + ], + 'zeiss-prismo-verity-gearpro': ['https://www.zeiss.com/metrology/en/products/industrial-metrology-solutions/'], + 'marposs-m62': ['https://www.marposs.com/eng/'], + 'dwfritz-zerotouch': ['https://www.zerotouchmetrology.com/en/products/zerotouch-gear-metrology-system'], + 'starrett-kmr-m3': ['https://www.starrett.com/'], + 'mahr-marshaft-3d': ['https://www.mahr.com/en/products/gear-measuring-machines/'], + 'nikon-ct': ['https://industry.nikon.com/'], + 'lasertec-hybrid': ['https://www.lasertec.co.jp/en/'], + 'creaform-goscan': ['https://www.creaform.com/'], + 'cn-hq-3920': ['http://www.hali.com.cn/'], +}; + +export { DEVICES, REFRESH_SOURCES, EVIDENCE_RETRIEVED_AT }; diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/engine.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/engine.mjs new file mode 100644 index 00000000..a60d081b --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/engine.mjs @@ -0,0 +1,613 @@ +'use strict'; + +import { DEVICES, REFRESH_SOURCES } from './devices.mjs'; + +/** + * Selection engine. + * + * Design rules (first principles, stated so the reasoning is auditable): + * - Hard constraints (coverage / space / environment / budget / measurement-principle + * compatibility) are gates, not weights. A device failing a gate is not "less good", + * it is unfit for that requirement. + * - Two decision modes weight the soft criteria differently: + * accuracy-first -> accuracy 0.50, stability 0.25, fit 0.15, cost 0.10 + * stability-first -> accuracy 0.30, stability 0.40, fit 0.20, cost 0.10 + * - Every score carries its own evidence grade and a "待核实" flag when the source + * value is not first-party verified. + * - A device whose metrology class cannot legally satisfy the required judgement + * (ISO 1328-1 final acceptance vs process screening) is flagged as a principle + * mismatch rather than silently down-ranked. + */ + +export const MODES = { + accuracy: { key: 'accuracy', label: '精度优先', weights: { accuracy: 0.50, stability: 0.25, fit: 0.15, cost: 0.10 } }, + stability: { key: 'stability', label: '综合稳定性优先', weights: { accuracy: 0.30, stability: 0.40, fit: 0.20, cost: 0.10 } }, +}; + +export const JUDGEMENT_TYPES = { + 'iso1328-final': { + key: 'iso1328-final', + label: 'ISO 1328-1 / AGMA 最终合格判定', + requiresMetrology: true, + note: '航空件按 ISO 1328-1 / AGMA 2001 验收;按 ISO 14253-1 需不确定度 ≤ 允差的 10%。', + }, + 'process-screening': { + key: 'process-screening', + label: '产线过程筛查 / 100% 全检', + requiresMetrology: false, + note: '面向节拍与覆盖率,用于过程反馈与工艺闭环,不承担最终放行。', + }, + 'waviness-nvh': { + key: 'waviness-nvh', + label: '全齿面波纹度 / NVH 关联分析', + requiresMetrology: false, + note: '光学全场方案的主战场;接触式无法替代。', + }, + 'internal-structure': { + key: 'internal-structure', + label: '内齿 / 花键 / 内部缺陷', + requiresMetrology: false, + note: '需 X-ray CT 等绝对尺度非接触手段。', + }, + 'tool-metrology': { + key: 'tool-metrology', + label: '齿轮刀具刃口与齿面微观形貌', + requiresMetrology: false, + note: '需激光共聚焦或显微级手段。', + }, +}; + +/** Default requirement derived from ISO 1328-1 / 14253-1 reasoning; every field is overridable. */ +export function defaultRequirement() { + return { + projectName: '航空齿轮测量方案选型', + judgementType: 'iso1328-final', + gearClass: '航空级渐开线圆柱齿轮', + moduleMm: 3, + diameterMm: 200, + faceWidthMm: 40, + toleranceUm: 8, + annualVolume: 2000, + methods: ['contact', 'non-contact', 'hybrid'], + needsFinalAcceptance: true, + space: { lengthM: 6, widthM: 4, heightM: 2.8, loadKg: 800, powerKw: 8, doorWidthMm: 900 }, + environment: { tempC: 20, tempStabilityK: 1, humidityPct: 50, vibration: '低', cleanliness: '计量间' }, + budget: { amount: 3000000, currency: 'CNY', includesInstallation: true }, + acceptance: { + mpeRequired: true, + uncertaintyRatio: 0.10, + requireTraceability: true, + requireGrR: true, + requireThirdPartyCalibration: true, + notes: '按 ISO 14253-1,判定不确定度 ≤ 允差的 10%;需索取该配置 MPE 报告与 VDI/VDE 2612 等级证明。', + }, + }; +} + +function num(v) { return typeof v === 'number' && Number.isFinite(v) ? v : null; } +function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); } + +/** Effective measurement uncertainty of a device at a given characteristic length (mm). */ +export function effectiveMpe(device, lengthMm) { + const a = device.accuracy; + if (a.mpeBase === null || a.mpeBase === undefined) return null; + const base = a.mpeBase; + if (!a.mpeLenCoef) return base; + const L = num(lengthMm); + if (L === null) return base; + return base + a.mpeLenCoef * L; +} + +/** Coverage gate: can the device physically hold and resolve the workpiece? */ +function checkCoverage(device, req) { + const failures = []; + const notes = []; + const c = device.coverage; + const mod = num(req.moduleMm); + const dia = num(req.diameterMm); + const face = num(req.faceWidthMm); + + if (mod !== null && c.moduleMin !== null && mod < c.moduleMin) { + failures.push('模数 ' + mod + ' mm 低于下限 ' + c.moduleMin + ' mm'); + } + if (mod !== null && c.moduleMax !== null && mod > c.moduleMax) { + failures.push('模数 ' + mod + ' mm 超出上限 ' + c.moduleMax + ' mm'); + } + if (dia !== null && c.maxDiaMm !== null && dia > c.maxDiaMm) { + failures.push('外径 ' + dia + ' mm 超出最大 ' + c.maxDiaMm + ' mm'); + } + if (face !== null && c.maxHeightMm !== null && face > c.maxHeightMm) { + failures.push('齿宽 ' + face + ' mm 超出最大工件高度 ' + c.maxHeightMm + ' mm'); + } + if (c.moduleMin === null || c.moduleMax === null) notes.push('模数范围待核实'); + if (c.maxDiaMm === null) notes.push('最大外径待核实'); + if (c.maxHeightMm === null) notes.push('最大工件高度待核实'); + return { pass: failures.length === 0, failures, notes }; +} + +/** Space gate: does the machine and its required footprint fit the lab? */ +function checkSpace(device, req) { + const failures = []; + const notes = []; + const s = device.space; + const roomL = (num(req.space.lengthM) || 0) * 1000; + const roomW = (num(req.space.widthM) || 0) * 1000; + const roomH = (num(req.space.heightM) || 0) * 1000; + + if (s.lengthMm === null || s.widthMm === null) { + notes.push('设备外形尺寸待核实,无法核算占地'); + } else { + const margin = 800; // operator aisle on the long sides + const needL = s.lengthMm + margin; + const needW = s.widthMm + margin; + if (needL > roomL || needW > roomW) { + failures.push('含操作通道占地约 ' + Math.round(needL / 100) / 10 + ' × ' + Math.round(needW / 100) / 10 + + ' m,超出可用 ' + req.space.lengthM + ' × ' + req.space.widthM + ' m'); + } + } + if (s.heightMm === null) { + notes.push('设备高度待核实'); + } else if (roomH > 0 && s.heightMm > roomH) { + failures.push('设备高度 ' + s.heightMm + ' mm 超出层高 ' + Math.round(roomH) + ' mm'); + } + if (s.weightKg === null) { + notes.push('设备重量待核实,无法核算地坪承重'); + } else if (s.weightKg > (num(req.space.loadKg) || 0)) { + failures.push('设备重量 ' + s.weightKg + ' kg 超出地坪承重 ' + req.space.loadKg + ' kg'); + } + if (s.powerKw === null) { + notes.push('设备功率待核实'); + } else if (s.powerKw > (num(req.space.powerKw) || 0)) { + failures.push('设备功率 ' + s.powerKw + ' kW 超出供电 ' + req.space.powerKw + ' kW'); + } + return { pass: failures.length === 0, failures, notes }; +} + +/** Environment gate: temperature band, vibration and cleanliness compatibility. */ +function checkEnvironment(device, req) { + const failures = []; + const notes = []; + const e = device.env; + const t = num(req.environment.tempC); + const tMin = num(e.tempMinC); + const tMax = num(e.tempMaxC); + + if (t !== null && tMin !== null && tMax !== null) { + if (t < tMin || t > tMax) { + failures.push('工作温度 ' + t + ' °C 超出标定区间 ' + tMin + '–' + tMax + ' °C'); + } + } else { + notes.push('标定温度区间待核实'); + } + if (req.environment.vibration === '高') { + failures.push('现场振动为高等级,光学/激光方案需独立隔振基础'); + } + if (req.environment.cleanliness === '洁净车间') { + notes.push('现场为洁净车间,需确认设备排气与气源兼容性'); + } + if (e.vibrationLimitMms !== null) { + notes.push('允许振动速度上限 ' + e.vibrationLimitMms + ' mm/s(峰-峰)'); + } else { + notes.push('振动允差待核实'); + } + return { pass: failures.length === 0, failures, notes }; +} + +/** Measurement-principle compatibility: can this device legally make the required judgement? */ +function checkPrinciple(device, req) { + const jt = JUDGEMENT_TYPES[req.judgementType]; + const notes = []; + const caps = device.capabilities || []; + let status = 'ok'; + let role = 'primary'; + + if (jt && !caps.includes(jt.key)) { + // Cannot serve the requested judgement type at all -> route as a complementary device + // when it clearly serves another task, otherwise exclude. + const other = caps.filter((c) => c !== jt.key); + if (other.length) { + status = 'complementary'; + role = 'complementary'; + notes.push('不承担本任务的主判定角色,可作为配套:' + + other.map((c) => (JUDGEMENT_TYPES[c] ? JUDGEMENT_TYPES[c].label : c)).join('、')); + } else { + status = 'mismatch'; + notes.push('测量原理不匹配:无法承担本任务要求的判定类型'); + } + } else if (jt && jt.requiresMetrology && req.needsFinalAcceptance) { + if (device.accuracy.metrology === 'process') { + status = 'mismatch'; + notes.push('该设备公开指标不构成计量级判定源,不能出具最终合格判定结论'); + } else if (device.accuracy.metrology === 'metrology') { + if (device.accuracy.mpeBase === null) { + status = 'unverified'; + notes.push('计量级定位,但未公布 MPE_E0,判定能力待厂商报告证实'); + } else { + notes.push('具备计量级公开 MPE,可支撑最终判定(仍须按实际配置索取报告)'); + } + } + } else { + if (device.accuracy.metrology === 'metrology') { + notes.push('该设备精度超出本任务所需,可降本使用'); + } + } + return { status, role, notes }; +} + +/** Accuracy score 0..100 against the required tolerance and judgement type. */ +function scoreAccuracy(device, req) { + const tol = num(req.toleranceUm); + const metrology = device.accuracy.metrology; + const notes = []; + + if (metrology === 'metrology') { + const mpe = effectiveMpe(device, req.diameterMm); + if (mpe === null) { + return { score: 45, confidence: 'low', mpe: null, notes: ['未公布 MPE_E0,精度按保守中位估计,待核实'], verified: false }; + } + if (tol === null) { + return { score: 70, confidence: 'medium', mpe, notes: ['未填目标允差,无法核算精度余量'], verified: true }; + } + const ratio = mpe / tol; + let score; + if (ratio <= 0.10) score = 100; + else if (ratio <= 0.20) score = 90; + else if (ratio <= 0.35) score = 75; + else if (ratio <= 0.50) score = 60; + else if (ratio <= 0.80) score = 40; + else score = 20; + notes.push('MPE_E0 约 ' + (Math.round(mpe * 100) / 100) + ' µm,为目标允差 ' + tol + ' µm 的 ' + + Math.round(ratio * 100) + '%'); + if (ratio > 0.10) { + notes.push('MPE/允差 高于 10%,不满足 ISO 14253-1 的判定不确定度前提,需降允差要求或改用更高精度方案'); + } + const evidence = device.evidence.find((e) => e.grade === 'A') || device.evidence[0]; + return { score, confidence: evidence && evidence.grade === 'A' ? 'high' : 'medium', mpe, notes, verified: !!(evidence && (evidence.grade === 'A' || evidence.grade === 'B')) }; + } + + // process-grade optical devices + const band = device.accuracy.measurableToleranceUm; + if (band) { + const [lo, hi] = band; + let score = 55; + if (tol !== null) { + if (tol >= lo && tol <= hi) score = 60; + else if (tol > hi) score = 70; + else score = 35; + } + notes.push('公开可测公差带 ' + lo + '–' + hi + ' µm(厂商口径,非 MPE)'); + notes.push('ISO 齿轮检测标准尚未定义光学方法,判定权须由企业规范或客户认可取得'); + return { score, confidence: 'medium', mpe: null, notes, verified: false }; + } + return { score: 30, confidence: 'low', mpe: null, notes: ['缺少可核对的精度指标,待核实'], verified: false }; +} + +/** Stability score 0..100 from temperature behaviour, base type and thermal gradient. */ +function scoreStability(device, req) { + const s = device.stability; + const notes = []; + let score = 40; + if (s.tempCompensated) { score += 20; notes.push('具备温度补偿'); } + if (s.base === '气浮') { score += 15; notes.push('气浮基身,热稳定性较好'); } + else if (s.base === '花岗岩') { score += 12; } + else if (s.base === '待核实') { score -= 5; notes.push('基身形式待核实'); } + if (s.tempRangeC && s.tempRangeC[1] - s.tempRangeC[0] >= 15) { score += 12; notes.push('标定温区宽(' + s.tempRangeC[0] + '–' + s.tempRangeC[1] + ' °C)'); } + else if (s.tempRangeC) { score += 5; } + else { score -= 5; notes.push('标定温区待核实'); } + if (s.tempGradient) { score += 8; notes.push(s.tempGradient); } + const wantStability = (num(req.environment.tempStabilityK) || 1) <= 0.5; + if (wantStability && !s.tempCompensated) { score -= 10; notes.push('现场温度稳定度要求高,该设备未声明温度补偿'); } + return { score: clamp(score, 0, 100), confidence: s.tempCompensated ? 'medium' : 'low', notes }; +} + +/** Fit score 0..100 from task coverage, throughput and required capability match. */ +function scoreFit(device, req) { + const notes = []; + let score = 50; + const cov = checkCoverage(device, req); + if (cov.pass && !cov.notes.length) { score += 25; notes.push('覆盖范围完整匹配'); } + else if (cov.pass) { score += 12; notes.push('覆盖范围匹配,部分参数待核实'); } + else { score -= 25; } + const jt = JUDGEMENT_TYPES[req.judgementType]; + const scen = (device.scenarios || []).join(' '); + if (jt && scen.includes(jt.label.slice(0, 4))) { score += 15; notes.push('适用场景直接匹配'); } + if (device.accuracy.metrology === 'metrology' && jt && !jt.requiresMetrology) { score += 10; notes.push('精度余量充足,可承担更高要求任务'); } + if (jt && jt.key === 'waviness-nvh' && device.method === 'non-contact') { score += 15; notes.push('非接触全场方案适合波纹度/NVH'); } + if (jt && jt.key === 'internal-structure' && /CT|射线/i.test(device.name + ' ' + (device.features || []).join(' '))) { score += 15; } + if (jt && jt.key === 'tool-metrology' && /共聚焦|HYBRID/i.test(device.name + ' ' + (device.features || []).join(' '))) { score += 15; } + const vol = num(req.annualVolume); + if (vol !== null && device.cycleTime && /秒/.test(device.cycleTime)) { + const secs = parseFloat(device.cycleTime.replace(/[^0-9.]/g, '')); + const perDay = Math.floor((8 * 3600) / secs); + if (vol / 365 <= perDay) { score += 10; notes.push('节拍约 ' + device.cycleTime + ',日产能满足年量 ' + vol + ' 件'); } + else { score -= 15; notes.push('节拍 ' + device.cycleTime + ' 难以覆盖年产 ' + vol + ' 件'); } + } + return { score: clamp(score, 0, 100), confidence: 'medium', notes }; +} + +/** Cost score 0..100. Price is 待核实 for every device, so this is a documented gap, not a fake number. */ +function scoreCost(device, req) { + const notes = []; + const budget = num(req.budget.amount); + if (device.price.value === null || device.price.value === undefined) { + notes.push('报价待核实(厂商询价制,无公开报价源)'); + const tier = device.budgetTierHint || null; + if (tier) notes.push('量级参考:' + tier); + return { score: 50, confidence: 'low', notes }; + } + if (budget === null) return { score: 50, confidence: 'low', notes: ['未设置预算上限'] }; + const ratio = device.price.value / budget; + const score = ratio <= 0.6 ? 100 : ratio <= 0.85 ? 85 : ratio <= 1.0 ? 70 : ratio <= 1.3 ? 45 : 20; + notes.push('报价 ' + device.price.value + ' ' + device.price.currency + ',占预算 ' + Math.round(ratio * 100) + '%'); + return { score, confidence: 'medium', notes }; +} + +/** Evaluate one device against one requirement set. */ +export function evaluateDevice(device, req) { + const coverage = checkCoverage(device, req); + const space = checkSpace(device, req); + const environment = checkEnvironment(device, req); + const principle = checkPrinciple(device, req); + const accuracy = scoreAccuracy(device, req); + const stability = scoreStability(device, req); + const fit = scoreFit(device, req); + const cost = scoreCost(device, req); + + const hardFailures = []; + if (!coverage.pass) hardFailures.push(...coverage.failures); + if (!space.pass) hardFailures.push(...space.failures); + if (!environment.pass) hardFailures.push(...environment.failures); + if (principle.status === 'mismatch') hardFailures.push('测量原理不匹配:无法承担本任务要求的判定类型'); + if (principle.status === 'complementary' && !coverage.pass) { + // still record coverage problems, it affects the complementary role too + } + + return { + id: device.id, + brand: device.brand, + model: device.model, + name: device.name, + method: device.method, + methodLabel: device.methodLabel, + role: device.role, + metrology: device.accuracy.metrology, + standard: device.accuracy.standard, + uncertaintyNote: device.accuracy.uncertaintyNote, + cycleTime: device.cycleTime, + price: device.price, + features: device.features, + scenarios: device.scenarios, + limits: device.limits, + evidence: device.evidence, + coverage, + space, + environment, + principle, + scores: { accuracy, stability, fit, cost }, + hardFailures, + routeRole: principle.role, + eligible: hardFailures.length === 0 && principle.role !== 'complementary', + complementary: principle.role === 'complementary', + verifiedFlag: device.evidence.some((e) => e.grade === 'A' || e.grade === 'B'), + pendingVerification: device.evidence.filter((e) => e.grade === 'C' || e.grade === 'D').length, + }; +} + +/** Composite ranking for a decision mode. Ineligible devices are ranked separately. */ +export function rankDevices(evaluations, modeKey) { + const mode = MODES[modeKey] || MODES.accuracy; + const w = mode.weights; + const scored = evaluations.map((e) => { + const total = e.scores.accuracy.score * w.accuracy + + e.scores.stability.score * w.stability + + e.scores.fit.score * w.fit + + e.scores.cost.score * w.cost; + return { ...e, composite: Math.round(total * 10) / 10, mode: mode.key, modeLabel: mode.label }; + }); + scored.sort((a, b) => { + if (a.eligible !== b.eligible) return a.eligible ? -1 : 1; + return b.composite - a.composite; + }); + return scored; +} + +/** Build the primary + auxiliary configuration list for the recommended device. */ +export function buildConfiguration(device, req, evaluations) { + const byId = new Map(evaluations.map((e) => [e.id, e])); + const primary = device; + + const site = []; + const envItems = []; + const aux = []; + + const s = primary.space; + const floorNeed = s.lengthMm && s.widthMm + ? Math.round((s.lengthMm * s.widthMm) / 1e6 * 10) / 10 + : null; + site.push({ + item: '计量室面积与布局', + spec: s.lengthMm && s.widthMm + ? '设备占地约 ' + (Math.round(s.lengthMm / 100) / 10) + ' × ' + (Math.round(s.widthMm / 100) / 10) + ' m(约 ' + floorNeed + ' m²),' + + '含操作与维修通道建议按 0.8 m 侧向裕量预留' + : '设备外形尺寸待核实,需向厂商索取三维包络与检修空间', + required: true, + basis: '设备手册尺寸(待核实)', + }); + site.push({ + item: '层高与吊装', + spec: s.heightMm + ? '设备高度 ' + s.heightMm + ' mm,需 ' + req.space.heightM + ' m 层高并预留吊装通道;门洞净宽 ≥ ' + req.space.doorWidthMm + ' mm' + : '设备高度与吊装需求待核实;门洞净宽按 ' + req.space.doorWidthMm + ' mm 预留', + required: true, + basis: '搬运与安装可行性', + }); + site.push({ + item: '地坪承重与隔振基础', + spec: '地坪承载 ≥ ' + req.space.loadKg + ' kg;' + (primary.stability.base === '气浮' + ? '气浮基身仍需独立平整基础,建议按设备自重 2 倍设计承重' + : '建议配置独立隔振基础与减振垫,隔离邻近车床与冲床振动'), + required: true, + basis: '振动与承重约束', + }); + site.push({ + item: '供电与气源', + spec: '专线供电 ≥ ' + req.space.powerKw + ' kW,含独立回路与浪涌保护;' + + (primary.method === 'non-contact' ? '蓝光/激光方案需注意环境光干扰与光学窗口清洁' : '触测方案需确认气浮气源压力等级与露点'), + required: true, + basis: '安装条件', + }); + + const tMin = primary.env.tempMinC; + const tMax = primary.env.tempMaxC; + envItems.push({ + item: '温度控制', + spec: tMin !== null && tMax !== null + ? '标定区间 ' + tMin + '–' + tMax + ' °C;目标 ' + req.environment.tempC + ' °C,' + + (req.environment.tempC < tMin || req.environment.tempC > tMax + ? '当前设定超出标定区间,需恒温舱补偿或重新标定' + : '落在标定区间内,建议加装独立恒温柜控制波动 ≤ ' + req.environment.tempStabilityK + ' K') + : '标定温度区间待核实;建议按 20 ± ' + req.environment.tempStabilityK + ' K 配置恒温环境', + required: true, + basis: 'MPE 温度条件', + }); + envItems.push({ + item: '湿度与露点', + spec: '相对湿度 ' + req.environment.humidityPct + '% ± 5%,气浮与气动系统需控制露点露化', + required: true, + basis: '气浮系统稳定性', + }); + envItems.push({ + item: '振动隔离', + spec: primary.env.vibrationLimitMms !== null + ? '设备允许振动速度上限 ' + primary.env.vibrationLimitMms + ' mm/s(峰-峰),需实测背景振动' + : '振动允差待核实;现场振动等级「' + req.environment.vibration + '」', + required: true, + basis: '设备振动允差', + }); + envItems.push({ + item: '洁净与光照', + spec: req.environment.cleanliness + ';' + (primary.method === 'non-contact' + ? '光学方案需避免直射光与强反射面,必要时加遮光罩' + : '触测方案需控制粉尘与切屑液污染花岗岩平台'), + required: true, + basis: '测量原理与环境适配', + }); + if (/CT|射线/i.test(primary.name)) { + envItems.push({ + item: '辐射安全', + spec: '射线屏蔽间、剂量监测、人员资质与辐射安全许可须先行落实', + required: true, + basis: '法规强制要求', + }); + } + + const isOptical = primary.method === 'non-contact'; + aux.push({ + item: '标准齿轮工件', + spec: 'DIN 3961/3962 标准齿轮 + BS ISO 18653 齿轮工件(NGML 与 PTB 联合研制)', + required: true, + basis: '溯源与量值比对', + }); + aux.push({ + item: '量值比对与 GR&R', + spec: '与现役接触式中心用同一标准件、同一评价口径做相关性试验;' + + (req.acceptance.requireGrR ? '需出具 GR&R 报告' : 'GR&R 未被要求(可在采购条款中补充)'), + required: req.acceptance.requireGrR, + basis: '验收指标', + }); + aux.push({ + item: '不确定度评估', + spec: req.acceptance.requireTraceability + ? '按 ISO/TS 15530-4 虚拟 CMM + 蒙特卡洛做不确定度评估,并索取该配置 MPE 报告' + : '未要求溯源评估(光学方案建议强制要求)', + required: req.acceptance.requireTraceability, + basis: 'ISO 14253-1 / ISO/TS 15530-4', + }); + aux.push({ + item: '第三方校准与资质证明', + spec: '需 PTB/DAkkS 或 CNAS 校准证书' + (primary.accuracy.standard !== '待核实' + ? ',以及 ' + primary.accuracy.standard + ' 等级证明' : ''), + required: req.acceptance.requireThirdPartyCalibration, + basis: '验收指标', + }); + if (isOptical) { + aux.push({ + item: '光学专项补充', + spec: '要求厂商提供齿顶/齿根多边形化误差与点间距数据,说明反转(reversal)补偿对几何误差的抵消效果', + required: true, + basis: '光学方案特有风险', + }); + } + aux.push({ + item: '统计与数据系统', + spec: '过程能力与 SPC 平台(QuickSPC / Gear AddOn 类),数据接口接入 PLM 或质量系统', + required: false, + basis: '运营需求', + }); + aux.push({ + item: '备件与耗材', + spec: '测针/样式库、扫描头校准件、标准件维护、易损件清单', + required: false, + basis: '运营需求', + }); + + const alternates = evaluations + .filter((e) => e.id !== primary.id && e.eligible) + .sort((a, b) => b.composite - a.composite) + .slice(0, 3) + .map((e) => ({ id: e.id, name: e.name, composite: e.composite, role: e.role })); + + // Complementary devices: excluded from the primary ranking, but each still carries a real + // task it can own in the same lab. They are listed as auxiliary roles, never dropped. + const complementary = evaluations + .filter((e) => e.complementary) + .sort((a, b) => b.composite - a.composite) + .map((e) => ({ + id: e.id, + name: e.name, + composite: e.composite, + role: e.role, + serves: (e.principle.notes[0] || '').replace('不承担本任务的主判定角色,可作为配套:', ''), + fitNotes: e.scores.fit.notes, + warnings: e.hardFailures, + })); + + const incompatible = evaluations + .filter((e) => !e.eligible && !e.complementary) + .map((e) => ({ id: e.id, name: e.name, reasons: e.hardFailures })); + + return { + primary: { id: primary.id, name: primary.name, brand: primary.brand, model: primary.model, role: primary.role }, + site, environment: envItems, aux, + alternates, complementary, incompatible, + }; +} + +/** Full analysis for a requirement set. */ +export function analyze(req, modeKey, deviceOverride) { + const list = deviceOverride && Array.isArray(deviceOverride) && deviceOverride.length + ? deviceOverride + : DEVICES; + const evaluations = list.map((d) => evaluateDevice(d, req)); + const ranked = rankDevices(evaluations, modeKey); + const eligible = ranked.filter((e) => e.eligible); + const best = eligible[0] || null; + const deviceById = new Map(list.map((d) => [d.id, d])); + const configuration = best ? buildConfiguration(deviceById.get(best.id), req, ranked) : null; + return { + mode: MODES[modeKey] || MODES.accuracy, + ranked, + eligibleCount: eligible.length, + configuration, + summary: { + total: ranked.length, + eligible: eligible.length, + complementary: ranked.filter((e) => e.complementary).length, + excluded: ranked.filter((e) => !e.eligible && !e.complementary).length, + topName: best ? best.name : null, + topScore: best ? best.composite : null, + }, + }; +} + +export { DEVICES, REFRESH_SOURCES }; diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/export.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/export.mjs new file mode 100644 index 00000000..e8baf28f --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/export.mjs @@ -0,0 +1,213 @@ +'use strict'; + +import { JUDGEMENT_TYPES, MODES } from './engine.mjs'; + +/** Escape for HTML text nodes and attribute values. */ +function esc(v) { + if (v === null || v === undefined) return ''; + return String(v) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +function fmt(n, digits) { + if (typeof n !== 'number' || !Number.isFinite(n)) return '—'; + return n.toFixed(digits === undefined ? 1 : digits); +} + +function scoreLabel(v) { + if (v === null || v === undefined) return '待核实'; + if (v >= 85) return '优'; + if (v >= 70) return '良'; + if (v >= 55) return '中'; + return '弱'; +} + +/** Build a standalone, self-contained HTML comparison sheet (no external assets). */ +export function buildHtmlReport(result, requirement, generatedAt) { + const cfg = result.configuration; + const jt = JUDGEMENT_TYPES[requirement.judgementType] || { label: requirement.judgementType }; + const rows = result.ranked; + + const deviceRows = rows.map((r) => { + const role = r.eligible ? '主设备候选' : (r.complementary ? '配套设备' : '不满足硬约束'); + const badges = []; + if (r.eligible) badges.push('合格'); + if (r.complementary) badges.push('配套'); + if (!r.eligible && !r.complementary) badges.push('排除'); + if (r.verifiedFlag) badges.push('A/B 级证据'); + else badges.push('待核实'); + const reasons = r.hardFailures.length + ? '
    ' + r.hardFailures.map((x) => '
  • ' + esc(x) + '
  • ').join('') + '
' + : '—'; + const serves = r.principle.notes && r.principle.notes.length ? r.principle.notes.join(';') : '—'; + return '' + + '' + esc(r.brand) + '
' + esc(r.model) + '
' + badges.join(' ') + '' + + '' + esc(r.methodLabel) + '
' + esc(role) + '' + + '' + esc(r.standard || '—') + '
' + esc(r.uncertaintyNote || '') + '' + + '' + esc(r.scores.accuracy.score) + ' (' + scoreLabel(r.scores.accuracy.score) + ')' + + '' + esc(r.scores.stability.score) + ' (' + scoreLabel(r.scores.stability.score) + ')' + + '' + esc(r.scores.fit.score) + '' + + '' + esc(r.scores.cost.score) + '' + + '' + esc(r.composite) + '' + + '' + serves + reasons + '' + + ''; + }).join(''); + + const listSection = (title, items) => items && items.length + ? '

' + esc(title) + '

' + + items.map((i) => '').join('') + + '
' + esc(i.item) + '' + esc(i.spec) + + '
依据:' + esc(i.basis) + (i.required ? ' · 必备' : ' · 建议') + '
' + : ''; + + const altRows = (cfg.alternates || []).map((a) => + '
  • ' + esc(a.name) + '(综合分 ' + esc(a.composite) + ')— ' + esc(a.role) + '
  • ').join(''); + + const compRows = (cfg.complementary || []).map((c) => + '
  • ' + esc(c.name) + ' — 可承担:' + esc(c.serves) + + (c.warnings && c.warnings.length ? '
    约束提示:' + esc(c.warnings.join(';')) + '
    ' : '') + + '
  • ').join(''); + + const exclRows = (cfg.incompatible || []).map((c) => + '
  • ' + esc(c.name) + '
    ' + esc(c.reasons.join(';')) + '
  • ').join(''); + + return '\n' + + '' + + '' + + '' + esc(requirement.projectName) + ' · 齿轮测量方案对比表' + + '' + + '

    ' + esc(requirement.projectName) + ' · 齿轮测量方案对比表

    ' + + '

    ' + esc(requirement.gearClass) + ' · 判定类型:' + esc(jt.label) + ' · 决策模式:' + esc(result.mode.label) + '

    ' + + '
    ' + + '
    模数' + esc(requirement.moduleMm) + ' mm
    ' + + '
    外径' + esc(requirement.diameterMm) + ' mm
    ' + + '
    齿宽' + esc(requirement.faceWidthMm) + ' mm
    ' + + '
    目标允差' + esc(requirement.toleranceUm) + ' µm
    ' + + '
    年产' + esc(requirement.annualVolume) + ' 件
    ' + + '
    预算' + esc(requirement.budget.amount) + ' ' + esc(requirement.budget.currency) + '
    ' + + '
    实验室' + esc(requirement.space.lengthM) + '×' + esc(requirement.space.widthM) + '×' + esc(requirement.space.heightM) + ' m
    ' + + '
    温度' + esc(requirement.environment.tempC) + ' °C ±' + esc(requirement.environment.tempStabilityK) + ' K
    ' + + '
    ' + + '
    口径声明:本表由内置核实库生成。证据分级 A=原厂一手页面,B=权威二手,' + + 'C=经销商转述,D=推断或待核实。价格一律为待核实(厂商询价制,无公开报价源)。' + + '标称 MPE 不等同于 ISO 14253-1 的判定不确定度,最终结论须以实际配置的校准与比对报告为准。
    ' + + '

    一、设备对比表(' + esc(result.summary.total) + ' 台:合格 ' + + esc(result.summary.eligible) + ' / 配套 ' + esc(result.summary.complementary) + ' / 排除 ' + + esc(result.summary.excluded) + ')

    ' + + '' + + '' + + deviceRows + '
    设备测量原理 / 角色精度与标准精度分稳定性分适配分成本分综合分说明与约束
    ' + + '

    二、推荐主设备

    ' + + (cfg.primary + ? '

    ' + esc(cfg.primary.name) + ' — ' + esc(cfg.primary.role) + '

    ' + : '

    无满足全部硬约束的设备,需放宽约束或补充候选。

    ') + + (altRows ? '

    备选

      ' + altRows + '
    ' : '') + + '
    ' + + '

    三、配套设备角色

    ' + + (compRows ? '
      ' + compRows + '
    ' : '

    无

    ') + + '
    ' + + listSection('四、场地配置清单', cfg.site) + + listSection('五、环境配置清单', cfg.environment) + + listSection('六、辅助设备与验收要求', cfg.aux) + + (exclRows ? '

    七、不满足硬约束的设备

      ' + exclRows + '
    ' : '') + + '
    生成时间:' + esc(generatedAt) + ' · 决策模式:' + esc(result.mode.label) + + '(精度 ' + esc(result.mode.weights.accuracy) + ' / 稳定性 ' + esc(result.mode.weights.stability) + + ' / 适配 ' + esc(result.mode.weights.fit) + ' / 成本 ' + esc(result.mode.weights.cost) + ')
    ' + + ''; +} + +/** Markdown twin of the HTML report. */ +export function buildMarkdownReport(result, requirement, generatedAt) { + const cfg = result.configuration; + const jt = JUDGEMENT_TYPES[requirement.judgementType] || { label: requirement.judgementType }; + const L = []; + L.push('# ' + requirement.projectName + ' · 齿轮测量方案对比表'); + L.push(''); + L.push('- 判定类型:' + jt.label); + L.push('- 决策模式:' + result.mode.label); + L.push('- 测量对象:' + requirement.gearClass + + ',模数 ' + requirement.moduleMm + ' mm,外径 ' + requirement.diameterMm + ' mm,齿宽 ' + requirement.faceWidthMm + ' mm'); + L.push('- 目标允差:' + requirement.toleranceUm + ' µm;年产 ' + requirement.annualVolume + ' 件'); + L.push('- 预算:' + requirement.budget.amount + ' ' + requirement.budget.currency + + ';实验室 ' + requirement.space.lengthM + '×' + requirement.space.widthM + '×' + requirement.space.heightM + ' m'); + L.push('- 环境:' + requirement.environment.tempC + ' °C ±' + requirement.environment.tempStabilityK + + ' K,湿度 ' + requirement.environment.humidityPct + '%,振动「' + requirement.environment.vibration + '」'); + L.push(''); + L.push('> 口径声明:证据分级 A=原厂一手页面,B=权威二手,C=经销商转述,D=推断或待核实。' + + '价格一律待核实(厂商询价制)。标称 MPE 不等同于 ISO 14253-1 判定不确定度。'); + L.push(''); + L.push('## 一、设备对比表'); + L.push(''); + L.push('| 设备 | 原理 / 角色 | 精度与标准 | 精度分 | 稳定性分 | 适配分 | 成本分 | 综合分 | 说明与约束 |'); + L.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- |'); + for (const r of result.ranked) { + const role = r.eligible ? '主设备候选' : (r.complementary ? '配套' : '排除'); + const notes = r.principle.notes.join(';'); + const fails = r.hardFailures.length ? ';约束:' + r.hardFailures.join(';') : ''; + L.push('| ' + [r.brand + ' ' + r.model, r.methodLabel + ' / ' + role, + (r.standard || '—') + ';' + (r.uncertaintyNote || ''), + r.scores.accuracy.score, r.scores.stability.score, r.scores.fit.score, r.scores.cost.score, + '**' + r.composite + '**', (notes + fails || '—')].join(' | ') + ' |'); + } + L.push(''); + L.push('## 二、推荐主设备'); + L.push(''); + L.push(cfg.primary ? '**' + cfg.primary.name + '** — ' + cfg.primary.role : '无满足全部硬约束的设备'); + if (cfg.alternates.length) { + L.push(''); + L.push('备选:'); + for (const a of cfg.alternates) L.push('- ' + a.name + '(综合分 ' + a.composite + ')— ' + a.role); + } + L.push(''); + L.push('## 三、配套设备角色'); + L.push(''); + if (cfg.complementary.length) { + for (const c of cfg.complementary) { + L.push('- **' + c.name + '** — 可承担:' + c.serves + + (c.warnings.length ? ';约束提示:' + c.warnings.join(';') : '')); + } + } else L.push('- 无'); + const sec = (title, items) => { + L.push(''); + L.push('## ' + title); + L.push(''); + L.push('| 项目 | 要求 | 依据 |'); + L.push('| --- | --- | --- |'); + for (const i of items) L.push('| ' + i.item + ' | ' + i.spec + ' | ' + i.basis + (i.required ? '(必备)' : '(建议)') + ' |'); + }; + sec('四、场地配置清单', cfg.site); + sec('五、环境配置清单', cfg.environment); + sec('六、辅助设备与验收要求', cfg.aux); + if (cfg.incompatible.length) { + L.push(''); + L.push('## 七、不满足硬约束的设备'); + L.push(''); + for (const c of cfg.incompatible) L.push('- ' + c.name + ':' + c.reasons.join(';')); + } + L.push(''); + L.push('---'); + L.push('生成时间:' + generatedAt + ' · 决策模式:' + result.mode.label + + '(精度 ' + result.mode.weights.accuracy + ' / 稳定性 ' + result.mode.weights.stability + + ' / 适配 ' + result.mode.weights.fit + ' / 成本 ' + result.mode.weights.cost + ')'); + return L.join('\n'); +} + +export { MODES }; diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/miniapp-api.ts b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/miniapp-api.ts new file mode 100644 index 00000000..5276c6f8 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/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/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/refresh.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/refresh.mjs new file mode 100644 index 00000000..e1240869 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/refresh.mjs @@ -0,0 +1,134 @@ +'use strict'; + +import { REFRESH_SOURCES } from './devices.mjs'; + +/** + * Optional online refresh of vendor specification pages. + * + * Contract with the user (confirmed before authoring): + * The built-in verified library is authoritative. Refresh is a best-effort extra pass that + * never replaces built-in values; it returns what the live page says so a human can judge. + * If a page cannot be read, the built-in value stands and the failure is reported. + * + * Vendor deep links drift (observed 404/403 during authoring), so every device declares a + * candidate list and refresh reports exactly which candidate succeeded or failed. + */ + +const TIMEOUT_MS = 12000; +const MAX_BYTES = 4 * 1024 * 1024; + +function stripHtml(html) { + return html + .replace(//gi, ' ') + .replace(//gi, ' ') + .replace(/<[^>]+>/g, ' ') + .replace(/ /gi, ' ') + .replace(/&/gi, '&') + .replace(/&#(\d+);/g, (_m, d) => String.fromCharCode(Number(d))) + .replace(/\s+/g, ' ') + .trim(); +} + +const SPEC_KEYWORDS = [ + /MPE[^.]{0,80}\d+(?:[.,]\d+)?\s*(?:µm|μm|um)/i, + /\d+(?:[.,]\d+)?\s*(?:µm|μm|um)\s*\+\s*L\/\d+/i, + /(?:accuracy|precision|repeatability|uncertainty)[^.]{0,90}\d+(?:[.,]\d+)?\s*(?:µm|μm|um)/i, + /VDI\s*\/?\s*VDE\s*2612[^.]{0,60}/i, + /ISO\s*10360[^.]{0,50}/i, + /ISO\s*1328[^.]{0,40}/i, + /PTB[^.]{0,60}/i, + /module\s*(?:range)?[^.]{0,60}\d+(?:[.,]\d+)?\s*mm/i, + /(?:outer|ring|maximum|max)[^.]{0,40}diameter[^.]{0,40}\d+\s*mm/i, + /cycle\s*time[^.]{0,50}\d+\s*(?:second|sec|s)\b/i, + /\d+\s*(?:s|seconds)\s*per\s*(?:part|piece)/i, + /ISO\s*14253[^.]{0,50}/i, +]; + +function extractEvidence(text) { + const hits = []; + const seen = new Set(); + for (const re of SPEC_KEYWORDS) { + const m = re.exec(text); + if (!m) continue; + const snippet = m[0].trim(); + const key = snippet.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + hits.push(snippet); + if (hits.length >= 8) break; + } + return hits; +} + +async function fetchOne(url) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); + try { + const res = await fetch(url, { + redirect: 'follow', + signal: controller.signal, + headers: { + 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) MiniApp-GearSelector/1.0', + accept: 'text/html,application/xhtml+xml', + }, + }); + if (!res.ok) { + return { url, ok: false, status: res.status, error: 'HTTP ' + res.status, hits: [] }; + } + const contentType = res.headers.get('content-type') || ''; + if (!/text\/html|text\/plain/i.test(contentType)) { + return { url, ok: false, status: res.status, error: '非 HTML 内容(' + contentType.split(';')[0] + '),未解析', hits: [] }; + } + const buf = Buffer.from(await res.arrayBuffer()); + if (buf.length > MAX_BYTES) { + return { url, ok: false, status: res.status, error: '页面过大,未解析', hits: [] }; + } + const text = stripHtml(buf.toString('utf8')); + return { url, ok: true, status: res.status, hits: extractEvidence(text), bytes: buf.length }; + } catch (error) { + const msg = error && error.name === 'AbortError' ? '请求超时' : (error && error.message) || '网络错误'; + return { url, ok: false, status: 0, error: msg, hits: [] }; + } finally { + clearTimeout(timer); + } +} + +/** Refresh one device against its declared vendor pages. Never throws. */ +export async function refreshDevice(deviceId) { + const candidates = REFRESH_SOURCES[deviceId] || []; + if (!candidates.length) { + return { deviceId, ok: false, reason: '该设备未登记可刷新的厂商页面', attempts: [] }; + } + const attempts = []; + for (const url of candidates) { + const r = await fetchOne(url); + attempts.push(r); + if (r.ok) { + return { + deviceId, + ok: true, + url, + status: r.status, + hits: r.hits, + attempts, + note: r.hits.length + ? '已抓取到规格片段,请人工比对;内置核实库的值不会被覆盖' + : '页面可访问,但未匹配到规格关键词,可能是改版或需人工查看', + }; + } + } + return { + deviceId, + ok: false, + reason: '全部候选页面读取失败,已保留内置核实库的值', + attempts, + }; +} + +export async function refreshMany(deviceIds) { + const out = []; + for (const id of deviceIds) { + out.push(await refreshDevice(id)); + } + return out; +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/server.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/server.mjs new file mode 100644 index 00000000..2d302e00 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/server.mjs @@ -0,0 +1,346 @@ +// @ts-check + +import { readFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { join, extname } from 'node:path'; + +import { DEVICES, REFRESH_SOURCES } from './devices.mjs'; +import { analyze, defaultRequirement, JUDGEMENT_TYPES, MODES } from './engine.mjs'; +import { readState, writeState } from './store.mjs'; +import { refreshDevice } from './refresh.mjs'; +import { buildHtmlReport, buildMarkdownReport } from './export.mjs'; + +/** @typedef {import('./miniapp-api.js').MiniAppContext} MiniAppContext */ +/** @typedef {import('./miniapp-api.js').MiniAppLifecycle} MiniAppLifecycle */ + +const SURFACE_PATH = '/dashboard'; +const CLIENT_DIR = 'miniapp/client'; + +const MIME = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', +}; + +function sendJson(response, status, payload) { + const body = JSON.stringify(payload); + response.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'content-length': Buffer.byteLength(body), + 'cache-control': 'no-store', + }); + response.end(body); +} + +function sendText(response, status, body, contentType) { + response.writeHead(status, { + 'content-type': contentType || 'text/plain; charset=utf-8', + 'content-length': Buffer.byteLength(body), + 'cache-control': 'no-store', + }); + response.end(body); +} + +async function readBody(request, limitBytes) { + const chunks = []; + let total = 0; + for await (const chunk of request) { + total += chunk.length; + if (total > limitBytes) throw new Error('请求体过大'); + chunks.push(chunk); + } + if (!total) return {}; + const raw = Buffer.concat(chunks).toString('utf8'); + try { + const parsed = JSON.parse(raw); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { + throw new Error('请求体不是合法 JSON'); + } +} + +/** Merge a stored requirement with a client payload; unknown keys are dropped. */ +function sanitizeRequirement(input) { + const base = defaultRequirement(); + if (!input || typeof input !== 'object') return base; + const r = { ...base }; + const str = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null); + const num = (v, lo, hi) => { + const n = Number(v); + if (!Number.isFinite(n)) return null; + return Math.min(hi, Math.max(lo, n)); + }; + + const s = str(input.projectName, 80); + if (s) r.projectName = s; + const g = str(input.gearClass, 80); + if (g) r.gearClass = g; + if (typeof input.judgementType === 'string' && JUDGEMENT_TYPES[input.judgementType]) { + r.judgementType = input.judgementType; + } + const m = num(input.moduleMm, 0.05, 100); if (m !== null) r.moduleMm = m; + const d = num(input.diameterMm, 1, 3000); if (d !== null) r.diameterMm = d; + const f = num(input.faceWidthMm, 1, 1000); if (f !== null) r.faceWidthMm = f; + const t = num(input.toleranceUm, 0.1, 500); if (t !== null) r.toleranceUm = t; + const v = num(input.annualVolume, 0, 10000000); if (v !== null) r.annualVolume = v; + if (typeof input.needsFinalAcceptance === 'boolean') r.needsFinalAcceptance = input.needsFinalAcceptance; + if (Array.isArray(input.methods)) { + const methods = input.methods.filter((x) => ['contact', 'non-contact', 'hybrid'].includes(x)); + if (methods.length) r.methods = methods; + } + + const sp = input.space || {}; + r.space = { + lengthM: num(sp.lengthM, 1, 100) ?? r.space.lengthM, + widthM: num(sp.widthM, 1, 100) ?? r.space.widthM, + heightM: num(sp.heightM, 1.5, 30) ?? r.space.heightM, + loadKg: num(sp.loadKg, 100, 100000) ?? r.space.loadKg, + powerKw: num(sp.powerKw, 0.5, 500) ?? r.space.powerKw, + doorWidthMm: num(sp.doorWidthMm, 300, 5000) ?? r.space.doorWidthMm, + }; + + const en = input.environment || {}; + r.environment = { + tempC: num(en.tempC, -10, 60) ?? r.environment.tempC, + tempStabilityK: num(en.tempStabilityK, 0.1, 10) ?? r.environment.tempStabilityK, + humidityPct: num(en.humidityPct, 5, 95) ?? r.environment.humidityPct, + vibration: ['低', '中', '高'].includes(en.vibration) ? en.vibration : r.environment.vibration, + cleanliness: str(en.cleanliness, 30) || r.environment.cleanliness, + }; + + const bu = input.budget || {}; + r.budget = { + amount: num(bu.amount, 0, 1000000000) ?? r.budget.amount, + currency: str(bu.currency, 8) || r.budget.currency, + includesInstallation: typeof bu.includesInstallation === 'boolean' ? bu.includesInstallation : r.budget.includesInstallation, + }; + + const ac = input.acceptance || {}; + r.acceptance = { + mpeRequired: typeof ac.mpeRequired === 'boolean' ? ac.mpeRequired : r.acceptance.mpeRequired, + uncertaintyRatio: num(ac.uncertaintyRatio, 0.01, 1) ?? r.acceptance.uncertaintyRatio, + requireTraceability: typeof ac.requireTraceability === 'boolean' ? ac.requireTraceability : r.acceptance.requireTraceability, + requireGrR: typeof ac.requireGrR === 'boolean' ? ac.requireGrR : r.acceptance.requireGrR, + requireThirdPartyCalibration: typeof ac.requireThirdPartyCalibration === 'boolean' ? ac.requireThirdPartyCalibration : r.acceptance.requireThirdPartyCalibration, + notes: str(ac.notes, 400) || r.acceptance.notes, + }; + return r; +} + +/** Apply the method filter before ranking. */ +function filterByMethod(evaluations, methods) { + if (!Array.isArray(methods) || !methods.length) return evaluations; + return evaluations.filter((e) => methods.includes(e.method)); +} + +/** + * @param {MiniAppContext} context + * @returns {Promise} + */ +export async function start(context) { + const clientRoot = join(context.pluginRoot, CLIENT_DIR); + + const server = createServer((request, response) => { + handle(context, clientRoot, request, response).catch((error) => { + context.logger.error('miniapp.request.failed', { message: String(error && error.message) }); + if (!response.headersSent) { + sendJson(response, 500, { error: 'internal_error', message: '服务内部错误' }); + } else { + response.end(); + } + }); + }); + + await listen(server, context.listen.host, context.listen.port); + context.logger.info('miniapp.runtime.listening'); + if (typeof context.onListening === 'function') { + const address = server.address(); + if (address && typeof address === 'object') context.onListening(address.port); + } + + let disposed = false; + const dispose = async () => { + if (disposed) return; + disposed = true; + context.signal.removeEventListener('abort', onAbort); + await close(server); + }; + const onAbort = () => { void dispose(); }; + context.signal.addEventListener('abort', onAbort, { once: true }); + if (context.signal.aborted) await dispose(); + + return { dispose }; +} + +async function handle(context, clientRoot, request, response) { + const url = new URL(request.url ?? '/', 'http://miniapp.local'); + const path = url.pathname; + const method = request.method ?? 'GET'; + + if (method === 'GET' && (path === SURFACE_PATH || path === '/' || path === '/index.html')) { + const html = await readFile(join(clientRoot, 'index.html'), 'utf8'); + sendText(response, 200, html, MIME['.html']); + return; + } + + if (method === 'GET' && (path === '/app.css' || path === '/app.js')) { + const file = path === '/app.css' ? 'app.css' : 'app.js'; + const body = await readFile(join(clientRoot, file), 'utf8'); + sendText(response, 200, body, MIME[extname(file)]); + return; + } + + if (method === 'GET' && path === '/api/bootstrap') { + const state = await readState(context.dataDir); + sendJson(response, 200, { + devices: DEVICES, + modes: MODES, + judgementTypes: JUDGEMENT_TYPES, + defaultRequirement: defaultRequirement(), + storedRequirements: state.state.requirements, + overrides: state.state.overrides, + refreshedAt: state.state.refreshedAt, + stateError: state.error, + evidenceRetrievedAt: '2026-11-30', + }); + return; + } + + if (method === 'POST' && path === '/api/analyze') { + let body; + try { + body = await readBody(request, 512 * 1024); + } catch (error) { + sendJson(response, 400, { error: 'bad_request', message: String(error.message) }); + return; + } + const requirement = sanitizeRequirement(body.requirement); + const mode = typeof body.mode === 'string' && MODES[body.mode] ? body.mode : 'accuracy'; + const result = analyze(requirement, mode); + result.ranked = filterByMethod(result.ranked, requirement.methods); + sendJson(response, 200, { requirement, mode, result, generatedAt: new Date().toISOString() }); + return; + } + + if (method === 'POST' && path === '/api/requirements') { + let body; + try { + body = await readBody(request, 512 * 1024); + } catch (error) { + sendJson(response, 400, { error: 'bad_request', message: String(error.message) }); + return; + } + const requirement = sanitizeRequirement(body.requirement); + const mode = typeof body.mode === 'string' && MODES[body.mode] ? body.mode : 'accuracy'; + const state = await readState(context.dataDir); + if (state.error) { + sendJson(response, 500, { error: 'state_corrupt', message: state.error }); + return; + } + const id = typeof body.id === 'string' && body.id ? body.id : 'req-' + Date.now().toString(36); + const record = { id, requirement, mode, savedAt: new Date().toISOString() }; + const list = state.state.requirements.filter((r) => r.id !== id); + list.push(record); + state.state.requirements = list; + await writeState(context.dataDir, state.state); + sendJson(response, 200, { ok: true, record, count: list.length }); + return; + } + + if (method === 'GET' && path === '/api/requirements') { + const state = await readState(context.dataDir); + sendJson(response, 200, { requirements: state.state.requirements, error: state.error }); + return; + } + + if (method === 'DELETE' && path.startsWith('/api/requirements/')) { + const id = decodeURIComponent(path.slice('/api/requirements/'.length)); + const state = await readState(context.dataDir); + state.state.requirements = state.state.requirements.filter((r) => r.id !== id); + await writeState(context.dataDir, state.state); + sendJson(response, 200, { ok: true, count: state.state.requirements.length }); + return; + } + + if (method === 'POST' && path === '/api/refresh') { + let body; + try { + body = await readBody(request, 64 * 1024); + } catch (error) { + sendJson(response, 400, { error: 'bad_request', message: String(error.message) }); + return; + } + const ids = Array.isArray(body.deviceIds) + ? body.deviceIds.filter((x) => typeof x === 'string' && REFRESH_SOURCES[x]).slice(0, 4) + : []; + if (!ids.length) { + sendJson(response, 400, { error: 'bad_request', message: '未指定可刷新的设备' }); + return; + } + const results = []; + for (const id of ids) results.push(await refreshDevice(id)); + const state = await readState(context.dataDir); + state.state.refreshedAt = new Date().toISOString(); + await writeState(context.dataDir, state.state); + sendJson(response, 200, { ok: true, results, refreshedAt: state.state.refreshedAt }); + return; + } + + if (method === 'POST' && path === '/api/export') { + let body; + try { + body = await readBody(request, 512 * 1024); + } catch (error) { + sendJson(response, 400, { error: 'bad_request', message: String(error.message) }); + return; + } + const requirement = sanitizeRequirement(body.requirement); + const mode = typeof body.mode === 'string' && MODES[body.mode] ? body.mode : 'accuracy'; + const result = analyze(requirement, mode); + result.ranked = filterByMethod(result.ranked, requirement.methods); + const stamp = new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-'); + const title = (requirement.projectName || 'gear-selection').replace(/[^\u4e00-\u9fa5A-Za-z0-9_-]/g, '_'); + const format = body.format === 'markdown' ? 'markdown' : 'html'; + const content = format === 'markdown' + ? buildMarkdownReport(result, requirement, new Date().toLocaleString('zh-CN')) + : buildHtmlReport(result, requirement, new Date().toLocaleString('zh-CN')); + sendJson(response, 200, { + ok: true, + format, + filename: title + '-' + mode + '-' + stamp + (format === 'markdown' ? '.md' : '.html'), + mime: format === 'markdown' ? 'text/markdown; charset=utf-8' : 'text/html; charset=utf-8', + content, + }); + return; + } + + if (method === 'GET' && path === '/api/device') { + const id = url.searchParams.get('id') || ''; + const device = DEVICES.find((d) => d.id === id); + if (!device) { + sendJson(response, 404, { error: 'not_found' }); + return; + } + sendJson(response, 200, { device }); + return; + } + + sendJson(response, 404, { error: 'not_found', path }); +} + +function listen(server, host, port) { + return new Promise((resolve, reject) => { + const onError = (error) => reject(error); + server.once('error', onError); + server.listen(port, host, () => { + server.off('error', onError); + resolve(); + }); + }); +} + +function close(server) { + return new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + }); +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/store.mjs b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/store.mjs new file mode 100644 index 00000000..debb4729 --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/miniapp/node/store.mjs @@ -0,0 +1,71 @@ +'use strict'; + +import { readFile, writeFile, mkdir, rename, unlink } from 'node:fs/promises'; +import { join } from 'node:path'; + +/** + * Durable store under the Host-provided dataDir. + * Writes are atomic: temp file in the same directory, then rename over the target. + * A corrupt or unreadable file is preserved (renamed aside) and reported, never silently reset. + */ + +const STATE_FILE = 'selection-state.json'; + +async function ensureDir(dir) { + await mkdir(dir, { recursive: true }); +} + +export async function readState(dataDir) { + const file = join(dataDir, STATE_FILE); + try { + const raw = await readFile(file, 'utf8'); + const parsed = JSON.parse(raw); + return { + ok: true, + state: { + requirements: Array.isArray(parsed.requirements) ? parsed.requirements : [], + overrides: parsed.overrides && typeof parsed.overrides === 'object' ? parsed.overrides : {}, + refreshedAt: parsed.refreshedAt || null, + notes: typeof parsed.notes === 'string' ? parsed.notes : '', + }, + error: null, + }; + } catch (error) { + if (error && error.code === 'ENOENT') { + return { ok: true, state: { requirements: [], overrides: {}, refreshedAt: null, notes: '' }, error: null }; + } + // Corrupt file: keep the original for diagnosis, do not overwrite it silently. + const salvage = file + '.corrupt-' + Date.now(); + try { + await rename(file, salvage); + } catch { + /* keep going; the caller still gets the parse error below */ + } + return { + ok: false, + state: { requirements: [], overrides: {}, refreshedAt: null, notes: '' }, + error: '状态文件损坏,已保留为 ' + STATE_FILE + '.corrupt-*,请检查后重新录入需求', + salvage, + }; + } +} + +export async function writeState(dataDir, state) { + await ensureDir(dataDir); + const file = join(dataDir, STATE_FILE); + const tmp = file + '.tmp-' + process.pid + '-' + Date.now(); + const payload = JSON.stringify(state, null, 2); + await writeFile(tmp, payload, 'utf8'); + await rename(tmp, file); + return true; +} + +export async function clearState(dataDir) { + const file = join(dataDir, STATE_FILE); + try { + await unlink(file); + } catch (error) { + if (!error || error.code !== 'ENOENT') throw error; + } + return true; +} diff --git a/plugins/tlk1973/tlk1973-gear-measurement-selector/package.json b/plugins/tlk1973/tlk1973-gear-measurement-selector/package.json new file mode 100644 index 00000000..aab6b8dc --- /dev/null +++ b/plugins/tlk1973/tlk1973-gear-measurement-selector/package.json @@ -0,0 +1,6 @@ +{ + "mcode": { + "schemaVersion": 2, + "miniApp": "./miniapp/miniapp.json" + } +}