From 9fd2c2b8f98a73d17e28dcac6e7468bf274cfcac Mon Sep 17 00:00:00 2001 From: Dr_rOot Date: Mon, 12 Oct 2026 07:22:53 +0800 Subject: [PATCH] feat(operations): add declarative plugin operations and scaffolding --- README.md | 18 +- README.zh-CN.md | 10 +- docs/operations.md | 509 +++++++++++++++++ docs/operations.zh-CN.md | 325 +++++++++++ examples/media-merge/README.md | 115 ++++ examples/media-merge/README.zh-CN.md | 63 +++ examples/media-merge/locales/en-US.json | 26 + examples/media-merge/locales/zh-CN.json | 26 + examples/media-merge/motrix-plugin.json | 224 ++++++++ examples/media-merge/src/index.ts | 36 ++ examples/media-merge/tsconfig.json | 13 + examples/text-tools/README.md | 124 +++++ examples/text-tools/README.zh-CN.md | 74 +++ examples/text-tools/locales/en-US.json | 19 + examples/text-tools/locales/zh-CN.json | 19 + examples/text-tools/motrix-plugin.json | 181 +++++++ examples/text-tools/src/index.ts | 19 + examples/text-tools/tsconfig.json | 13 + packages/create-motrix-plugin/README.md | 11 + packages/plugin-api/README.md | 8 +- packages/plugin-api/src/virtual-module.d.ts | 47 ++ packages/plugin-cli/README.md | 16 +- .../src/bin/create-motrix-plugin.ts | 14 +- packages/plugin-cli/src/bin/motrix-plugin.ts | 7 +- packages/plugin-cli/src/commands/init.ts | 23 +- .../src/templates/operation/.gitignore.tpl | 8 + .../src/templates/operation/README.md.tpl | 94 ++++ .../templates/operation/README.zh-CN.md.tpl | 57 ++ .../operation/esbuild.config.mjs.tpl | 13 + .../operation/locales/en-US.json.tpl | 19 + .../operation/locales/zh-CN.json.tpl | 19 + .../operation/motrix-plugin.json.tpl | 181 +++++++ .../src/templates/operation/package.json.tpl | 23 + .../src/templates/operation/src/index.ts.tpl | 19 + .../src/templates/operation/tsconfig.json.tpl | 14 + packages/plugin-cli/tests/cli.test.ts | 61 +++ .../tests/operation-template.test.ts | 125 +++++ packages/plugin-manifest-schema/README.md | 9 +- packages/plugin-manifest-schema/src/index.ts | 2 + .../src/operation-ui.ts | 151 ++++++ .../plugin-manifest-schema/src/operations.ts | 512 ++++++++++++++++++ packages/plugin-manifest-schema/src/schema.ts | 30 +- .../tests/operations.test.ts | 271 +++++++++ 43 files changed, 3516 insertions(+), 32 deletions(-) create mode 100644 docs/operations.md create mode 100644 docs/operations.zh-CN.md create mode 100644 examples/media-merge/README.md create mode 100644 examples/media-merge/README.zh-CN.md create mode 100644 examples/media-merge/locales/en-US.json create mode 100644 examples/media-merge/locales/zh-CN.json create mode 100644 examples/media-merge/motrix-plugin.json create mode 100644 examples/media-merge/src/index.ts create mode 100644 examples/media-merge/tsconfig.json create mode 100644 examples/text-tools/README.md create mode 100644 examples/text-tools/README.zh-CN.md create mode 100644 examples/text-tools/locales/en-US.json create mode 100644 examples/text-tools/locales/zh-CN.json create mode 100644 examples/text-tools/motrix-plugin.json create mode 100644 examples/text-tools/src/index.ts create mode 100644 examples/text-tools/tsconfig.json create mode 100644 packages/plugin-cli/src/templates/operation/.gitignore.tpl create mode 100644 packages/plugin-cli/src/templates/operation/README.md.tpl create mode 100644 packages/plugin-cli/src/templates/operation/README.zh-CN.md.tpl create mode 100644 packages/plugin-cli/src/templates/operation/esbuild.config.mjs.tpl create mode 100644 packages/plugin-cli/src/templates/operation/locales/en-US.json.tpl create mode 100644 packages/plugin-cli/src/templates/operation/locales/zh-CN.json.tpl create mode 100644 packages/plugin-cli/src/templates/operation/motrix-plugin.json.tpl create mode 100644 packages/plugin-cli/src/templates/operation/package.json.tpl create mode 100644 packages/plugin-cli/src/templates/operation/src/index.ts.tpl create mode 100644 packages/plugin-cli/src/templates/operation/tsconfig.json.tpl create mode 100644 packages/plugin-cli/tests/operation-template.test.ts create mode 100644 packages/plugin-manifest-schema/src/operation-ui.ts create mode 100644 packages/plugin-manifest-schema/src/operations.ts create mode 100644 packages/plugin-manifest-schema/tests/operations.test.ts diff --git a/README.md b/README.md index b056cc9..72bbabc 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,20 @@ inside a sandbox — no Node.js APIs, no direct file or network access. Everything reaches the outside world through capabilities you declare in the manifest, and users see exactly what you asked for at install time. +## Plugin operations (unreleased) + +The development operations protocol lets a plugin declare a host-rendered form, +entry points and a sandbox handler. No React or renderer code is required. +Start with the [authoring guide](docs/operations.md), then the complete +[text deduplication](examples/text-tools/README.md) and +[media merge](examples/media-merge/README.md) examples. + +This interface is **not released**. Use the guide's matching-source build +instructions, not the published scaffold above. The development CLI includes an `operation` template; see the guide for local +SDK dependency setup. Example engine ranges and package versions do not establish support in +an already released host, including beta.47. New components/capabilities require +host support; compatible plugin-only UI and business changes can update live. + ## Quick start ```bash @@ -45,6 +59,7 @@ Templates: |---|---| | `basic-resolver` (default) | A `beforeCreate` hook that inspects and rewrites downloads (`site-resolver` category) | | `post-action` | An `afterComplete` hook that fires a desktop notification (`post-action` category) | +| `operation` (unreleased) | A text deduplication form, scoped handler, both locales and typecheck/validate/pack/lint scripts | The scaffolded plugin id starts as `me.`. Set your real publisher (the `.` prefix) either by editing `id` in `motrix-plugin.json`, @@ -141,6 +156,7 @@ Field reference (enforced by `motrix-plugin validate`): | `activationEvents` | When the host loads you (e.g. `onTaskType:http`, `onStartup`). Required. | | `contributes.hooks` | Which lifecycle hooks you implement, each with a `role`. | | `contributes.commands` | Commands you register: id `..`, max 64. Commands marked `public: true` must declare `argsSchema` + `resultSchema` (a bounded JSON-Schema subset — no `$ref`/`oneOf`, ≤ 8 KiB, depth ≤ 8). | +| `contributes.operations` | **Unreleased:** host-rendered forms and scoped operation handlers. See the [operations guide](docs/operations.md). | | `contributes.configuration` | Your settings schema (same bounded subset). Read values via the `config` capability. | | `requestedHeapMB` | Sandbox heap, 32 (default) to 64. | | `l10n` | Directory of locale JSON files. | @@ -216,7 +232,7 @@ hooks across the task's lifetime. | Command | What it does | |---|---| -| `motrix-plugin init [-t basic-resolver\|post-action] [-p publisher]` | Scaffold a new plugin project | +| `motrix-plugin init [-t basic-resolver\|post-action\|operation] [-p publisher]` | Scaffold a new plugin project | | `motrix-plugin dev` | Watch-build + run your local Motrix with the plugin loaded (`MOTRIX_BIN` overrides discovery) | | `motrix-plugin validate` | Validate `motrix-plugin.json` against the official schema; non-zero exit on errors | | `motrix-plugin pack` | Bundle (esbuild, minified, ES2020) + zip into `dist/-.moext` | diff --git a/README.zh-CN.md b/README.zh-CN.md index 7d9bd04..51632a0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -28,6 +28,12 @@ pnpm run pack # produce a distributable .moext 里 —— 没有 Node.js API,不能直接访问文件或网络。与外界的一切交互都要 经过你在 manifest 里声明的 capability,用户在安装时能看到你申请了什么。 +## 插件操作(尚未发布) + +开发中的操作协议允许插件声明宿主渲染的表单、入口和沙箱处理函数,无需编写 React 或 renderer 代码。先阅读 [编写指南](docs/operations.zh-CN.md),再参考完整的 [文本去重](examples/text-tools/README.zh-CN.md) 和 [音视频合并](examples/media-merge/README.zh-CN.md) 示例。 + +此接口**尚未发布**。请按指南使用匹配源码构建,不能直接使用上方已发布的脚手架流程;开发版 CLI 已包含 `operation` 模板,本地 SDK 依赖配置见指南。示例的引擎范围和包版本不能证明 beta.47 等已发布宿主支持。新组件和能力需要宿主支持;兼容协议范围内的插件界面和业务更新可以热生效。 + ## 快速开始 ```bash @@ -41,6 +47,7 @@ pnpm create motrix-plugin my-plugin post-action # template as second argument |---|---| | `basic-resolver`(默认) | 一个检查并改写下载的 `beforeCreate` hook(`site-resolver` category) | | `post-action` | 一个下载完成后发桌面通知的 `afterComplete` hook(`post-action` category) | +| `operation`(尚未发布) | 文本去重表单、受限处理函数、中英文文案及 typecheck/validate/pack/lint 脚本 | 脚手架生成的插件 id 初始为 `me.`。要设置真实的 publisher (`.` 的前缀),可以直接编辑 `motrix-plugin.json` 里的 @@ -135,6 +142,7 @@ pnpm 内置的 tarball 打包命令,而不是脚手架里的 script。) | `activationEvents` | host 何时加载你(如 `onTaskType:http`、`onStartup`)。必填。 | | `contributes.hooks` | 你实现了哪些生命周期 hook,每个都要带 `role`。 | | `contributes.commands` | 你注册的 command:id 形如 `..`,最多 64 个。标记 `public: true` 的 command 必须声明 `argsSchema` + `resultSchema`(受限的 JSON-Schema 子集 —— 不支持 `$ref`/`oneOf`,≤ 8 KiB,深度 ≤ 8)。 | +| `contributes.operations` | **尚未发布:**宿主渲染的操作表单与受限处理函数,见 [操作指南](docs/operations.zh-CN.md)。 | | `contributes.configuration` | 你的设置 schema(同一受限子集)。运行时通过 `config` capability 读取。 | | `requestedHeapMB` | 沙箱堆大小,32(默认)到 64。 | | `l10n` | locale JSON 文件所在目录。 | @@ -208,7 +216,7 @@ Role 决定同一 hook 上多个插件的执行顺序: | 命令 | 作用 | |---|---| -| `motrix-plugin init [-t basic-resolver\|post-action] [-p publisher]` | 脚手架一个新插件项目 | +| `motrix-plugin init [-t basic-resolver\|post-action\|operation] [-p publisher]` | 脚手架一个新插件项目 | | `motrix-plugin dev` | watch-build + 启动本机 Motrix 并加载插件(`MOTRIX_BIN` 可覆盖自动定位) | | `motrix-plugin validate` | 用官方 schema 校验 `motrix-plugin.json`;有错误时非零退出 | | `motrix-plugin pack` | 打包(esbuild、minified、ES2020)并压成 `dist/-.moext` | diff --git a/docs/operations.md b/docs/operations.md new file mode 100644 index 0000000..92abcf6 --- /dev/null +++ b/docs/operations.md @@ -0,0 +1,509 @@ +# Authoring plugin operations (unreleased) + +**English** | [简体中文](./operations.zh-CN.md) + +> Development implementation, not a released SDK/host contract. Use a matching +> development checkout of the SDK and a Motrix build that implements the required +> capabilities. Examples and the operation template require +> `>=2.0.0-beta.48 <3.0.0`; beta.48 is the planned first supporting host release, +> not a claim that these features have shipped. Beta.47 is rejected, including +> development builds still reporting that version. Matching SDK packages remain +> unpublished, and a public JSON Schema URL does not establish support. The +> examples are not marketplace releases. + +## Start with a complete example + +- [Text deduplication](../examples/text-tools/README.md): one input, a boolean + option in a collapsible group, one output and a result count. Start here. +- [Media merge](../examples/media-merge/README.md): two file cards, a two-column + grid, an inline MP4/MKV selector, platform-specific hints and automatic input + order detection. This SDK adaptation uses `example.media-merge`, not the + reserved official identity `motrix.media-merge`. + +Both directories contain the full manifest, handler, English and Chinese locale +files, and a TypeScript configuration. These are executable source examples, +not abbreviated snippets. The snippets below illustrate individual fields and +are not complete manifests. + +For a TypeScript author, adapting an example is a small task; defining a new +operation from scratch has a moderate learning cost. The main work is aligning +schema fields, UI references, locale keys and file grants. No React or CSS is +needed. This is a source-based assessment, not a measured usability study. +The development CLI provides an `operation` template that creates the initial +references and files for you. `basic-resolver` and `post-action` remain lifecycle-hook +templates. Types are still handwritten; schema-to-TypeScript generation and UI +preview are not implemented. + +### Generate your own operation project + +The development CLI now includes `operation`, starting from text deduplication. +From the SDK repository root, choose an unused project name: + +```sh +pnpm install --frozen-lockfile +pnpm build +node packages/plugin-cli/dist/bin/motrix-plugin.js init my-operation -t operation -p acme +cd my-operation +pnpm add -D @motrix/plugin-api@file:../packages/plugin-api @motrix/plugin-cli@file:../packages/plugin-cli +pnpm run typecheck +pnpm run validate +pnpm run pack +pnpm run lint +``` + +This local dependency step is necessary while the operation API/CLI are +unreleased. The generated version ranges do not imply published support. If you +create the project elsewhere, adjust the two `file:` paths to the matching built +SDK packages. Do not change the host's schema or permissions to install it. + +Alternatively, from the SDK root, the create wrapper supports: + +```sh +node packages/create-motrix-plugin/bin/create.mjs my-operation operation +``` + +It defaults to publisher `me`; use the full CLI's `-p` option for a custom one. +Once matching versions are released, the public entry points will be +`motrix-plugin init my-operation -t operation -p acme` and +`pnpm create motrix-plugin my-operation operation`. They are not a claim that +currently published packages contain the template. + +The generator creates the complete manifest, handler, English/Chinese locales, +strict package-based `tsconfig.json`, esbuild config, package scripts, `.gitignore` +and paired READMEs. The project has its own publisher/name substitutions in the +operation/command/activation IDs. It requests only selected-file read/write, +includes both plugin-page and one-task menu entries, and uses `preserve-inputs`. +`typecheck`, `validate`, `pack` and `lint` are explicit scripts; `pack` does not +replace type checking. Handler types remain handwritten. No plugin is installed, +started, signed or published by scaffolding. + +### Run the examples from this SDK checkout + +Use Node.js 20 or newer and the pnpm version declared by this repository. From +the repository root: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/text-tools/tsconfig.json +cd examples/text-tools +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +Replace `text-tools` with `media-merge` to run the other example. `pack` bundles +`src/index.ts` itself and writes an unsigned `.moext` under that example's +ignored `dist/` directory. `lint` reads the bundle, so run it **after** `pack`. +Neither command publishes or signs anything. Install through the compatible +host's normal third-party package flow and review the requested permissions. + +The examples deliberately use this checkout's CLI and ambient API declaration; +there is no separate example dependency installation. Installing the currently +published npm packages is not a substitute for building these development +sources. When moving an example into a standalone project, use matching released +CLI/API packages once available, and replace the relative ambient declaration +include with the package's `types` setup. Keep `motrix:plugin-api` external when +bundling. `pack` validates and bundles; it does not replace TypeScript checking. + +## Ownership and files + +An operation is a host-rendered form connected to a sandbox handler: + +```text +manifest → host form → user file authorization → host job → sandbox handler + → validate and save result +``` + +| Authoring surface | Responsibility | +|---|---| +| `commands[].argsSchema` / `resultSchema` | Data types, required keys, defaults, bounds and return values | +| `operations.items[].fields` | Labels, widgets, help and presentation conditions | +| `operations.items[].files` | Input/output roles, text/media use and filename suggestions | +| `operations.items[].ui` | Layout, action labels and repeat policy | +| `operations.items[].entries` | Plugin detail and task menu entry points | +| `operations.items[].result` / `errors` | Displayed results and localized business errors | +| `commands.registerOperation()` | Business logic inside the existing sandbox | +| `locales/*.json` | Plugin-owned UI text | + +The host owns components, loading Skeletons, keyboard/focus behavior, progress, +cancellation, resource limits, file authorization and final output publication. +Plugins do not supply renderer JavaScript, HTML, CSS, DOM access or React. +Persistent settings still belong in `contributes.configuration` and the `config` +API. Operation arguments are per-invocation form values, not saved preferences. + +## Declare an operation and its command + +`contributes.operations` has `{ "version": 1, "items": [...] }`. Each item has +an `id`, `title`, `command`, `fields` and `entries`. It may also declare +`description`, `icon`, `requires`, `files`, `ui`, `result` and `errors`. +Operation and handler IDs must start with the plugin ID followed by a dot. +The handler must be a declared command with `execution: "operation"` and must +not be public; explicitly use `public: false`. Register it with +`commands.registerOperation`, and declare its `onCommand:` activation +event. Ordinary `commands.execute` and cross-plugin invocation cannot manufacture +an operation context or invoke the privileged handler. + +Operation icons are `action`, `media-merge`, `document` and `checksum`. +The current host advertises these feature identifiers: + +| Feature | Meaning | +|---|---| +| `operations.v1` | Operation descriptors and execution | +| `operations.ui.v1` | Composable layout and presentation | +| `files.selected.v1` | Selected-file references | +| `files.text.v1` | Scoped UTF-8 text read/write | +| `media.merge-streams.v1` | Scoped media probing and stream merging | + +List required features in `requires`. A custom `ui` requires +`operations.ui.v1`; unknown required features make the operation unavailable. +Feature declarations are not permissions and do not authorize files. + +### Data schemas + +Both schemas must be flat objects with `additionalProperties: false`, at most +24 properties, and only `string`, `boolean`, `number` or `integer` values. +Nested objects, arrays, patterns and general JSON Schema composition are not +supported. Non-enum strings need an explicit `maxLength` no greater than 4096; +numbers/integers need `minimum` and `maximum`. Only string enums are supported, +with at most 64 unique values. Defaults must validate against the same schema. + +For example, the format parameter is defined once in `argsSchema.properties`: + +```json +{ + "format": { + "type": "string", + "enum": ["mp4", "mkv"], + "default": "mp4" + } +} +``` + +Put `format` in `argsSchema.required` when it is required. UI fields only refer +to it; they do not redefine its type or enum. Labels fall back from `field.label` +to the schema property's `title`, then to the key. Use `field.help` for visible +help; a schema `description` is not automatically rendered as field help. +TypeScript handler generics are handwritten today: keep them aligned with the +schemas. The host validates arguments again at execution and validates results; +renderer validation is not an authority boundary. + +## Fields and widgets + +Every argument must have exactly one `fields` entry. `field` is its parameter +key; the supported widget names are `text`, `textarea`, `number`, `switch`, +`select` and `segmented`. The widget must match the schema type. + +| Schema/binding | Default control | Optional presentation | +|---|---|---| +| String | Text input | `textarea` | +| Number/integer | Numeric input | Bounds from the schema; integers use step 1 | +| Boolean | Switch | No alternative boolean control | +| String enum | Select | `segmented` for a single-choice segmented control | +| Input file binding | File card | Preset icon/tone and desktop drop affordance | +| Output file binding | Save-location card | Inline scalar accessory through layout | + +```json +{ + "field": "format", + "label": "%format%", + "widget": "segmented", + "optionLabels": { "mp4": "MP4", "mkv": "MKV" } +} +``` + +`optionLabels` changes displayed labels, not submitted values. Unmapped enum +values display literally. Required state comes from `argsSchema.required`; +the host currently provides accessible required descriptions without a visible +asterisk. Controls and execution validation remain host-owned. + +`appearance` accepts `placeholder`, `browseLabel`, `drop`, `icon` and `tone`: + +- `placeholder` is used by text/number/textarea inputs and empty file cards. +- `browseLabel` currently sets the file card's accessible name, not its visible + action text. The host supplies localized choose/change/drop instructions. +- `help` supplies extra explanation. A selected file's directory takes priority + over file help in the card. Avoid repeating the host's action hint in help or + placeholder text. +- File icons: `video`, `audio`, `folder`, `document`, `text`, `checksum`. +- File tones: `neutral`, `blue`, `violet`, `amber`; they are host presets. +- `drop: true` is valid only for input files. Actual support and authorization + depend on the host; it does not enable browser-local uploads. + +File fields cannot have `widget`, `optionLabels`, `visibleWhen` or `enabledWhen`. +Icons, tones and browse labels are file-only. No arbitrary style, image URL, +class name, event handler or HTML is accepted. + +## Compose the layout + +Without `ui`, fields render vertically in their declared order. When `ui` is +present, `ui.layout` is required. Every field must be bound exactly once across +`field` nodes and accessories, with no omitted or duplicated references. + +| Node | Properties and behavior | +|---|---| +| `field` | `field`, optional `span: 1\|2`, optional scalar `accessory` in the label row | +| `text` | Plain `text`, optional `tone: muted\|info`, `platform: desktop\|web`, `span` | +| `stack` | `children`, optional `title` and `span`; vertical order | +| `grid` | `children`, optional `columns: 1\|2`, `title`, `span`; narrow layouts collapse to one column | +| `group` | `children`, optional `title`, `collapsible`, `span`; bordered group | + +The media example uses: + +```json +{ + "type": "grid", + "columns": 2, + "children": [ + { "type": "field", "field": "videoInput" }, + { "type": "field", "field": "audioInput" }, + { "type": "field", "field": "output", "span": 2, "accessory": "format" } + ] +} +``` + +A file cannot be an accessory, and an input file cannot contain an accessory. +Collapsible groups require a title, default to expanded, and cannot contain +files even through nested containers. There is no configurable default-open +state. `columns` is valid only on a grid. Platform filtering applies only to +text nodes. Text is static plain text, without Markdown, HTML or interpolation +of form/result values. + +`ui.submitLabel`, `repeatLabel` and `footer` customize the primary action, repeat +action and footer. Cancel, job status, progress and result containers belong to +the host. Extra action buttons and custom success/failure layouts are unsupported. + +### Conditions + +Scalar fields can use `visibleWhen` and `enabledWhen`. Conditions support +`{ field, equals }`, `{ field, in: [...] }`, `{ all: [...] }`, `{ any: [...] }` +and `{ not: ... }`, with strict scalar equality: + +```json +{ + "visibleWhen": { "field": "mode", "equals": "replace" }, + "enabledWhen": { "not": { "field": "readOnly", "equals": true } } +} +``` + +The referenced fields and values must be valid in the argument schema. Conditions +cannot reference file fields. A conditional required field needs a valid default. +Hidden/disabled fields retain their values and are still validated/submitted; +conditions do not implement conditional requiredness, clear values or grant +permission. Enforce business rules in the handler too. There are no expressions, +callbacks, computed defaults, dynamic options or asynchronous field validators. + +## Selected files and permission boundaries + +A file parameter is a required bounded string in the argument schema, without +a default or enum, with `maxLength <= 128`. Current examples constrain it to 36 +characters. Treat it as an **opaque invocation reference**, never a path or a +value to synthesize, parse, persist or reuse across jobs. + +```json +{ + "input": { "kind": "input-file", "use": "text", "extensions": ["txt"] }, + "output": { + "kind": "output-file", + "use": "text", + "extensions": ["txt"], + "suggestedName": { "stemFrom": "input", "suffix": "-unique" } + } +} +``` + +`use` is `text` or `media`. Request `files.selected.read` for inputs and +`files.selected.write` for outputs; media bindings additionally require `ffmpeg`. +An output needs `extensions` or `extensionFrom`. Extensions are lowercase, +without a dot. `extensionFrom` refers to a string enum such as `format`. +`suggestedName.stemFrom` refers to an input; its suffix permits up to 32 ASCII +letters, digits, underscores or hyphens. Suggestions do not grant write access: +if necessary, submitting opens the save chooser before execution. + +Electron uses native open/save dialogs. Desktop drops are confirmed by the host. +Web uses server-side file selection within its directory policy; files on the +browser's computer are not uploaded. Task-menu entry binds host-validated task +files. A plugin-provided path is none of these authorization sources. + +The host binds grants to the owner, plugin, operation and invocation/policy +revision. Drafts expire after 15 minutes; refreshing a form does not extend them. +Repeated execution creates fresh references. Host checks include resolved-path +policy, file identity/change checks and execution-time authorization. It snapshots +inputs and owns temporary output, cancellation cleanup, validation and atomic +non-overwriting publication. Existing outputs are rejected. Unsupported filesystems +are rejected rather than weakening publication guarantees. Successful outputs +are not deleted by resetting the form. The official publisher gets no exemption. + +Media probing/merging permits supported standalone containers; playlists, concat +scripts, image sequences, network protocols and indirect file access are not an +escape hatch. There is no arbitrary FFmpeg argument API in `OperationContext`. + +## Handler, progress, errors and results + +Register once at module scope; perform work only inside the handler. The complete +handlers are in the example source files. The operation context supplies: + +| API | Contract | +|---|---| +| `jobId` | Job identity, useful in plugin logs | +| `signal` | `aborted`, `reason`, `throwIfAborted`, abort listener add/remove; a bounded sandbox subset of `AbortSignal` | +| `progress({ phase, fraction? })` | Async progress report; `phase` is `preparing` or `running`, fraction convention is 0–1 | +| `fail(code)` | Throw a stable business error mapped by the operation's `errors` | +| `files.readText(ref)` | Read a scoped UTF-8 input | +| `files.writeText(ref, content)` | Write a scoped new text output | +| `media.probe(ref)` | Return bounded stream metadata and optional duration | +| `media.mergeStreams({ video, audio, output, format, expectedDurationMs? })` | Merge streams using scoped refs; format is MP4 or MKV | + +Await capability calls, check cancellation during work, and do not catch a +cancellation just to return success. Host cancellation also revokes capabilities +and stops/cleans host-owned work if the handler fails to cooperate. + +The host owns job stages: accepted → preparing → running → validating → committing +→ cleaning → succeeded/failed/cancelled. Cancellation can introduce `cancelling`; +a host restart marks unfinished jobs `interrupted` and does not replay them. +Closing a form alone does not cancel a job. Final publication is a commit boundary: +a late cancellation cannot remove an already published result. + +Progress `phase` currently does not override the host's stage label. There is no +custom progress message. Reports are limited to 20 calls per second; send fewer. +The host coalesces updates, displays reported progress at most as 99%, and owns +100% after successful publication. Media merge progress is forwarded automatically. + +Declare errors as `{ "invalidInput": "%invalidInput%" }`, then call +`context.fail('invalidInput')`. Unmapped thrown messages use the host's generic +failure text; do not rely on raw exception strings reaching the user. + +`result.fields` selects scalar return keys to display as `title: value`; titles +come from `resultSchema.properties[key].title`. `result.files` selects the output +binding, which must also be declared in the result schema. Return the granted +output ref, not its path. Every declared output must be included in `result.files`. +The host validates the result and output before publishing. Desktop shows an +open-folder action; Web does not expose a desktop folder action. Custom result +cards, tables and result-value formatters are not implemented. + +### Repeat and refresh + +| `ui.repeat` | Scalar options | Inputs | Output | +|---|---|---|---| +| Omitted or `reset` | Schema defaults | Clear | Clear | +| `preserve-options` | Preserve | Clear | Clear | +| `preserve-inputs` | Preserve | Revalidate and reauthorize unchanged files | Clear | + +Media merge uses `preserve-options`: **Merge another file** clears both inputs +and the output, retaining MP4/MKV. Text deduplication uses `preserve-inputs`. +Previous task bindings are not automatically applied again on repeat. + +Ordinary navigation preserves form state in the renderer. Refresh can resume a +valid host draft without extending its authorization deadline. Running jobs are +host-owned. Historical completed jobs are not restored as a new form's current +result after restart. Plugin installation/update reloads descriptors and invalidates +obsolete form/grant state; compatible plugin updates do not require an app restart. +Language changes update labels without invalidating the current form or job. + +## Entry points + +`entries` supports `plugin-detail` and `task-menu`, at most once each. The detail +page shows one operation directly or a selector for multiple operations. +A task menu declaration can bind selected tasks to input fields: + +```json +{ + "surface": "task-menu", + "selection": { + "count": { "min": 1, "max": 1 }, + "every": { "status": "completed", "files": "single", "local": true } + }, + "bind": { "input": { "source": "task-file", "index": 0 } } +} +``` + +Task selection is currently limited to 1–4 completed single-file tasks with local +final files. Bind indexes must exist even at the minimum selection count. There +are no arbitrary task predicates or script-driven menu labels. Inapplicable task +selections omit the item. Disabled plugins, missing required capabilities, +security restrictions and missing FFmpeg show the appropriate unavailable state. +The host rechecks eligibility at preparation/execution, not only when drawing a +menu. Both surfaces invoke the same form and handler. + +## Localization and accessibility + +Set `l10n: "locales"`; use a whole-field `%key%` reference. `en-US.json` is required +when localization is declared; other languages can be partial and fall back to +English. Mixed text such as `"Choose %input%"` is invalid: translate the full +sentence under one key. IDs, parameter names and enum values are not translated. + +Operations resolve titles/descriptions, field labels/help, appearance text, +option labels, group titles, static text, action/footer labels, error messages and +schema titles/descriptions. The host language controls rendering. Generic status, +cancel and file-action text comes from the host's language resources. +Translated descriptors are bounded too; a short `%key%` is not a way around size +limits. CLI coverage checks English references, not translation quality or visual +fit in every locale. Check both example languages in the host. + +Labels and help connect to host controls; required descriptions, status live +regions and keyboard behavior come from those controls. Give every field a useful +label, including accessories whose visible label is compacted away. A custom +`browseLabel` should describe the file selection purpose. Do not use icon or tone +alone to convey meaning. + +## Limits and unsupported features + +These are current implementation limits, not promises that every plugin can +consume every resource simultaneously. + +| Surface | Current limit | +|---|---| +| Operations per plugin | 16 | +| Fields per operation / properties per data schema | 24 | +| Input/output files | 4 inputs, 1 output; all file fields required | +| Layout | 64 nodes, depth 4, at most 24 children per container | +| Conditions | 64 nodes total per operation, depth 4; `all`/`any` up to 8 children, `in` up to 64 values | +| Descriptor validation budget | 8 KiB per operation, 64 KiB for the contribution; conservative structural accounting, not raw manifest file size | +| General schema budget | 8 KiB per argument/result schema, also subject to the bounded schema validator | +| Text capability | UTF-8; 1 MiB input/output, at most 4 reads and one write per output | +| Media capability | 8 GiB per input, 16 GiB combined; at most 4 probes, 2 simultaneous probes, 1 merge | +| Host operation deadline | Media operations: 1 hour; other operations: 60 seconds; sandbox/resource limits can stop work earlier | +| Draft quota | 4 per owner, 16 globally; same valid draft is reused on refresh | + +File snapshots/staging also need free disk space. Limits cannot be increased by +adding fields to a manifest. The host may report resource or disk-space limits +before a handler starts. + +Not implemented: custom HTML/JS/CSS components, arbitrary images/styles, dynamic +options or async field validation, computed values, array/object editors, tables, +trees, multi-step wizards, arbitrary extra buttons, rich result layouts, directory +selection, multi-file array fields or browser-local uploads. Use separate small +operations when appropriate; requirements outside this component/capability set +need a protocol/host change, not an undocumented escape hatch. + +## Compatibility and troubleshooting + +UI text/layout/options and handler changes within this protocol can ship in a +plugin update. New widgets, layout nodes, condition operators, capabilities or +result renderers require SDK schema/API/CLI and host support. `operations.version` +selects the protocol, `requires` checks features on a capable host, and +`engines.motrix` sets the actual minimum supported host version. An older host may +reject an unknown manifest at installation rather than show an unavailable form. + +The current engine floor targets beta.48. Before any release, verify that beta.48 +actually ships these capabilities; if it does not, raise the floor to the first +release that does. Use matching SDK/CLI packages, and keep package and registry +compatibility/permission metadata consistent. The CLI embeds its schema at build +time: updating a separate schema dependency does not update an old CLI. The +public schema URL can also lag this development implementation. Official package +signing remains in the official plugin repository; these examples are unsigned. + +| Symptom | Check | +|---|---| +| Manifest fails schema validation | Matching host/CLI; private `execution: operation` handler; flat bounded schemas; required features | +| Layout rejected | Every field exactly once, including accessories; topology and depth limits | +| Conditional field rejected | Referenced scalar/value exists; a conditional required field has a default | +| File binding rejected | Required string without default/enum, permissions, output extension and returned output | +| `%key%` or English unexpectedly appears | `l10n`, English coverage, current language key and whole-field references | +| File action text appears twice | Remove duplicated host instructions from `help`/`placeholder`; `browseLabel` is an accessible name | +| `resourceLimit` | Progress frequency, read/probe counts, file size, concurrent drafts and free disk space | +| New output rejected | Choose a nonexistent destination; never disable overwrite protection | + +Use the complete examples as the starting point. Their README files include +expected behavior and manual checks for Electron/Web, localization, cancellation +and file authorization. Passing CLI validation alone does not prove those flows. diff --git a/docs/operations.zh-CN.md b/docs/operations.zh-CN.md new file mode 100644 index 0000000..7d42f4f --- /dev/null +++ b/docs/operations.zh-CN.md @@ -0,0 +1,325 @@ +# 编写插件操作(尚未发布) + +[English](./operations.md) | **简体中文** + +> 本文描述开发中的实现,不代表已经发布的 SDK 或宿主契约。请使用匹配的 SDK 开发源码和具备所需能力的 Motrix 构建。示例与 operation 模板要求 `>=2.0.0-beta.48 <3.0.0`;beta.48 是计划中的首个支持版本,不代表这些功能已发布。beta.47 会被拒绝,包括仍使用该版本号的开发构建。配套 SDK 包仍未发布,公开 JSON Schema 地址也不能证明已支持;示例不是已经上架的插件。 + +## 从完整示例开始 + +- [文本去重](../examples/text-tools/README.zh-CN.md):一个输入、折叠组中的布尔选项、一个输出和结果计数。建议先看这个示例。 +- [音视频合并](../examples/media-merge/README.zh-CN.md):两个文件卡片、双栏布局、内联 MP4/MKV 选择器、平台提示和输入顺序识别。SDK 教学版本使用 `example.media-merge`,不使用官方保留身份 `motrix.media-merge`。 + +两个目录都包含完整清单、处理函数、中英文语言文件和 TypeScript 配置,是可以执行的源码示例。下文代码片段只解释局部字段,不是完整清单。 + +对熟悉 TypeScript 的开发者,修改现有示例的工作量较小;从零定义操作的学习成本中等。主要难点是对齐参数 Schema、UI 引用、翻译键和文件授权,无需编写 React 或 CSS。这是基于源码的评估,没有经过开发者可用性研究。开发版 CLI 已提供 `operation` 模板,自动生成初始引用和文件;`basic-resolver` 和 `post-action` 仍为生命周期 Hook 模板。类型仍需手写维护,尚未实现从 Schema 生成 TypeScript 类型或 UI 预览。 + +### 生成自己的操作项目 + +开发版 CLI 现已提供 `operation` 模板,以文本去重为起点。从 SDK 仓库根目录开始,使用尚未占用的项目名: + +```sh +pnpm install --frozen-lockfile +pnpm build +node packages/plugin-cli/dist/bin/motrix-plugin.js init my-operation -t operation -p acme +cd my-operation +pnpm add -D @motrix/plugin-api@file:../packages/plugin-api @motrix/plugin-cli@file:../packages/plugin-cli +pnpm run typecheck +pnpm run validate +pnpm run pack +pnpm run lint +``` + +操作 API/CLI 尚未发布时,需要上述本地依赖步骤,生成的版本范围不代表已发布支持。若在其他位置创建项目,将两个 `file:` 路径调整为匹配且已构建的 SDK 包位置。不能通过修改宿主 Schema 或权限来安装。 + +也可以从 SDK 根目录使用 create 包装器: + +```sh +node packages/create-motrix-plugin/bin/create.mjs my-operation operation +``` + +它默认使用发布者 `me`;自定义发布者请使用完整 CLI 的 `-p`。配套版本正式发布后,公开入口为 `motrix-plugin init my-operation -t operation -p acme` 和 `pnpm create motrix-plugin my-operation operation`,这不代表当前已发布包包含该模板。 + +生成器提供完整清单、处理函数、中英文语言文件、基于安装包的严格 `tsconfig.json`、esbuild 配置、package scripts、`.gitignore` 和成对 README。操作、命令和激活 ID 自动使用项目的发布者与名称。模板只申请所选文件读写权限,包含插件页面及单任务菜单入口,使用 `preserve-inputs`。提供明确的 typecheck、validate、pack、lint 脚本;pack 不代替类型检查,处理函数类型仍需手写维护。生成项目不会安装、启动、签名或发布插件。 + +### 在 SDK 仓库中运行示例 + +使用 Node.js 20 或更高版本,以及仓库声明的 pnpm 版本。从仓库根目录开始: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/text-tools/tsconfig.json +cd examples/text-tools +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +将 `text-tools` 换成 `media-merge` 即可运行另一个示例。`pack` 会自行打包 `src/index.ts`,将未签名 `.moext` 写入示例目录下被 Git 忽略的 `dist/`。`lint` 读取构建后的 bundle,必须放在 **pack 之后**。这些命令不会签名或发布。通过兼容宿主的正常第三方安装流程安装,并检查所申请的权限。 + +示例直接使用当前仓库的 CLI 和 ambient API 类型声明,不需要为示例单独安装依赖。安装当前 npm 已发布包不能替代构建这些开发源码。将示例移到独立项目时,应在匹配版本正式发布后使用配套 CLI/API 包,将相对路径类型声明改成包的 `types` 配置;打包时保持 `motrix:plugin-api` 为 external。`pack` 负责校验和打包,不代替 TypeScript 类型检查。 + +## 文件与职责 + +操作是一张由宿主渲染、连接到沙箱处理函数的表单: + +```text +manifest → host form → user file authorization → host job → sandbox handler + → validate and save result +``` + +| 编写位置 | 职责 | +|---|---| +| `commands[].argsSchema` / `resultSchema` | 数据类型、必填项、默认值、范围和返回值 | +| `operations.items[].fields` | 标签、控件、说明和呈现条件 | +| `operations.items[].files` | 输入输出角色、文本或媒体用途、文件名建议 | +| `operations.items[].ui` | 布局、操作按钮文案和重复执行策略 | +| `operations.items[].entries` | 插件详情页和任务菜单入口 | +| `operations.items[].result` / `errors` | 展示的结果和本地化业务错误 | +| `commands.registerOperation()` | 现有沙箱中的业务逻辑 | +| `locales/*.json` | 插件提供的界面文案 | + +宿主管理组件、加载 Skeleton、键盘和焦点行为、进度、取消、资源限制、文件授权及最终输出保存。插件不提供 renderer JavaScript、HTML、CSS、DOM 访问或 React。长期配置仍属于 `contributes.configuration` 和 `config` API;操作参数属于本次调用的表单,不会自动保存为偏好设置。 + +## 声明操作及其命令 + +`contributes.operations` 的结构是 `{ "version": 1, "items": [...] }`。每个操作包含 `id`、`title`、`command`、`fields`、`entries`,还可以声明 `description`、`icon`、`requires`、`files`、`ui`、`result`、`errors`。 + +操作 ID 和处理命令 ID 都必须以插件 ID 加点号开头。处理命令必须在清单中声明 `execution: "operation"`,不能公开,建议显式填写 `public: false`。通过 `commands.registerOperation` 注册处理函数,并声明 `onCommand:` 激活事件。普通 `commands.execute` 和跨插件调用不能创建操作上下文或调用这一受控处理函数。 + +操作图标支持 `action`、`media-merge`、`document`、`checksum`。当前宿主提供以下能力标识: + +| 能力标识 | 含义 | +|---|---| +| `operations.v1` | 操作描述和执行 | +| `operations.ui.v1` | 可组合布局与呈现 | +| `files.selected.v1` | 所选文件引用 | +| `files.text.v1` | 受限 UTF-8 文本读写 | +| `media.merge-streams.v1` | 受限媒体探测和轨道合并 | + +在 `requires` 中列出所需能力。自定义 `ui` 必须声明 `operations.ui.v1`;未知的必需能力会使操作不可用。能力声明不是权限,也不授予文件访问权。 + +### 数据 Schema + +参数和结果 Schema 都必须是扁平对象,设置 `additionalProperties: false`,最多 24 个属性,只支持 `string`、`boolean`、`number`、`integer`。不支持嵌套对象、数组、正则或通用 JSON Schema 组合。非枚举字符串必须显式指定不超过 4096 的 `maxLength`;数字和整数必须指定 `minimum`、`maximum`。只支持字符串枚举,最多 64 个互不重复的值。默认值必须通过同一 Schema 的校验。 + +例如,在 `argsSchema.properties` 中定义一次格式参数: + +```json +{ + "format": { + "type": "string", + "enum": ["mp4", "mkv"], + "default": "mp4" + } +} +``` + +需要必填时,将 `format` 加入 `argsSchema.required`。UI 字段只引用它,不重新声明类型或枚举。标签依次取 `field.label`、Schema 属性的 `title`、参数名。可见说明使用 `field.help`,Schema 的 `description` 不会自动显示为字段说明。处理函数的 TypeScript 泛型目前仍需手写,应与 Schema 保持一致。宿主执行时会重新校验参数,并校验结果;renderer 校验不是权限边界。 + +## 字段与控件 + +每个参数必须在 `fields` 中恰好声明一次。`field` 是参数名;控件名支持 `text`、`textarea`、`number`、`switch`、`select`、`segmented`,必须与 Schema 类型匹配。 + +| Schema 或文件绑定 | 默认控件 | 可选呈现 | +|---|---|---| +| 字符串 | 文本输入框 | `textarea` | +| 数字或整数 | 数字输入框 | 范围来自 Schema;整数步长为 1 | +| 布尔值 | 开关 | 暂无其他布尔控件 | +| 字符串枚举 | 下拉选择 | `segmented` 显示单选分段按钮 | +| 输入文件绑定 | 文件卡片 | 预设图标、色调和桌面拖放入口 | +| 输出文件绑定 | 保存位置卡片 | 可通过布局附加普通参数控件 | + +```json +{ + "field": "format", + "label": "%format%", + "widget": "segmented", + "optionLabels": { "mp4": "MP4", "mkv": "MKV" } +} +``` + +`optionLabels` 只改变显示标签,不改变提交值;没有映射的枚举值直接显示原值。必填状态来自 `argsSchema.required`,宿主目前提供无障碍必填说明,不显示星号。控件行为和执行校验仍由宿主管理。 + +`appearance` 接受 `placeholder`、`browseLabel`、`drop`、`icon`、`tone`: + +- `placeholder` 用于文本、数字、多行输入框和未选择文件的卡片。 +- `browseLabel` 当前是文件卡片的无障碍名称,不是可见操作文字。选择、更换、拖入等通用指引由宿主本地化。 +- `help` 提供补充说明。文件选中后,卡片优先显示所在目录。不要在说明或占位文字中重复宿主的操作指引。 +- 文件图标:`video`、`audio`、`folder`、`document`、`text`、`checksum`。 +- 文件色调:`neutral`、`blue`、`violet`、`amber`,均为宿主预设。 +- `drop: true` 仅适用于输入文件,实际支持和授权取决于宿主;它不会启用浏览器本机文件上传。 + +文件字段不能声明 `widget`、`optionLabels`、`visibleWhen`、`enabledWhen`。图标、色调和浏览标签只适用于文件。协议不接受任意样式、图片 URL、class 名称、事件处理器或 HTML。 + +## 组合布局 + +不写 `ui` 时,宿主按照 `fields` 顺序纵向渲染。提供 `ui` 时必须填写 `ui.layout`。布局中的 `field` 节点和 accessory 必须将全部字段恰好绑定一次,不能遗漏或重复。 + +| 节点 | 属性与行为 | +|---|---| +| `field` | `field`,可选 `span: 1\|2`,可选普通参数 `accessory`,放在标签行 | +| `text` | 纯文本 `text`,可选 `tone: muted\|info`、`platform: desktop\|web`、`span` | +| `stack` | `children`,可选 `title`、`span`,纵向排列 | +| `grid` | `children`,可选 `columns: 1\|2`、`title`、`span`,窄窗口变为一栏 | +| `group` | `children`,可选 `title`、`collapsible`、`span`,带边框分组 | + +媒体示例采用以下布局: + +```json +{ + "type": "grid", + "columns": 2, + "children": [ + { "type": "field", "field": "videoInput" }, + { "type": "field", "field": "audioInput" }, + { "type": "field", "field": "output", "span": 2, "accessory": "format" } + ] +} +``` + +文件不能成为 accessory,输入文件也不能包含 accessory。折叠组必须有标题,默认展开,不能直接或通过嵌套容器包含文件字段,暂不支持配置初始折叠状态。`columns` 只用于 grid。平台过滤只适用于 text 节点。文本是静态纯文本,不支持 Markdown、HTML 或表单、结果变量插值。 + +`ui.submitLabel`、`repeatLabel`、`footer` 分别配置执行按钮、再次执行按钮和页脚文案。取消、任务状态、进度和结果容器由宿主提供,不支持额外操作按钮或自定义成功、失败布局。 + +### 条件 + +普通参数字段可以使用 `visibleWhen` 和 `enabledWhen`。支持 `{ field, equals }`、`{ field, in: [...] }`、`{ all: [...] }`、`{ any: [...] }`、`{ not: ... }`,采用严格的标量相等判断: + +```json +{ + "visibleWhen": { "field": "mode", "equals": "replace" }, + "enabledWhen": { "not": { "field": "readOnly", "equals": true } } +} +``` + +引用的字段和值必须符合参数 Schema,不能引用文件字段。带条件的必填字段需要有效默认值。隐藏或禁用字段保留原值,仍会参与校验和提交;条件不会改变必填规则、清空值或授予权限。业务规则也应在处理函数中检查。不支持表达式、回调、计算默认值、动态选项或异步字段校验。 + +## 所选文件与权限边界 + +文件参数在参数 Schema 中是必填的有界字符串,不能有默认值或枚举,`maxLength <= 128`。当前示例将长度约束为 36。必须将它视为**本次调用的不透明引用**,不能当成路径,也不能自行构造、解析、持久化或跨任务复用。 + +```json +{ + "input": { "kind": "input-file", "use": "text", "extensions": ["txt"] }, + "output": { + "kind": "output-file", + "use": "text", + "extensions": ["txt"], + "suggestedName": { "stemFrom": "input", "suffix": "-unique" } + } +} +``` + +`use` 为 `text` 或 `media`。输入申请 `files.selected.read`,输出申请 `files.selected.write`;媒体绑定还必须申请 `ffmpeg`。输出必须有 `extensions` 或 `extensionFrom`。扩展名使用不带点的小写字符;`extensionFrom` 引用 `format` 这样的字符串枚举。`suggestedName.stemFrom` 引用一个输入,其后缀只允许最多 32 个 ASCII 字母、数字、下划线或连字符。建议路径不授予写权限;必要时,提交会先打开保存选择器。 + +Electron 使用原生打开、保存对话框,桌面拖放由宿主确认。Web 在目录策略内选择服务端文件,不上传浏览器所在电脑的文件。任务菜单绑定经过宿主检查的任务文件。插件自行传入的路径不属于这些授权来源。 + +宿主将授权绑定到所有者、插件、操作以及本次调用和策略版本。草稿 15 分钟后过期,刷新表单不会延长有效期。再次执行会生成新引用。宿主检查包括解析后的路径策略、文件身份和变更、执行时授权;还负责输入快照、临时输出、取消清理、结果校验和原子无覆盖保存。已有输出会被拒绝,不能提供保存保证的文件系统也会被拒绝。重置表单不会删除已经成功生成的文件。官方身份没有豁免。 + +媒体探测和合并只接受支持的独立容器;播放列表、concat 脚本、图片序列、网络协议和间接文件访问不能借此绕过授权。`OperationContext` 不提供任意 FFmpeg 参数接口。 + +## 处理函数、进度、错误与结果 + +在模块顶层注册一次,将实际工作放进处理函数。完整处理函数见两个示例的源码文件。操作上下文提供: + +| API | 契约 | +|---|---| +| `jobId` | 本次任务标识,可用于插件日志 | +| `signal` | `aborted`、`reason`、`throwIfAborted`、添加和移除取消监听;是有数量限制的沙箱 `AbortSignal` 子集 | +| `progress({ phase, fraction? })` | 异步进度报告;`phase` 为 `preparing` 或 `running`,fraction 按 0~1 表达 | +| `fail(code)` | 抛出由操作 `errors` 映射的稳定业务错误 | +| `files.readText(ref)` | 读取授权的 UTF-8 输入 | +| `files.writeText(ref, content)` | 写入授权的新文本输出 | +| `media.probe(ref)` | 返回有界轨道信息和可选时长 | +| `media.mergeStreams({ video, audio, output, format, expectedDurationMs? })` | 使用授权引用合并轨道,格式为 MP4 或 MKV | + +等待能力调用完成,在工作过程中检查取消,不要捕获取消后伪装成成功。即使处理函数不配合,宿主取消也会撤销能力访问,停止并清理宿主管理的工作。 + +宿主管理任务阶段:accepted → preparing → running → validating → committing → cleaning → succeeded/failed/cancelled。取消可能进入 `cancelling`;宿主重启后,未完成任务标为 `interrupted`,不会重放。仅关闭表单不会取消任务。最终保存存在提交边界:迟到的取消不能删除已经保存的结果。 + +进度中的 `phase` 当前不会覆盖宿主的阶段标签,也没有自定义进度文案。每秒最多调用 20 次,应明显低于这一频率。宿主合并更新,上报进度最多显示为 99%,成功保存后由宿主设置 100%。媒体合并进度自动转发。 + +声明 `{ "invalidInput": "%invalidInput%" }` 错误映射后,调用 `context.fail('invalidInput')`。没有映射的异常使用宿主通用失败文案,不要依赖原始异常字符串直接展示给用户。 + +`result.fields` 选择要按“标题:值”展示的普通返回字段,标题来自 `resultSchema.properties[key].title`。`result.files` 指定输出文件绑定,结果 Schema 中也必须声明该字段。返回已授权的输出引用,不能返回路径。所有已声明输出都必须包含在 `result.files` 中。宿主校验结果和输出后才保存文件。桌面提供打开文件夹操作,Web 不提供桌面文件夹操作。暂不支持自定义结果卡片、表格或值格式化器。 + +### 再次执行与刷新 + +| `ui.repeat` | 普通选项 | 输入 | 输出 | +|---|---|---|---| +| 省略或 `reset` | Schema 默认值 | 清空 | 清空 | +| `preserve-options` | 保留 | 清空 | 清空 | +| `preserve-inputs` | 保留 | 对未变化文件重新检查并授权 | 清空 | + +媒体合并使用 `preserve-options`:“再次合并”清空两个输入和输出,保留 MP4/MKV。文本去重使用 `preserve-inputs`。再次执行不会自动重新应用上次任务绑定。 + +普通页面切换会保留 renderer 中的表单状态;刷新可以恢复有效的宿主草稿,但不会延长授权期限。运行中的任务归宿主管理。重启后不会把历史成功任务恢复成新表单的当前结果。插件安装或更新会重载描述并使过时表单、授权失效;兼容协议内的插件更新不需要重启应用。语言切换只更新标签,不使当前表单或任务失效。 + +## 操作入口 + +`entries` 支持 `plugin-detail` 和 `task-menu`,每种最多一个。详情页直接展示单个操作,多操作时提供切换入口。任务菜单可以将所选任务绑定到输入字段: + +```json +{ + "surface": "task-menu", + "selection": { + "count": { "min": 1, "max": 1 }, + "every": { "status": "completed", "files": "single", "local": true } + }, + "bind": { "input": { "source": "task-file", "index": 0 } } +} +``` + +当前任务条件限于 1~4 个已完成的单文件任务,且存在本地最终文件。即使只选择最少数量的任务,绑定索引也必须存在。不支持任意任务判断式或脚本生成菜单标签。不适用的任务选择不显示入口;插件停用、缺少能力、安全限制或缺少 FFmpeg 时显示对应不可用状态。宿主准备和执行时会重新检查资格,不只在画菜单时检查。两个入口共用同一表单和处理函数。 + +## 多语言与无障碍 + +设置 `l10n: "locales"`,使用占满整个字段的 `%key%` 引用。声明本地化后必须提供 `en-US.json`;其他语言可以不完整,缺失时回退英文。`"Choose %input%"` 这样的混合文本无效,应将完整句子放入一个翻译键。ID、参数名和枚举实际值不翻译。 + +操作会解析标题与说明、字段标签与帮助、appearance 文案、选项标签、分组标题、静态文本、按钮与页脚、错误文案、Schema 标题与说明。宿主语言决定显示语言;通用状态、取消和文件操作文字来自宿主语言资源。 + +翻译后的描述也有大小限制,短 `%key%` 不能绕过限制。CLI 检查英文引用覆盖,不验证每种语言的翻译质量或界面适配,应在宿主检查示例的两种语言。 + +宿主控件负责标签与说明关联、必填说明、状态 live region 和键盘行为。所有字段都应有清晰标签,包括可见标签被压缩隐藏的 accessory。自定义 `browseLabel` 应说明文件选择用途,不要只依靠图标或色调传递含义。 + +## 限制与暂不支持的能力 + +下列是当前实现限制,不代表每个插件能同时耗尽每类资源。 + +| 项目 | 当前限制 | +|---|---| +| 每插件操作数 | 16 | +| 每操作字段数、每个数据 Schema 属性数 | 24 | +| 输入、输出文件 | 4 个输入、1 个输出;文件字段全部必填 | +| 布局 | 64 个节点、深度 4、每个容器最多 24 个子节点 | +| 条件 | 单操作累计 64 个节点、深度 4;`all`、`any` 最多 8 个子项,`in` 最多 64 个值 | +| 描述校验预算 | 单操作 8 KiB,全部操作声明 64 KiB;采用保守结构计数,不等于清单文件原始大小 | +| 通用 Schema 预算 | 每个参数或结果 Schema 8 KiB,另受有界 Schema 校验约束 | +| 文本能力 | UTF-8;输入、输出各 1 MiB,最多读取 4 次,每个输出写入一次 | +| 媒体能力 | 每个输入 8 GiB、总输入 16 GiB;最多 4 次探测、同时 2 次探测、1 次合并 | +| 宿主操作超时 | 媒体操作 1 小时,其他操作 60 秒;沙箱或资源限制可能更早终止 | +| 草稿配额 | 每个所有者 4 个,全局 16 个;刷新复用同一有效草稿 | + +文件快照和暂存还需要足够可用磁盘空间,不能通过在清单增加字段来提高限制。宿主可能在处理函数开始前就报告资源或磁盘空间限制。 + +尚未实现:自定义 HTML/JS/CSS 组件、任意图片和样式、动态选项或异步字段校验、计算值、数组或对象编辑器、表格、树、多步骤向导、任意额外按钮、复杂结果布局、目录选择、多文件数组字段、浏览器本机上传。适合时可以拆成几个小操作;超出组件或能力集合的需求需要协议与宿主扩展,不能依靠未声明的旁路。 + +## 兼容性与排错 + +在当前协议内修改 UI 文案、布局、选项或业务函数,可以通过插件更新交付。新控件、布局节点、条件运算符、能力或结果渲染器需要 SDK Schema/API/CLI 和宿主共同支持。`operations.version` 选择协议,`requires` 在支持操作机制的宿主上检查能力,`engines.motrix` 声明真实的最低宿主版本。旧宿主可能在安装时拒绝未知清单,不一定能进入不可用操作页面。 + +当前引擎最低版本目标为 beta.48。正式发布前须确认 beta.48 实际包含这些能力;若延期,最低版本必须提高到首个实际支持的版本。使用配套 SDK/CLI,并保持包清单与注册表的兼容性、权限信息一致。CLI 在构建时内嵌 Schema,单独更新 Schema 依赖不能更新旧 CLI。公开 Schema 地址也可能落后于当前开发实现。官方包的签名继续由官方插件仓库负责,本仓库示例保持未签名。 + +| 现象 | 检查项 | +|---|---| +| 清单校验失败 | 宿主和 CLI 是否匹配;处理命令是否为私有 `execution: operation`;是否为扁平有界 Schema;是否声明所需能力 | +| 布局被拒绝 | 包括 accessory 在内,每个字段是否恰好引用一次;结构与深度是否超限 | +| 条件字段被拒绝 | 引用的普通字段和值是否存在;有条件的必填项是否有默认值 | +| 文件绑定被拒绝 | 必填字符串、无默认值与枚举、权限、输出扩展名和返回输出是否齐全 | +| 显示 `%key%` 或意外英文 | `l10n`、英文覆盖、当前语言键、是否使用完整字段引用 | +| 文件操作文案重复 | 从 `help`、`placeholder` 中移除重复的宿主指引;`browseLabel` 是无障碍名称 | +| `resourceLimit` | 进度频率、读取或探测次数、文件大小、并发草稿和可用磁盘空间 | +| 输出被拒绝 | 选择尚不存在的目标文件,不能关闭防覆盖保护 | + +从完整示例开始修改。示例 README 提供 Electron/Web、多语言、取消和文件授权的预期行为与手工检查步骤。通过 CLI 校验不能证明这些运行流程全部正确。 diff --git a/examples/media-merge/README.md b/examples/media-merge/README.md new file mode 100644 index 0000000..b588972 --- /dev/null +++ b/examples/media-merge/README.md @@ -0,0 +1,115 @@ +# Media merge operation example (unreleased) + +**English** | [简体中文](./README.zh-CN.md) + +A complete SDK example adapted from the official optional `motrix.media-merge` +plugin. The official implementation and signing authority remain in +[motrixapp/builtin-plugins](https://github.com/motrixapp/builtin-plugins). +This teaching copy uses **`example.media-merge`** and a distinct display name so +it can be installed as an unsigned third-party example without impersonating the +official plugin or requiring its signing key. It is not a marketplace release. + +**Requires the unreleased operations implementation in both the SDK and host.** +`engines.motrix` is `>=2.0.0-beta.48 <3.0.0`, targeting beta.48 as the first +supporting host release. This is a release target, not published availability. +Beta.47 is rejected, including development builds still reporting that version. +If the feature ships later, raise the minimum accordingly. Use matching SDK +packages and configure FFmpeg in the compatible host before using the operation. + +## Complete source + +| File | What to inspect | +|---|---| +| [motrix-plugin.json](./motrix-plugin.json) | Private command, bounded schemas, file bindings, two entry points, grid/accessory layout and repeat policy | +| [src/index.ts](./src/index.ts) | Track probing, automatic order correction, cancellation check and scoped merge | +| [locales/en-US.json](./locales/en-US.json) | All English UI and business-error text | +| [locales/zh-CN.json](./locales/zh-CN.json) | All Chinese UI and business-error text | +| [tsconfig.json](./tsconfig.json) | Strict checking against this SDK checkout's ambient API declaration | + +The source files are complete, not snippets. See the +[operation authoring guide](../../docs/operations.md) for the full protocol. + +## Build and validate + +From the SDK repository root: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/media-merge/tsconfig.json +cd examples/media-merge +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +Output: `dist/example.media-merge-0.1.0.moext`. These commands neither sign nor +publish. Install using the compatible host's normal third-party package flow. +Review `ffmpeg`, `files.selected.read` and `files.selected.write` permissions. +There is no network permission or download lifecycle hook. A published CLI with +an older embedded schema cannot validate this example. The TypeScript include is +checkout-relative by design; standalone projects need matching API types when +those packages are released. + +## Behavior and UI + +The operation shows two file cards in a responsive two-column grid. The output +spans the row with an MP4/MKV selector next to its label. It suggests a name based +on the video input plus `-merged`, with an extension matching the selected format. +A suggested path does not authorize writing: the host still requests output +selection/confirmation. Desktop and Web show different file-location hints. + +The handler probes both authorized inputs. If the selected order does not supply +video first and audio second but the reversed order does, it swaps the references +for execution. It copies the first video and audio tracks without re-encoding. +It does not concatenate clips, adjust synchronization, transcode incompatible +codecs or visually exchange the selected cards. If MP4 rejects a codec, try MKV. + +The plugin page and the task menu share the same operation. The task menu accepts +exactly two completed single-file tasks with local final files. The host owns +progress, cancellation, snapshots, output validation and non-overwriting save. +**Merge another file** uses `preserve-options`: clear both inputs, output and old +result, retain MP4/MKV, and do not reapply the previous task selection. + +Both languages are complete. Host language changes update labels without clearing +current selections. Generic drop/change/cancel/status text comes from the host; +`browseLabel` is the file card's accessible name. + +## Manual verification + +These are verification steps, not a claim that every platform has been tested: + +1. In Electron, choose standalone video and audio files with the native dialogs; + save to a new MP4/MKV path. In Web, choose files on the Motrix server within + its configured directory policy. Browser-local files are not uploaded. +2. Try unambiguously reversed inputs. The resulting file should contain video + and audio; the form need not visually swap the cards. Try the same input twice + and a pair missing the required tracks; expect an error and no published output. +3. Change MP4/MKV and confirm the output extension follows it. Select an existing + destination; expect rejection, with the original untouched. +4. Start a sufficiently long operation and cancel before final publication. + Wait for cleanup to settle: no final output should be published and inputs + should remain unchanged. Late cancellation cannot delete an already saved result. +5. Complete a job, click **Merge another file**, and verify empty file selections + with the format retained. Switch pages, refresh, and change English/Chinese; + check state handling, no repeated hint text and no unexpected untranslated labels. +6. Test both entry points. Disable the plugin or remove FFmpeg availability and + verify the host explains why the operation cannot run. +7. For desktop drops, confirm only the intended file through the host prompt. + A forged path, stale reference or reference from another invocation must not + become file access. Never test by weakening the host's authorization checks. + +Inputs must be supported standalone media, not playlists, concat scripts or image +sequences. Indirect local/network references are not authorized. Current limits +include 8 GiB per input, 16 GiB total, at most four probes/two simultaneous probes, +one merge and sufficient free space for snapshots/staging. Unsupported destination +filesystems fail safely. See the guide for shared time, draft and descriptor limits. + +## Adapt the example + +Change the plugin ID and every operation/command/activation reference together; +use your own non-reserved publisher. Keep `argsSchema`, `fields`, `ui.layout`, +file bindings, handler types and locale keys aligned. Change business behavior in +the sandbox handler and presentation in the manifest. Do not copy official +identity or signing assumptions. The SDK teaching copy is not the release source +for the official plugin. diff --git a/examples/media-merge/README.zh-CN.md b/examples/media-merge/README.zh-CN.md new file mode 100644 index 0000000..3820dd1 --- /dev/null +++ b/examples/media-merge/README.zh-CN.md @@ -0,0 +1,63 @@ +# 音视频合并操作示例(尚未发布) + +[English](./README.md) | **简体中文** + +这是根据官方可选插件 `motrix.media-merge` 改编的完整 SDK 示例。官方实现和签名权限仍属于 [motrixapp/builtin-plugins](https://github.com/motrixapp/builtin-plugins)。教学版本使用 **`example.media-merge`** 和独立显示名称,可以作为未签名第三方示例安装,不冒用官方插件,也不需要官方签名密钥。它不是已经上架的插件。 + +**需要 SDK 和宿主都包含尚未发布的操作实现。** `engines.motrix` 为 `>=2.0.0-beta.48 <3.0.0`,以 beta.48 为首个支持版本目标,不代表已经发布。beta.47 会被拒绝,包括仍使用该版本号的开发构建。若功能延期,最低版本也必须相应提高。使用匹配的 SDK 包,并在兼容宿主中配置 FFmpeg。 + +## 完整源码 + +| 文件 | 阅读重点 | +|---|---| +| [motrix-plugin.json](./motrix-plugin.json) | 私有命令、有界 Schema、文件绑定、两个入口、网格及 accessory 布局、重复执行策略 | +| [src/index.ts](./src/index.ts) | 轨道探测、输入顺序修正、取消检查和受限合并 | +| [locales/en-US.json](./locales/en-US.json) | 完整英文界面和业务错误文案 | +| [locales/zh-CN.json](./locales/zh-CN.json) | 完整中文界面和业务错误文案 | +| [tsconfig.json](./tsconfig.json) | 使用当前 SDK 仓库 ambient API 声明进行严格类型检查 | + +以上文件是完整源码,不是片段。完整协议说明见 [操作编写指南](../../docs/operations.zh-CN.md)。 + +## 构建与校验 + +从 SDK 仓库根目录开始: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/media-merge/tsconfig.json +cd examples/media-merge +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +输出为 `dist/example.media-merge-0.1.0.moext`。这些命令不会签名或发布。通过兼容宿主的正常第三方安装流程安装,检查 `ffmpeg`、`files.selected.read`、`files.selected.write` 权限。示例没有网络权限或下载生命周期 Hook。内嵌旧 Schema 的已发布 CLI 不能校验此示例。TypeScript include 有意使用仓库相对路径;独立项目需要在相关包发布后使用匹配的 API 类型。 + +## 行为与界面 + +两个输入文件卡片使用响应式双栏布局;输出区域跨一整行,标签旁显示 MP4/MKV 选择器。建议文件名来自视频输入,加上 `-merged`,扩展名跟随格式。建议路径不授予写权限,宿主仍要求选择或确认输出。桌面和 Web 显示不同的文件位置提示。 + +处理函数探测两个授权输入。如果当前顺序不能提供“视频在前、音频在后”,但反向顺序可以,就交换执行时的引用。它直接复制第一条视频轨和音频轨,不重新编码,不做片段拼接、同步偏移、编码转换,也不会在界面上交换已选卡片。MP4 不支持当前编码时可以尝试 MKV。 + +插件详情页和任务菜单共用同一操作。任务菜单接受恰好两个已完成的单文件任务,且存在本地最终文件。宿主负责进度、取消、快照、输出校验和无覆盖保存。“再次合并”使用 `preserve-options`:清空两个输入、输出和上次结果,保留 MP4/MKV,不重新填入上次任务选择。 + +两种语言的文案均完整,切换宿主语言会更新标签而不清空当前选择。通用拖入、更换、取消和状态文字来自宿主;`browseLabel` 是文件卡片的无障碍名称。 + +## 手工验证 + +以下是验证步骤,不代表所有平台均已验证: + +1. Electron 使用原生对话框选择独立视频和音频,保存到新的 MP4/MKV 路径。Web 在服务端目录策略范围内选择 Motrix 服务器文件,不上传浏览器本机文件。 +2. 将明确的视频和音频输入选反,输出应同时包含视频和音频,表单不必交换卡片。重复选择同一文件,或选择缺少所需轨道的文件,应报错且不生成最终输出。 +3. 切换 MP4/MKV,确认输出扩展名随之改变。选择已有目标文件,应被拒绝且不改动原文件。 +4. 开始足够长的操作,在最终保存前取消。等待清理完成,不应生成最终输出,源文件保持不变。迟到的取消不能删除已成功保存的结果。 +5. 完成后点击“再次合并”,确认文件选择清空而格式保留。切换页面、刷新、中英文切换,检查状态、重复提示和意外未翻译标签。 +6. 测试两个入口;停用插件或使 FFmpeg 不可用,确认宿主解释不能执行的原因。 +7. 桌面拖放时只在宿主确认框中授权目标文件。伪造路径、过期引用或另一调用的引用都不能取得文件访问权,不得通过削弱宿主授权检查来测试。 + +输入必须是支持的独立媒体,不能是播放列表、concat 脚本或图片序列,内部引用的本地或网络资源不因此获得授权。当前限制包括每个输入 8 GiB、总输入 16 GiB、最多四次探测及两次并行探测、一次合并,还需要足够快照和暂存空间。不支持的目标文件系统会安全失败。共享的时间、草稿和描述大小限制见指南。 + +## 改造成自己的插件 + +同时修改插件 ID、所有操作和命令 ID、激活引用,使用自己的非保留发布者。保持 `argsSchema`、`fields`、`ui.layout`、文件绑定、处理函数类型和翻译键一致。业务行为在沙箱处理函数中修改,呈现在清单中修改。不要复制官方身份或签名前提;SDK 教学版本不是官方插件的发布源码。 diff --git a/examples/media-merge/locales/en-US.json b/examples/media-merge/locales/en-US.json new file mode 100644 index 0000000..bdf3a03 --- /dev/null +++ b/examples/media-merge/locales/en-US.json @@ -0,0 +1,26 @@ +{ + "name": "Media Merge Example", + "description": "Combine local video and audio into MP4 or MKV through plugin operations without re-encoding.", + "merge": "Merge audio and video", + "differentFiles": "Choose two different files.", + "missingStreams": "The selected files must provide a video track and an audio track. Check the files and try again.", + "operationDescription": "Bring your video and audio together in one file, without re-encoding.", + "videoInput": "Video file", + "audioInput": "Audio file", + "format": "Output format", + "output": "Output file", + "videoInputPlaceholder": "Choose video", + "audioInputPlaceholder": "Choose audio", + "outputPlaceholder": "Choose a save location", + "videoInputBrowse": "Choose video file", + "audioInputBrowse": "Choose audio file", + "outputBrowse": "Choose output file", + "videoInputHint": "The picture for your merged file", + "audioInputHint": "The sound for your merged file", + "outputHint": "Save as MP4 or MKV", + "outputNotice": "Use a new filename; existing files cannot be overwritten. If MP4 is incompatible, try MKV.", + "serverNotice": "Select files on the Motrix server. Files on this computer are not uploaded.", + "mergeAction": "Merge", + "mergeAgain": "Merge another file", + "preserveOriginals": "Original files are kept" +} diff --git a/examples/media-merge/locales/zh-CN.json b/examples/media-merge/locales/zh-CN.json new file mode 100644 index 0000000..ee934f5 --- /dev/null +++ b/examples/media-merge/locales/zh-CN.json @@ -0,0 +1,26 @@ +{ + "name": "音视频合并示例", + "description": "通过插件操作将本地音视频合并为 MP4 或 MKV,无需重新编码。", + "merge": "合并音频和视频", + "differentFiles": "请选择两个不同的文件。", + "missingStreams": "所选文件需要分别提供视频轨和音频轨,请检查文件后重试。", + "operationDescription": "将视频画面与音频合为一个文件,无需重新编码。", + "videoInput": "视频文件", + "audioInput": "音频文件", + "format": "输出格式", + "output": "输出文件", + "videoInputPlaceholder": "选择视频", + "audioInputPlaceholder": "选择音频", + "outputPlaceholder": "选择保存位置", + "videoInputBrowse": "选择视频文件", + "audioInputBrowse": "选择音频文件", + "outputBrowse": "选择输出文件", + "videoInputHint": "提供合并后的画面", + "audioInputHint": "提供合并后的声音", + "outputHint": "保存为 MP4 或 MKV", + "outputNotice": "请使用新文件名,已有文件不会被覆盖。MP4 不兼容时可尝试 MKV。", + "serverNotice": "选择 Motrix 服务器上的文件;不会上传本机文件。", + "mergeAction": "合并", + "mergeAgain": "再次合并", + "preserveOriginals": "无损合并,保留源文件" +} diff --git a/examples/media-merge/motrix-plugin.json b/examples/media-merge/motrix-plugin.json new file mode 100644 index 0000000..3ddbde8 --- /dev/null +++ b/examples/media-merge/motrix-plugin.json @@ -0,0 +1,224 @@ +{ + "manifestVersion": 1, + "id": "example.media-merge", + "name": "%name%", + "version": "0.1.0", + "description": "%description%", + "categories": ["post-action"], + "engines": { + "motrix": ">=2.0.0-beta.48 <3.0.0" + }, + "main": "dist/plugin.js", + "permissions": ["ffmpeg", "files.selected.read", "files.selected.write"], + "activationEvents": ["onCommand:example.media-merge.mergeStreams"], + "contributes": { + "commands": [ + { + "id": "example.media-merge.mergeStreams", + "title": "%merge%", + "public": false, + "argsSchema": { + "type": "object", + "properties": { + "videoInput": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "audioInput": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "format": { + "type": "string", + "enum": ["mp4", "mkv"], + "default": "mp4" + } + }, + "required": ["videoInput", "audioInput", "output", "format"], + "additionalProperties": false + }, + "resultSchema": { + "type": "object", + "properties": { + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + } + }, + "required": ["output"], + "additionalProperties": false + }, + "execution": "operation" + } + ], + "operations": { + "version": 1, + "items": [ + { + "id": "example.media-merge.merge", + "title": "%merge%", + "description": "%operationDescription%", + "icon": "media-merge", + "command": "example.media-merge.mergeStreams", + "requires": [ + "operations.v1", + "files.selected.v1", + "media.merge-streams.v1", + "operations.ui.v1" + ], + "fields": [ + { + "field": "videoInput", + "label": "%videoInput%", + "appearance": { + "icon": "video", + "tone": "blue", + "placeholder": "%videoInputPlaceholder%", + "browseLabel": "%videoInputBrowse%", + "drop": true + }, + "help": "%videoInputHint%" + }, + { + "field": "audioInput", + "label": "%audioInput%", + "appearance": { + "icon": "audio", + "tone": "violet", + "placeholder": "%audioInputPlaceholder%", + "browseLabel": "%audioInputBrowse%", + "drop": true + }, + "help": "%audioInputHint%" + }, + { + "field": "format", + "label": "%format%", + "widget": "segmented", + "optionLabels": { + "mp4": "MP4", + "mkv": "MKV" + } + }, + { + "field": "output", + "label": "%output%", + "appearance": { + "icon": "folder", + "tone": "amber", + "placeholder": "%outputPlaceholder%", + "browseLabel": "%outputBrowse%" + }, + "help": "%outputHint%" + } + ], + "files": { + "videoInput": { + "kind": "input-file", + "use": "media" + }, + "audioInput": { + "kind": "input-file", + "use": "media" + }, + "output": { + "kind": "output-file", + "use": "media", + "extensionFrom": "format", + "suggestedName": { + "stemFrom": "videoInput", + "suffix": "-merged" + } + } + }, + "entries": [ + { + "surface": "plugin-detail" + }, + { + "surface": "task-menu", + "selection": { + "count": { + "min": 2, + "max": 2 + }, + "every": { + "status": "completed", + "files": "single", + "local": true + } + }, + "bind": { + "videoInput": { + "source": "task-file", + "index": 0 + }, + "audioInput": { + "source": "task-file", + "index": 1 + } + } + } + ], + "result": { + "files": ["output"] + }, + "errors": { + "differentFiles": "%differentFiles%", + "missingStreams": "%missingStreams%" + }, + "ui": { + "layout": { + "type": "stack", + "children": [ + { + "type": "grid", + "columns": 2, + "children": [ + { + "type": "field", + "field": "videoInput" + }, + { + "type": "field", + "field": "audioInput" + }, + { + "type": "field", + "field": "output", + "span": 2, + "accessory": "format" + } + ] + }, + { + "type": "text", + "text": "%outputNotice%", + "platform": "desktop" + }, + { + "type": "text", + "text": "%serverNotice%", + "platform": "web" + } + ] + }, + "submitLabel": "%mergeAction%", + "repeatLabel": "%mergeAgain%", + "footer": "%preserveOriginals%", + "repeat": "preserve-options" + } + } + ] + } + }, + "l10n": "locales" +} diff --git a/examples/media-merge/src/index.ts b/examples/media-merge/src/index.ts new file mode 100644 index 0000000..afb1098 --- /dev/null +++ b/examples/media-merge/src/index.ts @@ -0,0 +1,36 @@ +import { commands } from 'motrix:plugin-api' + +commands.registerOperation< + { + videoInput: string + audioInput: string + output: string + format: 'mp4' | 'mkv' + }, + { output: string } +>( + 'example.media-merge.mergeStreams', + async ({ videoInput, audioInput, output, format }, context) => { + if (videoInput === audioInput) context.fail('differentFiles') + const first = await context.media.probe(videoInput) + const second = await context.media.probe(audioInput) + const has = (info: typeof first, type: string) => + info.streams.some((stream) => stream.type === type) + let durationMs = first.durationMs + if (!(has(first, 'video') && has(second, 'audio'))) { + if (!(has(second, 'video') && has(first, 'audio'))) + context.fail('missingStreams') + ;[videoInput, audioInput] = [audioInput, videoInput] + durationMs = second.durationMs + } + context.signal.throwIfAborted() + await context.media.mergeStreams({ + video: videoInput, + audio: audioInput, + output, + format, + expectedDurationMs: durationMs, + }) + return { output } + } +) diff --git a/examples/media-merge/tsconfig.json b/examples/media-merge/tsconfig.json new file mode 100644 index 0000000..98c3060 --- /dev/null +++ b/examples/media-merge/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "types": [], + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "../../packages/plugin-api/src/virtual-module.d.ts"] +} diff --git a/examples/text-tools/README.md b/examples/text-tools/README.md new file mode 100644 index 0000000..f254440 --- /dev/null +++ b/examples/text-tools/README.md @@ -0,0 +1,124 @@ +# Text deduplication operation example (unreleased) + +**English** | [简体中文](./README.zh-CN.md) + +A complete unsigned third-party example, `community.text-tools`, that removes +duplicate lines from a user-selected UTF-8 file and saves a new file. It uses the +same operation protocol as the media example, without FFmpeg, network permission +or unrestricted filesystem access. It is not a marketplace release. + +**Requires the unreleased operations implementation in both the SDK and host.** +The engine range is `>=2.0.0-beta.48 <3.0.0`, targeting beta.48 as the first +supporting host release. It must actually provide `operations.ui.v1` and +`files.text.v1`; raise the minimum if those features ship later. Beta.47 is +rejected, including development builds still reporting that version. This target +does not imply published host or npm package support. + +## Complete source + +| File | What to inspect | +|---|---| +| [motrix-plugin.json](./motrix-plugin.json) | Bounded argument/result schemas, file cards, switch, collapsible group, result count and task binding | +| [src/index.ts](./src/index.ts) | Scoped read/write, first-occurrence deduplication, cancellation checks and progress | +| [locales/en-US.json](./locales/en-US.json) | Complete English UI text | +| [locales/zh-CN.json](./locales/zh-CN.json) | Complete Chinese UI text | +| [tsconfig.json](./tsconfig.json) | Strict checking against this SDK checkout's ambient API declaration | + +All files are complete source. See the +[operation authoring guide](../../docs/operations.md) for the shared protocol. + +## Build and validate + +From the SDK repository root: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/text-tools/tsconfig.json +cd examples/text-tools +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +Output: `dist/community.text-tools-0.1.0.moext`. These commands do not sign or +publish. Use the compatible host's third-party install flow and review +`files.selected.read` / `files.selected.write`. There is no example dependency +installation; commands and types resolve to this SDK checkout. Published packages +with older contracts do not work as substitutes. `pack` bundles the source; +`lint` checks that bundle and must run afterwards. Type checking is separate. + +## Behavior and UI + +Choose an input `.txt` file, optionally enable **Ignore case** in the initially +expanded **Matching options** group, and select a new output `.txt` file. The +host suggests an input-based `-unique` filename but still requires output +authorization. The handler reads UTF-8, keeps the first occurrence of each line +in its original position and spelling, writes the result, and returns the output +reference plus `lines`. `result.fields` exposes that count with a localized title. + +Comparison follows the sample's literal `split('\n')` algorithm: no trimming, +locale-specific case folding or line-ending normalization. With **Ignore case**, +keys use JavaScript `toLowerCase()`. Empty lines count as lines, including the +last empty segment after a trailing newline; even an empty input has one split +segment. CRLF retains its `\r` characters. This is an intentionally small example, +not a complete text-cleaning product. + +For the input string `Apple\napple\nBanana\nApple` **without a trailing newline**: + +| Ignore case | Output | Result count | +|---|---|---:| +| Off | `Apple\napple\nBanana` | 3 | +| On | `Apple\nBanana` | 2 | + +**Process another copy** uses `preserve-inputs`: retain scalar options, recheck +unchanged input identity and obtain a fresh invocation grant, then clear output. +It does not replay a job automatically. The task menu also supports one completed +single-file task with a local final file. Both entry points use the same handler. + +Labels, hints, actions and result titles follow the host language through `%key%` +references. Both English and Chinese are included; other languages fall back to +English. Language switching preserves the form and selected files. + +## Manual verification + +These steps describe expected behavior, not universal platform test coverage: + +1. Install and enable the example, open its operation, and process the sample + string above with **Ignore case** off and on. Confirm output and count. +2. In Electron, use native input/save dialogs. In Web, select server files within + the allowed directory policy. Browser-local files are not uploaded. +3. Verify the collapsible option, input/output labels, progress and result count + in English and Chinese. Generic file-action hints should not be repeated. +4. Click **Process another copy**: input and options remain, output clears. If + the input changed since selection, reauthorization must reject the stale file. +5. Choose an existing output, a disallowed file type, invalid UTF-8, or text larger + than 1 MiB. Expect rejection without overwriting files or publishing partial + output. A forged path/ref or another invocation's ref must not grant access. +6. Cancel before final publication and wait for cleanup. No partial output should + appear and input should remain unchanged. Small inputs can complete too quickly + to cancel manually; that is not cancellation evidence. Use a controlled host + integration test for deterministic cancellation, without adding an unsafe API. +7. Use the completed-task menu entry; repeat should use fresh grants. Switch pages + and refresh while the host remains running; do not treat a historical success + as a newly executed operation. + +The host limits UTF-8 input/output to 1 MiB, allows at most four text reads and one +write per output, and rejects existing destinations. Cancellation, finalization +and temporary resources belong to the host. See the guide for shared limits. + +## Adapt the example + +Change the plugin ID and matching operation/command/activation references to your +own non-reserved publisher. Add bounded scalar arguments before adding their +`fields` and layout references; every argument and every layout binding must +appear exactly once. Keep handler types and locales aligned. Business rules go in +the sandbox handler, not `visibleWhen` or an invented UI callback. + +## Generate a project with your own identity + +The development CLI now provides `init -t operation [-p publisher]` and +`create-motrix-plugin operation`. They generate this text-operation starting +point with substituted identities, standalone package-based type checking, build +scripts and paired READMEs. Follow the [guide](../../docs/operations.md) for the +matching local SDK dependency setup; published template/API support is not implied. diff --git a/examples/text-tools/README.zh-CN.md b/examples/text-tools/README.zh-CN.md new file mode 100644 index 0000000..8ab327d --- /dev/null +++ b/examples/text-tools/README.zh-CN.md @@ -0,0 +1,74 @@ +# 文本去重操作示例(尚未发布) + +[English](./README.md) | **简体中文** + +这是完整的未签名第三方示例 `community.text-tools`,去除用户所选 UTF-8 文件中的重复行并另存新文件。它与媒体示例使用相同的操作协议,不需要 FFmpeg、网络权限或任意文件系统访问。它不是已经上架的插件。 + +**需要 SDK 和宿主都包含尚未发布的操作实现。** 引擎范围为 `>=2.0.0-beta.48 <3.0.0`,以 beta.48 为首个支持版本目标;它必须实际提供 `operations.ui.v1` 和 `files.text.v1`,若延期须同步提高最低版本。beta.47 会被拒绝,包括仍使用该版本号的开发构建。此目标不代表宿主或 npm 包已发布支持。 + +## 完整源码 + +| 文件 | 阅读重点 | +|---|---| +| [motrix-plugin.json](./motrix-plugin.json) | 有界参数与结果 Schema、文件卡片、开关、折叠组、结果计数和任务绑定 | +| [src/index.ts](./src/index.ts) | 受限读写、保留首次出现行的去重、取消检查和进度 | +| [locales/en-US.json](./locales/en-US.json) | 完整英文 UI 文案 | +| [locales/zh-CN.json](./locales/zh-CN.json) | 完整中文 UI 文案 | +| [tsconfig.json](./tsconfig.json) | 使用当前 SDK 仓库 ambient API 声明进行严格类型检查 | + +所有文件均为完整源码,共享协议见 [操作编写指南](../../docs/operations.zh-CN.md)。 + +## 构建与校验 + +从 SDK 仓库根目录开始: + +```sh +pnpm install --frozen-lockfile +pnpm build +pnpm --filter @motrix/plugin-api exec tsc --noEmit -p ../../examples/text-tools/tsconfig.json +cd examples/text-tools +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js validate +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js pack +node ../../packages/plugin-cli/dist/bin/motrix-plugin.js lint +``` + +输出为 `dist/community.text-tools-0.1.0.moext`。这些命令不签名或发布。通过兼容宿主的第三方安装流程安装,检查 `files.selected.read`、`files.selected.write` 权限。无需为示例单独安装依赖,命令和类型都来自当前 SDK 仓库;契约较旧的已发布包不能代替。`pack` 打包源码,`lint` 检查生成的 bundle,必须在后面执行;类型检查是独立步骤。 + +## 行为与界面 + +选择输入 `.txt` 文件,在默认展开的“匹配选项”组中按需启用“忽略大小写”,再选择新的输出 `.txt`。宿主建议基于输入加 `-unique` 的文件名,但仍要求输出授权。处理函数读取 UTF-8,保留每行第一次出现的位置和原有大小写,写入结果,返回输出引用及 `lines`。`result.fields` 使用本地化标题展示该计数。 + +比较遵循示例的 `split('\n')` 算法,不裁剪空白,不按特定语言进行大小写折叠,也不归一化换行格式。“忽略大小写”通过 JavaScript `toLowerCase()` 生成比较键。空行也计为一行,包括末尾换行产生的空片段;空文件也有一个分割片段。CRLF 中的 `\r` 会保留。这是刻意保持简单的示例,不是完整文本清洗产品。 + +对于**没有末尾换行**的输入字符串 `Apple\napple\nBanana\nApple`: + +| 忽略大小写 | 输出 | 结果计数 | +|---|---|---:| +| 关闭 | `Apple\napple\nBanana` | 3 | +| 开启 | `Apple\nBanana` | 2 | + +“再次处理”使用 `preserve-inputs`:保留普通选项,重新检查未变化的输入身份并获得新的单次调用授权,清空输出。它不会自动重放任务。任务菜单支持一个已完成的单文件任务,且存在本地最终文件;两个入口共用同一处理函数。 + +标签、说明、按钮和结果标题通过 `%key%` 引用跟随宿主语言。示例同时包含英文和中文,其他语言回退英文。语言切换保留表单和已选文件。 + +## 手工验证 + +以下描述预期行为,不代表所有平台均已完成验证: + +1. 安装并启用示例,在操作页用上述字符串分别测试关闭、开启“忽略大小写”,确认输出和计数。 +2. Electron 使用原生输入和保存对话框;Web 在允许的目录策略内选择服务端文件,不上传浏览器本机文件。 +3. 在中英文下检查折叠选项、输入输出标签、进度和结果计数,通用文件操作指引不应重复。 +4. 点击“再次处理”,输入和选项保留,输出清空。若输入自选择后发生变化,重新授权必须拒绝旧文件。 +5. 选择已有输出、不允许的文件类型、无效 UTF-8 或超过 1 MiB 的文本,应被拒绝,不覆盖文件、不生成部分输出。伪造路径或引用、另一调用的引用不能取得访问权。 +6. 在最终保存前取消并等待清理,不应出现部分输出,输入保持不变。小文件可能快到无法手工取消,这不能作为取消验证证据。确定性取消应使用受控宿主集成测试,不增加不安全 API。 +7. 使用已完成任务菜单入口,再次处理应获得新授权。在宿主持续运行时切换页面、刷新,不把历史成功状态当成新执行的结果。 + +宿主将 UTF-8 输入和输出各限制为 1 MiB,最多读取四次,每个输出写入一次,并拒绝已有目标。取消、最终保存和临时资源由宿主管理,共享限制见指南。 + +## 改造成自己的插件 + +将插件 ID 以及对应操作、命令、激活引用改为自己的非保留发布者。先定义有界普通参数,再添加对应 `fields` 和布局引用;参数定义和布局绑定都必须恰好出现一次。保持处理函数类型与翻译文件一致。业务规则放在沙箱处理函数中,不要放进 `visibleWhen`,也不要发明 UI 回调字段。 + +## 生成自己的项目 + +开发版 CLI 现提供 `init -t operation [-p publisher]` 和 `create-motrix-plugin operation`,以此文本操作为起点,自动替换身份,生成基于安装包的独立类型检查配置、构建脚本和成对 README。请按 [指南](../../docs/operations.zh-CN.md) 配置匹配的本地 SDK 依赖,不能据此推断已发布模板或 API 支持。 diff --git a/examples/text-tools/locales/en-US.json b/examples/text-tools/locales/en-US.json new file mode 100644 index 0000000..693098d --- /dev/null +++ b/examples/text-tools/locales/en-US.json @@ -0,0 +1,19 @@ +{ + "name": "Text tools", + "description": "Remove duplicate lines from a selected text file and save a new copy.", + "deduplicate": "Deduplicate lines", + "operationDescription": "Remove duplicate lines while keeping their original order, then save a new UTF-8 file.", + "input": "Input file", + "inputPlaceholder": "Choose a text file", + "inputBrowse": "Choose input file", + "output": "Output file", + "outputPlaceholder": "Choose a save location", + "outputBrowse": "Choose output file", + "ignoreCase": "Ignore case", + "ignoreCaseHelp": "Treat Apple and apple as the same line.", + "matchingOptions": "Matching options", + "uniqueLines": "Unique lines", + "submit": "Deduplicate", + "repeat": "Process another copy", + "footer": "Original text stays unchanged." +} diff --git a/examples/text-tools/locales/zh-CN.json b/examples/text-tools/locales/zh-CN.json new file mode 100644 index 0000000..573bbb0 --- /dev/null +++ b/examples/text-tools/locales/zh-CN.json @@ -0,0 +1,19 @@ +{ + "name": "文本工具", + "description": "去除所选文本文件中的重复行,并另存为新文件。", + "deduplicate": "文本去重", + "operationDescription": "去除重复行,保留原有顺序,并另存为 UTF-8 文本文件。", + "input": "输入文件", + "inputPlaceholder": "选择文本文件", + "inputBrowse": "选择输入文件", + "output": "输出文件", + "outputPlaceholder": "选择保存位置", + "outputBrowse": "选择输出文件", + "ignoreCase": "忽略大小写", + "ignoreCaseHelp": "将 Apple 和 apple 视为同一行。", + "matchingOptions": "匹配选项", + "uniqueLines": "去重后行数", + "submit": "去重", + "repeat": "再次处理", + "footer": "保留原始文本文件。" +} diff --git a/examples/text-tools/motrix-plugin.json b/examples/text-tools/motrix-plugin.json new file mode 100644 index 0000000..12f17d7 --- /dev/null +++ b/examples/text-tools/motrix-plugin.json @@ -0,0 +1,181 @@ +{ + "manifestVersion": 1, + "id": "community.text-tools", + "name": "%name%", + "version": "0.1.0", + "description": "%description%", + "categories": ["post-action"], + "engines": { + "motrix": ">=2.0.0-beta.48 <3.0.0" + }, + "main": "dist/plugin.js", + "permissions": ["files.selected.read", "files.selected.write"], + "activationEvents": ["onCommand:community.text-tools.deduplicate"], + "contributes": { + "commands": [ + { + "id": "community.text-tools.deduplicate", + "title": "%deduplicate%", + "execution": "operation", + "public": false, + "argsSchema": { + "type": "object", + "properties": { + "input": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "ignoreCase": { + "type": "boolean", + "default": false + } + }, + "required": ["input", "output", "ignoreCase"], + "additionalProperties": false + }, + "resultSchema": { + "type": "object", + "properties": { + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "lines": { + "type": "integer", + "title": "%uniqueLines%", + "minimum": 0, + "maximum": 1048576 + } + }, + "required": ["output", "lines"], + "additionalProperties": false + } + } + ], + "operations": { + "version": 1, + "items": [ + { + "id": "community.text-tools.deduplicate", + "title": "%deduplicate%", + "description": "%operationDescription%", + "icon": "document", + "command": "community.text-tools.deduplicate", + "requires": ["operations.v1", "operations.ui.v1", "files.text.v1"], + "fields": [ + { + "field": "input", + "label": "%input%", + "appearance": { + "icon": "document", + "tone": "blue", + "drop": true, + "placeholder": "%inputPlaceholder%", + "browseLabel": "%inputBrowse%" + } + }, + { + "field": "ignoreCase", + "label": "%ignoreCase%", + "widget": "switch", + "help": "%ignoreCaseHelp%" + }, + { + "field": "output", + "label": "%output%", + "appearance": { + "icon": "folder", + "tone": "amber", + "placeholder": "%outputPlaceholder%", + "browseLabel": "%outputBrowse%" + } + } + ], + "files": { + "input": { + "kind": "input-file", + "use": "text", + "extensions": ["txt"] + }, + "output": { + "kind": "output-file", + "use": "text", + "extensions": ["txt"], + "suggestedName": { + "stemFrom": "input", + "suffix": "-unique" + } + } + }, + "entries": [ + { + "surface": "plugin-detail" + }, + { + "surface": "task-menu", + "selection": { + "count": { + "min": 1, + "max": 1 + }, + "every": { + "status": "completed", + "files": "single", + "local": true + } + }, + "bind": { + "input": { + "source": "task-file", + "index": 0 + } + } + } + ], + "result": { + "fields": ["lines"], + "files": ["output"] + }, + "ui": { + "layout": { + "type": "stack", + "children": [ + { + "type": "field", + "field": "input" + }, + { + "type": "group", + "title": "%matchingOptions%", + "children": [ + { + "type": "field", + "field": "ignoreCase" + } + ], + "collapsible": true + }, + { + "type": "field", + "field": "output" + } + ] + }, + "submitLabel": "%submit%", + "repeatLabel": "%repeat%", + "footer": "%footer%", + "repeat": "preserve-inputs" + } + } + ] + } + }, + "l10n": "locales" +} diff --git a/examples/text-tools/src/index.ts b/examples/text-tools/src/index.ts new file mode 100644 index 0000000..9ce0d0e --- /dev/null +++ b/examples/text-tools/src/index.ts @@ -0,0 +1,19 @@ +import { commands } from 'motrix:plugin-api' + +commands.registerOperation< + { input: string; output: string; ignoreCase: boolean }, + { output: string; lines: number } +>('community.text-tools.deduplicate', async (args, context) => { + const text = await context.files.readText(args.input) + const seen = new Set() + const lines = text.split('\n').filter((line) => { + context.signal.throwIfAborted() + const key = args.ignoreCase ? line.toLowerCase() : line + if (seen.has(key)) return false + seen.add(key) + return true + }) + await context.progress({ phase: 'running', fraction: 0.5 }) + await context.files.writeText(args.output, lines.join('\n')) + return { output: args.output, lines: lines.length } +}) diff --git a/examples/text-tools/tsconfig.json b/examples/text-tools/tsconfig.json new file mode 100644 index 0000000..98c3060 --- /dev/null +++ b/examples/text-tools/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "types": [], + "strict": true, + "noEmit": true, + "skipLibCheck": true + }, + "include": ["src", "../../packages/plugin-api/src/virtual-module.d.ts"] +} diff --git a/packages/create-motrix-plugin/README.md b/packages/create-motrix-plugin/README.md index aef5224..ddd947b 100644 --- a/packages/create-motrix-plugin/README.md +++ b/packages/create-motrix-plugin/README.md @@ -12,5 +12,16 @@ This is a thin wrapper that delegates to `create-motrix-plugin` bin (`motrix-plugin init` under the hood). See the plugin-cli README for template options and the full authoring workflow. +## Operation template (unreleased) + +The development wrapper accepts `my-operation operation` as its two positional +arguments and generates a complete text deduplication project with publisher `me`. +For a custom publisher, use `motrix-plugin init my-operation -t operation -p acme`. +Use a matching development SDK and host; current published packages and the +generated dependency ranges do not establish support. See the [English guide](../../docs/operations.md) +or [Chinese guide](../../docs/operations.zh-CN.md) for a runnable source-checkout +workflow and local dependency setup. After matching packages are released, the +public shorthand will be `pnpm create motrix-plugin my-operation operation`. + Part of the [motrixapp/plugin-sdk](https://github.com/motrixapp/plugin-sdk) monorepo. MIT licensed. diff --git a/packages/plugin-api/README.md b/packages/plugin-api/README.md index 6bb0c46..1daa5a1 100644 --- a/packages/plugin-api/README.md +++ b/packages/plugin-api/README.md @@ -61,10 +61,14 @@ alongside `dist`, and TypeScript picks up ambient module declarations from any `.d.ts` under `node_modules/@types` or reachable via `include`/`types` in `node_modules/@motrix/plugin-api`. +## Plugin operations (unreleased) + +`commands.registerOperation` and `OperationContext` are development-only additions. The context exposes scoped file/media methods, progress, cancellation and business errors; it does not grant access to arbitrary paths. Use the matching host implementation and the complete source examples. + +See the [English guide](../../docs/operations.md) or [Chinese guide](../../docs/operations.zh-CN.md), including complete media and text examples, supported controls, limits and compatibility requirements. The examples target Motrix beta.48 or later (below 3.0.0), contingent on that release shipping the required features; this is not a claim of published support. + ## Learn more - Scaffold a new plugin with [`@motrix/plugin-cli`](https://www.npmjs.com/package/@motrix/plugin-cli) (`pnpm create motrix-plugin`) - Manifest shape is validated against [`@motrix/plugin-manifest-schema`](https://www.npmjs.com/package/@motrix/plugin-manifest-schema) -- Design background: `docs/superpowers/specs/2026-05-09-plugin-ecosystem-design.md` - in the [motrix-turbo](https://gitlab.com/agalwood/motrix-turbo) repository diff --git a/packages/plugin-api/src/virtual-module.d.ts b/packages/plugin-api/src/virtual-module.d.ts index 0e20e8d..55a7be6 100644 --- a/packages/plugin-api/src/virtual-module.d.ts +++ b/packages/plugin-api/src/virtual-module.d.ts @@ -135,7 +135,54 @@ declare module 'motrix:plugin-api' { onError(fn: (ctx: OnErrorContext) => Promise): void } + /** A ref is an opaque, single-invocation credential; it is never a path. */ + export interface OperationContext { + readonly jobId: string + /** Cancellation surface supported by the sandbox. Listener count is bounded. */ + readonly signal: Pick< + AbortSignal, + | 'aborted' + | 'reason' + | 'throwIfAborted' + | 'addEventListener' + | 'removeEventListener' + > + progress(value: { + phase: 'preparing' | 'running' + fraction?: number + }): Promise + fail(code: string): never + readonly media: { + probe(file: string): Promise<{ + durationMs?: number + streams: Array<{ + type: 'video' | 'audio' | 'subtitle' | 'other' + codec?: string + }> + }> + mergeStreams(value: { + video: string + audio: string + output: string + format: 'mp4' | 'mkv' + expectedDurationMs?: number + }): Promise + } + readonly files: { + readText(file: string): Promise + writeText(file: string, content: string): Promise + } + } + export const commands: { + /** Only a host-authorized operation may invoke this handler. */ + registerOperation( + id: string, + handler: ( + args: TArgs, + context: OperationContext + ) => Promise | TResult + ): void // biome-ignore lint/suspicious/noConfusingVoidType: void is intentional — handlers may return void register( id: string, diff --git a/packages/plugin-cli/README.md b/packages/plugin-cli/README.md index c59c9c3..f7f8dfd 100644 --- a/packages/plugin-cli/README.md +++ b/packages/plugin-cli/README.md @@ -19,10 +19,12 @@ pnpm dlx @motrix/plugin-cli init my-plugin ## Commands ```bash -motrix-plugin init [-t basic-resolver|post-action] [-p ] +motrix-plugin init [-t basic-resolver|post-action|operation] [-p ] ``` -Scaffold a new plugin project from a template (`basic-resolver` or -`post-action`) into `./`. +Scaffold a new plugin project from `basic-resolver`, `post-action` or the +**unreleased** `operation` template into `./`. `operation` starts with text +deduplication, a host-rendered form, a private handler, both locales, strict type +checking and paired READMEs. Use the operations guide for matching local SDK setup. ```bash motrix-plugin dev @@ -98,9 +100,13 @@ pnpm create motrix-plugin my-plugin [template] Equivalent to `motrix-plugin init`, usable without a prior install via the `create-*` npm convention. +## Plugin operations (unreleased) + +The development CLI validates and packs operation manifests using its embedded development schema. Use `init -t operation [-p publisher]` or `create-motrix-plugin operation` to generate a complete text-operation project. Build this checkout and follow the guide's local dependency setup; installing a published CLI with an older embedded schema is insufficient. Run `validate`, then `pack`, then `lint` (which reads the bundle), with TypeScript checking separately. + +See the [English guide](../../docs/operations.md) or [Chinese guide](../../docs/operations.zh-CN.md), including complete media and text examples, supported controls, limits and compatibility requirements. The examples target Motrix beta.48 or later (below 3.0.0), contingent on that release shipping the required features; this is not a claim of published support. + ## Learn more - Manifest shape reference: [`@motrix/plugin-manifest-schema`](https://www.npmjs.com/package/@motrix/plugin-manifest-schema) - Plugin runtime types: [`@motrix/plugin-api`](https://www.npmjs.com/package/@motrix/plugin-api) -- Design background: `docs/superpowers/specs/2026-05-09-plugin-ecosystem-design.md` - in the [motrix-turbo](https://gitlab.com/agalwood/motrix-turbo) repository diff --git a/packages/plugin-cli/src/bin/create-motrix-plugin.ts b/packages/plugin-cli/src/bin/create-motrix-plugin.ts index 067bee9..f45ca39 100644 --- a/packages/plugin-cli/src/bin/create-motrix-plugin.ts +++ b/packages/plugin-cli/src/bin/create-motrix-plugin.ts @@ -1,22 +1,20 @@ #!/usr/bin/env node -import { init } from '../commands/init' - -const validTemplates = ['basic-resolver', 'post-action'] as const -type Template = (typeof validTemplates)[number] +import { init, type TemplateName, templateNames } from '../commands/init' const [name = 'my-plugin', rawTemplate = 'basic-resolver'] = process.argv.slice(2) -if (!validTemplates.includes(rawTemplate as Template)) { +if (!templateNames.includes(rawTemplate as TemplateName)) { console.error( - `Unknown template: ${rawTemplate}. Available: ${validTemplates.join(', ')}` + `Unknown template: ${rawTemplate}. Available: ${templateNames.join(', ')}` ) process.exit(1) } -const template = rawTemplate as Template -await init({ +const template = rawTemplate as TemplateName +const result = await init({ projectName: name, template, destDir: process.cwd(), publisher: 'me', }) console.log('Created', name) +if (result.notice) console.log(result.notice) diff --git a/packages/plugin-cli/src/bin/motrix-plugin.ts b/packages/plugin-cli/src/bin/motrix-plugin.ts index dc11d00..469b9ee 100644 --- a/packages/plugin-cli/src/bin/motrix-plugin.ts +++ b/packages/plugin-cli/src/bin/motrix-plugin.ts @@ -1,7 +1,7 @@ #!/usr/bin/env node import { Command, Option } from 'commander' import { dev } from '../commands/dev' -import { init } from '../commands/init' +import { init, type TemplateName, templateNames } from '../commands/init' import { lint } from '../commands/lint' import { pack } from '../commands/pack' import { validate } from '../commands/validate' @@ -16,7 +16,7 @@ program .command('init ') .addOption( new Option('-t, --template ', 'template') - .choices(['basic-resolver', 'post-action']) + .choices(templateNames) .default('basic-resolver') ) .option('-p, --publisher ', 'publisher name', 'me') @@ -24,7 +24,7 @@ program async ( name: string, opts: { - template: 'basic-resolver' | 'post-action' + template: TemplateName publisher: string } ) => { @@ -35,6 +35,7 @@ program publisher: opts.publisher, }) console.log(`Created ${r.created}`) + if (r.notice) console.log(r.notice) } ) diff --git a/packages/plugin-cli/src/commands/init.ts b/packages/plugin-cli/src/commands/init.ts index 78390ef..42db623 100644 --- a/packages/plugin-cli/src/commands/init.ts +++ b/packages/plugin-cli/src/commands/init.ts @@ -10,14 +10,23 @@ const TEMPLATES = path.resolve( '../../templates' ) +export const templateNames = [ + 'basic-resolver', + 'post-action', + 'operation', +] as const +export type TemplateName = (typeof templateNames)[number] + export interface InitOptions { projectName: string - template: 'basic-resolver' | 'post-action' + template: TemplateName destDir: string publisher: string } -export async function init(opts: InitOptions): Promise<{ created: string }> { +export async function init( + opts: InitOptions +): Promise<{ created: string; notice?: string }> { const target = path.resolve(opts.destDir, opts.projectName) await mkdir(target, { recursive: true }) const src = path.join(TEMPLATES, opts.template) @@ -26,7 +35,15 @@ export async function init(opts: InitOptions): Promise<{ created: string }> { PUBLISHER: opts.publisher, PLUGIN_ID: `${opts.publisher}.${opts.projectName}`, }) - return { created: target } + return { + created: target, + ...(opts.template === 'operation' + ? { + notice: + 'Unreleased operation template: use matching development SDK packages and host. Read README.md before installing dependencies; published package versions do not establish operation support.', + } + : {}), + } } async function copyTree( diff --git a/packages/plugin-cli/src/templates/operation/.gitignore.tpl b/packages/plugin-cli/src/templates/operation/.gitignore.tpl new file mode 100644 index 0000000..5f5736a --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/.gitignore.tpl @@ -0,0 +1,8 @@ +node_modules/ +dist/ +*.tsbuildinfo +*.log +.env +.env.* +!.env.example +.DS_Store diff --git a/packages/plugin-cli/src/templates/operation/README.md.tpl b/packages/plugin-cli/src/templates/operation/README.md.tpl new file mode 100644 index 0000000..57deccd --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/README.md.tpl @@ -0,0 +1,94 @@ +# {{PROJECT_NAME}} + +**English** | [简体中文](./README.zh-CN.md) + +A text deduplication operation scaffolded for `{{PLUGIN_ID}}`. + +> **Unreleased protocol and template.** Use a Motrix development build and SDK +> packages that implement operations v1, composable UI and scoped text files. +> The host range is `>=2.0.0-beta.48 <3.0.0`, targeting beta.48 as the first +> supporting release. Beta.47 is rejected, including development builds still +> reporting that version. This target and the dependency ranges do not establish +> published support. Raise the host floor if these features ship after beta.48. + +## Set up matching development dependencies + +Build a matching plugin-sdk checkout first with `pnpm install --frozen-lockfile` +and `pnpm build` in that checkout. If this project was created immediately inside +that checkout's root, run the following **from this project directory**: + +```sh +pnpm add -D @motrix/plugin-api@file:../packages/plugin-api @motrix/plugin-cli@file:../packages/plugin-cli +``` + +If the project lives elsewhere, adjust both `file:` paths to the matching built +SDK packages. Do not replace this step with a plain install of the older published +API/CLI. The source checkout's schema is embedded in its CLI build. When matching +SDK packages are released, replace these local dependencies with their actual +released versions; no minimum published SDK package version is assigned here. + +## Check and pack + +```sh +pnpm run typecheck +pnpm run validate +pnpm run pack +pnpm run lint +``` + +`pack` bundles `src/index.ts` and writes the unsigned +`dist/{{PLUGIN_ID}}-0.1.0.moext`. `lint` checks the built bundle, so it runs after +`pack`. `pnpm run build` is an optional bundle-only step. No command here signs or +publishes. Install the archive through a compatible host's normal third-party +installation flow and review the two selected-file permissions. + +## Files to edit + +| File | Role | +|---|---| +| `motrix-plugin.json` | Private operation command, argument/result schemas, fields, layout, files, entries and repeat policy | +| `src/index.ts` | Typed sandbox handler, cancellation checks, progress and scoped file calls | +| `locales/en-US.json`, `locales/zh-CN.json` | Complete labels, hints, actions and result titles | +| `tsconfig.json` | Strict checking through the installed `@motrix/plugin-api`; no SDK checkout path is embedded | +| `esbuild.config.mjs` | Standalone ES2020 bundle with `motrix:plugin-api` kept external | + +The handler and manifest use the same `{{PLUGIN_ID}}.deduplicate` identity. +Changing an argument means updating its schema, handler type, field and layout +reference together. Persistent preferences belong in plugin configuration, not +operation arguments. The current template does not generate types from schemas. + +## Behavior and limits + +Select one UTF-8 `.txt` file, optionally enable **Ignore case**, and select a new +output. The handler preserves the first occurrence and spelling of each LF-split +line; case-insensitive keys use `toLowerCase()`. It does not trim whitespace or +normalize line endings. Empty segments, including a trailing newline or an empty +file, count as lines; CRLF preserves `\r`. The host displays the unique line count. + +The form is available in the plugin page and for one completed single-file task. +**Process another copy** preserves options and reauthorizes unchanged input, +clearing output. Locale changes preserve form values. Electron selects native +files; Web selects files on the server, not browser-local uploads. + +File strings are opaque single-invocation references, never paths. Declaring +permissions does not grant arbitrary file access. The host limits text input and +output to 1 MiB, prohibits output overwrite, checks authorization again during +execution and handles progress, cancellation, temporary files and publication. +The template requests no FFmpeg, network or unrestricted filesystem capability. + +## Try it + +- For `Apple\napple\nBanana\nApple` without a trailing newline, expect 3 unique + lines with Ignore case off and 2 with it on. +- Check English/Chinese labels, the collapsible options group, both entry points + and repeated execution with a fresh output. +- An existing destination, stale/changed input or unauthorized reference must be + rejected. Never remove host authorization checks to make an example run. +- Cancel before output publication and wait for cleanup. A tiny input may finish + too quickly for manual cancellation; that is not cancellation test evidence. + +For current controls, layout/condition rules, file grants, limits and unsupported +features, read the [SDK operation guide](https://github.com/motrixapp/plugin-sdk/blob/main/docs/operations.md). +Before these sources are published, read `docs/operations.md` in the matching SDK +checkout instead. New UI nodes/capabilities need host support; the template does +not provide custom renderer HTML, JavaScript or CSS. diff --git a/packages/plugin-cli/src/templates/operation/README.zh-CN.md.tpl b/packages/plugin-cli/src/templates/operation/README.zh-CN.md.tpl new file mode 100644 index 0000000..774dce9 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/README.zh-CN.md.tpl @@ -0,0 +1,57 @@ +# {{PROJECT_NAME}} + +[English](./README.md) | **简体中文** + +为 `{{PLUGIN_ID}}` 生成的文本去重操作项目。 + +> **协议与模板尚未发布。** 使用包含操作 v1、可组合 UI 和受限文本文件能力的 Motrix 构建及 SDK 包。宿主范围为 `>=2.0.0-beta.48 <3.0.0`,以 beta.48 为首个支持版本目标。beta.47 会被拒绝,包括仍使用该版本号的开发构建。此目标与依赖版本范围不代表已发布支持;若功能晚于 beta.48 发布,须同步提高最低宿主版本。 + +## 配置匹配的开发依赖 + +先在匹配的 plugin-sdk 源码仓库执行 `pnpm install --frozen-lockfile` 和 `pnpm build`。如果本项目直接创建在该仓库根目录下,请在**本项目目录**执行: + +```sh +pnpm add -D @motrix/plugin-api@file:../packages/plugin-api @motrix/plugin-cli@file:../packages/plugin-cli +``` + +如果项目位于其他位置,将两个 `file:` 路径改为实际构建好的 SDK 包位置。不能用普通安装旧版 npm API/CLI 来代替这一步;源码中的 Schema 会内嵌到 CLI 构建产物中。配套 SDK 正式发布后,再将本地依赖改为实际发布版本;模板目前不指定已发布 SDK 包的最低版本。 + +## 检查与打包 + +```sh +pnpm run typecheck +pnpm run validate +pnpm run pack +pnpm run lint +``` + +`pack` 打包 `src/index.ts`,输出未签名的 `dist/{{PLUGIN_ID}}-0.1.0.moext`。`lint` 检查 bundle,因此在 pack 后执行。`pnpm run build` 是可选的单独构建 bundle 步骤。这些命令不签名或发布。通过兼容宿主的正常第三方安装流程安装归档,并检查两项所选文件权限。 + +## 需要编辑的文件 + +| 文件 | 作用 | +|---|---| +| `motrix-plugin.json` | 私有操作命令、参数和结果 Schema、字段、布局、文件、入口、再次执行策略 | +| `src/index.ts` | 带类型的沙箱处理函数、取消检查、进度和受限文件调用 | +| `locales/en-US.json`、`locales/zh-CN.json` | 完整标签、说明、按钮和结果标题 | +| `tsconfig.json` | 通过安装的 `@motrix/plugin-api` 严格检查,不内嵌 SDK 仓库路径 | +| `esbuild.config.mjs` | 独立 ES2020 bundle,保持 `motrix:plugin-api` 为 external | + +处理函数和清单使用相同的 `{{PLUGIN_ID}}.deduplicate` 身份。修改参数时,同时调整 Schema、处理函数类型、字段和布局引用。长期偏好属于插件配置,不属于操作参数;当前模板不从 Schema 自动生成类型。 + +## 行为与限制 + +选择一个 UTF-8 `.txt` 文件,按需启用“忽略大小写”,再选择新的输出。处理函数按 LF 分行,保留每行首次出现的位置和原文,忽略大小写时使用 `toLowerCase()` 比较键。不裁剪空白、不归一化换行;空片段也计为一行,包括末尾换行和空文件产生的片段,CRLF 保留 `\r`。宿主显示去重后的行数。 + +插件页面及一个已完成的单文件任务菜单均提供入口。“再次处理”保留选项、重新授权未变化输入并清空输出。语言切换保留表单值。Electron 选择原生文件;Web 选择服务器上的文件,不上传浏览器本机文件。 + +文件字符串是不透明单次调用引用,不是路径;声明权限不授予任意文件访问。宿主将文本输入、输出各限制为 1 MiB,禁止覆盖目标,执行时重新检查授权,并管理进度、取消、临时文件和最终保存。模板不申请 FFmpeg、网络或任意文件系统能力。 + +## 验证方法 + +- 使用没有末尾换行的 `Apple\napple\nBanana\nApple`,关闭忽略大小写时应得到 3 行,开启时应得到 2 行。 +- 检查中英文标签、可折叠选项组、两个入口,以及用新输出再次执行。 +- 已有目标、过期或变化的输入、未经授权引用应被拒绝;不能移除宿主授权检查来运行示例。 +- 在保存前取消并等待清理。小文件可能快到无法手工取消,不能将其算作取消验证证据。 + +控件、布局及条件、文件授权、限制和未支持能力见 [SDK 操作指南](https://github.com/motrixapp/plugin-sdk/blob/main/docs/operations.zh-CN.md)。源码发布前,请改为阅读配套 SDK 仓库中的 `docs/operations.zh-CN.md`。新增 UI 节点或能力需要宿主支持;模板不提供自定义 renderer HTML、JavaScript 或 CSS。 diff --git a/packages/plugin-cli/src/templates/operation/esbuild.config.mjs.tpl b/packages/plugin-cli/src/templates/operation/esbuild.config.mjs.tpl new file mode 100644 index 0000000..63001f9 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/esbuild.config.mjs.tpl @@ -0,0 +1,13 @@ +import { build } from 'esbuild' + +await build({ + entryPoints: ['src/index.ts'], + bundle: true, + format: 'esm', + target: 'es2020', + platform: 'neutral', + outfile: 'dist/plugin.js', + external: ['motrix:plugin-api'], + minify: true, + treeShaking: true, +}) diff --git a/packages/plugin-cli/src/templates/operation/locales/en-US.json.tpl b/packages/plugin-cli/src/templates/operation/locales/en-US.json.tpl new file mode 100644 index 0000000..51bf843 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/locales/en-US.json.tpl @@ -0,0 +1,19 @@ +{ + "name": "{{PROJECT_NAME}}", + "description": "Remove duplicate lines from a selected text file and save a new copy.", + "deduplicate": "Deduplicate lines", + "operationDescription": "Remove duplicate lines while keeping their original order, then save a new UTF-8 file.", + "input": "Input file", + "inputPlaceholder": "Choose a text file", + "inputBrowse": "Choose input file", + "output": "Output file", + "outputPlaceholder": "Choose a save location", + "outputBrowse": "Choose output file", + "ignoreCase": "Ignore case", + "ignoreCaseHelp": "Treat Apple and apple as the same line.", + "matchingOptions": "Matching options", + "uniqueLines": "Unique lines", + "submit": "Deduplicate", + "repeat": "Process another copy", + "footer": "Original text stays unchanged." +} diff --git a/packages/plugin-cli/src/templates/operation/locales/zh-CN.json.tpl b/packages/plugin-cli/src/templates/operation/locales/zh-CN.json.tpl new file mode 100644 index 0000000..09260e4 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/locales/zh-CN.json.tpl @@ -0,0 +1,19 @@ +{ + "name": "{{PROJECT_NAME}}", + "description": "去除所选文本文件中的重复行,并另存为新文件。", + "deduplicate": "文本去重", + "operationDescription": "去除重复行,保留原有顺序,并另存为 UTF-8 文本文件。", + "input": "输入文件", + "inputPlaceholder": "选择文本文件", + "inputBrowse": "选择输入文件", + "output": "输出文件", + "outputPlaceholder": "选择保存位置", + "outputBrowse": "选择输出文件", + "ignoreCase": "忽略大小写", + "ignoreCaseHelp": "将 Apple 和 apple 视为同一行。", + "matchingOptions": "匹配选项", + "uniqueLines": "去重后行数", + "submit": "去重", + "repeat": "再次处理", + "footer": "保留原始文本文件。" +} diff --git a/packages/plugin-cli/src/templates/operation/motrix-plugin.json.tpl b/packages/plugin-cli/src/templates/operation/motrix-plugin.json.tpl new file mode 100644 index 0000000..7548267 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/motrix-plugin.json.tpl @@ -0,0 +1,181 @@ +{ + "manifestVersion": 1, + "id": "{{PLUGIN_ID}}", + "name": "%name%", + "version": "0.1.0", + "description": "%description%", + "categories": ["post-action"], + "engines": { + "motrix": ">=2.0.0-beta.48 <3.0.0" + }, + "main": "dist/plugin.js", + "permissions": ["files.selected.read", "files.selected.write"], + "activationEvents": ["onCommand:{{PLUGIN_ID}}.deduplicate"], + "contributes": { + "commands": [ + { + "id": "{{PLUGIN_ID}}.deduplicate", + "title": "%deduplicate%", + "execution": "operation", + "public": false, + "argsSchema": { + "type": "object", + "properties": { + "input": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "ignoreCase": { + "type": "boolean", + "default": false + } + }, + "required": ["input", "output", "ignoreCase"], + "additionalProperties": false + }, + "resultSchema": { + "type": "object", + "properties": { + "output": { + "type": "string", + "minLength": 36, + "maxLength": 36 + }, + "lines": { + "type": "integer", + "title": "%uniqueLines%", + "minimum": 0, + "maximum": 1048576 + } + }, + "required": ["output", "lines"], + "additionalProperties": false + } + } + ], + "operations": { + "version": 1, + "items": [ + { + "id": "{{PLUGIN_ID}}.deduplicate", + "title": "%deduplicate%", + "description": "%operationDescription%", + "icon": "document", + "command": "{{PLUGIN_ID}}.deduplicate", + "requires": ["operations.v1", "operations.ui.v1", "files.text.v1"], + "fields": [ + { + "field": "input", + "label": "%input%", + "appearance": { + "icon": "document", + "tone": "blue", + "drop": true, + "placeholder": "%inputPlaceholder%", + "browseLabel": "%inputBrowse%" + } + }, + { + "field": "ignoreCase", + "label": "%ignoreCase%", + "widget": "switch", + "help": "%ignoreCaseHelp%" + }, + { + "field": "output", + "label": "%output%", + "appearance": { + "icon": "folder", + "tone": "amber", + "placeholder": "%outputPlaceholder%", + "browseLabel": "%outputBrowse%" + } + } + ], + "files": { + "input": { + "kind": "input-file", + "use": "text", + "extensions": ["txt"] + }, + "output": { + "kind": "output-file", + "use": "text", + "extensions": ["txt"], + "suggestedName": { + "stemFrom": "input", + "suffix": "-unique" + } + } + }, + "entries": [ + { + "surface": "plugin-detail" + }, + { + "surface": "task-menu", + "selection": { + "count": { + "min": 1, + "max": 1 + }, + "every": { + "status": "completed", + "files": "single", + "local": true + } + }, + "bind": { + "input": { + "source": "task-file", + "index": 0 + } + } + } + ], + "result": { + "fields": ["lines"], + "files": ["output"] + }, + "ui": { + "layout": { + "type": "stack", + "children": [ + { + "type": "field", + "field": "input" + }, + { + "type": "group", + "title": "%matchingOptions%", + "children": [ + { + "type": "field", + "field": "ignoreCase" + } + ], + "collapsible": true + }, + { + "type": "field", + "field": "output" + } + ] + }, + "submitLabel": "%submit%", + "repeatLabel": "%repeat%", + "footer": "%footer%", + "repeat": "preserve-inputs" + } + } + ] + } + }, + "l10n": "locales" +} diff --git a/packages/plugin-cli/src/templates/operation/package.json.tpl b/packages/plugin-cli/src/templates/operation/package.json.tpl new file mode 100644 index 0000000..986f969 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/package.json.tpl @@ -0,0 +1,23 @@ +{ + "name": "{{PROJECT_NAME}}", + "version": "0.1.0", + "type": "module", + "private": true, + "engines": { + "node": ">=20" + }, + "scripts": { + "build": "node esbuild.config.mjs", + "typecheck": "tsc --noEmit", + "validate": "motrix-plugin validate", + "pack": "motrix-plugin pack", + "lint": "motrix-plugin lint", + "dev": "motrix-plugin dev" + }, + "devDependencies": { + "@motrix/plugin-api": "^2.1.0", + "@motrix/plugin-cli": "^2.1.1", + "esbuild": "^0.28.2", + "typescript": "^7.0.2" + } +} diff --git a/packages/plugin-cli/src/templates/operation/src/index.ts.tpl b/packages/plugin-cli/src/templates/operation/src/index.ts.tpl new file mode 100644 index 0000000..0d4c47d --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/src/index.ts.tpl @@ -0,0 +1,19 @@ +import { commands } from 'motrix:plugin-api' + +commands.registerOperation< + { input: string; output: string; ignoreCase: boolean }, + { output: string; lines: number } +>('{{PLUGIN_ID}}.deduplicate', async (args, context) => { + const text = await context.files.readText(args.input) + const seen = new Set() + const lines = text.split('\n').filter((line) => { + context.signal.throwIfAborted() + const key = args.ignoreCase ? line.toLowerCase() : line + if (seen.has(key)) return false + seen.add(key) + return true + }) + await context.progress({ phase: 'running', fraction: 0.5 }) + await context.files.writeText(args.output, lines.join('\n')) + return { output: args.output, lines: lines.length } +}) diff --git a/packages/plugin-cli/src/templates/operation/tsconfig.json.tpl b/packages/plugin-cli/src/templates/operation/tsconfig.json.tpl new file mode 100644 index 0000000..e817842 --- /dev/null +++ b/packages/plugin-cli/src/templates/operation/tsconfig.json.tpl @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "skipLibCheck": true, + "types": ["@motrix/plugin-api"] + }, + "include": ["src"] +} diff --git a/packages/plugin-cli/tests/cli.test.ts b/packages/plugin-cli/tests/cli.test.ts index e3fcf4e..a686bc6 100644 --- a/packages/plugin-cli/tests/cli.test.ts +++ b/packages/plugin-cli/tests/cli.test.ts @@ -117,4 +117,65 @@ describe('motrix-plugin CLI', () => { const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) expect(manifest.id).toBe('alice.demo') }) + + it.each([ + { + bin: BIN, + args: ['init', 'text-demo', '-t', 'operation', '-p', 'alice'], + id: 'alice.text-demo', + }, + { + bin: path.join(path.dirname(BIN), 'create-motrix-plugin.js'), + args: ['text-demo', 'operation'], + id: 'me.text-demo', + }, + { + bin: path.join( + worktreeRoot, + 'packages/create-motrix-plugin/bin/create.mjs' + ), + args: ['text-demo', 'operation'], + id: 'me.text-demo', + }, + ])('scaffolds operation through $bin', async ({ bin, args, id }) => { + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'cli-operation-')) + try { + const stdout = execFileSync(process.execPath, [bin, ...args], { + cwd: tmpDir, + encoding: 'utf8', + }) + expect(stdout).toContain('Unreleased operation template') + const project = path.join(tmpDir, 'text-demo') + const manifest = JSON.parse( + await readFile(path.join(project, 'motrix-plugin.json'), 'utf8') + ) + expect(manifest.id).toBe(id) + expect(manifest.contributes.operations.items[0].command).toBe( + `${id}.deduplicate` + ) + expect(existsSync(path.join(project, 'README.zh-CN.md'))).toBe(true) + expect( + execFileSync(process.execPath, [BIN, 'validate'], { + cwd: project, + encoding: 'utf8', + }) + ).toContain('manifest OK') + } finally { + rmSync(tmpDir, { recursive: true, force: true }) + } + }) + + it('lists operation in template help and rejects unknown template names', () => { + expect( + execFileSync(process.execPath, [BIN, 'init', '--help'], { + encoding: 'utf8', + }) + ).toContain('operation') + const creator = path.join(path.dirname(BIN), 'create-motrix-plugin.js') + expect(() => + execFileSync(process.execPath, [creator, 'demo', 'unknown-template'], { + stdio: 'pipe', + }) + ).toThrow(/Available: basic-resolver, post-action, operation/) + }) }) diff --git a/packages/plugin-cli/tests/operation-template.test.ts b/packages/plugin-cli/tests/operation-template.test.ts new file mode 100644 index 0000000..92a4c78 --- /dev/null +++ b/packages/plugin-cli/tests/operation-template.test.ts @@ -0,0 +1,125 @@ +import { execFileSync } from 'node:child_process' +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { createRequire } from 'node:module' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { init } from '../src/commands/init' +import { lint } from '../src/commands/lint' +import { pack } from '../src/commands/pack' +import { validate } from '../src/commands/validate' +import { checkLocaleCoverage, ManifestSchema } from '../src/manifest-schema' + +const require = createRequire(import.meta.url) +const sdkRoot = path.resolve(fileURLToPath(import.meta.url), '../../../..') + +describe('operation template', () => { + let parent: string + let project: string + + beforeEach(async () => { + parent = mkdtempSync(path.join(os.tmpdir(), 'operation-template-')) + const result = await init({ + projectName: 'line-cleaner', + publisher: 'alice', + template: 'operation', + destDir: parent, + }) + project = result.created + }) + + afterEach(() => rmSync(parent, { recursive: true, force: true })) + + it('generates a localized private operation with consistent identities and file bindings', async () => { + const read = (file: string) => + readFileSync(path.join(project, file), 'utf8') + const manifest = ManifestSchema.parse( + JSON.parse(read('motrix-plugin.json')) + ) + expect(await validate(project)).toEqual({ ok: true }) + expect(manifest.id).toBe('alice.line-cleaner') + expect(manifest.engines.motrix).toBe('>=2.0.0-beta.48 <3.0.0') + expect(manifest.permissions).toEqual([ + 'files.selected.read', + 'files.selected.write', + ]) + expect(manifest.contributes.hooks).toBeUndefined() + expect(manifest.activationEvents).toEqual([ + 'onCommand:alice.line-cleaner.deduplicate', + ]) + expect(manifest.contributes.commands?.[0]).toMatchObject({ + id: 'alice.line-cleaner.deduplicate', + execution: 'operation', + public: false, + }) + expect(manifest.contributes.operations?.items[0]).toMatchObject({ + id: 'alice.line-cleaner.deduplicate', + command: 'alice.line-cleaner.deduplicate', + result: { fields: ['lines'], files: ['output'] }, + ui: { repeat: 'preserve-inputs' }, + }) + expect(read('src/index.ts')).toContain("'alice.line-cleaner.deduplicate'") + for (const locale of ['en-US', 'zh-CN']) { + const dictionary = JSON.parse(read(`locales/${locale}.json`)) + expect(dictionary.name).toBe('line-cleaner') + expect(() => checkLocaleCoverage(manifest, dictionary)).not.toThrow() + } + for (const file of [ + 'motrix-plugin.json', + 'src/index.ts', + 'locales/en-US.json', + 'locales/zh-CN.json', + 'package.json', + 'tsconfig.json', + 'esbuild.config.mjs', + 'README.md', + 'README.zh-CN.md', + '.gitignore', + ]) { + expect(read(file), file).not.toMatch(/\{\{[A-Z_]+\}\}/) + } + expect(read('.gitignore')).toContain('dist/') + expect(read('.gitignore')).toContain('node_modules/') + }) + + it('typechecks as a standalone project against the built API package files', () => { + // Match the npm package file layout, without a network install or a + // checkout-relative ambient declaration that could mask a broken tsconfig. + const installed = path.join(project, 'node_modules/@motrix/plugin-api') + mkdirSync(installed, { recursive: true }) + const api = path.join(sdkRoot, 'packages/plugin-api') + for (const file of ['package.json', 'dist', 'src/virtual-module.d.ts']) { + cpSync(path.join(api, file), path.join(installed, file), { + recursive: true, + }) + } + const config = JSON.parse( + readFileSync(path.join(project, 'tsconfig.json'), 'utf8') + ) + expect(config.compilerOptions.types).toEqual(['@motrix/plugin-api']) + expect(config.include).toEqual(['src']) + const pkg = JSON.parse( + readFileSync(path.join(project, 'package.json'), 'utf8') + ) + expect(pkg.scripts.typecheck).toBe('tsc --noEmit') + expect(pkg.scripts.validate).toBe('motrix-plugin validate') + expect(pkg.scripts.lint).toBe('motrix-plugin lint') + const typescriptPackage = require.resolve('typescript/package.json') + const { bin } = JSON.parse(readFileSync(typescriptPackage, 'utf8')) + const tsc = path.resolve(path.dirname(typescriptPackage), bin.tsc) + execFileSync(process.execPath, [tsc, '--noEmit'], { + cwd: project, + stdio: 'pipe', + }) + }) + + it('packs and lints without adding permissions or editing generated source', async () => { + const result = await pack({ projectDir: project }) + expect(result.outFile).toBe( + path.join(project, 'dist/alice.line-cleaner-0.1.0.moext') + ) + expect(result.totalSize).toBeGreaterThan(0) + expect(await lint(project)).toEqual({ warnings: [], errors: [] }) + }) +}) diff --git a/packages/plugin-manifest-schema/README.md b/packages/plugin-manifest-schema/README.md index 13ca72a..6a610c5 100644 --- a/packages/plugin-manifest-schema/README.md +++ b/packages/plugin-manifest-schema/README.md @@ -80,10 +80,13 @@ the codes the host emits at install time. This module performs no I/O and imports no Node built-ins, so it runs anywhere the schema does. +## Plugin operations (unreleased) + +`OperationsContributionSchema`, `OperationDefinitionSchema`, `OperationUiSchema`, `OperationDefinition`, `OperationLayout` and the operation validation helpers describe the development operations protocol. `ManifestSchema` enforces the cross-field operation rules; standalone structural parsers do not replace full manifest validation. This remains the only protocol definition, shared by host and CLI. + +See the [English guide](../../docs/operations.md) or [Chinese guide](../../docs/operations.zh-CN.md), including complete media and text examples, supported controls, limits and compatibility requirements. The examples target Motrix beta.48 or later (below 3.0.0), contingent on that release shipping the required features; this is not a claim of published support. + ## Learn more - Scaffold a manifest with [`@motrix/plugin-cli`](https://www.npmjs.com/package/@motrix/plugin-cli) (`motrix-plugin init`) -- Design background: `docs/superpowers/specs/2026-04-10-plugin-system-design.md` - and `docs/superpowers/plans/2026-05-16-extract-plugin-manifest-schema-package.md` - in the [motrix-turbo](https://gitlab.com/agalwood/motrix-turbo) repository diff --git a/packages/plugin-manifest-schema/src/index.ts b/packages/plugin-manifest-schema/src/index.ts index f4f3887..fe355b2 100644 --- a/packages/plugin-manifest-schema/src/index.ts +++ b/packages/plugin-manifest-schema/src/index.ts @@ -12,5 +12,7 @@ // Keep this file a pure re-export barrel; anything else belongs in one of the // two modules above. +export * from './operation-ui' +export * from './operations' export * from './schema' export * from './validate' diff --git a/packages/plugin-manifest-schema/src/operation-ui.ts b/packages/plugin-manifest-schema/src/operation-ui.ts new file mode 100644 index 0000000..6f0a7e6 --- /dev/null +++ b/packages/plugin-manifest-schema/src/operation-ui.ts @@ -0,0 +1,151 @@ +import { z } from 'zod' + +const field = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/) +const text = z.string().min(1).max(512) +export type OperationLayout = + | { type: 'field'; field: string; span?: 1 | 2; accessory?: string } + | { + type: 'text' + text: string + tone?: 'muted' | 'info' + platform?: 'desktop' | 'web' + span?: 1 | 2 + } + | { + type: 'stack' | 'grid' | 'group' + children: OperationLayout[] + title?: string + collapsible?: boolean + columns?: 1 | 2 + span?: 1 | 2 + } +const layout: z.ZodType = z.lazy(() => + z.union([ + z.strictObject({ + type: z.literal('field'), + field, + span: z.union([z.literal(1), z.literal(2)]).optional(), + accessory: field.optional(), + }), + z.strictObject({ + type: z.literal('text'), + text, + tone: z.enum(['muted', 'info']).optional(), + platform: z.enum(['desktop', 'web']).optional(), + span: z.union([z.literal(1), z.literal(2)]).optional(), + }), + z.strictObject({ + type: z.enum(['stack', 'grid', 'group']), + collapsible: z.boolean().optional(), + children: z.array(layout).min(1).max(24), + title: text.optional(), + columns: z.union([z.literal(1), z.literal(2)]).optional(), + span: z.union([z.literal(1), z.literal(2)]).optional(), + }), + ]) +) +export const OperationUiSchema = z.strictObject({ + layout: z + .unknown() + .refine((value) => { + const stack = [{ value, depth: 1 }] + const seen = new Set() + let count = 0 + while (stack.length) { + const item = stack.pop() + if (!item || ++count > 64 || item.depth > 4 || seen.has(item.value)) + return false + seen.add(item.value) + if ( + item.value && + typeof item.value === 'object' && + 'children' in item.value + ) { + const children = item.value.children + if (!Array.isArray(children) || children.length > 24) return false + for (const value of children) + stack.push({ value, depth: item.depth + 1 }) + } + } + return true + }, 'layout exceeds structural limits') + .pipe(layout), + submitLabel: text.optional(), + repeatLabel: text.optional(), + footer: text.optional(), + repeat: z.enum(['reset', 'preserve-options', 'preserve-inputs']).optional(), +}) +export const OperationFieldAppearanceSchema = z.strictObject({ + icon: z + .enum(['video', 'audio', 'folder', 'document', 'text', 'checksum']) + .optional(), + tone: z.enum(['neutral', 'blue', 'violet', 'amber']).optional(), + placeholder: text.optional(), + browseLabel: text.optional(), + drop: z.boolean().optional(), +}) +export type OperationUi = z.infer + +/** Validate topology and references before rendering. Layout never changes authority. */ +export function operationLayoutIssues( + ui: OperationUi, + fields: string[], + files: Record +): string[] { + const issues: string[] = [] + const bindings: string[] = [] + let count = 0 + const visit = (node: OperationLayout, depth: number, collapsible = false) => { + if (++count > 64 || depth > 4) { + issues.push('layout exceeds 64 nodes or 4 levels') + return + } + if (node.type === 'field') { + bindings.push(node.field) + if (collapsible && files[node.field]) + issues.push('file cannot be inside a collapsible group') + if (node.accessory) { + bindings.push(node.accessory) + if (files[node.accessory]) issues.push('file cannot be an accessory') + if (files[node.field]?.kind === 'input-file') + issues.push('input card cannot contain an accessory') + } + } else if ('children' in node) { + if (node.collapsible && (node.type !== 'group' || !node.title)) + issues.push('collapsible requires a titled group') + if (node.columns !== undefined && node.type !== 'grid') + issues.push('columns require grid') + for (const child of node.children) + visit(child, depth + 1, collapsible || node.collapsible === true) + } + } + visit(ui.layout, 1) + if ( + bindings.length !== fields.length || + new Set(bindings).size !== fields.length || + fields.some((f) => !bindings.includes(f)) + ) + issues.push('layout must bind every field exactly once') + return issues +} +export function mapOperationUiText( + ui: OperationUi, + map: (text: string) => string +): OperationUi { + const visit = (node: OperationLayout): OperationLayout => { + if (node.type === 'field') return node + if (node.type === 'text') return { ...node, text: map(node.text) } + return { + ...node, + ...(node.title ? { title: map(node.title) } : {}), + children: node.children.map(visit), + } + } + return { + ...ui, + layout: visit(ui.layout), + ...(ui.submitLabel ? { submitLabel: map(ui.submitLabel) } : {}), + ...(ui.repeatLabel ? { repeatLabel: map(ui.repeatLabel) } : {}), + ...(ui.footer ? { footer: map(ui.footer) } : {}), + } +} diff --git a/packages/plugin-manifest-schema/src/operations.ts b/packages/plugin-manifest-schema/src/operations.ts new file mode 100644 index 0000000..3427d0b --- /dev/null +++ b/packages/plugin-manifest-schema/src/operations.ts @@ -0,0 +1,512 @@ +import { z } from 'zod' +import { + OperationFieldAppearanceSchema, + OperationUiSchema, + operationLayoutIssues, +} from './operation-ui' +import type { BoundedJsonSchemaShape, ManifestZodOutput } from './schema' + +const own = (value: object, key: string) => Object.hasOwn(value, key) +const identifier = z + .string() + .regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/) + .refine((s) => !['__proto__', 'prototype', 'constructor'].includes(s)) +const qualifiedId = z.string().min(1).max(228) +const scalar = z.union([z.string().max(4096), z.number().finite(), z.boolean()]) +export type OperationScalar = z.infer + +/** Iterative limits run before recursive parsing, including for programmatic callers. */ +export function boundedOperationJson( + value: unknown, + bytes = 65536, + depth = 14 +): boolean { + const stack: { value: unknown; depth: number }[] = [{ value, depth: 0 }] + const seen = new Set() + let nodes = 0 + let budget = 0 + const utf8 = (text: string) => { + let size = 0 + for (const ch of text) { + const point = ch.codePointAt(0) ?? 0 + size += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4 + } + return size + } + while (stack.length) { + const item = stack.pop() + if (!item) break + if (++nodes > 4096 || item.depth > depth) return false + const v = item.value + if (v === null || typeof v === 'boolean') budget += 5 + else if (typeof v === 'string') budget += utf8(JSON.stringify(v)) + else if (typeof v === 'number' && Number.isFinite(v)) budget += 32 + else if (typeof v === 'object') { + if (seen.has(v)) return false + seen.add(v) + const entries = Object.entries(v) + budget += 2 + entries.length + for (const [key, child] of entries) { + if (['__proto__', 'constructor', 'prototype'].includes(key)) + return false + budget += utf8(JSON.stringify(key)) + 1 + stack.push({ value: child, depth: item.depth + 1 }) + } + } else return false + if (budget > bytes) return false + } + return true +} + +export type OperationCondition = + | { field: string; equals: OperationScalar } + | { field: string; in: OperationScalar[] } + | { all: OperationCondition[] } + | { any: OperationCondition[] } + | { not: OperationCondition } +const condition: z.ZodType = z.lazy(() => + z.union([ + z.strictObject({ field: identifier, equals: scalar }), + z.strictObject({ field: identifier, in: z.array(scalar).min(1).max(64) }), + z.strictObject({ all: z.array(condition).min(1).max(8) }), + z.strictObject({ any: z.array(condition).min(1).max(8) }), + z.strictObject({ not: condition }), + ]) +) +const conditionSchema = z + .unknown() + .refine( + (v) => boundedOperationJson(v, 4096, 9), + 'operation condition exceeds limits' + ) + .pipe(condition) +const extensions = z + .array(z.string().regex(/^[a-z0-9]{1,12}$/)) + .min(1) + .max(16) +export const OperationFileSchema = z.discriminatedUnion('kind', [ + z.strictObject({ + kind: z.literal('input-file'), + use: z.enum(['media', 'text']), + extensions: extensions.optional(), + }), + z.strictObject({ + kind: z.literal('output-file'), + use: z.enum(['media', 'text']), + extensions: extensions.optional(), + extensionFrom: identifier.optional(), + suggestedName: z + .strictObject({ + stemFrom: identifier, + suffix: z.string().regex(/^[A-Za-z0-9_-]{0,32}$/), + }) + .optional(), + }), +]) +export const OperationDefinitionSchema = z.strictObject({ + id: qualifiedId, + title: z.string().min(1).max(128), + description: z.string().max(512).optional(), + icon: z.enum(['action', 'media-merge', 'document', 'checksum']).optional(), + command: qualifiedId, + requires: z + .array(z.string().regex(/^[a-z][a-z0-9.-]{0,63}$/)) + .max(16) + .optional(), + ui: OperationUiSchema.optional(), + fields: z + .array( + z.strictObject({ + field: identifier, + label: z.string().min(1).max(128).optional(), + help: z.string().max(512).optional(), + appearance: OperationFieldAppearanceSchema.optional(), + widget: z + .enum(['text', 'textarea', 'number', 'switch', 'select', 'segmented']) + .optional(), + optionLabels: z + .record(z.string().max(4096), z.string().max(128)) + .optional(), + visibleWhen: conditionSchema.optional(), + enabledWhen: conditionSchema.optional(), + }) + ) + .max(24), + files: z.record(identifier, OperationFileSchema).optional(), + entries: z + .array( + z.discriminatedUnion('surface', [ + z.strictObject({ surface: z.literal('plugin-detail') }), + z.strictObject({ + surface: z.literal('task-menu'), + selection: z.strictObject({ + count: z.strictObject({ + min: z.number().int().min(1).max(4), + max: z.number().int().min(1).max(4), + }), + every: z.strictObject({ + status: z.literal('completed'), + files: z.literal('single'), + local: z.literal(true), + }), + }), + bind: z.record( + identifier, + z.strictObject({ + source: z.literal('task-file'), + index: z.number().int().min(0).max(3), + }) + ), + }), + ]) + ) + .min(1) + .max(2), + result: z + .strictObject({ + fields: z.array(identifier).max(24).optional(), + files: z.array(identifier).max(1).optional(), + }) + .optional(), + errors: z.record(identifier, z.string().min(1).max(512)).optional(), +}) +export const OperationsContributionSchema = z + .unknown() + .refine((v) => boundedOperationJson(v), 'operations exceed structural limits') + .pipe( + z.strictObject({ + version: z.literal(1), + items: z.array(OperationDefinitionSchema).min(1).max(16), + }) + ) +export type OperationDefinition = z.infer +export type OperationFileBinding = z.infer +export type OperationsContribution = z.infer< + typeof OperationsContributionSchema +> + +export function matchesOperationCondition( + test: OperationCondition | undefined, + args: Record +): boolean { + if (!test) return true + if ('all' in test) + return test.all.every((x) => matchesOperationCondition(x, args)) + if ('any' in test) + return test.any.some((x) => matchesOperationCondition(x, args)) + if ('not' in test) return !matchesOperationCondition(test.not, args) + const value = own(args, test.field) ? args[test.field] : undefined + return 'equals' in test + ? value === test.equals + : test.in.some((x) => x === value) +} + +export function validateOperationValues( + schema: BoundedJsonSchemaShape, + input: unknown, + defaults = true +): { + value: Record + errors: Record +} { + const value: Record = {} + const errors: Record = {} + if (!input || typeof input !== 'object' || Array.isArray(input)) + return { value, errors: { $: 'object' } } + const raw = input as Record + const props = schema.properties ?? {} + for (const key of Object.keys(raw)) + if (!own(props, key)) errors[key] = 'unknown' + for (const [key, p] of Object.entries(props)) { + const v = own(raw, key) ? raw[key] : defaults ? p.default : undefined + if (v === undefined) { + if (schema.required?.includes(key)) errors[key] = 'required' + continue + } + let valid = + p.type === 'string' + ? typeof v === 'string' + : p.type === 'boolean' + ? typeof v === 'boolean' + : typeof v === 'number' && + Number.isFinite(v) && + (p.type !== 'integer' || Number.isInteger(v)) + if (typeof v === 'string') + valid &&= + [...v].length >= (p.minLength ?? 0) && + [...v].length <= (p.maxLength ?? 4096) + if (typeof v === 'number') + valid &&= v >= (p.minimum ?? -Infinity) && v <= (p.maximum ?? Infinity) + if (p.enum) valid &&= p.enum.includes(v) + if (!valid) errors[key] = 'invalid' + else value[key] = v as OperationScalar + } + return { value, errors } +} + +/** Used by the manifest itself, so host parsing and both pack pipelines agree. */ +export function operationManifestIssues(manifest: ManifestZodOutput): string[] { + const ops = manifest.contributes.operations?.items ?? [] + const commands = manifest.contributes.commands ?? [] + const issues: string[] = [] + const fail = (message: string) => + issues.push(`plugin.manifest.operation: ${message}`) + const unique = (values: string[]) => new Set(values).size === values.length + if (!unique(ops.map((o) => o.id))) fail('duplicate operation id') + if (!unique(commands.map((c) => c.id))) fail('duplicate command id') + const checkSchema = ( + s: BoundedJsonSchemaShape | undefined + ): s is BoundedJsonSchemaShape => { + if ( + s?.type !== 'object' || + s.additionalProperties !== false || + !s.properties || + Object.keys(s.properties).length > 24 + ) + return false + if ( + s.pattern || + s.secret !== undefined || + s.items || + s.enum || + s.default !== undefined + ) + return false + if ( + !unique(s.required ?? []) || + s.required?.some((k) => !own(s.properties ?? {}, k)) + ) + return false + return Object.entries(s.properties).every(([key, p]) => { + if ( + !identifier.safeParse(key).success || + !['string', 'number', 'integer', 'boolean'].includes(p.type ?? '') + ) + return false + if ( + p.properties || + p.items || + p.pattern !== undefined || + p.secret !== undefined || + p.additionalProperties !== undefined || + p.required + ) + return false + if (p.type === 'string') { + if (p.minimum !== undefined || p.maximum !== undefined) return false + if (!p.enum && (p.maxLength === undefined || p.maxLength > 4096)) + return false + if ((p.minLength ?? 0) > (p.maxLength ?? 4096)) return false + if ( + p.enum && + (p.enum.length === 0 || + p.enum.length > 64 || + !p.enum.every((x) => typeof x === 'string' && x.length <= 4096) || + !unique(p.enum as string[])) + ) + return false + } else { + if (p.enum || p.minLength !== undefined || p.maxLength !== undefined) + return false + if ( + p.type !== 'boolean' && + (p.minimum === undefined || + p.maximum === undefined || + p.minimum > p.maximum) + ) + return false + if ( + p.type === 'boolean' && + (p.minimum !== undefined || p.maximum !== undefined) + ) + return false + } + return ( + p.default === undefined || + Object.keys( + validateOperationValues( + { properties: { [key]: p } }, + { [key]: p.default } + ).errors + ).length === 0 + ) + }) + } + for (const command of commands) { + if (command.execution !== 'operation') continue + if ( + command.public || + !checkSchema(command.argsSchema) || + !checkSchema(command.resultSchema) + ) + fail(`${command.id}: private operation requires flat bounded schemas`) + if (!ops.some((o) => o.command === command.id)) + fail(`${command.id}: orphan operation command`) + } + for (const op of ops) { + const c = commands.find((x) => x.id === op.command) + if ( + !op.id.startsWith(`${manifest.id}.`) || + !op.command.startsWith(`${manifest.id}.`) || + c?.execution !== 'operation' || + c.public + ) { + fail(`${op.id}: invalid handler`) + continue + } + if (!checkSchema(c.argsSchema) || !checkSchema(c.resultSchema)) continue + const props = c.argsSchema.properties ?? {} + const files = op.files ?? {} + if (!boundedOperationJson(op, 8192)) fail(`${op.id}: description too large`) + if ( + !unique(op.fields.map((f) => f.field)) || + op.fields.length !== Object.keys(props).length + ) + fail(`${op.id}: fields must bind every argument exactly once`) + if (op.ui) { + if (!op.requires?.includes('operations.ui.v1')) + fail(`${op.id}: UI capability required`) + for (const issue of operationLayoutIssues( + op.ui, + op.fields.map((f) => f.field), + files + )) + fail(`${op.id}: ${issue}`) + } + let nodes = 0 + const visit = (test: OperationCondition, depth = 1) => { + if (++nodes > 64 || depth > 4) { + fail(`${op.id}: condition limit`) + return + } + if ('field' in test) { + if (!own(props, test.field) || own(files, test.field)) + fail(`${op.id}: invalid condition field`) + const p = props[test.field] + for (const v of 'equals' in test ? [test.equals] : test.in) + if ( + !p || + Object.keys( + validateOperationValues( + { properties: { value: p } }, + { value: v } + ).errors + ).length + ) + fail(`${op.id}: condition value mismatch`) + } else if ('not' in test) visit(test.not, depth + 1) + else + for (const t of 'all' in test ? test.all : test.any) visit(t, depth + 1) + } + for (const f of op.fields) { + const p = props[f.field] + if (!p) { + fail(`${op.id}: unknown field`) + continue + } + if (f.visibleWhen) visit(f.visibleWhen) + if (f.enabledWhen) visit(f.enabledWhen) + if ( + (f.visibleWhen || f.enabledWhen) && + c.argsSchema.required?.includes(f.field) && + p.default === undefined + ) + fail(`${op.id}: conditional required field needs a default`) + if (f.appearance?.drop && files[f.field]?.kind !== 'input-file') + fail(`${op.id}: drop requires input file`) + if ( + (f.appearance?.icon || + f.appearance?.tone || + f.appearance?.browseLabel) && + !own(files, f.field) + ) + fail(`${op.id}: file appearance requires file`) + if (own(files, f.field)) { + if (f.widget || f.visibleWhen || f.enabledWhen || f.optionLabels) + fail(`${op.id}: file presentation cannot alter authorization`) + } else if ( + f.widget === 'select' || f.widget === 'segmented' + ? !p.enum + : f.widget === 'switch' + ? p.type !== 'boolean' + : f.widget === 'number' + ? !['number', 'integer'].includes(p.type ?? '') + : f.widget + ? p.type !== 'string' + : false + ) + fail(`${op.id}: incompatible widget`) + if ( + f.optionLabels && + Object.keys(f.optionLabels).some((key) => !p.enum?.includes(key)) + ) + fail(`${op.id}: option labels must reference enum values`) + } + const bindings = Object.entries(files) + if ( + bindings.filter(([, f]) => f.kind === 'input-file').length > 4 || + bindings.filter(([, f]) => f.kind === 'output-file').length > 1 + ) + fail(`${op.id}: too many files`) + for (const [key, f] of bindings) { + const p = props[key] + if ( + p?.type !== 'string' || + p.default !== undefined || + p.enum || + (p.maxLength ?? Infinity) > 128 || + !c.argsSchema.required?.includes(key) + ) + fail(`${op.id}: invalid file binding`) + const permission = + f.kind === 'input-file' ? 'files.selected.read' : 'files.selected.write' + if (!manifest.permissions.includes(permission)) + fail(`${op.id}: missing ${permission}`) + if (f.use === 'media' && !manifest.permissions.includes('ffmpeg')) + fail(`${op.id}: missing ffmpeg`) + if (f.kind === 'output-file') { + if ( + f.extensionFrom && + (!props[f.extensionFrom]?.enum?.length || + !props[f.extensionFrom].enum?.every( + (v) => typeof v === 'string' && /^[a-z0-9]{1,12}$/.test(v) + )) + ) + fail(`${op.id}: invalid extension source`) + if ( + f.suggestedName && + files[f.suggestedName.stemFrom]?.kind !== 'input-file' + ) + fail(`${op.id}: invalid suggested name source`) + if (!f.extensions && !f.extensionFrom) + fail(`${op.id}: output extensions required`) + } + } + if (!unique(op.entries.map((e) => e.surface))) + fail(`${op.id}: duplicate entry`) + for (const entry of op.entries) + if (entry.surface === 'task-menu') { + if (entry.selection.count.min > entry.selection.count.max) + fail(`${op.id}: invalid task count`) + for (const [key, binding] of Object.entries(entry.bind)) + if ( + files[key]?.kind !== 'input-file' || + binding.index >= entry.selection.count.min + ) + fail(`${op.id}: invalid task binding`) + } + for (const key of op.result?.fields ?? []) + if (!own(c.resultSchema.properties ?? {}, key)) + fail(`${op.id}: invalid result field`) + for (const key of op.result?.files ?? []) + if ( + files[key]?.kind !== 'output-file' || + c.resultSchema.properties?.[key]?.type !== 'string' + ) + fail(`${op.id}: invalid output result`) + for (const [key, f] of bindings) + if (f.kind === 'output-file' && !op.result?.files?.includes(key)) + fail(`${op.id}: output must be returned`) + } + return issues +} diff --git a/packages/plugin-manifest-schema/src/schema.ts b/packages/plugin-manifest-schema/src/schema.ts index 92a9a78..1905690 100644 --- a/packages/plugin-manifest-schema/src/schema.ts +++ b/packages/plugin-manifest-schema/src/schema.ts @@ -1,5 +1,10 @@ // packages/plugin-manifest-schema/src/index.ts import { z } from 'zod' +import { + boundedOperationJson, + OperationsContributionSchema, + operationManifestIssues, +} from './operations' export const RESERVED_PUBLISHERS = new Set([ 'motrix', @@ -165,8 +170,14 @@ function maxPropsAtAnyLevel(s: BoundedJsonSchemaShape): number { * check runs only at the top-level invocation so nested recursion does not * re-compute the same trees. */ -export const BoundedJsonSchemaTopLevel = BoundedJsonSchema.superRefine( - (schema, ctx) => { +export const BoundedJsonSchemaTopLevel = z + .unknown() + .refine( + (value) => boundedOperationJson(value, 8192, 18), + 'plugin.manifest.bounded_schema_invalid: structural limit' + ) + .pipe(BoundedJsonSchema) + .superRefine((schema, ctx) => { const serialized = JSON.stringify(schema) if (serialized.length > BOUNDED_SCHEMA_MAX_BYTES) { ctx.addIssue({ @@ -195,8 +206,7 @@ export const BoundedJsonSchemaTopLevel = BoundedJsonSchema.superRefine( message: `plugin.manifest.bounded_schema_invalid: ${props} properties at one level exceeds ${BOUNDED_SCHEMA_MAX_PROPS_PER_LEVEL}`, }) } - } -) + }) const CommandContributionSchema = z .object({ @@ -204,6 +214,7 @@ const CommandContributionSchema = z title: z.string().min(1).max(128), icon: z.string().max(64).optional(), public: z.boolean().default(false), + execution: z.literal('operation').optional(), argsSchema: BoundedJsonSchemaTopLevel.optional(), resultSchema: BoundedJsonSchemaTopLevel.optional(), }) @@ -277,10 +288,11 @@ const ContributesSchema = z commands: CommandsContribution.optional(), hooks: HookContributionSchema.optional(), configuration: ConfigurationContributionSchema.optional(), + operations: OperationsContributionSchema.optional(), }) .passthrough() -export const ManifestSchema = z +const ManifestStructureSchema = z .object({ $schema: z.string().optional(), manifestVersion: z.literal(1), @@ -339,5 +351,11 @@ export const ManifestSchema = z }) .strict() -export type ManifestZodOutput = z.infer +export type ManifestZodOutput = z.infer +export const ManifestSchema = ManifestStructureSchema.superRefine( + (manifest, context) => { + for (const message of operationManifestIssues(manifest)) + context.addIssue({ code: 'custom', message }) + } +) export type CommandContribution = z.infer diff --git a/packages/plugin-manifest-schema/tests/operations.test.ts b/packages/plugin-manifest-schema/tests/operations.test.ts new file mode 100644 index 0000000..903b85f --- /dev/null +++ b/packages/plugin-manifest-schema/tests/operations.test.ts @@ -0,0 +1,271 @@ +import { describe, expect, it } from 'vitest' +import { + boundedOperationJson, + ManifestSchema, + matchesOperationCondition, + validateOperationValues, +} from '../src' + +const makeManifest = () => ({ + manifestVersion: 1, + id: 'acme.text-tools', + name: 'Text tools', + version: '1.0.0', + description: 'Selected text', + categories: ['productivity'], + engines: { motrix: '>=3.0.0' }, + main: 'dist/plugin.js', + permissions: ['files.selected.read', 'files.selected.write'], + activationEvents: ['onCommand:acme.text-tools.run'], + contributes: { + commands: [ + { + id: 'acme.text-tools.run', + title: 'Run', + public: false, + execution: 'operation', + argsSchema: { + type: 'object', + additionalProperties: false, + required: ['input', 'output', 'sort'], + properties: { + input: { type: 'string', maxLength: 128 }, + output: { type: 'string', maxLength: 128 }, + sort: { type: 'boolean', default: false }, + }, + }, + resultSchema: { + type: 'object', + additionalProperties: false, + required: ['output'], + properties: { output: { type: 'string', maxLength: 128 } }, + }, + }, + ], + operations: { + version: 1, + items: [ + { + id: 'acme.text-tools.dedup', + title: 'Deduplicate', + command: 'acme.text-tools.run', + fields: [ + { field: 'input' }, + { field: 'sort', widget: 'switch' }, + { field: 'output' }, + ], + files: { + input: { kind: 'input-file', use: 'text' }, + output: { kind: 'output-file', use: 'text', extensions: ['txt'] }, + }, + entries: [{ surface: 'plugin-detail' }], + result: { files: ['output'] }, + }, + ], + }, + }, +}) +const rejects = (change: (m: ReturnType) => void) => { + const m = makeManifest() + change(m) + expect(ManifestSchema.safeParse(m).success).toBe(false) +} +describe('plugin operations', () => { + it('accepts an unsigned non-media operation', () => + expect(ManifestSchema.safeParse(makeManifest()).success).toBe(true)) + it('rejects public handlers', () => + rejects((m) => { + m.contributes.commands[0].public = true + })) + it('requires explicit file permissions', () => + rejects((m) => { + m.permissions = [] + })) + it('rejects foreign handlers', () => + rejects((m) => { + m.contributes.operations.items[0].command = 'other.plugin.run' + })) + it('rejects duplicate IDs and missing form bindings', () => { + rejects((m) => { + m.contributes.operations.items.push(m.contributes.operations.items[0]) + }) + rejects((m) => { + m.contributes.operations.items[0].fields.pop() + }) + }) + it('rejects code, regexes, default paths and hidden file fields', () => { + rejects((m) => { + m.contributes.operations.items[0].fields[1].widget = 'html' + }) + rejects((m) => { + Object.assign(m.contributes.commands[0].argsSchema.properties.input, { + pattern: '(a+)+$', + }) + }) + rejects((m) => { + Object.assign(m.contributes.commands[0].argsSchema.properties.input, { + default: '/etc/passwd', + }) + }) + rejects((m) => { + Object.assign(m.contributes.operations.items[0].fields[0], { + visibleWhen: { field: 'sort', equals: false }, + }) + }) + }) + it('bounds hostile trees and Unicode before recursive parsing', () => { + expect(boundedOperationJson(JSON.parse('{"__proto__":{}}'))).toBe(false) + expect(boundedOperationJson('😀'.repeat(20000))).toBe(false) + const cycle: Record = {} + cycle.x = cycle + expect(boundedOperationJson(cycle)).toBe(false) + let nested: unknown = true + for (let i = 0; i < 10000; i++) nested = { not: nested } + rejects((m) => { + Object.assign(m.contributes.operations.items[0].fields[1], { + visibleWhen: nested, + }) + }) + }) + it('evaluates finite scalar conditions', () => + expect( + matchesOperationCondition( + { + all: [ + { field: 'sort', equals: false }, + { not: { field: 'format', in: ['mkv'] } }, + ], + }, + { sort: false, format: 'mp4' } + ) + ).toBe(true)) + it('preserves false/zero/empty values and rejects unknown or missing args', () => { + expect( + validateOperationValues( + { + properties: { + flag: { type: 'boolean', default: true }, + count: { type: 'integer', minimum: 0, maximum: 5 }, + text: { type: 'string', maxLength: 5 }, + }, + }, + { flag: false, count: 0, text: '' } + ) + ).toEqual({ value: { flag: false, count: 0, text: '' }, errors: {} }) + const schema = ManifestSchema.parse(makeManifest()).contributes.commands![0] + .argsSchema! + expect( + validateOperationValues(schema, { input: 'r', output: 'r2' }).value.sort + ).toBe(false) + expect( + validateOperationValues(schema, { input: 'r', extra: 2 }).errors + ).toEqual({ extra: 'unknown', output: 'required' }) + expect( + validateOperationValues(schema, { + input: 'r', + output: 'r2', + sort: 'true', + }).errors.sort + ).toBe('invalid') + }) +}) + +describe('composable operation UI security', () => { + const withUi = (layout: unknown) => { + const m = makeManifest() + Object.assign(m.contributes.operations.items[0], { + requires: ['operations.ui.v1'], + ui: { layout }, + }) + return m + } + const fields = [ + { type: 'field', field: 'input' }, + { type: 'field', field: 'output', accessory: 'sort' }, + ] + it('accepts a two-column layout with an inline option', () => { + expect( + ManifestSchema.safeParse( + withUi({ type: 'grid', columns: 2, children: fields }) + ).success + ).toBe(true) + }) + it.each([ + { type: 'html', html: '' }, + { type: 'stack', style: { position: 'fixed' }, children: fields }, + { type: 'stack', children: [{ type: 'field', field: 'input' }] }, + { type: 'stack', children: [...fields, { type: 'field', field: 'input' }] }, + { + type: 'stack', + children: [ + { type: 'field', field: 'sort', accessory: 'input' }, + { type: 'field', field: 'output' }, + ], + }, + { + type: 'stack', + children: [ + { type: 'field', field: 'input', accessory: 'sort' }, + { type: 'field', field: 'output' }, + ], + }, + ])( + 'rejects executable, obscured, duplicated or missing controls', + (layout) => { + expect(ManifestSchema.safeParse(withUi(layout)).success).toBe(false) + } + ) + it('rejects excessive recursion before recursive parsing', () => { + let layout: unknown = { type: 'field', field: 'input' } + for (let i = 0; i < 10000; i++) + layout = { type: 'stack', children: [layout] } + expect(ManifestSchema.safeParse(withUi(layout)).success).toBe(false) + }) + it('rejects hiding authorized files inside collapsible groups', () => { + expect( + ManifestSchema.safeParse( + withUi({ + type: 'group', + title: 'Hidden files', + collapsible: true, + children: fields, + }) + ).success + ).toBe(false) + }) + it('requires the UI host capability and forbids output drop zones', () => { + const m = withUi({ type: 'grid', children: fields }) + Object.assign(m.contributes.operations.items[0], { requires: [] }) + expect(ManifestSchema.safeParse(m).success).toBe(false) + Object.assign(m.contributes.operations.items[0], { + requires: ['operations.ui.v1'], + }) + Object.assign(m.contributes.operations.items[0].fields[2], { + appearance: { drop: true }, + }) + expect(ManifestSchema.safeParse(m).success).toBe(false) + }) +}) + +it('accepts collapsible scalar options without hiding file grants', () => { + const m = makeManifest() + Object.assign(m.contributes.operations.items[0], { + requires: ['operations.ui.v1'], + ui: { + layout: { + type: 'stack', + children: [ + { type: 'field', field: 'input' }, + { + type: 'group', + title: 'Options', + collapsible: true, + children: [{ type: 'field', field: 'sort' }], + }, + { type: 'field', field: 'output' }, + ], + }, + }, + }) + expect(ManifestSchema.safeParse(m).success).toBe(true) +})