diff --git a/AGENTS.md b/AGENTS.md index 992780c6..05ba4fd1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,18 +9,15 @@ package at `plugins///`; the rest change the checks 1. New package: copy `examples/hello-miniapp/` to `plugins///`, then replace `name`, `displayName`, `description`, `author`, `exampleQueries`, the ``, the README, and the LICENSE holder. Update: open the existing package, keep its plugin ID, and raise `version` - in `plugin.json`. A newly declared field that raises the minimum client version - (`docs/package-contract.md`) drops older clients; say so in the README and the PR. Read - `docs/package-contract.md` before editing any manifest. -2. Read `docs/runtime.md` before editing `miniapp/node/*`. Read `docs/security.md` before the - Node code reads or writes files, spawns processes, or makes network requests. Read - `docs/client.md` before the page calls `window.mcode` or a browser permission such as - `getUserMedia` or `Notification`, `docs/agent.md` before declaring `agentAccess`, and - `docs/tool.md` before declaring `toolAccess`. + in `plugin.json`. A newly declared field or `engines.mcode` bound that raises the minimum client + version (`docs/package-contract.md`) drops older clients; say so in the README and the PR. +2. Before editing manifests, `miniapp/node/*`, `miniapp/client/*`, or permissions, read the + matching document in "Navigation" below. 3. Write `README.md` (English; `README.zh-CN.md` optional): what it does, how to install and open it, and the headings `## Tested environment` and `## Data & access` (files read/written, - network hosts, spawned processes, Agent turns, conversations read, tools called, microphone, - camera, and notification use, Host navigation read, where state is stored). When the package uses a feature with a minimum client version + network hosts, spawned processes, Agent turns, conversations read, tools and Connectors called, + microphone, camera, and notification use, Host navigation read, file extensions handled, where + state is stored). When the package uses a feature with a minimum client version (`docs/package-contract.md`), name a MiniMax Code version at or above it under `## Tested environment`. 4. Add one row to the table in both root READMEs. @@ -52,22 +49,31 @@ package at `plugins/<github-username>/<plugin-id>/`; the rest change the checks on top of it); `https`, `http2`, `tls`, raw `net`, or a child process on that port never becomes ready. Serve `surface.path` plus your own routes, none under `/__mavis/`. - A Mini App package is a MiniMax Plugin. Skills, subagents (`agents`), MCP servers, hooks, host - bindings, MCP endpoints, and `hostConnectorAccess` may all be declared; `npm run check` validates - their shape only, and the Host validates them at install time. This repository documents the Mini - App payload, the page APIs, the Agent API, and the tool API; treat `context.hostConnector` and the - other capabilities as outside its scope. -- Declare exactly the access the code uses: `agentAccess` (`session.run`, `session.read`), - `toolAccess`, `deviceAccess` (`microphone`, `camera`, `notifications`), `hostAccess` - (`navigation.read`). A call without its declaration fails at runtime, and - `npm run check` reports it as `ACCESS_UNDECLARED`; do not declare access the app does not use. -- `agentAccess` gives an Agent with files, shell, and MCP, and `session.read` exposes every user - conversation. Never answer a `permission.requested` with `allowOnce` unless the user chose it. -- The user can switch any declared access off at any time. Handle `NOT_PERMITTED` - (`not_permitted` on the page), `TOOL_NOT_PERMITTED`, and `NotAllowedError` where the call is made, - and keep the app running. + bindings, MCP endpoints, and `permissions.connector` may all be declared; `npm run check` + validates their shape, and the Host validates Connector providers at install time. This repository + documents the Mini App payload (`fileHandlers` included), the page APIs, the Agent/session APIs, + and the tool API; treat `context.connector` provider details and the other plugin capabilities as + outside its scope. +- Declare in `permissions` (`docs/package-contract.md`) exactly the grants the code uses, and pair + 3.1.20 names with `"engines": { "mcode": ">=3.1.20" }`. Keep legacy `*Access` fields and + `window.mcode.miniapp` only when a package intentionally supports clients before 3.1.20; mixing + `permissions` with any legacy `*Access` field fails with `MINIAPP_PERMISSIONS_INVALID`, and + undeclared calls fail `npm run check` with `ACCESS_UNDECLARED`. +- Hold `window.miniapp` in another variable name (such as `const api = window.miniapp`) or use + `<script type="module">`: `window.miniapp` is a read-only, non-configurable global, so a classic + script with a top-level `const`, `let`, `class`, or `function` named `miniapp` fails before + running (`CLIENT_GLOBAL_MINIAPP`). +- `permissions.agent: ["run"]` gives an Agent with files, shell, and MCP, and + `permissions.session: ["read"]` exposes every user conversation. Show every + `permission.requested` to the user and send `allowOnce` only after they choose it. +- The user can switch any declared permission off at any time. Handle `PERMISSION_DENIED` and + browser `NotAllowedError` where the call is made, explain what can be re-enabled in the plugin + settings, and keep the app running; treat `NOT_PERMITTED` as an author-fixable error. Page + promises reject with plain `{ code, message }` objects (`docs/client.md`). - The runtime payload is exactly `miniapp/client` and `miniapp/node`. Keep tests and docs outside `miniapp/`. Vendor third-party code inside the payload; `node_modules` is never committed. -- Paths are portable: ASCII, no symlinks, no `..`. `npm run check` enforces the full rule set. +- Paths are portable: ASCII, case-distinct, no symlinks, no `..`. `npm run check` enforces the full + rule set. - Secrets stay in the Node process: never in HTML, Client JavaScript, logs, or error responses. - Plugin ID = directory name = `plugin.json.name`, unique across the repository. @@ -86,7 +92,8 @@ suggestion. field and has installers for both macOS and Windows on the production CDN. A tag, a preview build, or a release on one platform only is not evidence: 3.1.5 shipped no installers and 3.1.8 none for Windows. Check that `MiniMax%20Code-<version>-arm64.dmg` and - `MiniMax%20Code%20Setup%20<version>.exe` answer 200 under both + `MiniMax%20Code%20Setup%20<version>-x64.exe` (and `-arm64.exe`; releases before 3.1.15 used + `MiniMax%20Code%20Setup%20<version>.exe`) answer 200 under both `https://filecdn.minimax.chat/public/minimax-agent-prod/release/` and `https://file.cdn.minimax.io/public/minimax-agent-prod/release/`. - A feature that ships first in the next release uses `NEXT_RELEASE` in `scripts/lib/contract.mjs`. @@ -102,17 +109,19 @@ suggestion. ## Navigation -- `docs/package-contract.md` — layout, the three manifests, portable paths, limits, permission - switches, minimum client versions, declared access versus code -- `docs/runtime.md` — `start(context)`, `dispose`, logger, lifecycle and reclaim, loopback - authentication -- `docs/client.md` — page APIs: `capabilities`, browser permissions (microphone, camera, - notifications), `message.append`, `agent`, `speech.transcribe`, `tool.request`, `host`, `window` -- `docs/agent.md` — `agentAccess`, sessions, calls, `whenBusy`, reading and observing sessions, - events, errors -- `docs/tool.md` — `toolAccess`, `context.tool`, permission prompts, errors -- `docs/security.md` — process boundary, state, writing outside `dataDir`, spawning, network, Agent - turns, reading conversations, calling tools, microphone and camera, notifications, Host navigation +- `docs/package-contract.md` — editing any manifest: layout, the three manifests, `permissions`, + `fileHandlers`, `surface.window`, switches, minimum client versions, static checks, legacy + `<3.1.20` compatibility +- `docs/runtime.md` — editing `miniapp/node/*`: `start(context)`, `dispose`, `context` namespaces, + logger, lifecycle and reclaim, loopback authentication +- `docs/client.md` — calling `window.miniapp`, handling file opens, or using browser permissions: + `capabilities`, `getUserMedia` / `Notification`, `host.composer.append`, `speech.transcribe`, + `tool.request`, `host`, `files.subscribe`, `window`, `{ code, message }` page errors +- `docs/agent.md` — declaring `permissions.agent` or `permissions.session`: sessions, `agent.*` and + `session.*` calls, `whenBusy`, events, errors +- `docs/tool.md` — declaring `permissions.tool`: `context.tool`, `tool.request`, prompts, errors +- `docs/security.md` — reading or writing files, spawning processes, making network requests, or + handling sensitive data across any capability - `docs/snippets/audio-capture.ts` — microphone capture in the format `speech.transcribe` takes - `examples/hello-miniapp/` — the copyable starting point - `CONTRIBUTING.md` — fork, pull request, and license steps for people diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 872b1ca8..7978a178 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,7 @@ We welcome tools, games, and other interesting apps you have built for MiniMax C 1. Fork this repository and add your complete plugin package under `plugins/<your-github-username>/<plugin-id>/`. Use a lowercase GitHub username for the author directory. 2. Start from `examples/hello-miniapp/`. Include the hidden `.minimax-plugin/` directory, `package.json`, `miniapp/`, and all required runtime assets. The plugin must work when copied on its own, without depending on other directories in this repository. The exact rules are in `docs/package-contract.md`, `docs/runtime.md`, `docs/client.md`, `docs/agent.md`, `docs/tool.md`, and `docs/security.md`. -3. Add a short English `README.md`. You may also include `README.zh-CN.md` with links between the two versions. Explain what the app does, how to install and use it, tested client versions and operating systems, required configuration, file access, network requests, any Agent turns it runs, conversations it reads, tools it calls, microphone, camera, or notification use, and whether it reads which MiniMax Code page you are on. Screenshots or GIFs are welcome. Declare in `miniapp/miniapp.json` exactly the access the code uses; `npm run check` reports calls without a declaration. If the app uses a feature that needs a newer client, such as `agentAccess`, `toolAccess`, `deviceAccess`, `hostAccess`, or `surface.window`, name a MiniMax Code version at or above its minimum under `## Tested environment` (see "Minimum client version" in `docs/package-contract.md`). +3. Add a short English `README.md`. You may also include `README.zh-CN.md` with links between the two versions. Explain what the app does, how to install and use it, tested client versions and operating systems, required configuration, file access, network requests, any Agent turns it runs, conversations it reads, tools it calls, microphone, camera, or notification use, file extensions it opens, and whether it reads which MiniMax Code page you are on. Screenshots or GIFs are welcome. Declare in `miniapp/miniapp.json` (`permissions`) exactly the access the code uses; `npm run check` reports calls without a declaration. If the app uses a feature that needs a newer client, such as `permissions`, `fileHandlers`, `surface.window`, or an `engines.mcode` bound, name a MiniMax Code version at or above its minimum under `## Tested environment` (see "Minimum client version" in `docs/package-contract.md`). 4. Include a `LICENSE` you are entitled to use, and preserve required attribution for third-party code and assets. 5. Add an entry to the app tables in both root READMEs, run `npm run check` (Node.js 22 or later) until it reports no errors, and open a pull request. diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.md index be1bf509..85411f1b 100644 --- a/CONTRIBUTING.zh-CN.md +++ b/CONTRIBUTING.zh-CN.md @@ -6,7 +6,7 @@ 1. Fork 本仓库,在 `plugins/<你的 GitHub username>/<plugin-id>/` 下放入完整插件包。用户名目录统一使用小写。 2. 从 `examples/hello-miniapp/` 复制开始。保留 `.minimax-plugin/` 隐藏目录、`package.json`、`miniapp/` 和运行所需资源。插件应能独立复制使用,不依赖仓库里的其他目录。具体规则见 `docs/package-contract.md`、`docs/runtime.md`、`docs/client.md`、`docs/agent.md`、`docs/tool.md` 和 `docs/security.md`(英文)。 -3. 添加简短的英文 `README.md`,可另附 `README.zh-CN.md` 并互相链接。说明用途、安装与使用方式、已验证的客户端版本和系统,以及需要的配置、文件访问、网络请求、会运行的 Agent 任务、会读取的会话、会调用的工具,是否使用麦克风、摄像头或系统通知,以及是否读取你当前所在的 MiniMax Code 页面。欢迎附上截图或 GIF。`miniapp/miniapp.json` 中只声明代码实际用到的权限;代码调用了未声明的能力时,`npm run check` 会报出来。如果用到了需要较新客户端的能力(如 `agentAccess`、`toolAccess`、`deviceAccess`、`hostAccess`、`surface.window`),请在 `## Tested environment` 中写明不低于最低要求的 MiniMax Code 版本(见 `docs/package-contract.md` 的 “Minimum client version”)。 +3. 添加简短的英文 `README.md`,可另附 `README.zh-CN.md` 并互相链接。说明用途、安装与使用方式、已验证的客户端版本和系统,以及需要的配置、文件访问、网络请求、会运行的 Agent 任务、会读取的会话、会调用的工具,是否使用麦克风、摄像头或系统通知,打开哪些文件扩展名,以及是否读取你当前所在的 MiniMax Code 页面。欢迎附上截图或 GIF。`miniapp/miniapp.json`(`permissions`)中只声明代码实际用到的权限;代码调用了未声明的能力时,`npm run check` 会报出来。如果用到了需要较新客户端的能力(如 `permissions`、`fileHandlers`、`surface.window` 或 `engines.mcode` 下限),请在 `## Tested environment` 中写明不低于最低要求的 MiniMax Code 版本(见 `docs/package-contract.md` 的 “Minimum client version”)。 4. 添加你有权使用的 `LICENSE`,保留第三方代码和素材要求的署名。 5. 在根目录中英文 README 的作品表格中各增加一行,运行 `npm run check`(需要 Node.js 22 或更高版本)直到没有 error,再提交 Pull Request。 diff --git a/README.md b/README.md index 86551113..e9b75cc3 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ MiniApps run inside the MiniMax Code desktop host through four cooperating layer - **Host management:** The host provides Electron page hosting, runtime services, plugin installation and publishing, Node process lifecycle, readiness and instance management, and permissions and credentials. It provides control across the stack while business logic remains owned by each plugin. - **Presentation layer (Chromium / Chrome engine):** The MiniApp page renders HTML, CSS, and JavaScript for filters, tables, charts, and interactive views. Host credentials stay out of the page. - **Application layer (Node.js):** The Node process owns data aggregation, transformation and processing, business rules, and persistence. Page APIs and Agent tools reuse the same business services. Node can also provide a managed MCP service for the host MCP client. -- **Capabilities and data access:** Plugins can use available Host Connector access, optional plugin-spawned CLI child processes, and the planned unified tool entry for authorized Connector or MCP access to external services, MCP services, local tools, and local data. +- **Capabilities and data access:** Plugins can use available Host Connector access, optional plugin-spawned CLI child processes, and the unified tool entry for authorized Connector or MCP access to external services, MCP services, local tools, and local data. The MiniMax Code Agent communicates through the host MCP client. Business requests and page data move between the presentation and application layers, while Agent calls and results are mediated by the host. This keeps credentials and control in the host, and keeps domain logic and persistence in the plugin. @@ -152,7 +152,7 @@ The preview uses synthetic data. The app interface is currently in Chinese. See ### Requirements -Use a MiniMax Code desktop version that supports MiniApps. Check the app's README for tested client versions, operating systems, configuration, and known limitations. Compatibility is documented per app. Apps that use newer capabilities need a newer client, and older versions cannot install them: running Agent tasks or opening in their own window needs MiniMax Code 3.1.2 or later; reading your conversations, calling your installed tools, or using the microphone needs 3.1.6 or later; using the camera or showing system notifications needs 3.1.9 or later; following which MiniMax Code page you are on needs 3.1.11 or later. From 3.1.6 you can switch off each permission an app declares, one by one, in its plugin details. +Use a MiniMax Code desktop version that supports MiniApps. Check the app's README for tested client versions, operating systems, configuration, and known limitations. Compatibility is documented per app. Apps that use newer capabilities need a newer client, and older versions cannot install them: running Agent tasks or opening in their own window needs MiniMax Code 3.1.2 or later; reading your conversations, calling your installed tools, or using the microphone needs 3.1.6 or later; using the camera or showing system notifications needs 3.1.9 or later; following which MiniMax Code page you are on needs 3.1.11 or later; opening files by extension needs 3.1.18 or later; and apps written against the grouped `permissions` manifest or `window.miniapp` APIs need 3.1.20 or later. From 3.1.6 you can switch off each permission an app declares, one by one, in its plugin details. ### 1. Download diff --git a/README.zh-CN.md b/README.zh-CN.md index 3178b68a..b5d4496f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -45,7 +45,7 @@ MiniApp 运行在 MiniMax Code 桌面宿主中,由四个相互配合的层组 - **宿主管理层:** 宿主提供 Electron 页面承载、运行时服务、插件安装与发布、Node 进程生命周期、就绪与实例管理,以及权限与凭证管理。宿主控制贯穿各层,但业务逻辑仍由插件负责。 - **展示层(Chromium / Chrome 引擎):** MiniApp 页面使用 HTML、CSS 和 JavaScript 实现筛选、表格、图表与交互式渲染;宿主凭证不会交给页面。 - **应用层(Node.js):** Node 进程负责数据聚合、转换与深度加工、业务规则和持久化。页面接口与 Agent 工具复用同一套业务服务;Node 还可以为宿主 MCP 客户端提供受管理的 MCP 服务。 -- **能力与数据接入层:** 插件可以使用现有的 Host Connector 能力、可选的插件子进程 CLI,以及规划中的统一工具入口,在获得授权后访问 Connector 或 MCP,连接外部业务服务、MCP 服务、本地工具与本地数据。 +- **能力与数据接入层:** 插件可以使用现有的 Host Connector 能力、可选的插件子进程 CLI,以及统一工具入口,在获得授权后访问 Connector 或 MCP,连接外部业务服务、MCP 服务、本地工具与本地数据。 MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求与页面数据在展示层和应用层之间流转,Agent 的调用与结果由宿主进行中介和管理。这样既能让凭证与控制权留在宿主,也能让领域逻辑与持久化留在插件中。 @@ -152,7 +152,7 @@ MiniMax Code Agent 通过宿主 MCP 客户端与 MiniApp 协作。业务请求 ### 使用要求 -需要支持 MiniApp 的 MiniMax Code 桌面端版本。各作品的 README 会说明已验证的客户端版本、操作系统、所需配置和已知限制,兼容性以具体作品为准。使用较新能力的作品需要较新的客户端,旧版本无法安装:运行 Agent 任务、在独立窗口中打开需要 MiniMax Code 3.1.2 或更高版本;读取你的会话、调用你已安装的工具或使用麦克风需要 3.1.6 或更高版本;使用摄像头或发送系统通知需要 3.1.9 或更高版本;读取你当前所在的 MiniMax Code 页面需要 3.1.11 或更高版本。从 3.1.6 起,你可以在每个作品的插件详情里逐项关闭它声明的权限。 +需要支持 MiniApp 的 MiniMax Code 桌面端版本。各作品的 README 会说明已验证的客户端版本、操作系统、所需配置和已知限制,兼容性以具体作品为准。使用较新能力的作品需要较新的客户端,旧版本无法安装:运行 Agent 任务、在独立窗口中打开需要 MiniMax Code 3.1.2 或更高版本;读取你的会话、调用你已安装的工具或使用麦克风需要 3.1.6 或更高版本;使用摄像头或发送系统通知需要 3.1.9 或更高版本;读取你当前所在的 MiniMax Code 页面需要 3.1.11 或更高版本;按文件扩展名打开文件需要 3.1.18 或更高版本;使用分组 `permissions` 清单或 `window.miniapp` 接口的作品需要 3.1.20 或更高版本。从 3.1.6 起,你可以在每个作品的插件详情里逐项关闭它声明的权限。 ### 1. 下载 diff --git a/docs/agent.md b/docs/agent.md index 9a70652e..a2b352d6 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -1,43 +1,48 @@ -# Mini App Agent API +# Mini App Agent and Session APIs -Verified against MiniMax Code 3.1.11. Clients before 3.1.2 reject packages that declare -`agentAccess`, and clients before 3.1.6 reject `"session.read"`. +Verified against MiniMax Code 3.1.21. -A Mini App can run Agent turns from its Node entry (`context.agent`) or its page -(`window.mcode.miniapp.agent`). The Agent keeps its full capabilities: files, shell, Skills, and MCP, -including this Mini App's own MCP tools. Declare it only when the Mini App genuinely needs an Agent -at runtime; a page that only prepares text for the user to send should use -`window.mcode.miniapp.message.append` instead (see `docs/client.md`). +A Mini App can run Agent turns through `context.agent` / `window.miniapp.agent` and read or observe +conversations through `context.session` / `window.miniapp.session` (MiniMax Code 3.1.20 or later; +see "Legacy `<3.1.20` compatibility" in `docs/package-contract.md` for older clients). The Agent +keeps its full capabilities: files, shell, Skills, and MCP, including this Mini App's own MCP tools. +Declare `permissions.agent: ["run"]` only when the Mini App genuinely needs an Agent at runtime; a +page that only prepares text for the user to send should use `window.miniapp.host.composer.append` +instead (see `docs/client.md`). -## Grant +## Grants ```json { - "agentAccess": ["session.run", "session.read"], - "agentConcurrency": 4 + "permissions": { + "agent": ["run"], + "session": ["read"] + }, + "agentConcurrency": 4, + "engines": { "mcode": ">=3.1.20" } } ``` -- `agentAccess` in `miniapp/miniapp.json` is the only grant. Absent or `[]` means no access: - `context.agent` is absent and page calls reject with `not_permitted`. -- `"session.run"` runs Agent turns in this Mini App's own sessions: `run`, `answer`, `reply`, - `cancel`, `open`, `models`, `agents`, `create`. -- `"session.read"` (MiniMax Code 3.1.6 or later) lists, reads, and observes the user's own - conversations, including the final reply of every turn: `sessions()`, `session()`, and - `observe()` (see [Reading and observing the user's sessions](#reading-and-observing-the-users-sessions)). +- `permissions.agent` and `permissions.session` in `miniapp/miniapp.json` grant access; absent or + `[]` denies it, and undeclared calls reject with `NOT_PERMITTED`. +- `permissions.agent: ["run"]` runs Agent turns in this Mini App's own sessions: `agent.run`, + `agent.answer`, `agent.reply`, `agent.open`, `agent.models`, `agent.list`, `agent.create`. Page + `agent.cancel` needs no grant. +- `permissions.session: ["read"]` lists, reads, and observes the user's own conversations, + including the final reply of every turn: `session.list()`, `session.get()`, and + `session.observe()` (see [Reading and observing conversations](#reading-and-observing-conversations)). It does not let the Mini App run, answer, or continue those conversations. -- The two values are independent; declare both when the Mini App needs both. Either one lets the - Mini App read and observe its own sessions. +- The two grants are independent; declare both when the Mini App needs both. Either one lets the + Mini App read and observe its own sessions (`session.get(id)`, `session.observe({ sessionId })`); + `session.observe({ all: true })` always requires `permissions.session: ["read"]`. - `agentConcurrency` (1–32, default 4) caps how many turns of this Mini App run at once. - Changing any of these fields restarts the Mini App process when the package is updated. -- The user can switch either value off in the plugin details (MiniMax Code 3.1.6 or later). The - Mini App keeps running and `context.agent` stays; calls covered by that value fail with - `NOT_PERMITTED` / `not_permitted` until the user switches it back on. Show an explanation in the - page instead of failing. +- The user can switch `agent:run` or `session:read` off in the plugin details. The Mini App keeps + running and the namespaces stay present; calls covered by the switched-off grant reject with + `PERMISSION_DENIED` (`{ code: 'PERMISSION_DENIED', message: 'permission_denied' }` on the page) + until the user switches it back on. Show an explanation in the page instead of failing. - State in the README `## Data & access` that the Mini App runs Agent turns or reads the user's conversations, and what it does with them (see `docs/security.md`). -- Feature-detect calls added after 3.1.2 with `capabilities?.has(...)`: `agent.observe`, - `agent.sessions`, and `agent.session` exist from 3.1.6. ## Sessions @@ -50,9 +55,9 @@ session list. | Working directory | That chat's project directory when it has one; otherwise this Mini App's own Agent directory. | This Mini App's own Agent directory. | | Model | A snapshot of that chat's model and thinking level; the runtime default otherwise. | The runtime default. | -- Pass `agent` (a `name` from `agents()`) to `create` or to the first `run` to start the session as - another agent. The alias `main` is rejected. A session never changes its agent; passing `agent` - when continuing is `INVALID_ARGUMENTS` / `invalid_request`. +- Pass `agent` (a `name` from `agent.list()`) to `create` or to the first `run` to start the + session as another agent. The alias `main` is rejected. A session never changes its agent; + passing `agent` when continuing is `INVALID_ARGUMENTS`. - A continued session keeps its agent and directory. Its model is fixed at creation and does not follow later changes in the chat; pass `model` to `run` or `answer` to switch it first. - `create({ agent? })` makes a session without running a turn and returns `{ sessionId }`. A page can @@ -60,35 +65,36 @@ session list. - Inside a session this Mini App started, the Agent cannot publish, restart, or stop Mini Apps, and `@`-mentions do not start other Mini Apps. Sessions it delegates to sub-agents are not covered. -## Calls +## `agent` calls Node calls take an options object `{ signal?, onEvent? }`; page calls take `{ onEvent? }` and use -`requestId` with `cancel(requestId)` instead of a signal. +`requestId` with `agent.cancel(requestId)` instead of a signal. | Call | Result | | --- | --- | -| `run({ text, sessionId?, model?, agent?, whenBusy? })` (page also `requestId?`) | `{ sessionId, turnId?, model?, status, text?, error?, pendingQuestion? }` when the turn ends. `status` is `finished`, `error`, `aborted`, or (only with `whenBusy`) `steered`; `text` is the final reply. `text` input is at most 100,000 UTF-16 code units. | -| `answer({ sessionId, answers, model? })` with `requestId` (Node) or `questionId` (page) naming the questionnaire | Same as `run`, for the continuation turn. | -| `reply({ sessionId, requestId, decision })` | Decides a waiting `permission.requested`; `decision` is `allowOnce` or `deny`. There is no "always allow". | -| `models()` | `{ models, default, host? }`: the models the user can use, the runtime default, and (page only) the chat's current model. `default` and `host` can be passed as `model` directly. | -| `agents()` | `{ agents }`: each `{ name, displayName, primary }`. | -| `create({ agent? })` | `{ sessionId }`, without running a turn. | -| `open(sessionId)` (page only) | Shows the session as a tab in the side panel of the chat the Mini App is open in, where the user can read it and answer its cards. Idempotent. | -| `cancel(requestId)` (page only) | Cancels that call or observer; unknown or finished ids do nothing. | -| `sessions()`, `session()`, `observe()` | See [Reading and observing the user's sessions](#reading-and-observing-the-users-sessions). | +| `agent.run({ text, sessionId?, model?, agent?, whenBusy? })` (page also `requestId?`) | `{ sessionId, turnId?, model?, status, text?, error?, pendingQuestion? }` when the turn ends. `status` is `finished`, `error`, `aborted`, or (only with `whenBusy`) `steered`; `text` is the final reply. `text` input is at most 100,000 UTF-16 code units. | +| `agent.answer({ sessionId, answers, model? })` with `requestId` (Node) or `questionId` (page) naming the questionnaire | Same as `run`, for the continuation turn. | +| `agent.reply({ sessionId, requestId, decision })` | Decides a waiting `permission.requested`; `decision` is `allowOnce` or `deny`. There is no "always allow". | +| `agent.models()` | `{ models, default, host? }`: the models the user can use, the runtime default, and (page only) the chat's current model. `default` and `host` can be passed as `model` directly. | +| `agent.list()` | `{ agents }`: each `{ name, displayName, primary }` (replaces deprecated `agent.agents()`). | +| `agent.create({ agent? })` | `{ sessionId }`, without running a turn. | +| `agent.open(sessionId)` (page only) | Shows the session as a tab in the side panel of the chat the Mini App is open in, where the user can read it and answer its cards. Idempotent. | +| `agent.cancel(requestId)` (page only) | Cancels that call or `session.observe` subscription; unknown or finished ids do nothing. Needs no grant. | - A model is `{ providerId, modelId, variant?, thinking?: { effort } }`. Build it from a `models()` entry; pick `variant` from `variants` and `effort` from `thinking.efforts`. `variant: ''` means thinking is off and must be passed as is. -- Call `context.agent` from request handlers, never inside `start(context)`. -- Node allows 16 outstanding `run` / `answer` / `models` / `agents` / `create` requests (shared with - Host Connector requests) plus 16 for `reply`, so a full queue can still answer approvals. +- Call `context.agent` and `context.session` from request handlers, never inside `start(context)`. +- Node allows 16 outstanding `run` / `answer` / `models` / `list` / `create` requests (shared with + Connector requests) plus 16 for `reply`, so a full queue can still answer approvals. ### Follow-ups while the session is busy (`whenBusy`) -From MiniMax Code 3.1.6, `run({ sessionId, text, whenBusy })` decides what happens when that session -is already running a turn; without `whenBusy` the call fails with `busy`. On an idle session both -values just start a turn. +`agent.run({ sessionId, text, whenBusy })` decides what happens when that session is already busy: +running a turn (whoever started it, including the chat side panel or a Host background callback), +compacting, or holding queued messages such as ones the user stopped. Without `whenBusy` the call +rejects with `BUSY` (`reason: 'session_busy'`) and the text reaches no turn, so sending it again +later runs it once. On an idle session both `whenBusy` values start a turn as usual. - `'queue'`: the text waits in the session queue and runs as its own turn after the turns ahead of it. You get `run.queued` with its queue `position`, then the call resolves like any `run`. @@ -109,23 +115,23 @@ to free the slot. - At most `agentConcurrency` turns per Mini App run at once, one per session. Further `run` / `answer` calls wait in order, up to four times `agentConcurrency`; beyond that they fail with - `busy`. -- A Mini App starts at most 12 turns per 60 seconds, or 5 × `agentConcurrency` when that is larger - (MiniMax Code 3.1.6 or later). Past that, calls fail with `busy`. The count survives a Mini App - restart. + `BUSY`. +- A Mini App starts at most 12 turns per 60 seconds, or 5 × `agentConcurrency` when that is larger. + Past that, calls fail with `BUSY`. The count survives a Mini App restart. - Node sees why a call is `BUSY` in `reason`: `session_busy`, `queue_full`, `rate_limited`, or - `observer_limit`. The page only receives `busy`. + `observer_limit`. Page `agent.*` / `session.*` rejections carry `reason` (`session_busy` or + `queue_full`) and `retryable`. ## Interaction Two interactions block a turn. The Mini App renders them itself, or lets the Host do it with the -page's `open(sessionId)`: +page's `agent.open(sessionId)`: -- `permission.requested` → `reply`: a tool call waits for approval. -- `question.requested` → `answer`: the turn paused on a questionnaire (a question to the user, a - feature enable, or a plan review). The same questionnaire is in `result.pendingQuestion`, so a run - without `onEvent` can render it too. Call `answer` only after the paused `run` has resolved; an - earlier `answer` fails with `busy`. +- `permission.requested` → `agent.reply`: a tool call waits for approval. +- `question.requested` → `agent.answer`: the turn paused on a questionnaire (a question to the user, + a feature enable, or a plan review). The same questionnaire is in `result.pendingQuestion`, so a + run without `onEvent` can render it too. Call `answer` only after the paused `run` has resolved; + an earlier `answer` fails with `BUSY`. A permission request waits only while someone can answer it: the run that owns the session passed `onEvent`, or the session is open in a chat side panel through `open`. Otherwise the Host denies it @@ -142,7 +148,7 @@ async function runWithApproval(agent, text, confirmTool, askUser) { .then((allowed) => agent.reply({ sessionId: event.sessionId, requestId: event.requestId, decision: allowed ? 'allowOnce' : 'deny' }), ) - .catch(() => {}); // request_not_found: the run was cancelled meanwhile + .catch(() => {}); // REQUEST_NOT_FOUND: the run was cancelled meanwhile }; let result = await agent.run({ text }, { onEvent }); while (result.pendingQuestion) { @@ -177,50 +183,55 @@ Ignore any `type` you do not know; new types may be added. | `question.requested` | The turn paused on a questionnaire; carries `requestId`, `mode`, `request`. | | `turn.finished` | Last unless the call ended `steered`; same `status`, `text?`, `error?` as the result. | -## Reading and observing the user's sessions +## Reading and observing conversations -These calls exist from MiniMax Code 3.1.6. They need `"session.read"`, except for this Mini App's own -sessions, which either `agentAccess` value covers. They change nothing: a lost answer is -`AGENT_UNAVAILABLE` / `runtime_unavailable` and safe to retry. +`context.session` and `window.miniapp.session` replace the deprecated `agent.sessions()`, +`agent.session()`, and `agent.observe()` methods. They need `permissions.session: ["read"]`, except +for this Mini App's own sessions, which `permissions.agent: ["run"]` also covers. They change +nothing: a lost answer is `AGENT_UNAVAILABLE` / `RUNTIME_UNAVAILABLE` and safe to retry. -- `sessions()` resolves with `{ sessions }`, the 50 most recently updated user conversations, each - `{ sessionId, title?, agent, status, workspaceDir, isDefaultWorkspace, createdAtMs, updatedAtMs }`. +- `session.list()` resolves with `{ sessions }`, the 50 most recently updated user conversations, + each `{ sessionId, title?, agent, status, workspaceDir, isDefaultWorkspace, createdAtMs, updatedAtMs }`. `status` is `idle`, `running`, `error`, or `aborted`; `isDefaultWorkspace` is `true` when the conversation has no project. Mini App, scheduled, and sub-agent sessions are not listed. -- `session(sessionId)` adds `model?`, `error?: { message }` while `status` is `error`, and +- `session.get(sessionId)` adds `model?`, `error?: { message }` while `status` is `error`, and `lastAssistantText?`, the final text of the latest reply. -- On the page, `session()` without an id reads the chat the page is open in, for example to work in - its project directory; it resolves with `undefined` outside a chat. That chat is the user's - conversation, so it needs `"session.read"` too. Node has no current chat: the page passes the id. -- `observe({ all: true }, { onEvent })` reports `turn.started`, `message.committed` (the final - reply), and `turn.finished` of every user conversation, each with `sessionId` and the - conversation's `title` when it has one. `observe({ sessionId }, { onEvent })` reports every - progress event of one session, turn after turn. Pass exactly one target. +- On the page, `session.get()` without an id reads the chat the page is open in, for example to work + in its project directory; it resolves with `undefined` outside a chat. That chat is the user's + conversation, so it needs `permissions.session: ["read"]` too. Node has no current chat: the page + passes the id. +- `session.observe({ all: true }, { onEvent })` reports `turn.started`, `message.committed` (the + final reply), and `turn.finished` of every user conversation, each with `sessionId` and the + conversation's `title` when it has one. `session.observe({ sessionId }, { onEvent })` reports + every progress event of one session, turn after turn. Pass exactly one target. - An observer never receives `permission.requested` or `question.requested`, and cannot answer them. `turn.started` carries `model` only when the Host could read it, and `turn.finished` comes - without `text` when the Host could not read the final reply; read `session()` if you need it. - When events back up, `text.delta` and `tool.*` events may be dropped, never the start, the final - reply, or the finish. -- `observe` resolves when the subscription ends: Node aborts its `signal`, the page calls - `cancel(requestId)` with the `requestId` it passed, the session is deleted, the Mini App stops, or - the user switches `"session.read"` off. It rejects when it could not start. At most 4 observers per - Mini App (`busy`); they use no run slots. Missed events are not replayed, so refresh with - `session()` after re-subscribing. + without `text` when the Host could not read the final reply; read `session.get(id)` if you need + it. When events back up, `text.delta` and `tool.*` events may be dropped, never the start, the + final reply, or the finish. +- `session.observe` resolves when the subscription ends: Node aborts its `signal`, the page calls + `agent.cancel(requestId)` with the `requestId` it passed, the session is deleted, the Mini App + stops, or the user switches `session:read` off. It rejects when it could not start. At most 4 + observers per Mini App (`BUSY`); they use no run slots. Missed events are not replayed, so refresh + with `session.get(id)` after re-subscribing. ## Errors -Node errors carry `code` and `retryable`; page errors are an `Error` whose `message` is the code. +Node errors are `Error` instances carrying `code`, `retryable`, and (on `BUSY`) `reason`. Page +calls on `window.miniapp` reject with plain `{ code, message, retryable, reason? }` objects +(`instanceof Error` is `false`). -| Node `code` | Page `message` | Meaning | +| Node `code` | Page `code` (`message`) | Meaning | | --- | --- | --- | -| `NOT_PERMITTED` | `not_permitted` | Not declared in `agentAccess`, switched off by the user, or (page `open`) the Mini App is not open in a chat. | -| `BUSY` | `busy` | The session already runs a turn, the queue is full, the per-minute limit was hit, or 4 observers are running. Retryable. | -| `SESSION_NOT_FOUND` | `session_not_found` | Not a session this Mini App may use. | -| `INVALID_ARGUMENTS` | `invalid_request` | Malformed input, an unusable model, `agent` on an existing session, or not exactly one `observe` target. | -| `AGENT_UNAVAILABLE` | `runtime_unavailable` | Nothing was started; retry later. Also returned to a page or process left over from before a restart. | -| `REQUEST_CANCELLED` | `cancelled` | Cancelled before anything ran, or removed from the session queue. | -| `AGENT_OUTCOME_UNKNOWN` | `result_unknown` | The turn may have run, or a steered text could not be withdrawn. Never retry automatically; check the session first. | -| `REQUEST_NOT_FOUND` | `request_not_found` | The permission request or questionnaire is unknown or already settled. | +| `NOT_PERMITTED` | `NOT_PERMITTED` (`not_permitted`) | Required grant not declared in `permissions`, or (page `agent.open`) the Mini App is not open in a chat. | +| `PERMISSION_DENIED` | `PERMISSION_DENIED` (`permission_denied`) | Declared `agent:run` or `session:read` grant is switched off by the user. | +| `BUSY` | `BUSY` (`busy`) | The session is busy, the queue is full, the per-minute limit was hit, or 4 observers are running. Retryable. | +| `SESSION_NOT_FOUND` | `SESSION_NOT_FOUND` (`session_not_found`) | Not a session this Mini App may use. | +| `INVALID_ARGUMENTS` | `INVALID_ARGUMENTS` (`invalid_request`) | Malformed input, an unusable model, `agent` on an existing session, or not exactly one `observe` target. | +| `AGENT_UNAVAILABLE` | `RUNTIME_UNAVAILABLE` (`runtime_unavailable`) | Nothing was started; retry later. Also returned to a page or process left over from before a restart. | +| `REQUEST_CANCELLED` | `CANCELLED` (`cancelled`) | Cancelled before anything ran, or removed from the session queue. | +| `AGENT_OUTCOME_UNKNOWN` | `RESULT_UNKNOWN` (`result_unknown`) | The turn may have run, or a steered text could not be withdrawn. Never retry automatically; check the session first. | +| `REQUEST_NOT_FOUND` | `REQUEST_NOT_FOUND` (`request_not_found`) | The permission request or questionnaire is unknown or already settled. | A cancelled turn resolves with `status: "aborted"` only when the Host confirmed the abort. A process restart cancels in-flight turns, and reloading or closing the page cancels the page's turns. diff --git a/docs/client.md b/docs/client.md index 5aa29d75..527299ff 100644 --- a/docs/client.md +++ b/docs/client.md @@ -1,42 +1,74 @@ # Mini App page APIs -Verified against MiniMax Code 3.1.11. - -MiniMax Code injects `window.mcode.miniapp` into the Mini App's own page. Older clients, ordinary -Browser tabs, and other browsers do not provide it, so check that a method exists before calling -it. No SDK is needed. For type checking, copy `examples/hello-miniapp/miniapp/client/client-api.ts` -next to your Client source and reference it from TypeScript or JSDoc; never load it with a script -tag or import it at runtime. +Verified against MiniMax Code 3.1.21. + +From MiniMax Code 3.1.20, the Host injects `window.miniapp` into the Mini App's own page (and +keeps `window.mcode.miniapp` as a deprecated alias for older packages). Pair `window.miniapp` with +`"engines": { "mcode": ">=3.1.20" }` in `miniapp/miniapp.json` unless the page falls back for older +clients. Ordinary Browser tabs and external browsers do not provide the bridge, so check that a +method exists before calling it. No SDK is needed. For type checking, copy +`examples/hello-miniapp/miniapp/client/client-api.ts` next to your Client source and reference it +from TypeScript or JSDoc; never load it with a script tag or import it at runtime. + +`window.miniapp` is defined as a read-only, non-configurable global on `window`. A classic +`<script>` (without `type="module"`) cannot declare a top-level `const`, `let`, `class`, or +`function` named `miniapp` — the script fails with a `SyntaxError` or `TypeError` before running, +and `npm run check` reports it as `CLIENT_GLOBAL_MINIAPP`. Hold the bridge in another name such as +`const api = window.miniapp`, or use `<script type="module">`. The bridge only works in the page's own top-level document on its own origin. Keep third-party scripts out of that document: anything running there shares the page's access to the bridge. +## Errors on the page + +Every rejected `window.miniapp` promise throws a plain `{ code, message }` object (`instanceof +Error` is `false` so `code` survives Electron's context bridge): + +- `error.code` is an upper-case token: `INVALID_ARGUMENTS`, `NOT_PERMITTED`, `PERMISSION_DENIED`, + `BUSY`, `SESSION_NOT_FOUND`, `REQUEST_NOT_FOUND`, `RUNTIME_UNAVAILABLE`, `RESULT_UNKNOWN`, + `CANCELLED`, `TEXT_TOO_LARGE`, `AUDIO_TOO_LARGE`, `USER_CANCELLED`, `TARGET_UNAVAILABLE`, + `NOT_ALLOWED`, `HOST_UNAVAILABLE`, `UNSUPPORTED_SOURCE`, `UNSUPPORTED_TARGET`, + `TRANSCRIPTION_FAILED`, `INLINE_MODE`, or `APPROVAL_REQUIRED`. Switch on `error.code`. +- `error.message` keeps the legacy lower-case string (such as `'permission_denied'` or + `'user_cancelled'`); do not display it directly as prose. +- `error.retryable` (boolean) and `error.reason` (`'session_busy' | 'queue_full'` on `BUSY`) are + included on `agent.*` and `session.*` rejections. +- `NOT_PERMITTED` means an undeclared grant or invalid call context (author-fixable); + `PERMISSION_DENIED` means the user switched off a declared permission or denied a tool prompt. + +The deprecated `window.mcode.miniapp` shell keeps its historical shapes (`Error` with lower-case +`message` on older namespaces, lower-case `{ code, message }` on `host` and `files`, and +`not_permitted` for both permission states). + ## `miniapp.capabilities.has(name)` -From MiniMax Code 3.1.6, `window.mcode.miniapp.capabilities.has(name)` answers synchronously whether -this client supports a feature, named by its API path: `message.append`, `agent.run`, `agent.open`, -`agent.models`, `agent.agents`, `agent.create`, `agent.observe`, `agent.sessions`, -`agent.session`, `speech.transcribe`, `tool`, `tool.request`, `window`, `hostConnector`, and from -3.1.11 `host.ui.getState`, `host.ui.subscribe`, `host.navigation.getState`, -`host.navigation.subscribe`, `host.navigation.open`. The list is -the same on the page and in Node (`context.capabilities`), and it describes the client, not this -Mini App's grants: `has('agent.run')` is true even without `agentAccess`. Earlier clients have no -`capabilities`, so write `window.mcode?.miniapp?.capabilities?.has('agent.observe')`. +`window.miniapp.capabilities.has(name)` answers synchronously whether this client offers `name` +**on the page**, named by its API path: `agent.run`, `agent.reply`, `agent.answer`, `agent.cancel`, +`agent.open`, `agent.models`, `agent.list`, `agent.create`, `session.list`, `session.get`, +`session.observe`, `host.composer.append`, `host.ui.getState`, `host.ui.subscribe`, +`host.navigation.getState`, `host.navigation.subscribe`, `host.navigation.open`, `files.subscribe`, +`speech.transcribe`, `tool.request`, `window.getState`, `window.update`, `window.focus`, +`window.onDidChangeState` (plus deprecated aliases while they remain). Node-only names such as +`tool.call` and `connector.call` answer `false` on `window.miniapp` and `true` on Node +`context.capabilities`. + +`capabilities.has` describes the client version, not this Mini App's grants: `has('agent.run')` is +`true` even without `permissions.agent`, and an undeclared call then rejects with `NOT_PERMITTED`. +Write `window.miniapp?.capabilities?.has('session.list')` when probing. ## Browser permissions From MiniMax Code 3.1.6 the Host decides every browser permission request from a Mini App page and never shows a browser prompt. Sanitized clipboard writes, fullscreen, pointer lock, and keyboard lock work without a declaration. The microphone, the camera, and system notifications work only when -`miniapp.json` declares their `deviceAccess` value (`docs/package-contract.md`) and the user has not -switched it off, and only from the page's main frame. Geolocation, clipboard reads, screen +`miniapp.json` declares their `permissions.device` item (`docs/package-contract.md`) and the user +has not switched it off, and only from the page's main frame. Geolocation, clipboard reads, screen capture, and everything else a browser would prompt for are always denied. Earlier clients granted these requests silently. -- **Microphone** (`"microphone"`): `getUserMedia({ audio: true })`; without the grant it rejects with - `NotAllowedError`. Call `getUserMedia` instead of querying first: from 3.1.9 - `navigator.permissions.query({ name: 'microphone' })` reports whether the value is declared and - switched on, but 3.1.6 to 3.1.8 report `granted` only after a granted `getUserMedia`. +- **Microphone** (`"microphone"`): `getUserMedia({ audio: true })`; without the grant or when + switched off it rejects with `NotAllowedError`. Call `getUserMedia` directly instead of querying + `navigator.permissions` first. - **Camera** (`"camera"`, MiniMax Code 3.1.9 or later): `getUserMedia({ video: true })`. A request for audio and video together needs both values and fails with `NotAllowedError` when either is missing or switched off, so request them separately when the page can work with one. The operating @@ -55,7 +87,7 @@ itself back with `window.focus()` (see [`miniapp.window`](#miniappwindow-propose ```js const notice = new Notification('Build finished', { body: 'All 42 checks passed.' }); notice.addEventListener('click', () => { - window.mcode?.miniapp?.window?.focus().catch(() => {}); + window.miniapp?.window?.focus().catch(() => {}); }); ``` @@ -63,91 +95,93 @@ A popped-out page shows and focuses its window; a page in the side panel brings and selects its tab. This works only while the page that created the notification is still open: after that page closes or reloads, clicking its notification does nothing. -## `miniapp.message.append(text)` +## `miniapp.host.composer.append(text)` -Asks the user to add plain text to the chat input of the conversation the Mini App is open in. The -Host shows its own confirmation with the plugin, the target conversation, and the text. After the -user confirms, the text is appended to the unsent draft; the user can still edit it and must press -Send. The page cannot send messages, read chat history, or change sent messages. +Asks the user to add plain text to the chat input of the conversation the Mini App is open in +(replacing the deprecated `miniapp.message.append(text)`). The Host shows its own confirmation with +the plugin, the target conversation, and the text. After the user confirms, the text is appended to +the unsent draft; the user can still edit it and must press Send. The page cannot send messages, +read chat history, or change sent messages. ```js async function addToChat(text, status) { - const message = window.mcode?.miniapp?.message; - if (!message?.append) { + const composer = window.miniapp?.host?.composer; + if (!composer?.append) { status.textContent = 'This version of MiniMax Code cannot add text to the chat input.'; return; } try { - await message.append(text); + await composer.append(text); status.textContent = 'Added to the chat input. Review it there and press Send.'; } catch (error) { - status.textContent = error?.message === 'user_cancelled' ? 'Cancelled.' : `Not added (${error?.message}).`; + status.textContent = error?.code === 'USER_CANCELLED' ? 'Cancelled.' : `Not added (${error?.code}).`; } } ``` - Call it from a user action, such as a button click. `text` is at most 100,000 UTF-16 code units - and is appended literally. Every call needs its own confirmation. -- Failures reject with an `Error` whose `message` is `user_cancelled`, `invalid_request`, - `text_too_large`, `not_allowed`, `target_unavailable` (no conversation to add to), or - `result_unknown`. After `result_unknown` the text may already be in the draft; never repeat the + and is appended literally. Every call needs its own confirmation; needs no `permissions` entry. +- Failures reject with `{ code, message }` where `code` is `USER_CANCELLED`, `INVALID_ARGUMENTS`, + `TEXT_TOO_LARGE`, `NOT_ALLOWED`, `TARGET_UNAVAILABLE` (no conversation to add to), or + `RESULT_UNKNOWN`. After `RESULT_UNKNOWN` the text may already be in the draft; never repeat the call automatically. - A resolved promise means the text reached the draft, not that the Agent started or replied. -## `miniapp.agent` +## `miniapp.agent` and `miniapp.session` -Runs Agent turns from the page, and from MiniMax Code 3.1.6 also reads and observes the user's -conversations. Present only on MiniMax Code 3.1.2 or later; calls reject with `not_permitted` -unless `miniapp.json` declares the matching `agentAccess` value. The calls, sessions, events, and -errors are in `docs/agent.md`. +`window.miniapp.agent` runs Agent turns (`permissions.agent: ["run"]`), and `window.miniapp.session` +lists, reads, and observes the user's conversations (`permissions.session: ["read"]`, or +`agent: ["run"]` for the Mini App's own sessions). Undeclared calls reject with `NOT_PERMITTED` and +switched-off grants reject with `PERMISSION_DENIED`. Full details, events, and errors are in +`docs/agent.md`. ## `miniapp.speech.transcribe(input, options?)` -From MiniMax Code 3.1.6, `window.mcode.miniapp.speech.transcribe({ audio, format }, { onPartial? })` -turns one utterance the page recorded into text with the Host's speech recognition and resolves -`{ text }`. The page owns the microphone and the interaction; the Host only transcribes. It needs -`deviceAccess: ["microphone"]` and the user's microphone switch on, or it rejects with -`not_permitted`. +`window.miniapp.speech.transcribe({ audio, format }, { onPartial? })` turns one utterance the page +recorded into text with the Host's speech recognition and resolves `{ text }`. The page owns the +microphone and the interaction; the Host only transcribes. It needs +`permissions.device: ["microphone"]` (`NOT_PERMITTED` when undeclared) and the user's microphone +switch on (`PERMISSION_DENIED` when switched off). - `format` must be exactly `{ sampleRate: 16000, channelCount: 1, sampleFormat: 's16' }`, and `audio` an `Int16Array` (or the buffer behind one) of 16 kHz mono samples, at most 16,000,000 bytes (500 seconds). WAV, WebM, Ogg, FLAC, MP3, and `MediaRecorder` output are rejected with - `invalid_request`. `docs/snippets/audio-capture.ts` records in exactly this format: copy it next + `INVALID_ARGUMENTS`. `docs/snippets/audio-capture.ts` records in exactly this format: copy it next to your Client source. - The Host returns text after it has the whole utterance; it does not caption live speech. `onPartial` reports the transcript so far while it works. Decide in the page when an utterance ends (push to talk, a toggle, or splitting on silence) and call once per utterance. -- One call per Mini App runs at a time; a second call rejects with `busy`. -- Other failures: `runtime_unavailable` (speech recognition is off or the user is signed out; - offer typing instead), `transcription_failed` and `result_unknown` (the same audio may be sent - again), `audio_too_large`. +- One call per Mini App runs at a time; a second call rejects with `BUSY`. +- Other `code` values: `RUNTIME_UNAVAILABLE` (speech recognition is off or the user is signed out; + offer typing instead), `TRANSCRIPTION_FAILED` and `RESULT_UNKNOWN` (the same audio may be sent + again), `AUDIO_TOO_LARGE`. - The Host shows nothing while a page records. Show your own recording indicator, stop the microphone as soon as the utterance ends, and make the stop path work even when the pointer is released outside the button or `getUserMedia` has not resolved yet. ## `miniapp.tool.request(names)` -From MiniMax Code 3.1.6, a page whose manifest declares `toolAccess: ["call"]` can ask the user, -inside a click handler, to always allow tools its Node entry calls. Listing and calling stay in -Node. See `docs/tool.md`. +A page whose manifest declares `permissions.tool: ["call"]` can ask the user, inside a click +handler, to always allow tools its Node entry calls. Listing and calling stay in Node. See +`docs/tool.md`. ## `miniapp.host` -From MiniMax Code 3.1.11, `window.mcode.miniapp.host` reads MiniMax Code's display preferences and, -with `hostAccess`, which part of the app the user is on, and opens a few Host pages. Feature-detect -`window.mcode?.miniapp?.host`; without it, use the Mini App's own defaults. The Host does not style -or translate the page for you. +From MiniMax Code 3.1.11, `host` reads MiniMax Code's display preferences, observes which public +view the user is on (with `permissions.host: ["navigation.read"]`), opens a few Host pages, and +from 3.1.20 also provides `host.composer.append` (above). Feature-detect `window.miniapp?.host`; +without it, use the Mini App's own defaults. The Host does not style or translate the page for you. | Call | Resolves or delivers | Needs | | --- | --- | --- | | `host.ui.getState()` | `{ theme, language }` | Nothing | | `host.ui.subscribe(listener, { onError }?)` | The full state at once, then every change. Returns `{ dispose() }`. | Nothing | -| `host.navigation.getState()` | `{ key, view, overlay }` | `hostAccess: ["navigation.read"]`, its switch on, and the page visible | +| `host.navigation.getState()` | `{ key, view, overlay }` | `permissions.host: ["navigation.read"]`, its switch on, and the page visible | | `host.navigation.subscribe(listener, { onError }?)` | The full state at once, then every change. Returns `{ dispose() }`. | The same; paused while the page is hidden | | `host.navigation.open(target)` | `{ status: 'opened' }` or `{ status: 'cancelled', reason }` | A user gesture | ```js -const host = window.mcode?.miniapp?.host; +const host = window.miniapp?.host; const display = host?.ui.subscribe( ({ theme, language }) => { document.documentElement.dataset.theme = theme; @@ -170,39 +204,66 @@ settingsButton.addEventListener('click', () => { navigation, also when the user returns to a view they just left. It is an opaque value for this page only: it contains no session ID or URL, and `open` does not accept it. Navigating does not change the conversation the Mini App is bound to. -- Navigation is delivered only while the page is visible: `getState()` rejects while it is hidden, - and a subscription pauses and, once the page is shown again, delivers only the latest state. A - page in the side panel still counts as visible while settings cover it. +- Navigation is delivered only while the page is visible: `getState()` rejects with `NOT_PERMITTED` + while it is hidden, and a subscription pauses and, once the page is shown again, delivers only the + latest state. A page in the side panel still counts as visible while settings cover it. - Call `open(target)` directly in a click or key handler; it checks `navigator.userActivation.isActive`. Targets: `{ id: 'home' }`, `{ id: 'plugins' }`, `{ id: 'schedule' }`, `{ id: 'settings', section }` with an optional `section` of `'appearance'` or `'language'`, and `{ id: 'session', sessionId, source: 'local' }`. Paths and URLs are not - accepted. Opening a session whose ID the Mini App already holds needs no `"session.read"` and + accepted. Opening a session whose ID the Mini App already holds needs no `session: ["read"]` and grants no access to it. A session that does not exist and one the Mini App may not see both fail - with `target_unavailable`; any `source` but `'local'` fails with `unsupported_source`. + with `TARGET_UNAVAILABLE`; any `source` but `'local'` fails with `UNSUPPORTED_SOURCE`. - `opened` means the page is shown, not that its data has loaded. `cancelled` with `user_cancelled` means the user chose to stay on unsaved work; `superseded` means another navigation replaced the request. -- Failures reject with a plain object `{ code, message }`, not an `Error`: read `code`, and do not - test `instanceof Error`. `code` is `invalid_request`, `not_permitted`, `host_unavailable`, - `unsupported_source`, `unsupported_target`, `target_unavailable`, or `result_unknown`. - Subscriptions report the same object through `onError` when they fail to start or end. -- `result_unknown`, which `open` also returns after 60 seconds without an answer, means the outcome +- Failures reject (and report through `onError`) with `{ code, message }`, where `code` is + `INVALID_ARGUMENTS`, `NOT_PERMITTED` (undeclared grant, hidden page, missing gesture, or + subscription cap), `PERMISSION_DENIED` (declared `navigation.read` switched off), + `HOST_UNAVAILABLE`, `UNSUPPORTED_SOURCE`, `UNSUPPORTED_TARGET`, `TARGET_UNAVAILABLE`, or + `RESULT_UNKNOWN`. +- `RESULT_UNKNOWN`, which `open` also returns after 60 seconds without an answer, means the outcome is unknown. Do not repeat `open` automatically. - A page holds at most 64 Host subscriptions; dispose them when done. A subscription ended by the - user switching `navigation.read` off, or by `host_unavailable`, does not resume: subscribe again + user switching `navigation.read` off, or by `HOST_UNAVAILABLE`, does not resume: subscribe again later. +## `miniapp.files.subscribe(listener, options?)` + +From MiniMax Code 3.1.18, receives files opened in this Mini App through `fileHandlers` in +`miniapp/miniapp.json` (`docs/package-contract.md`). Feature-detect with `window.miniapp?.files` or +`capabilities?.has('files.subscribe')`. + +```js +const subscription = window.miniapp?.files?.subscribe( + ({ handlerId, files }) => { + for (const file of files) openThroughBackend(handlerId, file.path); + }, + { onError: ({ code }) => console.warn('File open subscription failed:', code) }, +); +addEventListener('pagehide', () => subscription?.dispose(), { once: true }); +``` + +- Each event carries `{ handlerId, files }`, where each file is `{ path, name, extension }` (`path` + is absolute and `extension` is lowercase dotted). Read the file through your own Node route; the + page cannot read local paths directly. +- Up to 16 opens per tab queue before the first listener subscribes and replay in order on + subscribe. An existing same-origin tab is focused and receives the event in place without + reloading or navigating, even when it is not on the handler's `path`: subscribe once at the app + root and route in-app by `handlerId`. +- `options.onError` receives `{ code, message }` (`INVALID_ARGUMENTS`, `HOST_UNAVAILABLE`, or + `RESULT_UNKNOWN`). + ## `miniapp.window` (proposed) Present on MiniMax Code 3.1.2 or later. **Proposed:** the shape may still change. Feature-detect -`window.mcode?.miniapp?.window` and do not rely on it long-term. +`window.miniapp?.window` and do not rely on it long-term. The handle controls this Mini App's own window: whether the page sits in the side panel (`inline`) or is popped out (`window`), and, when popped out, its position, size, and a few flags. ```js -const handle = window.mcode?.miniapp?.window; +const handle = window.miniapp?.window; if (handle) { const state = await handle.getState(); // { mode: 'inline' } or { mode: 'window', window: {...} } button.addEventListener('click', () => { @@ -220,7 +281,7 @@ if (handle) { (`docs/package-contract.md`), and a patch containing them is rejected. - Changing `mode`, and `focus()`, must come from a user gesture (for example, synchronously inside a click handler, or in the `click` handler of a notification the page created); otherwise they - reject with `not_permitted`. + reject with `NOT_PERMITTED`. - When `getState()` includes `modeChangeReloadsPage: true`, changing `mode` reloads the page. The window `id` and the Node process stay, but the document, its JavaScript state, streams, and pending promises do not. Save what the page needs before calling `update({ mode })`, do not put @@ -231,9 +292,9 @@ if (handle) { field `true`. `width` / `height` are rejected when the window is not resizable. `x` / `y` are rejected when the window would not overlap any display. - Several `update` calls in one animation frame are merged into one request and share its outcome. -- Failures reject with an `Error` whose `message` is `inline_mode` (only `mode` may change while - inline), `not_permitted`, `busy` (a confirmation, `mode` change, or page reload is already in - progress), `invalid_request`, or `result_unknown`. +- Failures reject with `{ code, message }` where `code` is `INLINE_MODE` (only `mode` may change + while inline), `NOT_PERMITTED`, `BUSY` (a confirmation, `mode` change, or page reload is already + in progress), `INVALID_ARGUMENTS`, or `RESULT_UNKNOWN`. Pitfalls: diff --git a/docs/package-contract.md b/docs/package-contract.md index f7bce051..56bdd04b 100644 --- a/docs/package-contract.md +++ b/docs/package-contract.md @@ -1,6 +1,6 @@ # Mini App package contract -Verified against MiniMax Code 3.1.11. +Verified against MiniMax Code 3.1.21. A Mini App is a MiniMax Plugin whose `package.json` declares a Mini App payload. MiniMax Code enforces the manifest, payload, and path rules below when the package is installed. `npm run check` @@ -8,8 +8,8 @@ enforces the same rules here, plus this repository's own requirements: `README.m a real image file behind `icon`, `lifecycle` limited to `on-demand`, no hard links, no committed `node_modules`, routes outside the Host-reserved `/__mavis/` prefix, the Node entry conventions in `docs/runtime.md`, a stated minimum client version for newer features (see -[Minimum client version](#minimum-client-version)), and code that only calls what the manifest -declares (see [Declared access must match the code](#declared-access-must-match-the-code)). +[Minimum client version](#minimum-client-version)), and code that matches the declared permissions +and target version (see [Declared access must match the code](#declared-access-must-match-the-code)). ## Layout @@ -19,7 +19,7 @@ declares (see [Declared access must match the code](#declared-access-must-match- package.json Mini App declaration (see below) icon.png Plugin icon (PNG, JPEG, or WebP) miniapp/ - miniapp.json Payload roots, Node entry, page route + miniapp.json Payload roots, Node entry, page route, permissions client/ Runtime payload: files served to the page node/ Runtime payload: the Node entry and what it imports README.md Required by this repository @@ -110,70 +110,120 @@ No other keys are allowed inside `mcode`. Other top-level keys (`name`, `type`, `docs/runtime.md`). - `surface.path` is the route the Node entry serves the page on. It is relative to the Host and must not contain an origin, query, fragment, or backslash. A missing leading `/` is added. -- `surface.window` is optional; see [`surface.window`](#surfacewindow). +- `surface.window` is optional; see [`surface.window`](#surfacewindow). `surface.widget` + (`{ "kind": "display" | "interactive", "size": "small" | "medium" }`) is accepted from MiniMax + Code 3.1.15, though the desktop Mini App Pad currently opens `surface.path` directly and renders + no compact widget view, so new packages should omit it. - `mcpEndpoints` is an array of `{ "server": string, "path": string }`. `server` matches `^[a-zA-Z0-9_-]{1,128}$` and must name a server declared through `plugin.json.mcpServers`; MiniMax Code checks that reference at install time. `server` and `path` are each unique. Use `[]` when there are none. -- No route (`surface.path` or an MCP endpoint `path`) may be `/__mavis` or start with `/__mavis/`. - The Host owns that prefix and answers some of it itself. -- `hostConnectorAccess` is optional: `{ "providers": string[] }`, each matching - `^[a-z0-9_-]{1,64}$` and unique. Declared providers are granted by the Host at install time; this - repository does not document their use. -- `agentAccess` is optional: an array of `"session.run"` (run Agent turns) and `"session.read"` - (list, read, and observe the user's own conversations). Neither implies the other; declare both - when the Mini App needs both. Absent or `[]` means no Agent access. See `docs/agent.md` before - declaring it. Requires MiniMax Code 3.1.2 or later; `"session.read"` requires 3.1.6 or later. +- `fileHandlers` is optional (MiniMax Code 3.1.18 or later); see [`fileHandlers`](#filehandlers). +- No route (`surface.path`, an MCP endpoint `path`, or a `fileHandlers` `path`) may be `/__mavis` + or start with `/__mavis/`. The Host owns that prefix and answers some of it itself. +- `permissions` is optional (MiniMax Code 3.1.20 or later) and declares every switchable grant as + plain string arrays grouped by namespace: + + ```json + { + "permissions": { + "agent": ["run"], + "session": ["read"], + "tool": ["call"], + "device": ["microphone", "camera", "notifications"], + "host": ["navigation.read"], + "connector": ["notion"] + }, + "engines": { "mcode": ">=3.1.20" } + } + ``` + + - `agent`: `["run"]` — run Agent turns in this Mini App's own sessions through `context.agent` + or `window.miniapp.agent` (see `docs/agent.md`). + - `session`: `["read"]` — list, read, and observe the user's own conversations through + `context.session` or `window.miniapp.session` (see `docs/agent.md`). Neither grant implies the + other; declare both when the Mini App needs both. Reading or observing this Mini App's own + sessions works with either `agent: ["run"]` or `session: ["read"]`. + - `tool`: `["call"]` — call installed MCP and Connector tools through `context.tool`, judged by + the user's permission rules (see `docs/tool.md`). + - `device`: `"microphone"` (`getUserMedia({ audio })` and `window.miniapp.speech.transcribe`), + `"camera"` (`getUserMedia({ video })`), and/or `"notifications"` (`new Notification(...)`). See + "Browser permissions" in `docs/client.md`. + - `host`: `["navigation.read"]` — observe which public Host view the user is on through + `window.miniapp.host.navigation` (see `docs/client.md`). Reading theme and language, and opening + known Host entries from a user gesture, need no grant. + - `connector`: unique provider IDs matching `^[a-z0-9_-]{1,64}$`, granted by the Host at install + time for `context.connector` (provider runtime details are outside this repository's docs). + + Unknown groups, unknown items, or duplicate items fail with `MINIAPP_PERMISSIONS_INVALID`. Declare + `permissions` **or** the legacy `*Access` fields (see [Legacy `<3.1.20` compatibility](#legacy-3120-compatibility)), + never both: mixing `permissions` with any legacy `*Access` field fails with + `MINIAPP_PERMISSIONS_INVALID`. - `agentConcurrency` is optional: an integer from 1 to 32, default 4. It caps how many Agent turns - of this Mini App run at once; it has no effect without `agentAccess`. Requires MiniMax Code 3.1.2 + of this Mini App run at once; it has no effect without an Agent grant. Requires MiniMax Code 3.1.2 or later. -- `toolAccess` is optional. The only allowed value is `["call"]`, which gives the Node entry - `context.tool` to call the MCP and Connector tools installed on the user's MiniMax Code, each call - judged by the user's permission rules. See `docs/tool.md`. Requires MiniMax Code 3.1.6 or later. -- `deviceAccess` is optional: an array of the browser permissions the page may hold. Absent or `[]` - means none. See "Browser permissions" in `docs/client.md`. - - `"microphone"`: `getUserMedia({ audio })` and `window.mcode.miniapp.speech.transcribe`. - Requires MiniMax Code 3.1.6 or later. - - `"camera"`: `getUserMedia({ video })`. Requires MiniMax Code 3.1.9 or later. - - `"notifications"`: `new Notification(...)`. Requires MiniMax Code 3.1.9 or later. - - A request for audio and video together needs both `"microphone"` and `"camera"`. Requests from an - iframe are denied, and so is every other permission a browser would prompt for. Clients that - predate a value reject the package with `MINIAPP_DEVICE_ACCESS_INVALID`. -- `hostAccess` is optional. The only allowed value is `["navigation.read"]`, which lets the page - read which part of MiniMax Code the user is looking at through - `window.mcode.miniapp.host.navigation` (see `docs/client.md`). Reading the Host's theme and - language, and opening Host pages, need no declaration. Other values fail with - `MINIAPP_HOST_ACCESS_INVALID`. Requires MiniMax Code 3.1.11 or later. -- `engines` is optional: `{ "mcode": ">=MAJOR.MINOR.PATCH" }`, nothing else. A client at 3.1.6 or - later but older than the bound keeps the plugin with its Skills and MCP servers, and withholds - the Mini App and its `mcpEndpoints`; publishing such a package from a workspace fails with - `MINIAPP_HOST_TOO_OLD`. Clients before 3.1.6 do not know the field and reject the whole package, - so the bound only matters above 3.1.6. Write it only when the package needs a specific newer - client; it is not required for the features in the table below. Requires MiniMax Code 3.1.6 or - later. +- `engines` is optional: `{ "mcode": ">=MAJOR.MINOR.PATCH" }`, nothing else. Write + `"engines": { "mcode": ">=3.1.20" }` whenever the manifest or code uses a 3.1.20 name + (`permissions`, `window.miniapp`, `session.*`, `agent.list`, `host.composer.append`, + `context.connector`); omit it when the package uses none of them or intentionally targets older + clients with legacy spellings. A client that knows `engines` (3.1.6 or later) and can parse the + rest of the manifest, but is older than the bound, keeps the plugin's standalone Skills and MCP + servers, withholds the Mini App and its `mcpEndpoints`, and fails workspace publishing with + `MINIAPP_HOST_TOO_OLD`. Note that unknown manifest fields such as `permissions` fail earlier in + the reader with `MINIAPP_MANIFEST_FIELD_UNSUPPORTED` on clients before 3.1.20, whereas a package + without 3.1.20 manifest fields that calls `window.miniapp` relies on `engines.mcode` to keep + older clients from installing a broken page. ### Permission switches -From MiniMax Code 3.1.6 the user can switch off, item by item in the plugin details, what the -manifest declares: each `hostConnectorAccess` provider, each `agentAccess` value, `toolAccess` -`"call"`, each `deviceAccess` value, and `hostAccess` `"navigation.read"`. Everything starts on, -with no first-use prompt and no browser permission prompt. A switch -applies at once and does not restart the Mini App: `context.agent` and `context.tool` stay present, -and their calls fail until the user switches the item back on: +The user can switch off, item by item in the plugin details, every item the manifest declares: +`agent:run`, `session:read`, `tool:call`, `device:<item>`, `host:navigation.read`, and +`connector:<provider>`. Everything starts on, with no first-use prompt and no browser permission +prompt. A switch applies at once without restarting the Mini App. + +On MiniMax Code 3.1.20 and later, every namespace stays present and distinguishes **undeclared** +grants (`NOT_PERMITTED` — an author-fixable packaging or call-context mistake) from **switched-off +or denied** grants (`PERMISSION_DENIED` — the user's choice): -| Switched off | What fails | +| State or switched-off item | What happens on 3.1.20 and later | | --- | --- | -| `session.run` | Running turns end as `aborted`; `run`, `reply`, `answer`, `cancel`, `open`, `models`, `agents`, `create` fail with `NOT_PERMITTED` (`not_permitted` on the page). | -| `session.read` | Observers end; `sessions()`, `observe({ all: true })`, and reading or observing the user's sessions fail the same way. | -| `tool:call` | `context.tool.call` fails with `TOOL_NOT_PERMITTED`; `list()` reports every tool as `deny`. | -| `microphone` | The next `getUserMedia` fails with `NotAllowedError` and `speech.transcribe` with `not_permitted`; a recording already open keeps its stream until the page stops it. | -| `camera` | The next `getUserMedia` that asks for video fails with `NotAllowedError`; a stream already open keeps running until the page stops it. | -| `notifications` | New notifications are not shown, and `Notification.permission` reads `denied`. | -| `navigation.read` | Navigation subscriptions end through `onError`; `getState()` and new subscriptions fail with `not_permitted`. Subscribe again once it is back on. | +| Grant not declared in `miniapp.json` | Node calls reject with `NOT_PERMITTED`; page calls reject with `{ code: 'NOT_PERMITTED', message: 'not_permitted' }` (including `tool.request()`). | +| `agent:run` switched off | Running turns end as `aborted`; `run`, `reply`, `answer`, `open`, `models`, `list`, `create` reject with `PERMISSION_DENIED` (`permission_denied` in `message`). Page `agent.cancel` still works. | +| `session:read` switched off | Observers end; `session.list()`, `session.observe({ all: true })`, and reading or observing the user's sessions reject with `PERMISSION_DENIED`. Own sessions stay readable when `agent:run` is on. | +| `tool:call` switched off | `context.tool.call` rejects with `PERMISSION_DENIED` (and so does a tool denied by a rule or prompt); `list()` and `request()` resolve with `deny` for every tool without prompting. | +| `connector:<provider>` switched off | `context.connector.list()` omits that provider; `call()` rejects with `PERMISSION_DENIED`. | +| `device:microphone` switched off | The next `getUserMedia` rejects with `NotAllowedError` and `speech.transcribe` rejects with `PERMISSION_DENIED`; an open stream keeps running until the page stops it. | +| `device:camera` switched off | The next `getUserMedia` asking for video rejects with `NotAllowedError`; an open stream keeps running until the page stops it. | +| `device:notifications` switched off | New notifications are not shown, and `Notification.permission` reads `denied`. | +| `host:navigation.read` switched off | Navigation subscriptions end through `onError` with `PERMISSION_DENIED`; `getState()` and new subscriptions reject with `PERMISSION_DENIED`. Subscribe again once it is back on. | + +Handle `PERMISSION_DENIED` and `NotAllowedError` where the call is made and explain in the page +what the user can turn back on in the plugin settings. `surface.window` flags are not switches. + +### `fileHandlers` + +Optional (MiniMax Code 3.1.18 or later). Declares which file extensions can open in this Mini App +and which route a newly opened tab starts on: + +```json +{ + "fileHandlers": [ + { "id": "model-3d", "path": "/viewer", "extensions": [".stl", ".step"] } + ] +} +``` -Handle these errors where the call is made and explain in the page what the user can turn back on. -`surface.window` flags are not switches. +- Non-empty array of at most 256 handlers; each entry has only `id`, `path`, and `extensions` + (`MINIAPP_FILE_HANDLERS_INVALID`). +- `id` matches `^[a-z0-9-]{1,32}$` and is unique across the manifest. +- `path` follows the `surface.path` rules, is at most 4096 characters without control characters + (`MINIAPP_ROUTE_PATH_INVALID`), and stays outside `/__mavis/` (`MINIAPP_ROUTE_RESERVED`). +- `extensions` is a non-empty array of at most 256 lowercase dotted extensions matching + `^\.[a-z0-9]{1,16}$`, unique across the entire manifest, with at most 512 extensions in total. +- Files are delivered to the page through `window.miniapp.files.subscribe` (see `docs/client.md`). + Code-editor extensions (`.json`, `.yaml`, `.ts`, `Makefile`, etc.) stay with the built-in editor; + extensions that already have a built-in preview show an "Open with" chooser unless the user saved + a default. ### `surface.window` @@ -213,9 +263,36 @@ panel into its own window. Requires MiniMax Code 3.1.2 or later. | Any other field | Rejected. Title, position, parent window, and close behaviour are always set by the Host. | | The window never opens at launch: it opens when the user pops the page out, or when the page -switches to it from a user gesture through `window.mcode.miniapp.window` (see `docs/client.md`). +switches to it from a user gesture through `window.miniapp.window` (see `docs/client.md`). Closing it, or Cmd/Ctrl+W, returns the page to the side panel. +### Legacy `<3.1.20` compatibility + +Packages that must keep loading on MiniMax Code before 3.1.20 omit `permissions` and any `>=3.1.20` +`engines.mcode` bound, and use the legacy manifest fields and runtime aliases consistently: + +| Legacy spelling (`<3.1.20`) | 3.1.20 replacement | Minimum when using legacy field | +| --- | --- | --- | +| `agentAccess: ["session.run"]` | `permissions.agent: ["run"]` | 3.1.2 | +| `agentAccess` with `"session.read"` | `permissions.session: ["read"]` | 3.1.6 | +| `toolAccess: ["call"]` | `permissions.tool: ["call"]` | 3.1.6 | +| `deviceAccess: ["microphone"]` | `permissions.device: ["microphone"]` | 3.1.6 | +| `deviceAccess` with `"camera"` or `"notifications"` | `permissions.device` | 3.1.9 | +| `hostAccess: ["navigation.read"]` | `permissions.host: ["navigation.read"]` | 3.1.11 | +| `hostConnectorAccess: { "providers": [...] }` | `permissions.connector: [...]` | 3.1.2 | +| `window.mcode.miniapp.*` | `window.miniapp.*` | — | +| `message.append(text)` | `host.composer.append(text)` | — | +| `agent.agents()` | `agent.list()` | — | +| `agent.sessions()`, `agent.session(id?)`, `agent.observe(...)` | `session.list()`, `session.get(id?)`, `session.observe(...)` | 3.1.6 | +| `context.hostConnector` | `context.connector` | — | +| `TOOL_NOT_PERMITTED`, `CONNECTOR_NOT_PERMITTED` | `PERMISSION_DENIED` (removed without aliases in 3.1.20) | — | + +MiniMax Code 3.1.20 and later still accept the legacy manifest fields without reader diagnostics +(unless mixed with `permissions`), keep the legacy runtime method aliases with a one-time warning, +and preserve the legacy `Error` / lower-case `{ code, message }` rejection shapes behind +`window.mcode.miniapp`. Node `TOOL_NOT_PERMITTED` and `CONNECTOR_NOT_PERMITTED` were removed in +3.1.20 in favour of `PERMISSION_DENIED`. + ## Minimum client version Clients older than the version below reject the whole package when it declares the feature, so @@ -224,15 +301,16 @@ the package cannot be installed there at all. | Feature | Declared in | Minimum MiniMax Code | | --- | --- | --- | | `agents` | `plugin.json` | 3.1.2 | -| `agentAccess` | `miniapp/miniapp.json` | 3.1.2 | -| `agentAccess` with `"session.read"` | `miniapp/miniapp.json` | 3.1.6 | +| `surface.window` | `miniapp/miniapp.json` | 3.1.2 | | `agentConcurrency` | `miniapp/miniapp.json` | 3.1.2 | -| `deviceAccess` | `miniapp/miniapp.json` | 3.1.6 | -| `deviceAccess` with `"camera"` or `"notifications"` | `miniapp/miniapp.json` | 3.1.9 | +| `agentAccess` (legacy) | `miniapp/miniapp.json` | 3.1.2 (`3.1.6` with `"session.read"`) | | `engines` | `miniapp/miniapp.json` | 3.1.6, or its own bound when higher | -| `hostAccess` | `miniapp/miniapp.json` | 3.1.11 | -| `surface.window` | `miniapp/miniapp.json` | 3.1.2 | -| `toolAccess` | `miniapp/miniapp.json` | 3.1.6 | +| `toolAccess` (legacy) | `miniapp/miniapp.json` | 3.1.6 | +| `deviceAccess` (legacy) | `miniapp/miniapp.json` | 3.1.6 (`3.1.9` with `"camera"` or `"notifications"`) | +| `hostAccess` (legacy) | `miniapp/miniapp.json` | 3.1.11 | +| `surface.widget` | `miniapp/miniapp.json` | 3.1.15 | +| `fileHandlers` | `miniapp/miniapp.json` | 3.1.18 | +| `permissions` | `miniapp/miniapp.json` | 3.1.20 | Each minimum is the first MiniMax Code release with installers for both macOS and Windows. 3.1.5 shipped no installers and 3.1.8 none for Windows, so neither is ever a minimum. Preview builds do @@ -240,40 +318,40 @@ not count either: they can accept a field before the release that ships it. The package's minimum is the highest entry it declares. When it has one, name a MiniMax Code version at or above it under `## Tested environment` in its README, for example -`- MiniMax Code 3.1.6 on macOS 15`. `npm run check` warns until it finds one there. A pre-release -such as `3.1.11-preview.4900` ranks below `3.1.11`. +`- MiniMax Code 3.1.20 on macOS 15`. `npm run check` warns until it finds one there. A pre-release +such as `3.1.20-preview.1` ranks below `3.1.20`. To use a newer page or Node API only where it exists, without raising the minimum, feature-detect -it: `capabilities?.has('agent.observe')` (MiniMax Code 3.1.6 and later), or test that the method -exists. A manifest field cannot be feature-detected: declaring it is what raises the minimum. +it: `capabilities?.has('session.list')`, or fall back across `window.miniapp ?? window.mcode?.miniapp`. +A manifest field cannot be feature-detected: declaring it is what raises the minimum. ## Declared access must match the code -`npm run check` scans the files that run in the page or in Node (`.js`, `.mjs`, `.cjs`, `.html`, -`.htm` under `artifacts.client` and `artifacts.node`, outside `node_modules`) for calls that need a -grant the manifest does not make, and reports them as `ACCESS_UNDECLARED`. +`npm run check` scans the files that run in the page or in Node (`.js`, `.mjs`, `.cjs`, and +executable `<script>` / `on*` code in `.html` and `.htm` under `artifacts.client` and +`artifacts.node`, outside `node_modules`) and reports mismatches: -| Call | Needs | Level | +| Check | Diagnostic | Level | | --- | --- | --- | -| `context.agent` / page `agent` `run`, `answer`, `reply`, `cancel`, `open`, `models`, `agents`, `create` | `agentAccess` `"session.run"` | error | -| `agent.sessions()`, `agent.observe({ all: true })`, page `agent.session()` without an id | `agentAccess` `"session.read"` | error | -| `agent.session(id)`, `agent.observe({ sessionId })` on the Mini App's own sessions | either `agentAccess` value | error | -| `context.tool.*`, page `tool.request()` | `toolAccess: ["call"]` | error | -| `speech.transcribe()` | `deviceAccess: ["microphone"]` | error | -| page `host.navigation.getState()`, `host.navigation.subscribe()` | `hostAccess: ["navigation.read"]` | error | -| `getUserMedia({ audio })`, `getUserMedia({ video })` | `deviceAccess` `"microphone"`, `"camera"`; either one when the constraints are not an object literal | error when the package's minimum is 3.1.6 or later; warning otherwise | -| `new Notification()`, `Notification.requestPermission()` | `deviceAccess: ["notifications"]` | error when the package's minimum is 3.1.6 or later; warning otherwise | - -The Agent rows are reported once per file, naming every missing value, and so are the browser -permission rows. The rows marked error never work without the grant, on any client. Browser -permissions worked without a grant before MiniMax Code 3.1.6, which denies every permission the -manifest does not declare. A package whose minimum is below 3.1.6 still installs on those earlier -clients, so the check only warns; declaring the `deviceAccess` value fixes the call and raises the -minimum to 3.1.6, or 3.1.9 for `"camera"` and `"notifications"`. - -The scan matches source text, so it misses calls through a renamed variable and can flag dormant -code, such as an engine's audio input that the app never turns on. Explain a warning in the pull -request instead of declaring a permission the app does not use. +| `agent` `run`, `answer`, `reply`, `open`, `models`, `list` (`agents`), `create` without `permissions.agent: ["run"]` | `ACCESS_UNDECLARED` | error | +| `session.list()`, `session.observe({ all: true })`, page `session.get()` without an id (or their legacy `agent.*` forms) without `permissions.session: ["read"]` | `ACCESS_UNDECLARED` | error | +| `session.get(id)`, `session.observe({ sessionId })` (or legacy `agent.session(id)`, `agent.observe({ sessionId })`) on own sessions with neither `agent: ["run"]` nor `session: ["read"]` | `ACCESS_UNDECLARED` | error | +| `context.tool.*`, page `tool.request()` without `permissions.tool: ["call"]` | `ACCESS_UNDECLARED` | error | +| `context.connector.*` (`context.hostConnector.*`) without `permissions.connector` | `ACCESS_UNDECLARED` | error | +| `speech.transcribe()` without `permissions.device: ["microphone"]` | `ACCESS_UNDECLARED` | error | +| page `host.navigation.getState()`, `host.navigation.subscribe()` without `permissions.host: ["navigation.read"]` | `ACCESS_UNDECLARED` | error | +| `getUserMedia({ audio })`, `getUserMedia({ video })` without matching `permissions.device` | `ACCESS_UNDECLARED` | error when minimum >= 3.1.6; warning otherwise | +| `new Notification()`, `Notification.requestPermission()` without `permissions.device: ["notifications"]` | `ACCESS_UNDECLARED` | error when minimum >= 3.1.6; warning otherwise | +| Classic `<script>` (no `type="module"`) declaring a top-level `miniapp` binding | `CLIENT_GLOBAL_MINIAPP` | error | +| Package minimum >= 3.1.20 still calling deprecated `window.mcode.miniapp`, `message.append`, `agent.agents/sessions/session/observe`, or `context.hostConnector` | `DEPRECATED_API` | warning | +| Package minimum >= 3.1.20 checking removed `TOOL_NOT_PERMITTED` or `CONNECTOR_NOT_PERMITTED` | `REMOVED_ERROR_CODE` | warning | +| Package minimum < 3.1.20 using 3.1.20 APIs (`window.miniapp`, `session.*`, `agent.list`, `host.composer.append`, `context.connector`) with no `window.mcode` or `capabilities.has` fallback | `ENGINES_MIN_VERSION_MISSING` | warning | + +Page `agent.cancel(requestId)` needs no grant so read-only session observers can cancel cleanly. +The scan matches source text (and parses classic `<script>` bindings with V8 without executing +code), so it misses calls through renamed variables and can flag dormant code, such as an engine's +audio input that the app never turns on. Explain a warning in the pull request instead of declaring +a permission the app does not use. ## Portable paths diff --git a/docs/runtime.md b/docs/runtime.md index bce2057c..eee5f66b 100644 --- a/docs/runtime.md +++ b/docs/runtime.md @@ -1,6 +1,6 @@ # Mini App Node runtime -Verified against MiniMax Code 3.1.11. +Verified against MiniMax Code 3.1.21. ## Loading @@ -24,18 +24,21 @@ to your entry for editor type checking; it is never imported at runtime. | --- | --- | | `pluginId` | The plugin ID (`plugin.json.name`). | | `pluginRoot` | Real path of the installed package. Read your Client files from here. | -| `dataDir` | a private directory the Host creates and owns for this plugin; its location is opaque and may change; there is no supported way to reach Host files from it. Store durable state here. | +| `dataDir` | A private directory the Host creates and owns for this plugin; its location is opaque and may change; there is no supported way to reach Host files from it. Store durable state here. | | `listen` | `{ host: "127.0.0.1", port }`. Bind exactly this address; never pick your own port. | | `signal` | An `AbortSignal` that fires when the Host stops the Mini App. | | `logger` | `debug` / `info` / `warn` / `error` `(message, fields?)`. Messages are truncated at 4 KiB. Only the **keys** of `fields` leave the process; values stay local, so put diagnostic detail in the message. | -| `hostConnector` | May be absent. Its use is outside the scope of this repository. | -| `agent` | Present when `miniapp.json` declares `agentAccess` (`"session.run"`, and from MiniMax Code 3.1.6 also `"session.read"`). See `docs/agent.md`. | -| `tool` | Present when `miniapp.json` declares `"toolAccess": ["call"]` (MiniMax Code 3.1.6 or later). See `docs/tool.md`. | -| `capabilities` | `has(name)` answers whether this client supports a feature, such as `has('agent.observe')`; the names are listed in `docs/client.md`. Absent before MiniMax Code 3.1.6, so write `context.capabilities?.has(...)`. | - -`agent` and `tool` follow the manifest, not the user's permission switches: when the user switches -a granted item off, the object stays and its calls fail until the item is switched back on (see -"Permission switches" in `docs/package-contract.md`). +| `agent` | Runs Agent turns when `miniapp.json` declares `permissions.agent: ["run"]` (`NOT_PERMITTED` when undeclared, `PERMISSION_DENIED` when switched off). Always present on MiniMax Code 3.1.20 or later; see `docs/agent.md`. | +| `session` | Reads and observes conversations when `miniapp.json` declares `permissions.session: ["read"]` (or `permissions.agent: ["run"]` for the Mini App's own sessions). Present from MiniMax Code 3.1.20; see `docs/agent.md`. | +| `tool` | Calls installed MCP and Connector tools when `miniapp.json` declares `permissions.tool: ["call"]`. Always present on 3.1.20 or later; see `docs/tool.md`. | +| `connector` | Calls Connector providers declared in `permissions.connector` (`hostConnector` remains a deprecated alias). Provider-specific use is outside the scope of this repository. | +| `capabilities` | `has(name)` answers synchronously whether this client offers a Node API method (`agent.run`, `agent.reply`, `agent.answer`, `agent.models`, `agent.list`, `agent.create`, `session.list`, `session.get`, `session.observe`, `tool.call`, `tool.list`, `tool.request`, `connector.call`, `connector.list`, plus deprecated aliases while they remain); page-only names return `false`. Absent before MiniMax Code 3.1.6, so write `context.capabilities?.has(...)`. | + +On MiniMax Code 3.1.20 and later, `agent`, `session`, `tool`, and `connector` are always present: +undeclared calls reject with `NOT_PERMITTED`, and switching a declared permission off rejects new +calls with `PERMISSION_DENIED` without restarting the Mini App (see "Permission switches" in +`docs/package-contract.md`). On clients before 3.1.20, `agent`, `tool`, and `hostConnector` were +omitted unless declared, and `session` / `connector` did not exist. ## `start(context)` @@ -44,7 +47,8 @@ a granted item off, the object stays and its calls fail until the item is switch - Return `{ dispose }` or `undefined`. An object without `dispose` is rejected as an invalid lifecycle. Throwing fails the start; a port collision is reported as its own error. - Do not fetch business data inside `start`. Register handlers and resolve. -- Do not call `context.agent` or `context.tool` inside `start`; call them from a request handler. +- Do not call `context.agent`, `context.session`, `context.tool`, or `context.connector.call` + inside `start`; call them from a request handler. ## `dispose()` @@ -111,10 +115,10 @@ your process do not count as use, so polling or heartbeats keep nothing alive. Reclaim never stops a Mini App that has a visible page, that the current chat turn mentions with `@`, whose MCP tools the Agent is calling, or that started less than 60 seconds ago; the user can still stop it, and an update or restart replaces its process. A Mini App whose Node entry has a Host -request in flight (`context.agent`, `context.tool`, `context.hostConnector`), or finished one less -than 10 minutes ago, is not stopped to make room for another, and under critical pressure is -stopped only after the others. That makes a stop less likely but never rules it out. An open -`agent.observe` counts only when it starts. +request in flight (`context.agent`, `context.session`, `context.tool`, `context.connector`), or +finished one less than 10 minutes ago, is not stopped to make room for another, and under critical +pressure is stopped only after the others. That makes a stop less likely but never rules it out. An +open `session.observe` counts only when it starts. Write the Mini App so that a stop or reload loses nothing: diff --git a/docs/security.md b/docs/security.md index fb1d2e11..02561881 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1,6 +1,6 @@ # Mini App security rules -Verified against MiniMax Code 3.1.11. +Verified against MiniMax Code 3.1.21. ## Process boundary @@ -10,7 +10,8 @@ Verified against MiniMax Code 3.1.11. `docs/runtime.md`). Do not add another scheme that expects or forwards the Host's credential, and do not log request headers. - Keep routes out of the Host-reserved `/__mavis/` prefix. -- Validate every request parameter. Treat the page as untrusted input to the Node process. +- Validate every request parameter, including file paths received through `files.subscribe`. Treat + the page as untrusted input to the Node process. - Secrets stay in the Node process. Never place credentials in HTML, Client JavaScript, log messages, or error responses. @@ -39,11 +40,11 @@ Disclose every outbound host in the README. The default is none. ## Agent turns -An Agent run by a Mini App (`agentAccess`, see `docs/agent.md`) can read and write files, run -shell commands, and call MCP tools. +An Agent run by a Mini App (`permissions.agent: ["run"]`, see `docs/agent.md`) can read and write +files, run shell commands, and call MCP tools. -- Declare `agentAccess` only when the Mini App needs it, and state in the README `## Data & access` - that it runs Agent turns and what it asks them to do. +- Declare `permissions.agent: ["run"]` only when the Mini App needs it, and state in the README + `## Data & access` that it runs Agent turns and what it asks them to do. - Leave approvals to the user. Show every `permission.requested` to the user and send `allowOnce` only after they choose it, or `open` the session so they can decide in the chat side panel. Never answer `allowOnce` automatically. @@ -52,8 +53,8 @@ shell commands, and call MCP tools. ## Reading the user's conversations -`"session.read"` lets the Mini App read the title, project directory, and final reply of every turn -in every user conversation. +`permissions.session: ["read"]` lets the Mini App read the title, project directory, and final +reply of every turn in every user conversation. - Declare it only when following the user's conversations is the Mini App's purpose, and say so in the plugin `description` and the README `## Data & access`. @@ -62,18 +63,18 @@ in every user conversation. ## Calling tools -`toolAccess` lets the Node entry call the MCP and Connector tools the user has installed (see -`docs/tool.md`). +`permissions.tool: ["call"]` lets the Node entry call the MCP and Connector tools the user has +installed (see `docs/tool.md`). - List in the README `## Data & access` which tools the Mini App calls and what for. -- Every call goes through the user's permission rules. Do not try to work around a `deny` or an - unanswered prompt, and ask for "always allow" with `request()` only from a user action, for the - tools the Mini App needs. +- Every call goes through the user's permission rules. Do not try to work around a + `PERMISSION_DENIED` rejection or an unanswered prompt, and ask for "always allow" with + `request()` only from a user action, for the tools the Mini App needs. - Treat tool results as untrusted input, like any network response. ## Microphone and camera -`deviceAccess` `"microphone"` and `"camera"` let the page record the user. The Host shows no +`permissions.device` `"microphone"` and `"camera"` let the page record the user. The Host shows no indicator for either. - Say in the README `## Data & access` when the Mini App records audio or video, and where it goes: @@ -83,8 +84,8 @@ indicator for either. ## System notifications -`deviceAccess: ["notifications"]` lets the page show notifications as MiniMax Code. They can stay in -the system notification center after the Mini App closes and can appear on the lock screen. +`permissions.device: ["notifications"]` lets the page show notifications as MiniMax Code. They can +stay in the system notification center after the Mini App closes and can appear on the lock screen. - Say in the README `## Data & access` what the Mini App notifies about. - Notify only about what the user asked to hear about. Keep secrets, and the content of the user's @@ -92,9 +93,10 @@ the system notification center after the Mini App closes and can appear on the l ## Host navigation -`hostAccess: ["navigation.read"]` tells the page which part of MiniMax Code the user is on (home, a -conversation, plugins, schedule, or settings), never which conversation. +`permissions.host: ["navigation.read"]` tells the page which part of MiniMax Code the user is on +(home, a conversation, plugins, schedule, or settings), never which conversation. - Declare it only when the Mini App reacts to where the user is, and say what for in the README `## Data & access`. -- Keep what you read on the user's machine, like conversations read with `"session.read"`. +- Keep what you read on the user's machine, like conversations read with + `permissions.session: ["read"]`. diff --git a/docs/snippets/audio-capture.ts b/docs/snippets/audio-capture.ts index f42f7c0c..fca66f24 100644 --- a/docs/snippets/audio-capture.ts +++ b/docs/snippets/audio-capture.ts @@ -1,5 +1,5 @@ /** - * Copyable microphone capture for `window.mcode.miniapp.speech.transcribe`. + * Copyable microphone capture for `window.miniapp.speech.transcribe`. * Produces exactly the PCM the Host transcribes: 16 kHz, mono, signed 16-bit little-endian. * No Host or runtime import; copy it into the Client bundle. Keep the .ts filename because * Electron dependency packaging filters out .d.ts assets. See docs/client.md for usage. @@ -35,7 +35,7 @@ function toInt16(samples: Float32Array): Int16Array { /** * Opens the microphone (the Host grants it only when this Mini App declares - * `deviceAccess: ["microphone"]` and the user left the switch on; otherwise `getUserMedia` + * `permissions.device: ["microphone"]` and the user left the switch on; otherwise `getUserMedia` * rejects with `NotAllowedError`) and accumulates 16 kHz mono PCM until `stop()`. */ export async function startSpeechCapture( diff --git a/docs/tool.md b/docs/tool.md index 9f011102..12d5443d 100644 --- a/docs/tool.md +++ b/docs/tool.md @@ -1,26 +1,34 @@ # Mini App tool API -Verified against MiniMax Code 3.1.11. Clients before 3.1.6 reject packages that declare -`toolAccess`. +Verified against MiniMax Code 3.1.21. `context.tool` lets the Node entry call the tools installed on the user's MiniMax Code: every plugin's MCP servers (this one's included), the user's own MCP servers, the Host's built-in MCP servers, and every Connector provider the user has connected. Agent built-in tools such as files, -shell, and browser are not reachable. Declare it only when the Mini App really calls tools. +shell, and browser are not reachable. Declare `permissions.tool: ["call"]` only when the Mini App +really calls tools. ```json -{ "toolAccess": ["call"] } +{ + "permissions": { + "tool": ["call"] + }, + "engines": { "mcode": ">=3.1.20" } +} ``` -- `context.tool` is present whenever the manifest declares `"toolAccess": ["call"]`, the only - accepted value. `hostConnectorAccess` does not grant it. +- Declare `"permissions": { "tool": ["call"] }` (or the legacy `"toolAccess": ["call"]` on packages + targeting clients before 3.1.20; see `docs/package-contract.md`). `permissions.connector` does + not grant `context.tool`. +- Without the grant, every `context.tool` method and page `tool.request()` reject with + `NOT_PERMITTED`. - The grant only lets the Mini App ask. Every call is judged by the user's permission rules, and the user may be prompted. -- The user can switch `tool:call` off in the plugin details. `context.tool` stays and nothing - restarts: new calls fail with `TOOL_NOT_PERMITTED`, `list()` reports every tool as `deny`, and - `request()` answers `deny` without a prompt. A call already running finishes. -- Feature-detect with `context.capabilities?.has('tool')`, and `has('tool.request')` before using - `request()`. +- The user can switch `tool:call` off in the plugin details without restarting the Mini App: new + `call()` invocations reject with `PERMISSION_DENIED`, while `list()` and `request()` resolve with + `deny` for every tool without prompting. A call already running finishes. +- Feature-detect with `context.capabilities?.has('tool.call')` (Node) and + `window.miniapp?.capabilities?.has('tool.request')` (page). - List in the README `## Data & access` which tools the Mini App calls and why. ## Listing and calling @@ -59,7 +67,7 @@ Agent and session rules do not apply, because the call belongs to no Agent or se - `allow` runs the tool. With no rule, MCP and Connector tools are allowed, as for an Agent; arguments that name paths outside the Host's data directory ask. -- `deny` fails with `TOOL_NOT_PERMITTED`. +- `deny` fails with `PERMISSION_DENIED`. - `ask` shows a Host prompt naming this Mini App, the tool, and the arguments, with **Allow once**, **Always allow**, and **Deny**. Always allow writes the same global rule as the chat approval card, so it also applies to Agents. The prompt appears when the Host window is visible or this @@ -75,7 +83,7 @@ present: ```js // Page, inside a click handler such as a "Connect tools" button. -const states = await window.mcode?.miniapp?.tool?.request([searchName, sendName]); +const states = await window.miniapp?.tool?.request([searchName, sendName]); // Node, while a page of this Mini App is open. const state = await context.tool.request([searchName]); ``` @@ -83,22 +91,23 @@ const state = await context.tool.request([searchName]); - One Host prompt lists the named tools that are still `ask`, each with a checkbox. The result maps every name to its state afterwards; it is for your UI only. - The page may call `request()` only inside a user gesture, with 1 to 10 names; otherwise it - rejects with `invalid_request`. Names come from Node `list()`, passed to the page through your - own route. The page has no `list()` or `call()`. + rejects with `{ code: 'INVALID_ARGUMENTS', message: 'invalid_request' }`. Names come from Node + `list()`, passed to the page through your own route. The page has no `list()` or `call()`. - In Node, when nobody can be asked, `request()` rejects with `TOOL_APPROVAL_REQUIRED` and the error carries `permissions`, the unchanged state. ## Errors -Errors carry `code`, `message`, `disposition`, and `retryable`. Only `disposition` says whether the -tool may have run: `not_dispatched` means it did not, so retrying is safe when `retryable` is +Node errors carry `code`, `message`, `disposition`, and `retryable`. Only `disposition` says whether +the tool may have run: `not_dispatched` means it did not, so retrying is safe when `retryable` is true; `unknown_after_dispatch` means it may have, so read the domain state before repeating a write. The Host never retries. | `code` | Cause | `disposition` | | --- | --- | --- | | `INVALID_ARGUMENTS` | The name is not listed (list again), or the arguments or name list are malformed | `not_dispatched` | -| `TOOL_NOT_PERMITTED` | `tool:call` switched off, a deny rule, or the user chose Deny | `not_dispatched` | +| `NOT_PERMITTED` | `permissions.tool: ["call"]` was not declared in `miniapp.json` | `not_dispatched` | +| `PERMISSION_DENIED` | `tool:call` switched off, a deny rule, or the user chose Deny (replaced `TOOL_NOT_PERMITTED` and `CONNECTOR_NOT_PERMITTED` in 3.1.20) | `not_dispatched` | | `TOOL_APPROVAL_REQUIRED` | The rules ask and no Host window can show the prompt | `not_dispatched` | | `TOOL_REF_STALE` | The tool disappeared between listing and the call; list again | `not_dispatched` | | `TOOL_UNAVAILABLE` | Tools are not available to this process yet | `not_dispatched` | @@ -110,8 +119,9 @@ write. The Host never retries. | `TOOL_OUTCOME_UNKNOWN` | The outcome was lost, for example because the channel closed | `unknown_after_dispatch` | Connector tools also keep their Connector codes, such as `CONNECTOR_PROVIDER_ERROR` and -`CONNECTOR_UNAVAILABLE`. Page `request()` rejects with an `Error` whose `message` is -`invalid_request`, `not_permitted`, `approval_required`, `runtime_unavailable`, or `result_unknown`. +`CONNECTOR_UNAVAILABLE`. Page `tool.request()` rejects with `{ code, message }` where `code` is +`INVALID_ARGUMENTS`, `NOT_PERMITTED`, `PERMISSION_DENIED`, `APPROVAL_REQUIRED`, +`RUNTIME_UNAVAILABLE`, or `RESULT_UNKNOWN`. The type declarations are `MiniAppToolClient` in `examples/hello-miniapp/miniapp/node/miniapp-api.ts` and `MiniAppToolRequestAPI` in `examples/hello-miniapp/miniapp/client/client-api.ts`. diff --git a/examples/hello-miniapp/README.md b/examples/hello-miniapp/README.md index 17bce1d5..afdfda0d 100644 --- a/examples/hello-miniapp/README.md +++ b/examples/hello-miniapp/README.md @@ -31,7 +31,7 @@ Install section explains where that directory is). Restart MiniMax Code and ask package.json Mini App declaration miniapp/miniapp.json Payload roots, Node entry, page route miniapp/client/index.html The page served at /dashboard -miniapp/client/client-api.ts Type declarations for the page APIs (window.mcode); not loaded at runtime +miniapp/client/client-api.ts Type declarations for the page APIs (window.miniapp); not loaded at runtime miniapp/node/server.mjs Node entry: start(context) → { dispose } miniapp/node/miniapp-api.ts Type declarations for the runtime context icon.png Plugin icon diff --git a/examples/hello-miniapp/miniapp/client/client-api.ts b/examples/hello-miniapp/miniapp/client/client-api.ts index a944e304..966cd457 100644 --- a/examples/hello-miniapp/miniapp/client/client-api.ts +++ b/examples/hello-miniapp/miniapp/client/client-api.ts @@ -1,9 +1,10 @@ /** * Copyable Mini App Client declarations for TypeScript and JavaScript/JSDoc authoring. - * No Host implementation or runtime import: Electron preload provides window.mcode. + * No Host implementation or runtime import: the Electron preload provides window.miniapp. * Keep the .ts filename because Electron dependency packaging filters out .d.ts assets. * Node start(context) uses miniapp-api.ts instead. See docs/client.md for usage and errors. */ +/** @deprecated `window.miniapp.host.composer`, which has the same `append(text)`. */ export interface MiniAppMessageAPI { /** * Ask the user to append plain text to this Mini App's conversation input. @@ -278,7 +279,7 @@ export interface MiniAppAgentRunInput { */ readonly model?: MiniAppAgentModelSelection; /** - * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. A session + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. A session * never changes its agent, so passing it with `sessionId` is `invalid_request`. */ readonly agent?: string; @@ -318,12 +319,15 @@ export interface MiniAppAgentRunOptions { } /** - * Absent on older Hosts. `run` / `reply` / `answer` / `open` / `models` / `agents` / `create` reject - * with `not_permitted` unless the manifest declares `agentAccess: ["session.run"]`; `observe` / - * `sessions` need `"session.read"` for anything but this Mini App's own sessions (see - * docs/agent.md). A new session uses the Agent of the chat this page is open in; - * a page without a host chat uses the primary Agent unless `run({ agent })` / `create({ agent })` - * names one from `agents()`. Continuing a session keeps its Agent. + * Absent on older Hosts. `run` / `reply` / `answer` / `open` / `models` / `list` / `create` + * require `permissions.agent: ["run"]` (or the older `agentAccess: ["session.run"]`). + * They reject with `NOT_PERMITTED` if the grant is undeclared and `PERMISSION_DENIED` if the + * user switched it off. `cancel` needs no grant and stops this page's own + * in-flight run or observer; the deprecated `observe` / `sessions` / `session` are the + * `miniapp.session` methods and follow its rule (see docs/agent.md). A new session uses + * the Agent of the chat this page is open in; a page without a host chat uses the primary Agent + * unless `run({ agent })` / `create({ agent })` names one from `list()`. Continuing a session + * keeps its Agent. * The Agent works in the host chat's project directory when it has one, otherwise in this Mini * App's own Agent directory; a continued session keeps its directory. A new session takes the * model and thinking level of the host chat (the runtime default when the chat has none) and keeps @@ -338,11 +342,12 @@ export interface MiniAppAgentRunOptions { * `cancel` or the page closes; there is no timeout. Up to `agentConcurrency` runs (default 4) per * Mini App run at once, one per session; further `run` / `answer` calls wait in order (up to four * times that many, see `run.queued`), and `cancel` on a waiting call rejects it with `cancelled`. - * `busy` means the session already has a run in progress (never with `whenBusy`) or the wait - * queue is full. - * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, `busy`, - * `session_not_found`, `runtime_unavailable`, `cancelled`, `result_unknown`, or - * `request_not_found`. `runtime_unavailable` means nothing was started; `result_unknown` means + * `busy` means the session is running a turn, compacting, or has messages queued ahead (never with + * `whenBusy`; the text reached no turn) or the wait queue is full. + * Failures reject with `{ code, message }`: `code` is `INVALID_ARGUMENTS`, `NOT_PERMITTED`, `PERMISSION_DENIED`, `BUSY`, + * `SESSION_NOT_FOUND`, `RUNTIME_UNAVAILABLE`, `CANCELLED`, `RESULT_UNKNOWN` or `REQUEST_NOT_FOUND`, + * and `message` keeps the old lower-case string. + * `RUNTIME_UNAVAILABLE` means nothing was started; `RESULT_UNKNOWN` means * the turn may have run (or ended without the Host knowing whether a question is pending), so * never repeat it automatically. */ @@ -380,44 +385,66 @@ export interface MiniAppAgentAPI { */ models(): Promise<MiniAppAgentModels>; /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise<MiniAppAgentAgents>; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ agents(): Promise<MiniAppAgentAgents>; /** * Create a session bound to this chat (agent, project directory, model) without running a * turn, and return its `sessionId`; continue it with `run({ sessionId })` here or hand it to - * Node code. `agent` picks the session's agent from `agents()`; a session never changes it. + * Node code. `agent` picks the session's agent from `list()`; a session never changes it. * Takes no run slot. If the Host's 60 s deadline passes it rejects with `runtime_unavailable` * although the session may already exist. */ create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; - /** - * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). Pass a `requestId` to be - * able to stop it with `cancel(requestId)`. Resolves when the subscription ended: cancelled, the - * session was deleted, the page or Mini App stopped, or `session.read` was switched off. Rejects - * with `invalid_request` (not exactly one target), `not_permitted`, `session_not_found`, or - * `busy` past 4 observers per Mini App; observers use no run slots. Check - * `capabilities?.has('agent.observe')` first: older Hosts lack it. - */ + /** @deprecated Use `miniapp.session.observe`; the Host warns once and removes this name in a later version. */ observe( target: MiniAppAgentObserveTarget & { readonly requestId?: string }, options: { readonly onEvent: (event: MiniAppAgentObservedEvent) => void }, ): Promise<void>; - /** Check `capabilities?.has('agent.sessions')` first: older Hosts lack it. */ + /** @deprecated Use `miniapp.session.list`; the Host warns once and removes this name in a later version. */ sessions(): Promise<MiniAppAgentSessions>; + /** @deprecated Use `miniapp.session.get`; the Host warns once and removes this name in a later version. */ + session(): Promise<MiniAppAgentSessionDetail | undefined>; + /** @deprecated Use `miniapp.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise<MiniAppAgentSessionDetail>; +} + +/** + * The user's own conversations (the Desktop chat list), read-only. Absent on Hosts that predate + * it: check `capabilities?.has('session.list')`. Every method needs `permissions.session: ["read"]`, + * except that this Mini App's own sessions (those `agent.create` / `agent.run` made) are readable + * under `permissions.agent: ["run"]` alone; while the user has `read` switched off, calls on other + * sessions reject with `PERMISSION_DENIED` and running observers end. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionAPI { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise<MiniAppAgentSessions>; /** - * The chat this page is open in (needs `session.read`: it is the user's conversation, not this - * Mini App's); undefined when the page is not in a chat tab. Check - * `capabilities?.has('agent.session')` first. + * The chat this page is open in; undefined when the page is not in a chat tab. The Agent's + * `run` / `create` cannot target it: it is the user's conversation, not this Mini App's. */ - session(): Promise<MiniAppAgentSessionDetail | undefined>; + get(): Promise<MiniAppAgentSessionDetail | undefined>; /** One conversation with its model and latest reply. */ - session(sessionId: string): Promise<MiniAppAgentSessionDetail>; + get(sessionId: string): Promise<MiniAppAgentSessionDetail>; + /** + * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). Pass a `requestId` to be + * able to stop it with `agent.cancel(requestId)`. Resolves when the subscription ended: + * cancelled, the session was deleted, the page or Mini App stopped, or `read` was switched off. + * Rejects with `INVALID_ARGUMENTS` (not exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, + * `SESSION_NOT_FOUND`, or `BUSY` past 4 observers per Mini App. Observers use no run slots. + */ + observe( + target: MiniAppAgentObserveTarget & { readonly requestId?: string }, + options: { readonly onEvent: (event: MiniAppAgentObservedEvent) => void }, + ): Promise<void>; } /** * Page entry for asking "always allow" ahead of time, while the user is present, so later Node * calls need no prompt. Listing and calling tools is Node `context.tool` only. Needs - * `"toolAccess": ["call"]` and a running Node process; check - * `capabilities.has('tool.request')`. + * `permissions.tool: ["call"]` (or the older `"toolAccess": ["call"]`) and a running Node + * process; check `capabilities.has('tool.request')` (see docs/tool.md). */ export interface MiniAppToolRequestAPI { /** @@ -425,29 +452,55 @@ export interface MiniAppToolRequestAPI { * that are still `ask`; the user ticks which to always allow. Resolves each name's state * afterwards; the Host never trusts this map back. Only inside a user gesture * (`navigator.userActivation.isActive`), 1–10 distinct names, else `invalid_request`. - * Other rejections: `not_permitted` (no `toolAccess`), `approval_required` (no Host window - * can show the prompt), `runtime_unavailable` (Node process not running), `result_unknown`. + * With `tool:call` switched off, resolves with `deny` for every name. Other rejections: + * `NOT_PERMITTED` (no `permissions.tool`), `APPROVAL_REQUIRED` (no Host window can show the prompt), + * `RUNTIME_UNAVAILABLE` (Node process not running), `RESULT_UNKNOWN`. If the switch turns off + * while the names are being resolved, the request rejects with `PERMISSION_DENIED`; a change + * after that leaves the open prompt alone. */ request(names: readonly string[]): Promise<Record<string, 'allow' | 'ask' | 'deny'>>; } +export interface MiniAppOpenedFile { + readonly path: string; + readonly name: string; + readonly extension: string; +} + +export interface MiniAppFileOpen { + readonly handlerId: string; + readonly files: readonly MiniAppOpenedFile[]; +} + +export interface MiniAppFilesAPI<Failure = MiniAppHostError> { + subscribe( + listener: (open: MiniAppFileOpen) => void, + options?: MiniAppHostSubscribeOptions<Failure>, + ): MiniAppHostDisposable; +} + export interface MiniAppClientAPI { - readonly message: MiniAppMessageAPI; + /** @deprecated `host.composer`; ABSENT on a Host that dropped the alias. */ + readonly message?: MiniAppMessageAPI; readonly agent?: MiniAppAgentAPI; + /** Absent on Hosts that predate it; check `capabilities?.has('session.list')`. */ + readonly session?: MiniAppSessionAPI; /** Absent on Hosts without `tool.request`. */ readonly tool?: MiniAppToolRequestAPI; /** * Proposed: shape may still change. Feature-detect with - * `window.mcode?.miniapp?.window` before use. + * `window.miniapp?.window` before use. */ readonly window?: MiniAppWindowHandle; /** Absent on older Hosts; check `capabilities.has('speech.transcribe')`. */ readonly speech?: MiniAppSpeechAPI; /** Effective Host preferences and bounded navigation; absent on older Hosts. */ readonly host?: MiniAppHostAPI; + /** Absent on older Hosts; check `capabilities.has('files.subscribe')`. */ + readonly files?: MiniAppFilesAPI; /** * Synchronous probe of Host features, fixed per Host version; independent of this Mini App's - * manifest or grants. Absent on older Hosts: check `window.mcode?.miniapp?.capabilities?.has`. + * manifest or grants. Absent on older Hosts: check `window.miniapp?.capabilities?.has`. */ readonly capabilities?: MiniAppHostCapabilities; } @@ -459,7 +512,7 @@ export interface MiniAppHostCapabilities { /** * The only PCM the Host transcribes. Capture at exactly this (an `AudioContext` created with * `sampleRate: 16000`, one channel, samples converted to `Int16Array`) and pass the object - * verbatim; any other value is `invalid_request`. See `audio-capture.ts` for a capture helper. + * verbatim; any other value is `invalid_request`. See `docs/snippets/audio-capture.ts` for a capture helper. */ export interface MiniAppSpeechAudioFormat { readonly sampleRate: 16000; @@ -484,14 +537,16 @@ export interface MiniAppSpeechTranscribeOptions { /** * Speech recognition of audio the page captured. Requires the manifest to declare - * `deviceAccess: ["microphone"]` and the user's "Use the microphone" switch to be on (the same - * switch that lets `getUserMedia` succeed); otherwise calls reject with `not_permitted`. + * `permissions.device: ["microphone"]` and the user's "Use the microphone" switch to be on (the same + * switch that lets `getUserMedia` succeed). Undeclared grants reject with `NOT_PERMITTED`. + * Switched-off grants reject with `PERMISSION_DENIED`. * The Host transcribes after it has the whole utterance: decide the utterance boundary in the * page (release of a push-to-talk button, a stop button, a silence detector), then call once * per utterance. One call per Mini App runs at a time; a second is `busy`. - * Failures reject with an `Error` whose `message` is `invalid_request`, `not_permitted`, - * `audio_too_large`, `busy`, `runtime_unavailable` (speech recognition is disabled or the user - * is signed out), `transcription_failed`, or `result_unknown`. + * Failures reject with `{ code, message }`: `code` is `INVALID_ARGUMENTS`, `NOT_PERMITTED`, `PERMISSION_DENIED`, + * `AUDIO_TOO_LARGE`, `BUSY`, `RUNTIME_UNAVAILABLE` (speech recognition is disabled or the user is + * signed out), `TRANSCRIPTION_FAILED` or `RESULT_UNKNOWN`, and `message` keeps the old lower-case + * string. */ export interface MiniAppSpeechAPI { transcribe( @@ -544,8 +599,8 @@ export interface MiniAppWindowDisposable { } /** - * Page-side handle for this Mini App's own window (proposed). Separate from - * `message`; the Host injects both under the same `mcode.miniapp` namespace. + * Page-side handle for this Mini App's own window (proposed). The Host injects it under + * `window.miniapp.window` (see docs/package-contract.md for `surface.window`). */ export interface MiniAppWindowHandle { /** Opaque and stable across pop-out and return; never a Session or launch identifier. */ @@ -592,50 +647,99 @@ export type MiniAppHostOpenResult = | { readonly status: 'opened' } | { readonly status: 'cancelled'; readonly reason: 'user_cancelled' | 'superseded' }; +/** The upper-case `code` of a `host.*` or `files.*` failure; `message` keeps the lower-case string. */ export type MiniAppHostErrorCode = - | 'invalid_request' - | 'not_permitted' - | 'host_unavailable' - | 'unsupported_source' - | 'unsupported_target' - | 'target_unavailable' - | 'result_unknown'; + | 'INVALID_ARGUMENTS' + | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' + | 'HOST_UNAVAILABLE' + | 'UNSUPPORTED_SOURCE' + | 'UNSUPPORTED_TARGET' + | 'TARGET_UNAVAILABLE' + | 'RESULT_UNKNOWN'; export interface MiniAppHostError { readonly code: MiniAppHostErrorCode; readonly message: string; } +/** + * What the deprecated `window.mcode.miniapp` shell hands a `host.*` / `files.*` failure as: the + * lower-case string the shell was published with, in both fields. `permission_denied` never + * reaches it; the shell reports `not_permitted` for a switched-off grant too. + */ +export interface MiniAppLegacyHostError { + readonly code: + | 'invalid_request' + | 'not_permitted' + | 'host_unavailable' + | 'unsupported_source' + | 'unsupported_target' + | 'target_unavailable' + | 'result_unknown'; + readonly message: string; +} export interface MiniAppHostDisposable { dispose(): void; } -export interface MiniAppHostSubscribeOptions { - readonly onError?: (error: MiniAppHostError) => void; +export interface MiniAppHostSubscribeOptions<Failure = MiniAppHostError> { + readonly onError?: (error: Failure) => void; } -export interface MiniAppHostAPI { +export interface MiniAppHostAPI<Failure = MiniAppHostError> { + /** + * The host chat's unsent draft. `append` asks the user to confirm, then appends; sent messages + * are never writable. Was `miniapp.message.append`. + */ + readonly composer: { + append(text: string): Promise<void>; + }; readonly ui: { getState(): Promise<MiniAppHostUIState>; subscribe( listener: (state: MiniAppHostUIState) => void, - options?: MiniAppHostSubscribeOptions, + options?: MiniAppHostSubscribeOptions<Failure>, ): MiniAppHostDisposable; }; readonly navigation: { getState(): Promise<MiniAppHostNavigationState>; subscribe( listener: (state: MiniAppHostNavigationState) => void, - options?: MiniAppHostSubscribeOptions, + options?: MiniAppHostSubscribeOptions<Failure>, ): MiniAppHostDisposable; open(target: MiniAppHostOpenTarget): Promise<MiniAppHostOpenResult>; }; } -export interface McodeClientAPI { +export interface MiniAppGlobalAPI { readonly miniapp: MiniAppClientAPI; } +/** + * The API as the deprecated `window.mcode.miniapp` shell hands it out: the same methods, but + * `host.*` / `files.*` failures (Promise rejections and `onError`) keep the published lower-case + * `{ code, message }`, and every other namespace rejects with an `Error` whose `message` is the + * lower-case string. Only the shell is old; write new code against `window.miniapp`. + */ +export type MiniAppLegacyClientAPI = Omit<MiniAppClientAPI, 'host' | 'files'> & { + readonly host?: MiniAppHostAPI<MiniAppLegacyHostError>; + readonly files?: MiniAppFilesAPI<MiniAppLegacyHostError>; +}; + +/** + * `window.mcode`: the old entry under its shell. Kept as its own name for code that typed the + * whole object, and so `McodeClientAPI['miniapp']` still means the API the shell hands out. + */ +export interface McodeClientAPI { + readonly miniapp: MiniAppLegacyClientAPI; +} + declare global { interface Window { /** Absent outside a supported managed Mini App main page. Check before use. */ + readonly miniapp?: MiniAppClientAPI; + /** + * @deprecated `window.miniapp`, under the shell the old entry had. Only the shell is old: + * every method warns once when called and is removed in a later version. + */ readonly mcode?: McodeClientAPI; } } diff --git a/examples/hello-miniapp/miniapp/node/miniapp-api.ts b/examples/hello-miniapp/miniapp/node/miniapp-api.ts index f1eed850..49a0dc87 100644 --- a/examples/hello-miniapp/miniapp/node/miniapp-api.ts +++ b/examples/hello-miniapp/miniapp/node/miniapp-api.ts @@ -2,7 +2,7 @@ * Agent-facing Mini App runtime authoring declarations. * * Copy this file into a generated plugin for type checking. It contains no Host implementation; - * the Host injects runtime values through start(context). + * the Host injects runtime values through start(context) (see docs/runtime.md). * Keep the .ts filename: Electron packaging excludes .d.ts files from dependency assets. */ export type JsonPrimitive = null | boolean | number | string; @@ -66,8 +66,10 @@ export type HostConnectorErrorCode = | 'INVALID_ARGUMENTS' | 'CONNECTOR_PROVIDER_ERROR' | 'CONNECTOR_UNAVAILABLE' + /** The manifest did not declare the required grant; not dispatched. */ + | 'NOT_PERMITTED' /** The user switched this provider off for the Mini App; not dispatched. */ - | 'CONNECTOR_NOT_PERMITTED' + | 'PERMISSION_DENIED' | 'CONNECTOR_OUTCOME_UNKNOWN'; export interface HostConnectorError extends Error { @@ -143,7 +145,6 @@ export type MiniAppToolCallResult = export type MiniAppToolErrorCode = | HostConnectorErrorCode | 'INVALID_ARGUMENTS' - | 'TOOL_NOT_PERMITTED' | 'TOOL_APPROVAL_REQUIRED' | 'TOOL_REF_STALE' | 'TOOL_UNAVAILABLE' @@ -155,13 +156,14 @@ export type MiniAppToolErrorCode = | 'SERVICE_RESTARTED'; /** - * Present whenever the manifest declares `"toolAccess": ["call"]`, even when the user switched - * `tool:call` off: calls then fail with `TOOL_NOT_PERMITTED`. Every `call` is judged by the user's - * global permission rules: `deny` is `TOOL_NOT_PERMITTED`, `ask` shows a Host prompt, and nobody to - * ask is `TOOL_APPROVAL_REQUIRED`. `list` works before activation; call `call` only from request - * handling after activation. Connector tools time out after 30 s and MCP tools after at most 120 s, - * counted after any prompt. The Host never retries; reconcile an `unknown_after_dispatch` outcome - * before repeating a write. + * Always present (MiniMax Code 3.1.20 or later; see docs/tool.md). Without `permissions.tool: ["call"]` + * (or the older `"toolAccess": ["call"]`), every method rejects `NOT_PERMITTED`. With `tool:call` + * switched off, `call()` rejects `PERMISSION_DENIED` while `list()` and `request()` resolve with + * `deny` for each tool. Every `call` is judged by the user's global rules: `deny` is + * `PERMISSION_DENIED`, `ask` shows a Host prompt, and nobody to ask is `TOOL_APPROVAL_REQUIRED`. + * `list` works before activation; call `call` only from request handling after activation. Connector + * tools time out after 30 s and MCP tools after at most 120 s, counted after any prompt. The Host + * never retries; reconcile an `unknown_after_dispatch` outcome before repeating a write. */ export interface MiniAppToolClient { list(options?: HostConnectorCallOptions): Promise<MiniAppToolListResult>; @@ -317,8 +319,7 @@ export interface MiniAppAgentRunResult { * - `tool.started` / `tool.finished`: a tool call by name; `ok` is false when it failed. * - `turn.finished`: last unless the call ended `steered`; same `status`, `text`, and `error` * as the run result. - */ -/** + * * Every event except `run.queued` names its session, so `reply` can be called from `onEvent` even * before the `run` that created the session has returned. `answer` cannot: the paused `run` still holds the * session's single-run slot while `question.requested` is delivered, so call `answer` only after @@ -459,6 +460,7 @@ export interface MiniAppAgentRunOptions { export type MiniAppAgentErrorCode = | 'NOT_PERMITTED' + | 'PERMISSION_DENIED' | 'BUSY' | 'SESSION_NOT_FOUND' | 'INVALID_ARGUMENTS' @@ -475,18 +477,18 @@ export interface MiniAppAgentError extends Error { */ readonly retryable: boolean; /** - * Set on every `BUSY`: the session already has a run in flight, the wait queue is full, the - * per-minute start cap was hit, or `observe` found 4 observers already running. + * Set on every `BUSY`: the session is running a turn, compacting, or has messages queued ahead + * (the text reached no turn), the wait queue is full, the per-minute start cap was hit, or + * `observe` found 4 observers already running. */ readonly reason?: 'session_busy' | 'queue_full' | 'rate_limited' | 'observer_limit'; } /** - * Present when the manifest declares `agentAccess` (`"session.run"` and/or `"session.read"`). - * `run` / `reply` / `answer` / `models` / `agents` / `create` need `session.run`; `observe` and - * `sessions` need `session.read` except for this Mini App's own sessions (see - * docs/agent.md). - * A new Node session uses the primary Agent unless `agent` names one from `agents()`, and works in + * Always present (MiniMax Code 3.1.20 or later; see docs/agent.md). `run` / `reply` / `answer` / + * `models` / `list` / `create` need `permissions.agent: ["run"]`. The deprecated `observe` / + * `sessions` / `session` are the `context.session` methods and follow its rule (see docs/agent.md). + * A new Node session uses the primary Agent unless `agent` names one from `list()`, and works in * this Mini App's own Agent directory and on the runtime default model; * continuing a session keeps its Agent, directory and model (unless `model` switches it), including * one a page created using its host chat's Agent, project directory and model; a session never @@ -517,7 +519,7 @@ export interface MiniAppAgentClient { */ readonly model?: MiniAppAgentModelSelection; /** - * Only when starting a session (no `sessionId`): an agent `name` from `agents()`. Passing it + * Only when starting a session (no `sessionId`): an agent `name` from `list()`. Passing it * with `sessionId` is `INVALID_ARGUMENTS`. */ readonly agent?: string; @@ -531,7 +533,7 @@ export interface MiniAppAgentClient { ): Promise<MiniAppAgentRunResult>; /** * Decide a pending permission request. Never writes the user's global rules. Node replies - * have 16 separate pending slots; `run` / `answer` / `models` / `agents` / `create` and Connector + * have 16 separate pending slots; `run` / `answer` / `models` / `list` / `create` and Connector * requests share another 16. Filling that ordinary budget still permits replies. A full reply * budget rejects with retryable `AGENT_UNAVAILABLE`. */ @@ -562,24 +564,57 @@ export interface MiniAppAgentClient { */ models(): Promise<MiniAppAgentModels>; /** The agents the user has configured; `agent` of `create` / a first `run` must be one of them. */ + list(): Promise<MiniAppAgentAgents>; + /** @deprecated Use `list()`; the Host warns once and removes this name in a later version. */ agents(): Promise<MiniAppAgentAgents>; /** * Create a session (agent, this Mini App's Agent directory, the runtime default model) without * running a turn, and return its `sessionId`; continue it with `run({ sessionId })`. A page's * `create` binds the session to its chat instead, and its `sessionId` can be continued here. * Takes no Host run slot but uses the ordinary Node request budget. `agent` picks the session's - * agent from `agents()`; a session never changes it. + * agent from `list()`; a session never changes it. */ create(input?: { readonly agent?: string }): Promise<{ readonly sessionId: string }>; + /** @deprecated Use `context.session.observe`; the Host warns once and removes this name in a later version. */ + observe( + target: MiniAppAgentObserveTarget, + options: { + readonly onEvent: (event: MiniAppAgentObservedEvent) => void; + readonly signal?: AbortSignal; + }, + ): Promise<void>; + /** @deprecated Use `context.session.list`; the Host warns once and removes this name in a later version. */ + sessions(): Promise<MiniAppAgentSessions>; + /** @deprecated Use `context.session.get`; the Host warns once and removes this name in a later version. */ + session(sessionId: string): Promise<MiniAppAgentSessionDetail>; +} + +/** + * Always present (MiniMax Code 3.1.20 or later; see docs/agent.md). Read-only access to the user's + * conversations (the Desktop chat list). + * Every method needs `permissions.session: ["read"]`, except that this Mini App's own sessions (those + * `agent.create` / `agent.run` made) are readable under `permissions.agent: ["run"]` alone; while the + * user has `read` switched off, calls on other sessions fail with `PERMISSION_DENIED` and running + * observers end. Check `context.capabilities?.has('session.list')` on Hosts that may predate it. + * Neither grant implies the other; `observe({ all: true })` always needs `permissions.session: ["read"]`. + */ +export interface MiniAppSessionClient { + /** The user's visible root conversations, most recently updated first (at most 50). */ + list(): Promise<MiniAppAgentSessions>; + /** + * One conversation with its model and latest reply. `sessionId` is required: Node serves every + * tab, so it has no current chat; a page passes its chat's id (from its own `session.get()`). + */ + get(sessionId: string): Promise<MiniAppAgentSessionDetail>; /** * Watch the user's Agent at work (see `MiniAppAgentObserveTarget`). No request timeout; abort * `signal` to stop, after which `onEvent` gets nothing more. Resolves when the subscription * ended: `signal` aborted, the session was deleted, the process is stopping or being replaced, - * or `session.read` was switched off. + * or `read` was switched off. * Rejects with a `MiniAppAgentError` when it could not start or failed: `INVALID_ARGUMENTS` (not - * exactly one target), `NOT_PERMITTED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers + * exactly one target), `NOT_PERMITTED`, `PERMISSION_DENIED`, `SESSION_NOT_FOUND`, retryable `BUSY` past 4 observers * per Mini App (`reason: 'observer_limit'`) or `AGENT_UNAVAILABLE`. Observers use no run slots - * and no ordinary request budget. Check `context.capabilities?.has('agent.observe')` first. + * and no ordinary request budget. */ observe( target: MiniAppAgentObserveTarget, @@ -588,14 +623,6 @@ export interface MiniAppAgentClient { readonly signal?: AbortSignal; }, ): Promise<void>; - /** Check `context.capabilities?.has('agent.sessions')` first. */ - sessions(): Promise<MiniAppAgentSessions>; - /** - * One conversation with its model and latest reply. `sessionId` is required: Node serves every - * tab, so it has no current chat; a page passes its chat's id (from its own `session()`). - * Check `context.capabilities?.has('agent.session')`. - */ - session(sessionId: string): Promise<MiniAppAgentSessionDetail>; } export interface MiniAppLifecycle { @@ -610,24 +637,44 @@ export interface MiniAppContext { readonly signal: AbortSignal; readonly logger: MiniAppLogger; /** - * Synchronous probe of Host features, fixed per Host version. It says nothing about this - * Mini App's manifest or authorization: `has('agent.run')` is true on a Host that supports the - * Agent API even when `context.agent` is absent because `agentAccess` was not declared. - * Older Hosts do not inject `capabilities`; check `context.capabilities?.has(...)`. + * Synchronous probe of the methods this Host offers **on the Node side**, named by API path + * (`agent.run`, `agent.list`, `session.list`, `session.get`, `session.observe`, + * `connector.call`, `connector.list`, `tool.call`, `tool.list`, `tool.request`). A + * page-only method is false here. A few Host-wide names remain until the deprecated aliases go: + * `agent.agents`, `agent.observe`, `agent.sessions`, `agent.session`, `hostConnector`, `tool`. + * The `hostConnector*` probe names stay beside `connector.*` until the alias goes. + * It says nothing about this Mini App's manifest or authorization: `has('agent.run')` is true + * even when the manifest does not grant it. Older Hosts do not + * inject `capabilities`; check `context.capabilities?.has(...)`. `has('session.list')` tells a + * `context.session` Host from one that only has the deprecated `context.agent.sessions` names. */ readonly capabilities?: MiniAppHostCapabilities; /** - * Present when the manifest declares a `hostConnectorAccess` provider; a provider the user - * switched off is missing from `list()` and its calls fail with `CONNECTOR_NOT_PERMITTED`. + * Always present on MiniMax Code 3.1.20 or later. Without `permissions.connector` (or the older + * `hostConnectorAccess`), every method rejects `NOT_PERMITTED`. A provider the user switched off + * is missing from `list()` and its calls reject with `PERMISSION_DENIED`. + */ + readonly connector: HostConnectorClient; + /** + * @deprecated `connector`. Always present on 3.1.20 or later. Forwards to the same client and + * warns once on the first method call (`MINIAPP-DEP-007`); it is not the same object reference, + * so do not compare the two or use both as map keys. + */ + readonly hostConnector: HostConnectorClient; + /** Always present on 3.1.20 or later. Calls installed MCP and Connector tools under the user's permission rules. */ + readonly tool: MiniAppToolClient; + /** + * Always present on 3.1.20 or later, as on the page. Its methods need `permissions.agent: ["run"]`; + * they reject with `NOT_PERMITTED` if the manifest does not declare it and `PERMISSION_DENIED` + * if the user switched it off. Session aliases follow `context.session`'s rules. */ - readonly hostConnector?: HostConnectorClient; - /** Installed MCP and Connector tools, each call judged by the user's permission rules. */ - readonly tool?: MiniAppToolClient; + readonly agent: MiniAppAgentClient; /** - * Present when the manifest declares `agentAccess: ["session.run"]`; while the user has it - * switched off, calls fail with `NOT_PERMITTED`. + * Always present on 3.1.20 or later, as on the page. Reading conversations other than this Mini + * App's own needs `permissions.session: ["read"]`. Own sessions can also use + * `permissions.agent: ["run"]`. */ - readonly agent?: MiniAppAgentClient; + readonly session: MiniAppSessionClient; } export interface MiniAppHostCapabilities { diff --git a/scripts/lib/contract.mjs b/scripts/lib/contract.mjs index f24122fe..bc39e559 100644 --- a/scripts/lib/contract.mjs +++ b/scripts/lib/contract.mjs @@ -1,10 +1,11 @@ // Constants shared by every rule. Values mirror the MiniMax Code package reader. +// When a feature ships first in the next unreleased version, hold its version in NEXT_RELEASE here +// so a late renumbering is a one-line change. -// The next MiniMax Code release, frozen from preview_train. Features that ship first in it use this -// constant, so a late renumbering is a one-line change. -const NEXT_RELEASE = '3.1.11'; - -export const HOST_VERSION = NEXT_RELEASE; +// The release that introduced the grouped `permissions` manifest field, `window.miniapp`, +// `session.*`, `agent.list`, `host.composer.append`, `context.connector`, `{ code, message }` page +// errors, and `PERMISSION_DENIED`. +export const MINIAPP_API_VERSION = '3.1.20'; // A feature's minimum is the first version with released installers for both macOS and Windows. // Clients older than it reject the whole package when it declares the feature. 3.1.5 shipped no @@ -19,7 +20,10 @@ export const FEATURE_MIN_HOST_VERSION = Object.freeze({ 'deviceAccess.camera': '3.1.9', 'deviceAccess.notifications': '3.1.9', engines: '3.1.6', - hostAccess: NEXT_RELEASE, + fileHandlers: '3.1.18', + hostAccess: '3.1.11', + permissions: MINIAPP_API_VERSION, + 'surface.widget': '3.1.15', 'surface.window': '3.1.2', toolAccess: '3.1.6', }); @@ -89,6 +93,7 @@ export const MINIAPP_FIELDS = new Set([ 'runtime', 'surface', 'mcpEndpoints', + 'permissions', 'hostConnectorAccess', 'agentAccess', 'agentConcurrency', @@ -96,14 +101,22 @@ export const MINIAPP_FIELDS = new Set([ 'toolAccess', 'deviceAccess', 'hostAccess', + 'fileHandlers', ]); export const ARTIFACT_FIELDS = new Set(['client', 'node']); export const RUNTIME_FIELDS = new Set(['kind', 'entry', 'lifecycle']); -export const SURFACE_FIELDS = new Set(['path', 'window']); +export const SURFACE_FIELDS = new Set(['path', 'window', 'widget']); +export const SURFACE_WIDGET_FIELDS = new Set(['kind', 'size']); +export const SURFACE_WIDGET_KINDS = new Set(['display', 'interactive']); +export const SURFACE_WIDGET_SIZES = new Set(['small', 'medium']); export const SURFACE_WINDOW_DIMENSION_FIELDS = ['width', 'height', 'minWidth', 'minHeight']; export const SURFACE_WINDOW_BOOLEAN_FIELDS = ['resizable', 'frame', 'transparent', 'alwaysOnTop', 'skipTaskbar', 'clickThrough']; export const SURFACE_WINDOW_DIMENSION_MIN = 200; export const SURFACE_WINDOW_DIMENSION_MAX = 10_000; +export const LEGACY_ACCESS_FIELDS = ['agentAccess', 'toolAccess', 'deviceAccess', 'hostAccess', 'hostConnectorAccess']; +export const PERMISSION_DOMAINS = ['agent', 'session', 'tool', 'device', 'host', 'connector']; +export const AGENT_PERMISSION_ITEMS = new Set(['run']); +export const SESSION_PERMISSION_ITEMS = new Set(['read']); export const AGENT_ACCESS_CAPABILITIES = new Set(['session.run', 'session.read']); export const AGENT_CONCURRENCY_MAX = 32; export const TOOL_ACCESS_CAPABILITIES = new Set(['call']); @@ -115,6 +128,13 @@ export const ENGINES_REQUIREMENT = /^>=\s*(\d+)\.(\d+)\.(\d+)$/u; // The Host answers requests under this prefix itself; plugin routes there never work. export const RESERVED_ROUTE_PREFIX = '/__mavis'; export const MCP_ENDPOINT_FIELDS = new Set(['server', 'path']); +export const FILE_HANDLER_FIELDS = new Set(['id', 'path', 'extensions']); +export const FILE_HANDLER_ID = /^[a-z0-9-]{1,32}$/u; +export const FILE_EXTENSION = /^\.[a-z0-9]{1,16}$/u; +export const FILE_HANDLERS_MAX = 256; +export const FILE_HANDLER_EXTENSIONS_MAX = 256; +export const FILE_HANDLER_TOTAL_EXTENSIONS_MAX = 512; +export const FILE_HANDLER_PATH_MAX_LENGTH = 4096; export const HOST_CONNECTOR_ACCESS_FIELDS = new Set(['providers']); export const MCP_SERVER_NAME = /^[a-zA-Z0-9_-]{1,128}$/u; export const CONNECTOR_PROVIDER = /^[a-z0-9_-]{1,64}$/u; diff --git a/scripts/lib/js-source.mjs b/scripts/lib/js-source.mjs new file mode 100644 index 00000000..70d48914 --- /dev/null +++ b/scripts/lib/js-source.mjs @@ -0,0 +1,196 @@ +export const CLASSIC_SCRIPT_TYPES = new Set([ + '', + 'text/javascript', + 'application/javascript', + 'text/ecmascript', + 'application/ecmascript', + 'javascript', +]); + +// Single-pass HTML tokenizer: `<!-- ... -->` comments outside `<script>` are skipped, while raw +// `<script>` bodies keep strings like `"<!-- -->"` intact. +const HTML_TOKEN = /<!--[\s\S]*?-->|<script\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*?)<\/script>/giu; +const INLINE_HANDLER_ATTR = /\bon[a-z]+\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"'=<>`]+))/giu; + +export function parseHtmlScriptsAndHandlers(html) { + const scripts = []; + const chunks = []; + let cursor = 0; + for (const match of html.matchAll(HTML_TOKEN)) { + collectInlineHandlers(html.slice(cursor, match.index), chunks); + cursor = match.index + match[0].length; + if (match[0].startsWith('<!--')) continue; + const attributes = match[1]; + const body = match[2]; + const type = scriptMimeEssence(attributes); + const src = readHtmlAttribute(attributes, 'src'); + scripts.push({ type, src, body }); + if (type === 'module' || CLASSIC_SCRIPT_TYPES.has(type)) chunks.push(body); + } + collectInlineHandlers(html.slice(cursor), chunks); + return { scripts, executableCode: chunks.join('\n') }; +} + +function collectInlineHandlers(markup, chunks) { + for (const match of markup.matchAll(INLINE_HANDLER_ATTR)) { + chunks.push(match[1] ?? match[2] ?? match[3] ?? ''); + } +} + +function readHtmlAttribute(attributes, name) { + const match = new RegExp(String.raw`\b${name}\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))`, 'iu').exec(attributes); + return match ? (match[1] ?? match[2] ?? match[3] ?? '').trim() : undefined; +} + +function scriptMimeEssence(attributes) { + const raw = readHtmlAttribute(attributes, 'type'); + return raw === undefined ? '' : raw.toLowerCase().split(';', 1)[0].trim(); +} + +const REGEX_PRECEDING_KEYWORDS = new Set([ + 'return', + 'throw', + 'case', + 'typeof', + 'void', + 'delete', + 'in', + 'of', + 'instanceof', + 'new', + 'yield', + 'await', + 'else', +]); +const CONDITION_PAREN_KEYWORDS = new Set(['if', 'while', 'for', 'with']); +const REGEX_PRECEDING_CHARS = new Set('(,=:[!&|?{};+-*%~^<>'); + +// Strips `//` and `/* ... */` comments and blanks `/.../` regex bodies so neither comments nor +// regex patterns trigger source checks, while keeping string and template literals intact. +export function stripCommentsAndRegexes(source) { + let out = ''; + let canStartRegex = true; + let nextParenIsCondition = false; + const parenStack = []; + const templateBraceDepths = []; + + const appendTemplateChunk = (fromIndex) => { + const chunk = readTemplateChunk(source, fromIndex + 1); + out += source.slice(fromIndex, chunk.end + 1); + nextParenIsCondition = false; + if (chunk.openedExpression) { + templateBraceDepths.push(0); + canStartRegex = true; + } else { + canStartRegex = false; + } + return chunk.end; + }; + + for (let index = 0; index < source.length; index += 1) { + const char = source[index]; + const next = source[index + 1]; + if (char === '"' || char === "'") { + const end = quotedEnd(source, index); + if (end === -1) { + out += source.slice(index); + break; + } + out += source.slice(index, end + 1); + index = end; + canStartRegex = false; + nextParenIsCondition = false; + } else if (char === '`') { + index = appendTemplateChunk(index); + } else if (char === '{' && templateBraceDepths.length > 0) { + templateBraceDepths[templateBraceDepths.length - 1] += 1; + out += char; + canStartRegex = true; + nextParenIsCondition = false; + } else if (char === '}' && templateBraceDepths.length > 0 && templateBraceDepths.at(-1) === 0) { + templateBraceDepths.pop(); + index = appendTemplateChunk(index); + } else if (char === '}' && templateBraceDepths.length > 0) { + templateBraceDepths[templateBraceDepths.length - 1] -= 1; + out += char; + canStartRegex = true; + nextParenIsCondition = false; + } else if (char === '/' && next === '/') { + const newline = source.indexOf('\n', index + 2); + if (newline === -1) break; + out += '\n'; + index = newline; + } else if (char === '/' && next === '*') { + const close = source.indexOf('*/', index + 2); + if (close === -1) break; + out += ' '; + index = close + 1; + } else if (char === '/' && canStartRegex) { + const end = regexEnd(source, index); + if (end !== -1) { + out += '/ /'; + index = end; + canStartRegex = false; + nextParenIsCondition = false; + } else { + out += char; + } + } else if (char === '(') { + parenStack.push(nextParenIsCondition); + nextParenIsCondition = false; + canStartRegex = true; + out += char; + } else if (char === ')') { + canStartRegex = parenStack.pop() ?? false; + nextParenIsCondition = false; + out += char; + } else { + out += char; + if (/[A-Za-z0-9_$]/u.test(char)) { + let wordEnd = index; + while (/[A-Za-z0-9_$]/u.test(source[wordEnd + 1] ?? '')) wordEnd += 1; + const word = source.slice(index, wordEnd + 1); + out += source.slice(index + 1, wordEnd + 1); + index = wordEnd; + canStartRegex = REGEX_PRECEDING_KEYWORDS.has(word); + nextParenIsCondition = CONDITION_PAREN_KEYWORDS.has(word); + } else if (!/\s/u.test(char)) { + canStartRegex = REGEX_PRECEDING_CHARS.has(char); + nextParenIsCondition = false; + } + } + } + return out; +} + +export function quotedEnd(source, start) { + const quote = source[start]; + for (let index = start + 1; index < source.length; index += 1) { + if (source[index] === '\\') index += 1; + else if (source[index] === quote) return index; + } + return -1; +} + +export function readTemplateChunk(source, start) { + for (let index = start; index < source.length; index += 1) { + const char = source[index]; + if (char === '\\') index += 1; + else if (char === '`') return { end: index, openedExpression: false }; + else if (char === '$' && source[index + 1] === '{') return { end: index + 1, openedExpression: true }; + } + return { end: source.length - 1, openedExpression: false }; +} + +function regexEnd(source, start) { + let inCharClass = false; + for (let index = start + 1; index < source.length; index += 1) { + const char = source[index]; + if (char === '\\') index += 1; + else if (char === '\n' || char === '\r') return -1; + else if (char === '[') inCharClass = true; + else if (char === ']') inCharClass = false; + else if (char === '/' && !inCharClass) return index; + } + return -1; +} diff --git a/scripts/lib/package.mjs b/scripts/lib/package.mjs index 59a8de35..155c17a5 100644 --- a/scripts/lib/package.mjs +++ b/scripts/lib/package.mjs @@ -2,6 +2,7 @@ import path from 'node:path'; import { readJsonFile } from './fs.mjs'; import { createReport } from './report.mjs'; +import { checkClient } from './rules/client.mjs'; import { checkFiles } from './rules/files.mjs'; import { checkImageFile, checkLayout, checkNameMatchesDirectory } from './rules/layout.mjs'; import { checkManifest } from './rules/manifest.mjs'; @@ -39,9 +40,11 @@ export async function validatePackage(packageDir, { requireLowercaseAuthor = tru await checkFiles(report, { packageDir: dir }); await checkReadme(report, { packageDir: dir, features, engines: resolved.engines }); await checkNode(report, { packageDir: dir, entry: resolved.entry, nodeRoots: resolved.nodeRoots }); + await checkClient(report, { packageDir: dir, clientRoots: resolved.clientRoots }); await checkAccessUsage(report, { packageDir: dir, - roots: [...resolved.clientRoots, ...resolved.nodeRoots], + clientRoots: resolved.clientRoots, + nodeRoots: resolved.nodeRoots, access: resolved.access, minimum: requiredHostVersion(features, resolved.engines), }); diff --git a/scripts/lib/rules/client.mjs b/scripts/lib/rules/client.mjs new file mode 100644 index 00000000..5479be41 --- /dev/null +++ b/scripts/lib/rules/client.mjs @@ -0,0 +1,178 @@ +import path from 'node:path'; +import { Script } from 'node:vm'; + +import { collectPayloadFiles, pathExists, readText } from '../fs.mjs'; +import { + CLASSIC_SCRIPT_TYPES, + parseHtmlScriptsAndHandlers, + quotedEnd, + readTemplateChunk, + stripCommentsAndRegexes, +} from '../js-source.mjs'; +import { isCoveredBy } from '../paths.mjs'; + +const HTML_EXTENSIONS = new Set(['.html', '.htm']); +const EXPR_BEFORE_FUNCTION = new Set([ + '=', + '(', + '[', + ',', + ':', + '?', + '!', + '~', + '+', + '-', + '*', + '%', + '&', + '|', + '^', + '<', + '>', + 'return', + 'throw', + 'typeof', + 'void', + 'delete', + 'new', + 'await', + 'yield', + 'in', + 'of', + 'instanceof', +]); + +export async function checkClient(report, { packageDir, clientRoots }) { + const checkedExternal = new Set(); + for (const relativePath of await collectPayloadFiles(packageDir, clientRoots, HTML_EXTENSIONS)) { + const raw = await readText(path.join(packageDir, ...relativePath.split('/'))); + if (raw === undefined) continue; + const { scripts } = parseHtmlScriptsAndHandlers(raw); + let reportedInline = false; + for (const { type, src, body } of scripts) { + if (!CLASSIC_SCRIPT_TYPES.has(type)) continue; + if (src !== undefined) { + const target = await resolveClientScriptSrc(packageDir, clientRoots, relativePath, src); + if (!target || checkedExternal.has(target)) continue; + checkedExternal.add(target); + const externalCode = await readText(path.join(packageDir, ...target.split('/'))); + if (externalCode !== undefined && declaresTopLevelMiniapp(externalCode)) { + reportGlobalMiniapp(report, target); + } + } else if (!reportedInline && declaresTopLevelMiniapp(body)) { + reportedInline = true; + reportGlobalMiniapp(report, relativePath); + } + } + } +} + +async function resolveClientScriptSrc(packageDir, clientRoots, htmlRelativePath, src) { + if (!src || /^(?:https?:|\/\/|data:|blob:|javascript:)/iu.test(src)) return undefined; + const clean = src.split(/[?#]/u, 1)[0]; + if (!clean) return undefined; + const candidates = clean.startsWith('/') + ? clientRoots.map((root) => path.posix.normalize(`${root}${clean}`)) + : [path.posix.normalize(path.posix.join(path.posix.dirname(htmlRelativePath), clean))]; + for (const candidate of candidates) { + if (!isCoveredBy(candidate, clientRoots)) continue; + if (await pathExists(path.join(packageDir, ...candidate.split('/')), 'file')) return candidate; + } + return undefined; +} + +// Pure parse-time check (never executes plugin code, and behaves identically across Node 22+ V8): +// 1. `;var miniapp;` fails at parse time for any top-level `const` / `let` / `class` binding named `miniapp`. +// 2. `;const miniapp = 0;` fails only for top-level `var` or `function` bindings; `hasTopLevelFunctionDeclaration` +// then separates top-level `function miniapp` declarations (which fail on Electron's non-configurable global) +// from `var miniapp` and named function expressions (`const x = function miniapp() {}`). +function declaresTopLevelMiniapp(code) { + if (!/\bminiapp\b/u.test(code)) return false; + try { + new Script(code); + } catch { + return false; + } + const body = code.replace(/^#!.*\r?\n/u, ''); + try { + new Script(`${body}\n;var miniapp;`); + } catch { + return true; + } + try { + new Script(`${body}\n;const miniapp = 0;`); + return false; + } catch { + return hasTopLevelFunctionDeclaration(stripCommentsAndRegexes(body)); + } +} + +function hasTopLevelFunctionDeclaration(stripped) { + let depth = 0; + let prevToken = ''; + const templateBraceDepths = []; + + const enterTemplateChunk = (fromIndex) => { + const chunk = readTemplateChunk(stripped, fromIndex + 1); + if (chunk.openedExpression) { + templateBraceDepths.push(0); + depth += 1; + prevToken = '{'; + } else { + prevToken = 'lit'; + } + return chunk.end; + }; + + for (let index = 0; index < stripped.length; index += 1) { + const char = stripped[index]; + if (/\s/u.test(char)) continue; + if (char === '"' || char === "'") { + const end = quotedEnd(stripped, index); + if (end === -1) break; + index = end; + prevToken = 'lit'; + } else if (char === '`') { + index = enterTemplateChunk(index); + } else if (char === '{' && templateBraceDepths.length > 0) { + templateBraceDepths[templateBraceDepths.length - 1] += 1; + depth += 1; + prevToken = char; + } else if (char === '}' && templateBraceDepths.length > 0 && templateBraceDepths.at(-1) === 0) { + templateBraceDepths.pop(); + depth = Math.max(0, depth - 1); + index = enterTemplateChunk(index); + } else if (char === '}' && templateBraceDepths.length > 0) { + templateBraceDepths[templateBraceDepths.length - 1] -= 1; + depth = Math.max(0, depth - 1); + prevToken = char; + } else if (char === '{' || char === '(' || char === '[') { + depth += 1; + prevToken = char; + } else if (char === '}' || char === ')' || char === ']') { + depth = Math.max(0, depth - 1); + prevToken = char; + } else if (/[A-Za-z0-9_$]/u.test(char)) { + let end = index; + while (/[A-Za-z0-9_$]/u.test(stripped[end + 1] ?? '')) end += 1; + const word = stripped.slice(index, end + 1); + if (depth === 0 && word === 'function' && !EXPR_BEFORE_FUNCTION.has(prevToken)) { + if (/^\s*\*?\s*miniapp\b/u.test(stripped.slice(end + 1))) return true; + } + if (word !== 'async') prevToken = word; + index = end; + } else { + prevToken = char; + } + } + return false; +} + +function reportGlobalMiniapp(report, relativePath) { + report.error( + 'CLIENT_GLOBAL_MINIAPP', + 'declares a top-level "miniapp" binding in a classic script, which collides with the read-only window.miniapp global on MiniMax Code 3.1.20 and later; rename the binding or use <script type="module">', + relativePath, + ); +} diff --git a/scripts/lib/rules/miniapp.mjs b/scripts/lib/rules/miniapp.mjs index 1d6bd5ba..c6573ab1 100644 --- a/scripts/lib/rules/miniapp.mjs +++ b/scripts/lib/rules/miniapp.mjs @@ -3,6 +3,7 @@ import path from 'node:path'; import { AGENT_ACCESS_CAPABILITIES, AGENT_CONCURRENCY_MAX, + AGENT_PERMISSION_ITEMS, ARTIFACT_FIELDS, CONNECTOR_PROVIDER, DEVICE_ACCESS_ITEMS, @@ -10,15 +11,28 @@ import { ENGINES_REQUIREMENT, ENTRY_EXTENSION, EXCLUDED_DIRECTORY, + FILE_EXTENSION, + FILE_HANDLERS_MAX, + FILE_HANDLER_EXTENSIONS_MAX, + FILE_HANDLER_FIELDS, + FILE_HANDLER_ID, + FILE_HANDLER_PATH_MAX_LENGTH, + FILE_HANDLER_TOTAL_EXTENSIONS_MAX, HOST_ACCESS_CAPABILITIES, HOST_CONNECTOR_ACCESS_FIELDS, + LEGACY_ACCESS_FIELDS, MCP_ENDPOINT_FIELDS, MCP_SERVER_NAME, MINIAPP_FIELDS, PAYLOAD_DIRECTORY, + PERMISSION_DOMAINS, RESERVED_ROUTE_PREFIX, RUNTIME_FIELDS, + SESSION_PERMISSION_ITEMS, SURFACE_FIELDS, + SURFACE_WIDGET_FIELDS, + SURFACE_WIDGET_KINDS, + SURFACE_WIDGET_SIZES, SURFACE_WINDOW_BOOLEAN_FIELDS, SURFACE_WINDOW_DIMENSION_FIELDS, SURFACE_WINDOW_DIMENSION_MAX, @@ -30,9 +44,13 @@ import { isCoveredBy, normalizePluginPath, normalizeRoutePath } from '../paths.m const FILE = 'miniapp/miniapp.json'; +function emptyAccess() { + return { agent: [], session: [], tool: false, device: [], host: [], connector: [] }; +} + // What a package without a readable miniapp.json resolves to: no payload, no features, no access. export function emptyMiniApp() { - return { nodeRoots: [], clientRoots: [], features: [], access: { agent: [], tool: false, device: [], host: [] } }; + return { nodeRoots: [], clientRoots: [], features: [], access: emptyAccess() }; } export async function checkMiniApp(report, { packageDir, manifest }) { @@ -53,26 +71,20 @@ export async function checkMiniApp(report, { packageDir, manifest }) { if (entry) resolved.entry = entry; checkSurface(report, manifest.surface); checkMcpEndpoints(report, manifest.mcpEndpoints); - checkHostConnectorAccess(report, manifest.hostConnectorAccess); - const agent = checkAccessList(report, manifest.agentAccess, 'agentAccess', AGENT_ACCESS_CAPABILITIES, 'MINIAPP_AGENT_ACCESS_INVALID'); + resolved.access = + manifest.permissions === undefined + ? checkLegacyAccess(report, manifest, resolved.features) + : checkPermissions(report, manifest, resolved.features); checkAgentConcurrency(report, manifest.agentConcurrency); - const tool = checkAccessList(report, manifest.toolAccess, 'toolAccess', TOOL_ACCESS_CAPABILITIES, 'MINIAPP_TOOL_ACCESS_INVALID'); - const device = checkAccessList(report, manifest.deviceAccess, 'deviceAccess', DEVICE_ACCESS_ITEMS, 'MINIAPP_DEVICE_ACCESS_INVALID'); - const host = checkAccessList(report, manifest.hostAccess, 'hostAccess', HOST_ACCESS_CAPABILITIES, 'MINIAPP_HOST_ACCESS_INVALID'); const engines = checkEngines(report, manifest.engines); if (engines) resolved.engines = engines; - resolved.access = { agent, tool: tool.includes('call'), device, host }; + checkFileHandlers(report, manifest.fileHandlers); - if (manifest.agentAccess !== undefined) resolved.features.push('agentAccess'); - if (Array.isArray(manifest.agentAccess) && manifest.agentAccess.includes('session.read')) resolved.features.push('agentAccess.session.read'); if (manifest.agentConcurrency !== undefined) resolved.features.push('agentConcurrency'); if (isRecord(manifest.surface) && manifest.surface.window !== undefined) resolved.features.push('surface.window'); - for (const field of ['engines', 'toolAccess', 'deviceAccess', 'hostAccess']) { - if (manifest[field] !== undefined) resolved.features.push(field); - } - for (const item of ['camera', 'notifications']) { - if (device.includes(item)) resolved.features.push(`deviceAccess.${item}`); - } + if (isRecord(manifest.surface) && manifest.surface.widget !== undefined) resolved.features.push('surface.widget'); + if (manifest.engines !== undefined) resolved.features.push('engines'); + if (manifest.fileHandlers !== undefined) resolved.features.push('fileHandlers'); return resolved; } @@ -149,13 +161,14 @@ async function checkRuntime(report, packageDir, value, nodeRoots) { function checkSurface(report, value) { if (!isRecord(value) || Object.keys(value).some((k) => !SURFACE_FIELDS.has(k))) { - report.error('MINIAPP_SURFACE_INVALID', 'surface must be an object with only "path" and "window"', FILE); + report.error('MINIAPP_SURFACE_INVALID', 'surface must be an object with only "path", "window", and "widget"', FILE); return; } const route = normalizeRoutePath(value.path); if (!route.ok) report.error('MINIAPP_SURFACE_INVALID', `surface.path ${route.reason}`, FILE); else checkRouteNotReserved(report, route.value, 'surface.path'); if (value.window !== undefined) checkSurfaceWindow(report, value.window); + if (value.widget !== undefined) checkSurfaceWidget(report, value.widget); } // Same rule set as the Host's validateMiniAppSurfaceWindow. @@ -193,6 +206,17 @@ function checkSurfaceWindow(report, value) { } } +function checkSurfaceWidget(report, value) { + if ( + !isRecord(value) || + Object.keys(value).some((k) => !SURFACE_WIDGET_FIELDS.has(k)) || + !SURFACE_WIDGET_KINDS.has(value.kind) || + !SURFACE_WIDGET_SIZES.has(value.size) + ) { + report.error('MINIAPP_SURFACE_INVALID', 'surface.widget must be { "kind": "display" | "interactive", "size": "small" | "medium" }', FILE); + } +} + function checkRouteNotReserved(report, route, label) { if (route === RESERVED_ROUTE_PREFIX || route.startsWith(`${RESERVED_ROUTE_PREFIX}/`)) { report.error('MINIAPP_ROUTE_RESERVED', `${label} "${route}" is under ${RESERVED_ROUTE_PREFIX}/, which the Host reserves`, FILE); @@ -230,13 +254,105 @@ function checkMcpEndpoints(report, value) { } } +const PERMISSION_ITEMS_BY_GROUP = new Map([ + ['agent', (item) => AGENT_PERMISSION_ITEMS.has(item)], + ['session', (item) => SESSION_PERMISSION_ITEMS.has(item)], + ['tool', (item) => TOOL_ACCESS_CAPABILITIES.has(item)], + ['device', (item) => DEVICE_ACCESS_ITEMS.has(item)], + ['host', (item) => HOST_ACCESS_CAPABILITIES.has(item)], + ['connector', (item) => typeof item === 'string' && CONNECTOR_PROVIDER.test(item)], +]); + +function checkPermissions(report, manifest, features) { + features.push('permissions'); + const mixed = LEGACY_ACCESS_FIELDS.filter((field) => manifest[field] !== undefined); + if (mixed.length > 0) { + report.error('MINIAPP_PERMISSIONS_INVALID', `permissions replaces ${mixed.join(', ')}; declare one spelling or the other`, FILE); + return emptyAccess(); + } + const value = manifest.permissions; + if (!isRecord(value)) { + report.error('MINIAPP_PERMISSIONS_INVALID', 'permissions must be a grouped object', FILE); + return emptyAccess(); + } + for (const group of Object.keys(value)) { + if (!PERMISSION_DOMAINS.includes(group)) { + report.error('MINIAPP_PERMISSIONS_INVALID', `permissions contains an unknown group "${group}"`, FILE); + return emptyAccess(); + } + } + const parsed = new Map(); + for (const group of PERMISSION_DOMAINS) { + const list = value[group]; + if (list === undefined) continue; + if (!Array.isArray(list)) { + report.error('MINIAPP_PERMISSIONS_INVALID', `permissions.${group} must be an array`, FILE); + return emptyAccess(); + } + const isOwnItem = PERMISSION_ITEMS_BY_GROUP.get(group); + const seen = new Set(); + for (const item of list) { + if (!isOwnItem(item)) { + report.error('MINIAPP_PERMISSIONS_INVALID', `permissions.${group} contains an invalid item: ${JSON.stringify(item)}`, FILE); + return emptyAccess(); + } + if (seen.has(item)) { + report.error('MINIAPP_PERMISSIONS_INVALID', `permissions.${group} contains a duplicate: "${item}"`, FILE); + return emptyAccess(); + } + seen.add(item); + } + parsed.set(group, [...seen]); + } + const connector = parsed.get('connector') ?? []; + if (connector.length > 0) warnConnectorUnverified(report); + return { + agent: parsed.get('agent') ?? [], + session: parsed.get('session') ?? [], + tool: (parsed.get('tool') ?? []).includes('call'), + device: [...(parsed.get('device') ?? [])].sort(), + host: [...(parsed.get('host') ?? [])].sort(), + connector, + }; +} + +function checkLegacyAccess(report, manifest, features) { + const connector = checkHostConnectorAccess(report, manifest.hostConnectorAccess); + const legacyAgent = checkAccessList(report, manifest.agentAccess, 'agentAccess', AGENT_ACCESS_CAPABILITIES, 'MINIAPP_AGENT_ACCESS_INVALID'); + const tool = checkAccessList(report, manifest.toolAccess, 'toolAccess', TOOL_ACCESS_CAPABILITIES, 'MINIAPP_TOOL_ACCESS_INVALID'); + const device = checkAccessList(report, manifest.deviceAccess, 'deviceAccess', DEVICE_ACCESS_ITEMS, 'MINIAPP_DEVICE_ACCESS_INVALID'); + const host = checkAccessList(report, manifest.hostAccess, 'hostAccess', HOST_ACCESS_CAPABILITIES, 'MINIAPP_HOST_ACCESS_INVALID'); + + if (manifest.agentAccess !== undefined) features.push('agentAccess'); + if (Array.isArray(manifest.agentAccess) && manifest.agentAccess.includes('session.read')) features.push('agentAccess.session.read'); + for (const field of ['toolAccess', 'deviceAccess', 'hostAccess']) { + if (manifest[field] !== undefined) features.push(field); + } + for (const item of ['camera', 'notifications']) { + if (device.includes(item)) features.push(`deviceAccess.${item}`); + } + return { + agent: legacyAgent.includes('session.run') ? ['run'] : [], + session: legacyAgent.includes('session.read') ? ['read'] : [], + tool: tool.includes('call'), + device, + host, + connector, + }; +} + function checkHostConnectorAccess(report, value) { - if (value === undefined) return; + if (value === undefined) return []; const providers = isRecord(value) && !Object.keys(value).some((k) => !HOST_CONNECTOR_ACCESS_FIELDS.has(k)) ? value.providers : undefined; if (!Array.isArray(providers) || providers.some((p) => typeof p !== 'string' || !CONNECTOR_PROVIDER.test(p)) || new Set(providers).size !== providers.length) { report.error('MINIAPP_HOST_CONNECTOR_INVALID', `hostConnectorAccess.providers must be unique strings matching ${CONNECTOR_PROVIDER.source}`, FILE); - return; + return []; } + if (providers.length > 0) warnConnectorUnverified(report); + return [...providers]; +} + +function warnConnectorUnverified(report) { report.warning('HOST_CONNECTOR_UNVERIFIED', 'declared providers are granted by the Host at install time and are not checked here', FILE); } @@ -270,3 +386,60 @@ function checkEngines(report, value) { } return match.slice(1, 4).map(Number).join('.'); } + +// Same rule set as the Host's validateMiniAppFileHandlers plus reserved-route rejection. +function checkFileHandlers(report, value) { + if (value === undefined) return; + if (!Array.isArray(value) || value.length === 0) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', 'fileHandlers must be a non-empty array', FILE); + return; + } + if (value.length > FILE_HANDLERS_MAX) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `fileHandlers supports at most ${FILE_HANDLERS_MAX} handlers`, FILE); + return; + } + const ids = new Set(); + const extensions = new Set(); + for (const [index, item] of value.entries()) { + const label = `fileHandlers[${index}]`; + if (!isRecord(item) || Object.keys(item).some((k) => !FILE_HANDLER_FIELDS.has(k))) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `${label} must contain only "id", "path", and "extensions"`, FILE); + return; + } + if (typeof item.id !== 'string' || !FILE_HANDLER_ID.test(item.id) || ids.has(item.id)) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `${label}.id must match ${FILE_HANDLER_ID.source} and be unique`, FILE); + return; + } + ids.add(item.id); + const route = normalizeRoutePath(item.path); + if (!route.ok || route.value.length > FILE_HANDLER_PATH_MAX_LENGTH || /[\u0000-\u001f\u007f]/u.test(route.value)) { + report.error( + 'MINIAPP_ROUTE_PATH_INVALID', + `${label}.path must be a canonical host-relative route of at most ${FILE_HANDLER_PATH_MAX_LENGTH} characters without an origin, query, fragment, backslash, or control characters`, + FILE, + ); + return; + } + if (!Array.isArray(item.extensions) || item.extensions.length === 0 || item.extensions.length > FILE_HANDLER_EXTENSIONS_MAX) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `${label}.extensions must be a non-empty array of at most ${FILE_HANDLER_EXTENSIONS_MAX} extensions`, FILE); + return; + } + for (const [extIndex, extension] of item.extensions.entries()) { + const extLabel = `${label}.extensions[${extIndex}]`; + if (typeof extension !== 'string' || !FILE_EXTENSION.test(extension)) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `${extLabel} must match ${FILE_EXTENSION.source} (for example ".stl")`, FILE); + return; + } + if (extensions.has(extension)) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `${extLabel} repeats "${extension}"`, FILE); + return; + } + if (extensions.size === FILE_HANDLER_TOTAL_EXTENSIONS_MAX) { + report.error('MINIAPP_FILE_HANDLERS_INVALID', `fileHandlers supports at most ${FILE_HANDLER_TOTAL_EXTENSIONS_MAX} extensions in total`, FILE); + return; + } + extensions.add(extension); + } + checkRouteNotReserved(report, route.value, `${label}.path`); + } +} diff --git a/scripts/lib/rules/usage.mjs b/scripts/lib/rules/usage.mjs index dabf951c..0f566c07 100644 --- a/scripts/lib/rules/usage.mjs +++ b/scripts/lib/rules/usage.mjs @@ -1,56 +1,151 @@ import path from 'node:path'; -import { BROWSER_PERMISSION_GATE_VERSION } from '../contract.mjs'; +import { BROWSER_PERMISSION_GATE_VERSION, MINIAPP_API_VERSION } from '../contract.mjs'; import { collectPayloadFiles, readText } from '../fs.mjs'; +import { parseHtmlScriptsAndHandlers, quotedEnd, readTemplateChunk, stripCommentsAndRegexes } from '../js-source.mjs'; import { compareVersions } from '../version.mjs'; // Files that run in the page or in Node. Declaration files (.ts) never run and are skipped. const SCANNED_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.html', '.htm']); +const HTML_EXTENSIONS = new Set(['.html', '.htm']); // Mini App APIs that never work without their declaration, on any client. +// `agent.cancel(requestId)` is omitted on purpose: it needs no grant and also cancels `session.observe`. const AGENT_PREFIX = String.raw`\b(?:context|miniapp)\??\.agent\??\.`; -const AGENT_RUN_CALL = new RegExp(String.raw`${AGENT_PREFIX}(?:run|answer|reply|cancel|open|models|agents|create)\s*\(`, 'u'); -const AGENT_OWN_SESSION_CALL = new RegExp(String.raw`${AGENT_PREFIX}(?:observe|session)\s*\(`, 'u'); -const USER_SESSION_CALL = /\bagent\??\.sessions\s*\(|\bagent\??\.observe\s*\(\s*\{\s*all\s*:\s*(?:true|!0)|\bagent\??\.session\s*\(\s*\)/u; +const SESSION_PREFIX = String.raw`\b(?:context|miniapp)\??\.session\??\.`; +const AGENT_RUN_CALL = new RegExp(String.raw`${AGENT_PREFIX}(?:run|answer|reply|open|models|list|agents|create)\s*\(`, 'u'); +const OWN_SESSION_CALL = new RegExp( + String.raw`(?:${AGENT_PREFIX}(?:observe|session)|${SESSION_PREFIX}(?:observe|get))\s*\(`, + 'u', +); +const USER_SESSION_CALL = new RegExp( + [ + String.raw`${SESSION_PREFIX}list\s*\(`, + String.raw`\bagent\??\.sessions\s*\(`, + String.raw`(?:${SESSION_PREFIX}|\bagent\??\.)observe\s*\(\s*\{\s*all\s*:\s*(?:true|!0)`, + String.raw`\b(?:miniapp\??\.session\??\.get|agent\??\.session)\s*\(\s*\)`, + ].join('|'), + 'u', +); const API_RULES = [ { pattern: /\b(?:context|miniapp)\??\.tool\??\.(?:call|list|request)\s*\(/u, granted: (access) => access.tool, - message: 'calls the tool API but miniapp.json does not declare toolAccess ["call"]; context.tool is absent and page tool.request rejects', + message: + 'calls the tool API but miniapp.json does not declare permissions.tool ["call"] (or toolAccess ["call"]); calls reject with NOT_PERMITTED', + }, + { + pattern: /\bcontext\??\.(?:connector|hostConnector)\??\.(?:call|list)\s*\(/u, + granted: (access) => (access.connector?.length ?? 0) > 0, + message: + 'calls context.connector but miniapp.json does not declare permissions.connector (or hostConnectorAccess); calls reject with NOT_PERMITTED', }, { pattern: /\bspeech\??\.transcribe\s*\(/u, granted: (access) => access.device.includes('microphone'), - message: 'calls speech.transcribe but miniapp.json does not declare deviceAccess ["microphone"]; every call rejects with not_permitted', + message: + 'calls speech.transcribe but miniapp.json does not declare permissions.device ["microphone"] (or deviceAccess ["microphone"]); every call rejects with NOT_PERMITTED', }, { // Any identifier ending in host/Host, such as `miniAppHost`; a bare `navigation` is a router's. pattern: /\b\w*[Hh]ost\??\.navigation\??\.(?:getState|subscribe)\s*(?:\?\.)?\s*\(/u, granted: (access) => access.host.includes('navigation.read'), - message: 'reads Host navigation but miniapp.json does not declare hostAccess ["navigation.read"]; the calls reject with not_permitted', + message: + 'reads Host navigation but miniapp.json does not declare permissions.host ["navigation.read"] (or hostAccess ["navigation.read"]); the calls reject with NOT_PERMITTED', + }, +]; + +const DEPRECATED_API_RULES = [ + { pattern: /\bwindow\s*\.\s*mcode\b|\bmcode\??\.miniapp\b/u, replacement: 'window.miniapp' }, + { pattern: /\bminiapp\??\.message\??\.append\s*\(/u, replacement: 'host.composer.append' }, + { pattern: new RegExp(String.raw`${AGENT_PREFIX}agents\s*\(`, 'u'), replacement: 'agent.list' }, + { pattern: new RegExp(String.raw`${AGENT_PREFIX}sessions\s*\(`, 'u'), replacement: 'session.list' }, + { pattern: new RegExp(String.raw`${AGENT_PREFIX}session\s*\(`, 'u'), replacement: 'session.get' }, + { pattern: new RegExp(String.raw`${AGENT_PREFIX}observe\s*\(`, 'u'), replacement: 'session.observe' }, + { + pattern: /\bcontext\??\.hostConnector\b|\bcapabilities\??\.has\s*\(\s*['"]hostConnector(?:\.(?:list|call))?['"]\s*\)/u, + replacement: 'context.connector', + }, +]; + +const CURRENT_ONLY_API_RULES = [ + { pattern: /\bwindow\s*\.\s*miniapp\b/u, name: 'window.miniapp' }, + { pattern: new RegExp(String.raw`${SESSION_PREFIX}(?:list|get|observe)\s*\(`, 'u'), name: 'session.*' }, + { pattern: new RegExp(String.raw`${AGENT_PREFIX}list\s*\(`, 'u'), name: 'agent.list' }, + { pattern: /\b\w*[Hh]ost\??\.composer\??\.append\s*\(/u, name: 'host.composer.append' }, + { + pattern: /\bcontext\??\.connector\b|\bcapabilities\??\.has\s*\(\s*['"]connector(?:\.(?:list|call))?['"]\s*\)/u, + name: 'context.connector', }, ]; +const COMPATIBILITY_FALLBACK = /\bwindow\s*\.\s*mcode\b|\bmcode\??\.miniapp\b|\bcapabilities\??\.has\s*\(/u; +const REMOVED_ERROR_CODES = ['TOOL_NOT_PERMITTED', 'CONNECTOR_NOT_PERMITTED']; + const GET_USER_MEDIA = /\bgetUserMedia\s*\(/gu; const NOTIFICATION = /\bnew\s+(?:window\.)?Notification\s*\(|\bNotification\s*\.\s*requestPermission\s*\(/u; const DEVICE_ORDER = ['microphone', 'camera', 'notifications']; const FALSE_LIKE = new Set(['false', '!1', '0', 'null', 'undefined']); const EITHER_MEDIA_DEVICE = '"microphone" or "camera"'; -export async function checkAccessUsage(report, { packageDir, roots, access, minimum }) { +export async function checkAccessUsage(report, { packageDir, clientRoots = [], nodeRoots = [], access, minimum }) { const gated = minimum !== undefined && compareVersions(minimum, BROWSER_PERMISSION_GATE_VERSION) >= 0; - for (const relativePath of await collectPayloadFiles(packageDir, roots, SCANNED_EXTENSIONS)) { - const source = await readText(path.join(packageDir, ...relativePath.split('/'))); - if (source === undefined) continue; - checkAgentUsage(report, source, access.agent, relativePath); + const targetsCurrentApi = minimum !== undefined && compareVersions(minimum, MINIAPP_API_VERSION) >= 0; + + const files = await collectPayloadFiles(packageDir, [...clientRoots, ...nodeRoots], SCANNED_EXTENSIONS); + for (const relativePath of files) { + const raw = await readText(path.join(packageDir, ...relativePath.split('/'))); + if (raw === undefined) continue; + const isHtml = HTML_EXTENSIONS.has(path.extname(relativePath).toLowerCase()); + const code = stripCommentsAndRegexes(isHtml ? parseHtmlScriptsAndHandlers(raw).executableCode : raw); + + checkAgentAndSessionUsage(report, code, access, relativePath); for (const rule of API_RULES) { - if (!rule.granted(access) && rule.pattern.test(source)) report.error('ACCESS_UNDECLARED', rule.message, relativePath); + if (!rule.granted(access) && rule.pattern.test(code)) report.error('ACCESS_UNDECLARED', rule.message, relativePath); + } + checkBrowserPermissions(report, code, access.device, relativePath, gated); + + if (targetsCurrentApi) { + checkDeprecatedApis(report, code, relativePath); + checkRemovedErrorCodes(report, code, relativePath); + } else if (!COMPATIBILITY_FALLBACK.test(code)) { + checkMissingCurrentEngines(report, code, relativePath); } - checkBrowserPermissions(report, source, access.device, relativePath, gated); } } +function checkDeprecatedApis(report, code, relativePath) { + const replacements = DEPRECATED_API_RULES.filter((rule) => rule.pattern.test(code)).map((rule) => rule.replacement); + if (replacements.length === 0) return; + const unique = [...new Set(replacements)]; + report.warning( + 'DEPRECATED_API', + `targets MiniMax Code ${MINIAPP_API_VERSION} or later but still uses deprecated Mini App APIs; switch to ${listOf(unique)}`, + relativePath, + ); +} + +function checkRemovedErrorCodes(report, code, relativePath) { + const found = REMOVED_ERROR_CODES.filter((name) => new RegExp(String.raw`\b${name}\b`, 'u').test(code)); + if (found.length === 0) return; + report.warning( + 'REMOVED_ERROR_CODE', + `checks removed error code ${listOf(found.map((c) => `"${c}"`))}; MiniMax Code ${MINIAPP_API_VERSION} and later reject switched-off or denied grants with "PERMISSION_DENIED" (and undeclared grants with "NOT_PERMITTED")`, + relativePath, + ); +} + +function checkMissingCurrentEngines(report, code, relativePath) { + const used = CURRENT_ONLY_API_RULES.filter((rule) => rule.pattern.test(code)).map((rule) => rule.name); + if (used.length === 0) return; + report.warning( + 'ENGINES_MIN_VERSION_MISSING', + `uses MiniMax Code ${MINIAPP_API_VERSION} APIs (${listOf(used)}) without engines.mcode ">=${MINIAPP_API_VERSION}" or a compatibility fallback; clients before ${MINIAPP_API_VERSION} install the package without those APIs`, + relativePath, + ); +} + // The devices each getUserMedia call asks for: its literal constraints when it has them, or // undefined when the request cannot be read (not an object literal, or one naming neither key). function requestedMediaDevices(source) { @@ -71,25 +166,41 @@ function objectLiteralAt(source, start) { while (/\s/u.test(source[index] ?? '')) index += 1; if (source[index] !== '{') return undefined; let depth = 0; + const templates = []; for (let end = index; end < source.length; end += 1) { const char = source[end]; - if (char === '"' || char === "'" || char === '`') { - end = stringEnd(source, end); + if (char === '"' || char === "'") { + end = quotedEnd(source, end); if (end === -1) return undefined; - } else if (char === '{') depth += 1; - else if (char === '}' && (depth -= 1) === 0) return source.slice(index, end + 1); + } else if (char === '`') { + const chunk = readTemplateChunk(source, end + 1); + end = chunk.end; + if (chunk.openedExpression) { + templates.push(0); + depth += 1; + } + } else if (char === '{') { + if (templates.length > 0) templates[templates.length - 1] += 1; + depth += 1; + } else if (char === '}') { + if (templates.length > 0 && templates.at(-1) === 0) { + templates.pop(); + depth -= 1; + const chunk = readTemplateChunk(source, end + 1); + end = chunk.end; + if (chunk.openedExpression) { + templates.push(0); + depth += 1; + } + } else { + if (templates.length > 0) templates[templates.length - 1] -= 1; + if ((depth -= 1) === 0) return source.slice(index, end + 1); + } + } } return undefined; } -function stringEnd(source, start) { - for (let index = start + 1; index < source.length; index += 1) { - if (source[index] === '\\') index += 1; - else if (source[index] === source[start]) return index; - } - return -1; -} - // `{ audio: true }`, `{ "audio": !0 }`, and shorthand `{ audio }` ask for the device; false-like // values do not. Undefined when the literal does not name the key. function keyRequest(literal, key) { @@ -114,13 +225,13 @@ function checkBrowserPermissions(report, source, granted, relativePath, gated) { missing.push(EITHER_MEDIA_DEVICE); } if (missing.length === 0) return; - const base = `uses browser permissions that need deviceAccess ${listOf(missing)}; MiniMax Code ${BROWSER_PERMISSION_GATE_VERSION} and later deny them`; + const base = `uses browser permissions that need permissions.device ${listOf(missing)} (or deviceAccess); MiniMax Code ${BROWSER_PERMISSION_GATE_VERSION} and later deny them`; if (gated) { report.error('ACCESS_UNDECLARED', `${base}, and this package needs ${BROWSER_PERMISSION_GATE_VERSION} or later`, relativePath); } else { report.warning( 'ACCESS_UNDECLARED', - `${base}; they work only on clients before ${BROWSER_PERMISSION_GATE_VERSION}. Declaring deviceAccess raises the package's minimum client version (docs/package-contract.md)`, + `${base}; they work only on clients before ${BROWSER_PERMISSION_GATE_VERSION}. Declaring permissions.device raises the package's minimum client version (docs/package-contract.md)`, relativePath, ); } @@ -131,19 +242,21 @@ function listOf(items) { return `${items.slice(0, -1).join(', ')}, and ${items.at(-1)}`; } -// One diagnostic per file, naming every agentAccess value the file's calls need and lack. -function checkAgentUsage(report, source, granted, relativePath) { +// One diagnostic per file, naming every Agent/session grant the file's calls need and lack. +function checkAgentAndSessionUsage(report, source, access, relativePath) { + const hasRun = access.agent.includes('run'); + const hasRead = (access.session ?? []).includes('read'); const missing = []; - if (!granted.includes('session.run') && AGENT_RUN_CALL.test(source)) missing.push('"session.run"'); - if (!granted.includes('session.read') && USER_SESSION_CALL.test(source)) missing.push('"session.read"'); - // Reading or observing the Mini App's own sessions works with either value. - if (missing.length === 0 && granted.length === 0 && AGENT_OWN_SESSION_CALL.test(source)) { - missing.push('"session.run" or "session.read"'); + if (!hasRun && AGENT_RUN_CALL.test(source)) missing.push('permissions.agent ["run"]'); + if (!hasRead && USER_SESSION_CALL.test(source)) missing.push('permissions.session ["read"]'); + // Reading or observing the Mini App's own sessions works with either grant. + if (missing.length === 0 && !hasRun && !hasRead && OWN_SESSION_CALL.test(source)) { + missing.push('permissions.agent ["run"] or permissions.session ["read"]'); } if (missing.length === 0) return; report.error( 'ACCESS_UNDECLARED', - `calls Agent APIs that need agentAccess ${missing.join(' and ')}; without it context.agent is absent or the calls reject with not_permitted`, + `calls Agent/session APIs that need ${missing.join(' and ')} (or legacy agentAccess); without it calls reject with NOT_PERMITTED`, relativePath, ); } diff --git a/test/client.test.mjs b/test/client.test.mjs new file mode 100644 index 00000000..1d31cd86 --- /dev/null +++ b/test/client.test.mjs @@ -0,0 +1,63 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdir, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { checkClient } from '../scripts/lib/rules/client.mjs'; +import { createReport } from '../scripts/lib/report.mjs'; +import { codes, copyExample, makeTmpRoot } from './helpers.mjs'; + +const CLIENT_ROOTS = ['miniapp/client']; + +async function run(files) { + const root = await makeTmpRoot(); + const { dir } = await copyExample(root); + for (const [relativePath, source] of Object.entries(files)) { + const file = path.join(dir, ...relativePath.split('/')); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, source); + } + const report = createReport(); + await checkClient(report, { packageDir: dir, clientRoots: CLIENT_ROOTS }); + return report.diagnostics; +} + +test('client: classic scripts declaring a top-level miniapp binding are errors', async () => { + for (const inline of [ + '<script>const miniapp = window.miniapp;</script>\n', + '<script type="text/javascript">let miniapp;</script>\n', + '<script>class miniapp {}</script>\n', + '<script>function miniapp() {}</script>\n', + '<script>async function miniapp() {}</script>\n', + '<script>function* miniapp() {}</script>\n', + '<script>const { miniapp } = window;</script>\n', + '<script>const marker = "<!-- -->"; const miniapp = window.miniapp;</script>\n', + '<script>const tpl = `${"`"}`; function miniapp() {}</script>\n', + ]) { + const diagnostics = await run({ 'miniapp/client/index.html': inline }); + assert.deepEqual(codes(diagnostics), ['CLIENT_GLOBAL_MINIAPP'], inline); + assert.equal(diagnostics[0].level, 'error'); + assert.equal(diagnostics[0].path, 'miniapp/client/index.html'); + } + + const external = await run({ + 'miniapp/client/index.html': '<script src="./app.js"></script>\n', + 'miniapp/client/app.js': 'const miniapp = window.miniapp;\n', + }); + assert.deepEqual(codes(external), ['CLIENT_GLOBAL_MINIAPP']); + assert.equal(external[0].path, 'miniapp/client/app.js'); +}); + +test('client: module scripts, var bindings, named function expressions, and inner scopes pass', async () => { + for (const valid of [ + '<script type="module">const miniapp = window.miniapp;</script>\n', + '<script>var miniapp = window.miniapp;</script>\n', + '<script>"use strict";\nvar miniapp;</script>\n', + '<script>var miniapp = window.miniapp; const fn = function miniapp() {};</script>\n', + '<script>(function () { const re = /\\}/; const miniapp = window.miniapp; })();</script>\n', + '<script>function init() { const miniapp = window.miniapp; }</script>\n', + '<script type="application/json">{"miniapp": true}</script>\n', + '<!-- <script>const miniapp = 1;</script> -->\n', + ]) { + assert.deepEqual(await run({ 'miniapp/client/index.html': valid }), [], valid); + } +}); diff --git a/test/files.test.mjs b/test/files.test.mjs index c86458ba..ae8dcf0a 100644 --- a/test/files.test.mjs +++ b/test/files.test.mjs @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdir, symlink, writeFile } from 'node:fs/promises'; +import { mkdir, stat, symlink, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { checkFiles } from '../scripts/lib/rules/files.mjs'; import { createReport } from '../scripts/lib/report.mjs'; @@ -53,7 +53,15 @@ test('files: a package root that is itself a symlink is rejected before walking' assert.deepEqual(codes(diagnostics), ['PACKAGE_ROOT_SYMLINK']); }); -test('files: two paths that differ only in letter case collide', async () => { +async function isCaseSensitiveFs() { + const probe = await makeTmpRoot(); + await writeFile(path.join(probe, 'probe'), ''); + const insensitive = await stat(path.join(probe, 'PROBE')).then(() => true, () => false); + return !insensitive; +} + +test('files: two paths that differ only in letter case collide', async (t) => { + if (!(await isCaseSensitiveFs())) return t.skip('temp directory is case-insensitive'); const diagnostics = await run(async (dir) => { await writeFile(path.join(dir, 'Readme.md'), ''); await mkdir(path.join(dir, 'docs'), { recursive: true }); @@ -63,7 +71,8 @@ test('files: two paths that differ only in letter case collide', async () => { assert.deepEqual(codes(diagnostics).sort(), ['PATH_CASE_COLLISION', 'PATH_CASE_COLLISION']); }); -test('files: a directory and a file that differ only in letter case collide', async () => { +test('files: a directory and a file that differ only in letter case collide', async (t) => { + if (!(await isCaseSensitiveFs())) return t.skip('temp directory is case-insensitive'); const diagnostics = await run(async (dir) => { await mkdir(path.join(dir, 'Docs'), { recursive: true }); await writeFile(path.join(dir, 'docs'), ''); diff --git a/test/miniapp.test.mjs b/test/miniapp.test.mjs index be2c6534..82017d2d 100644 --- a/test/miniapp.test.mjs +++ b/test/miniapp.test.mjs @@ -26,7 +26,7 @@ test('miniapp: baseline passes and resolves entry and roots', async () => { nodeRoots: ['miniapp/node'], clientRoots: ['miniapp/client'], features: [], - access: { agent: [], tool: false, device: [], host: [] }, + access: { agent: [], session: [], tool: false, device: [], host: [], connector: [] }, }); }); @@ -80,10 +80,14 @@ test('miniapp: mcpEndpoints shape and uniqueness', async () => { assert.deepEqual(codes(badServer.report.diagnostics), ['MINIAPP_MCP_ENDPOINT_INVALID']); }); -test('miniapp: hostConnectorAccess is validated for shape and reported as unverified', async () => { +test('miniapp: hostConnectorAccess is validated for shape and reported as unverified when non-empty', async () => { const ok = await run((m) => { m.hostConnectorAccess = { providers: ['notion'] }; return m; }); assert.deepEqual(codes(ok.report.diagnostics), ['HOST_CONNECTOR_UNVERIFIED']); assert.equal(ok.report.diagnostics[0].level, 'warning'); + assert.deepEqual(ok.resolved.access.connector, ['notion']); + const empty = await run((m) => { m.hostConnectorAccess = { providers: [] }; return m; }); + assert.deepEqual(empty.report.diagnostics, []); + assert.deepEqual(empty.resolved.access.connector, []); const bad = await run((m) => { m.hostConnectorAccess = { providers: ['Bad!'] }; return m; }); assert.deepEqual(codes(bad.report.diagnostics), ['MINIAPP_HOST_CONNECTOR_INVALID']); }); @@ -245,11 +249,147 @@ test('miniapp: hostAccess allows only "navigation.read", reports the feature, an } }); -test('miniapp: access lists only the valid agentAccess values', async () => { +test('miniapp: access normalizes valid legacy agentAccess values into agent and session grants', async () => { const both = await run((m) => { m.agentAccess = ['session.read', 'session.run']; return m; }); - assert.deepEqual(both.resolved.access.agent, ['session.read', 'session.run']); + assert.deepEqual(both.resolved.access.agent, ['run']); + assert.deepEqual(both.resolved.access.session, ['read']); const bad = await run((m) => { m.agentAccess = ['session.run', 'session.write']; return m; }); assert.deepEqual(bad.resolved.access.agent, []); + assert.deepEqual(bad.resolved.access.session, []); +}); + +test('miniapp: permissions accepts all six groups, reports the feature, and normalizes grants', async () => { + const full = await run((m) => { + m.permissions = { + agent: ['run'], + session: ['read'], + tool: ['call'], + device: ['notifications', 'microphone', 'camera'], + host: ['navigation.read'], + connector: ['notion', 'slack'], + }; + return m; + }); + assert.deepEqual(codes(full.report.diagnostics), ['HOST_CONNECTOR_UNVERIFIED']); + assert.equal(full.report.diagnostics[0].level, 'warning'); + assert.deepEqual(full.resolved.features, ['permissions']); + assert.deepEqual(full.resolved.access, { + agent: ['run'], + session: ['read'], + tool: true, + device: ['camera', 'microphone', 'notifications'], + host: ['navigation.read'], + connector: ['notion', 'slack'], + }); + + const emptyGroups = await run((m) => { + m.permissions = { agent: [], connector: [] }; + return m; + }); + assert.deepEqual(emptyGroups.report.diagnostics, []); + assert.deepEqual(emptyGroups.resolved.features, ['permissions']); + assert.deepEqual(emptyGroups.resolved.access, { + agent: [], + session: [], + tool: false, + device: [], + host: [], + connector: [], + }); +}); + +test('miniapp: permissions rejects non-objects, unknown groups, foreign items, duplicates, and mixing with legacy fields', async () => { + const badPermissions = [ + null, + [], + 'all', + { filesystem: ['read'] }, + { agent: 'run' }, + { agent: ['session.run'] }, + { session: ['run'] }, + { tool: ['list'] }, + { device: ['camera', 'camera'] }, + { host: ['ui.read'] }, + { connector: { providers: ['notion'] } }, + { connector: ['Bad!'] }, + { connector: ['notion', 'notion'] }, + ]; + for (const permissions of badPermissions) { + const bad = await run((m) => { m.permissions = permissions; return m; }); + assert.deepEqual(codes(bad.report.diagnostics), ['MINIAPP_PERMISSIONS_INVALID'], JSON.stringify(permissions)); + } + + for (const [legacyField, legacyValue] of [ + ['agentAccess', ['session.run']], + ['toolAccess', ['call']], + ['deviceAccess', ['microphone']], + ['hostAccess', ['navigation.read']], + ['hostConnectorAccess', { providers: ['notion'] }], + ]) { + const mixed = await run((m) => { + m.permissions = { agent: ['run'] }; + m[legacyField] = legacyValue; + return m; + }); + assert.deepEqual(codes(mixed.report.diagnostics), ['MINIAPP_PERMISSIONS_INVALID'], legacyField); + } +}); + +test('miniapp: surface.widget accepts valid kind/size pairs and reports the feature', async () => { + for (const kind of ['display', 'interactive']) { + for (const size of ['small', 'medium']) { + const ok = await run((m) => { m.surface.widget = { kind, size }; return m; }); + assert.deepEqual(ok.report.diagnostics, [], `${kind}/${size}`); + assert.deepEqual(ok.resolved.features, ['surface.widget']); + } + } + for (const widget of [null, [], {}, { kind: 'display' }, { kind: 'display', size: 'large' }, { kind: 'card', size: 'small' }, { kind: 'display', size: 'small', extra: true }]) { + const bad = await run((m) => { m.surface.widget = widget; return m; }); + assert.deepEqual(codes(bad.report.diagnostics), ['MINIAPP_SURFACE_INVALID'], JSON.stringify(widget)); + } +}); + +test('miniapp: fileHandlers validates handlers, paths, reserved routes, and extension limits', async () => { + const ok = await run((m) => { + m.fileHandlers = [ + { id: 'model-3d', path: 'viewer', extensions: ['.stl', '.step'] }, + { id: 'mesh', path: '/mesh/', extensions: ['.obj'] }, + ]; + return m; + }); + assert.deepEqual(ok.report.diagnostics, []); + assert.deepEqual(ok.resolved.features, ['fileHandlers']); + + const badHandlers = [ + [], + 'viewer', + Array.from({ length: 257 }, (_v, i) => ({ id: `h-${i}`, path: '/v', extensions: [`.e${i}`] })), + [{ id: 'model', path: '/v', extensions: ['.stl'], extra: true }], + [{ id: 'Bad_Id', path: '/v', extensions: ['.stl'] }], + [{ id: 'dup', path: '/v', extensions: ['.stl'] }, { id: 'dup', path: '/w', extensions: ['.obj'] }], + [{ id: 'empty-ext', path: '/v', extensions: [] }], + [{ id: 'no-dot', path: '/v', extensions: ['stl'] }], + [{ id: 'upper', path: '/v', extensions: ['.STL'] }], + [{ id: 'dup-ext-a', path: '/v', extensions: ['.stl'] }, { id: 'dup-ext-b', path: '/w', extensions: ['.stl'] }], + [{ id: 'too-many-ext', path: '/v', extensions: Array.from({ length: 257 }, (_v, i) => `.e${i}`) }], + [ + { id: 'half-a', path: '/v', extensions: Array.from({ length: 256 }, (_v, i) => `.a${i}`) }, + { id: 'half-b', path: '/w', extensions: Array.from({ length: 256 }, (_v, i) => `.b${i}`) }, + { id: 'over', path: '/x', extensions: ['.c0'] }, + ], + ]; + for (const fileHandlers of badHandlers) { + const bad = await run((m) => { m.fileHandlers = fileHandlers; return m; }); + assert.deepEqual(codes(bad.report.diagnostics), ['MINIAPP_FILE_HANDLERS_INVALID'], JSON.stringify(fileHandlers).slice(0, 80)); + } + + for (const route of ['https://x/y', '/v?x=1', '/a/../b', `/${'a'.repeat(4096)}`, '/v\u0000']) { + const badRoute = await run((m) => { m.fileHandlers = [{ id: 'model', path: route, extensions: ['.stl'] }]; return m; }); + assert.deepEqual(codes(badRoute.report.diagnostics), ['MINIAPP_ROUTE_PATH_INVALID'], route.slice(0, 40)); + } + + const reserved = await run((m) => { m.fileHandlers = [{ id: 'model', path: '/__mavis/open', extensions: ['.stl'] }]; return m; }); + assert.deepEqual(codes(reserved.report.diagnostics), ['MINIAPP_ROUTE_RESERVED']); }); test('miniapp: unknown field and wrong schemaVersion', async () => { diff --git a/test/package.test.mjs b/test/package.test.mjs index e3668510..36e2d918 100644 --- a/test/package.test.mjs +++ b/test/package.test.mjs @@ -96,3 +96,23 @@ test('package: an engines bound decides the minimum version for both the README const [readme] = diagnostics.filter((d) => d.code === 'README_MIN_VERSION_MISSING'); assert.match(readme.message, /MiniMax Code 3\.2\.0/u); }); + +test('package: a 3.1.20 package with permissions, engines, and window.miniapp passes cleanly', async () => { + const root = await makeTmpRoot(); + const { dir } = await copyExample(root); + await editJson(path.join(dir, 'miniapp', 'miniapp.json'), (m) => ({ + ...m, + permissions: { agent: ['run'], session: ['read'] }, + engines: { mcode: '>=3.1.20' }, + })); + await writeFile( + path.join(dir, 'miniapp', 'client', 'app.js'), + 'export const go = async () => { await window.miniapp.agent.list(); return window.miniapp.session.list(); };\n', + ); + const readme = path.join(dir, 'README.md'); + await writeFile(readme, (await readFile(readme, 'utf8')).replace('MiniMax Code 3.0.73', 'MiniMax Code 3.1.20')); + assert.deepEqual(await validatePackage(dir), []); + + await writeFile(path.join(dir, 'miniapp', 'client', 'index.html'), '<script>const miniapp = window.miniapp;</script>\n'); + assert.deepEqual(codes(await validatePackage(dir)), ['CLIENT_GLOBAL_MINIAPP']); +}); diff --git a/test/paths.test.mjs b/test/paths.test.mjs index 88605015..f4a2a9c8 100644 --- a/test/paths.test.mjs +++ b/test/paths.test.mjs @@ -5,6 +5,7 @@ import { normalizePluginPath, normalizeRoutePath, portablePathIssue, + registerPortablePrefix, } from '../scripts/lib/paths.mjs'; test('normalizePluginPath strips ./ and rejects non-canonical input', () => { @@ -42,3 +43,11 @@ test('isCoveredBy matches a root itself and its descendants only', () => { assert.equal(isCoveredBy('miniapp/node', ['miniapp/node']), true); assert.equal(isCoveredBy('miniapp/nodejs/x.mjs', ['miniapp/node']), false); }); + +test('registerPortablePrefix flags paths or prefixes that differ only in letter case', () => { + const prefixes = new Map(); + assert.equal(registerPortablePrefix(prefixes, 'README.md'), undefined); + assert.deepEqual(registerPortablePrefix(prefixes, 'Readme.md'), ['README.md', 'Readme.md']); + assert.equal(registerPortablePrefix(prefixes, 'Docs/guide.md'), undefined); + assert.deepEqual(registerPortablePrefix(prefixes, 'docs/other.md'), ['Docs', 'docs']); +}); diff --git a/test/readme.test.mjs b/test/readme.test.mjs index d43614fc..620e1a03 100644 --- a/test/readme.test.mjs +++ b/test/readme.test.mjs @@ -70,6 +70,9 @@ test('readme: each feature names the first release with installers for both plat [['agentAccess.session.read', 'toolAccess', 'deviceAccess', 'engines'], '3.1.6', ['3.1.4-preview.4773', '3.1.5']], [['deviceAccess.camera', 'deviceAccess.notifications'], '3.1.9', ['3.1.8']], [['hostAccess'], '3.1.11', ['3.1.10', '3.1.11-preview.4900']], + [['surface.widget'], '3.1.15', ['3.1.14']], + [['fileHandlers'], '3.1.18', ['3.1.17']], + [['permissions'], '3.1.20', ['3.1.19', '3.1.20-preview.1']], ]; for (const [features, minimum, tooOld] of cases) { for (const feature of features) { diff --git a/test/usage.test.mjs b/test/usage.test.mjs index c848cd61..ef08a3e4 100644 --- a/test/usage.test.mjs +++ b/test/usage.test.mjs @@ -6,8 +6,9 @@ import { checkAccessUsage } from '../scripts/lib/rules/usage.mjs'; import { createReport } from '../scripts/lib/report.mjs'; import { codes, copyExample, makeTmpRoot } from './helpers.mjs'; -const NONE = { agent: [], tool: false, device: [], host: [] }; -const ROOTS = ['miniapp/client', 'miniapp/node']; +const NONE = { agent: [], session: [], tool: false, device: [], host: [], connector: [] }; +const CLIENT_ROOTS = ['miniapp/client']; +const NODE_ROOTS = ['miniapp/node']; async function run(files, { access = NONE, minimum } = {}) { const root = await makeTmpRoot(); @@ -18,7 +19,7 @@ async function run(files, { access = NONE, minimum } = {}) { await writeFile(file, source); } const report = createReport(); - await checkAccessUsage(report, { packageDir: dir, roots: ROOTS, access, minimum }); + await checkAccessUsage(report, { packageDir: dir, clientRoots: CLIENT_ROOTS, nodeRoots: NODE_ROOTS, access, minimum }); return report.diagnostics; } @@ -26,74 +27,125 @@ test('usage: the example declares nothing and calls nothing', async () => { assert.deepEqual(await run({}), []); }); -test('usage: Agent calls without agentAccess are errors on the page and in Node', async () => { - const page = await run({ 'miniapp/client/app.js': 'await window.mcode?.miniapp?.agent?.run({ text });\n' }); - assert.deepEqual(codes(page, 'error'), ['ACCESS_UNDECLARED']); - assert.match(page[0].message, /agentAccess/u); - const node = await run({ 'miniapp/node/agent.mjs': 'export const go = (context) => context.agent.create({});\n' }); +test('usage: Agent calls without permissions.agent ["run"] are errors on the page and in Node', async () => { + for (const source of [ + 'await window.miniapp?.agent?.run({ text });\n', + 'await window.miniapp.agent.list();\n', + 'await window.mcode?.miniapp?.agent?.run({ text });\n', + ]) { + const page = await run({ 'miniapp/client/app.js': source }, { minimum: '3.1.20' }); + assert.deepEqual(codes(page, 'error'), ['ACCESS_UNDECLARED'], source); + assert.match(page[0].message, /permissions\.agent \["run"\]/u); + } + const node = await run({ 'miniapp/node/agent.mjs': 'export const go = (context) => context.agent.create({});\n' }, { minimum: '3.1.20' }); assert.deepEqual(codes(node, 'error'), ['ACCESS_UNDECLARED']); - assert.deepEqual(await run({ 'miniapp/node/agent.mjs': 'export const go = (context) => context.agent.run({ text: "x" });\n' }, { access: { ...NONE, agent: ['session.run'] } }), []); + assert.deepEqual( + await run( + { 'miniapp/node/agent.mjs': 'export const go = async (context) => { await context.agent.list(); return context.agent.run({ text: "x" }); };\n' }, + { access: { ...NONE, agent: ['run'] }, minimum: '3.1.20' }, + ), + [], + ); }); -test('usage: listing sessions, observing every session, and reading the page chat need session.read', async () => { - const runOnly = { ...NONE, agent: ['session.run'] }; +test('usage: listing sessions, observing every session, and reading the page chat need permissions.session ["read"]', async () => { + const runOnly = { ...NONE, agent: ['run'] }; for (const source of [ + 'const { sessions } = await miniapp.session.list();\n', + 'const { sessions } = await context.session.list();\n', + 'miniapp.session.observe({ all: true }, { onEvent });\n', + 'context.session?.observe({all:!0},{onEvent:e});\n', + 'const chat = await window.miniapp.session.get();\n', 'const { sessions } = await agent.sessions();\n', 'agent.observe({ all: true }, { onEvent });\n', - 'agent?.observe({all:!0},{onEvent:e});\n', 'const chat = await window.mcode.miniapp.agent.session();\n', ]) { - const diagnostics = await run({ 'miniapp/client/app.js': source }, { access: runOnly }); + const diagnostics = await run({ 'miniapp/client/app.js': source }, { access: runOnly, minimum: '3.1.20' }); assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED'], source); - assert.match(diagnostics[0].message, /session\.read/u); - assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { access: { ...NONE, agent: ['session.read', 'session.run'] } }), [], source); + assert.match(diagnostics[0].message, /permissions\.session \["read"\]/u); + assert.deepEqual( + await run({ 'miniapp/client/app.js': source }, { access: { ...NONE, agent: ['run'], session: ['read'] }, minimum: '3.1.20' }).then((d) => + codes(d, 'error'), + ), + [], + source, + ); } - for (const source of ['agent.observe({ sessionId }, { onEvent });\n', 'await agent.session(ownSessionId);\n']) { - assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { access: runOnly }), [], source); + for (const source of [ + 'miniapp.session.observe({ sessionId }, { onEvent });\n', + 'await miniapp.session.get(ownSessionId);\n', + 'await context.session.get(ownSessionId);\n', + 'agent.observe({ sessionId }, { onEvent });\n', + 'await agent.session(ownSessionId);\n', + ]) { + assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { access: runOnly, minimum: '3.1.20' }).then((d) => codes(d, 'error')), [], source); } + // Unrelated local `session.get(key)` (e.g. a Map) must never be flagged. + assert.deepEqual(await run({ 'miniapp/node/cache.mjs': 'const session = new Map();\nexport const read = (id) => session.get(id);\n' }), []); +}); + +test('usage: agent.cancel needs no agent:run grant so read-only session observers can cancel cleanly', async () => { + const source = [ + 'window.miniapp.session.observe({ all: true, requestId: "obs" }, { onEvent });', + 'window.miniapp.agent.cancel("obs");', + ].join('\n'); + assert.deepEqual( + await run({ 'miniapp/client/app.js': `${source}\n` }, { access: { ...NONE, session: ['read'] }, minimum: '3.1.20' }), + [], + ); }); -test('usage: running turns needs session.run even when session.read is declared', async () => { +test('usage: running turns needs permissions.agent ["run"] even when permissions.session ["read"] is declared', async () => { const diagnostics = await run( { 'miniapp/node/agent.mjs': 'export const go = (context) => context.agent.run({ text: "x" });\n' }, - { access: { ...NONE, agent: ['session.read'] } }, + { access: { ...NONE, session: ['read'] }, minimum: '3.1.20' }, ); assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED']); - assert.match(diagnostics[0].message, /"session\.run"/u); + assert.match(diagnostics[0].message, /permissions\.agent \["run"\]/u); }); -test('usage: one Agent diagnostic per file names every missing agentAccess value', async () => { - const pageChat = await run({ 'miniapp/client/app.js': 'await window.mcode.miniapp.agent.session();\n' }); +test('usage: one Agent/session diagnostic per file names every missing grant', async () => { + const pageChat = await run({ 'miniapp/client/app.js': 'await window.miniapp.session.get();\n' }, { minimum: '3.1.20' }); assert.equal(pageChat.length, 1); - assert.match(pageChat[0].message, /"session\.read"/u); - const both = await run({ 'miniapp/client/app.js': 'await miniapp.agent.run({ text });\nawait miniapp.agent.sessions();\n' }); + assert.match(pageChat[0].message, /permissions\.session \["read"\]/u); + const both = await run({ 'miniapp/client/app.js': 'await miniapp.agent.run({ text });\nawait miniapp.session.list();\n' }, { minimum: '3.1.20' }); assert.equal(both.length, 1); - assert.match(both[0].message, /"session\.run" and "session\.read"/u); + assert.match(both[0].message, /permissions\.agent \["run"\] and permissions\.session \["read"\]/u); }); -test('usage: reading or observing its own sessions needs either agentAccess value', async () => { - const source = 'context.agent.observe({ sessionId }, { onEvent });\n'; - const none = await run({ 'miniapp/node/watch.mjs': source }); - assert.deepEqual(codes(none, 'error'), ['ACCESS_UNDECLARED']); - assert.match(none[0].message, /"session\.run" or "session\.read"/u); - for (const agent of [['session.run'], ['session.read']]) { - assert.deepEqual(await run({ 'miniapp/node/watch.mjs': source }, { access: { ...NONE, agent } }), [], agent[0]); +test('usage: reading or observing its own sessions needs either agent ["run"] or session ["read"]', async () => { + for (const source of ['context.session.observe({ sessionId }, { onEvent });\n', 'context.agent.observe({ sessionId }, { onEvent });\n']) { + const none = await run({ 'miniapp/node/watch.mjs': source }, { minimum: '3.1.20' }); + assert.deepEqual(codes(none, 'error'), ['ACCESS_UNDECLARED'], source); + assert.match(none[0].message, /permissions\.agent \["run"\] or permissions\.session \["read"\]/u); + assert.deepEqual(await run({ 'miniapp/node/watch.mjs': source }, { access: { ...NONE, agent: ['run'] }, minimum: '3.1.20' }).then((d) => codes(d, 'error')), []); + assert.deepEqual(await run({ 'miniapp/node/watch.mjs': source }, { access: { ...NONE, session: ['read'] }, minimum: '3.1.20' }).then((d) => codes(d, 'error')), []); } }); -test('usage: tool calls without toolAccess are errors', async () => { - for (const source of ['await context.tool.call(name, {});\n', 'const { tools } = await context.tool?.list();\n', 'await window.mcode.miniapp.tool.request([name]);\n']) { - const diagnostics = await run({ 'miniapp/node/tools.mjs': source }); +test('usage: tool and connector calls without their grants are errors', async () => { + for (const source of ['await context.tool.call(name, {});\n', 'const { tools } = await context.tool?.list();\n', 'await window.miniapp.tool.request([name]);\n']) { + const diagnostics = await run({ 'miniapp/node/tools.mjs': source }, { minimum: '3.1.20' }); + assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED'], source); + assert.match(diagnostics[0].message, /permissions\.tool/u); + assert.deepEqual(await run({ 'miniapp/node/tools.mjs': source }, { access: { ...NONE, tool: true }, minimum: '3.1.20' }), [], source); + } + for (const source of ['await context.connector.list();\n', 'await context.connector?.call(ref, {});\n', 'await context.hostConnector.list();\n']) { + const diagnostics = await run({ 'miniapp/node/connector.mjs': source }); assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED'], source); - assert.match(diagnostics[0].message, /toolAccess/u); - assert.deepEqual(await run({ 'miniapp/node/tools.mjs': source }, { access: { ...NONE, tool: true } }), [], source); + assert.match(diagnostics[0].message, /permissions\.connector/u); + assert.deepEqual( + await run({ 'miniapp/node/connector.mjs': source }, { access: { ...NONE, connector: ['notion'] } }).then((d) => codes(d, 'error')), + [], + source, + ); } }); test('usage: speech.transcribe without the microphone is an error on every version', async () => { const diagnostics = await run({ 'miniapp/client/index.html': '<script>speech.transcribe({ audio, format });</script>\n' }); assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED']); - assert.match(diagnostics[0].message, /deviceAccess/u); + assert.match(diagnostics[0].message, /permissions\.device/u); assert.deepEqual(await run({ 'miniapp/client/index.html': '<script>speech.transcribe({ audio, format });</script>\n' }, { access: { ...NONE, device: ['microphone'] } }), []); }); @@ -138,7 +190,7 @@ test('usage: getUserMedia needs the devices it asks for', async () => { } }); -test('usage: system notifications need deviceAccess "notifications"', async () => { +test('usage: system notifications need permissions.device "notifications"', async () => { for (const source of ["new Notification('Done', { body });\n", 'await Notification.requestPermission();\n']) { const anyVersion = await run({ 'miniapp/client/app.js': source }); assert.deepEqual(codes(anyVersion), ['ACCESS_UNDECLARED'], source); @@ -158,29 +210,135 @@ test('usage: one browser-permission diagnostic per file names every missing devi assert.match(diagnostics[0].message, /"microphone", "camera", and "notifications"/u); }); -test('usage: reading Host navigation needs hostAccess; Host UI state and opening entries need nothing', async () => { +test('usage: reading Host navigation needs permissions.host ["navigation.read"]; Host UI state and opening entries need nothing', async () => { for (const source of [ - 'await window.mcode?.miniapp?.host?.navigation.getState();\n', + 'await window.miniapp?.host?.navigation.getState();\n', 'host.navigation.subscribe(render, { onError });\n', 'miniAppHost.navigation.subscribe(render);\n', 'host?.navigation?.getState?.();\n', ]) { - const diagnostics = await run({ 'miniapp/client/app.js': source }); + const diagnostics = await run({ 'miniapp/client/app.js': source }, { minimum: '3.1.20' }); assert.deepEqual(codes(diagnostics, 'error'), ['ACCESS_UNDECLARED'], source); - assert.match(diagnostics[0].message, /hostAccess/u); - assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { access: { ...NONE, host: ['navigation.read'] } }), [], source); + assert.match(diagnostics[0].message, /permissions\.host/u); + assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { access: { ...NONE, host: ['navigation.read'] }, minimum: '3.1.20' }), [], source); } for (const source of ["host.navigation.open({ id: 'home' });\n", 'host.ui.subscribe(apply);\nawait host.ui.getState();\n', 'const state = navigation.getState();\n']) { - assert.deepEqual(await run({ 'miniapp/client/app.js': source }), [], source); + assert.deepEqual(await run({ 'miniapp/client/app.js': source }, { minimum: '3.1.20' }), [], source); + } +}); + +test('usage: packages targeting >=3.1.20 warn on deprecated API calls and removed error codes; <3.1.20 packages stay quiet', async () => { + const deprecatedCases = [ + ['const api = window.mcode?.miniapp;\n', /window\.miniapp/u], + ['await miniapp.message.append(text);\n', /host\.composer\.append/u], + ['await context.agent.agents();\n', /agent\.list/u], + ['await miniapp.agent.sessions();\n', /session\.list/u], + ['await context.agent.session(id);\n', /session\.get/u], + ['context.agent.observe({ sessionId }, { onEvent });\n', /session\.observe/u], + ['await context.hostConnector.list();\n', /context\.connector/u], + ]; + const fullAccess = { agent: ['run'], session: ['read'], tool: true, device: [], host: [], connector: ['notion'] }; + for (const [source, replacement] of deprecatedCases) { + const onNew = await run({ 'miniapp/node/legacy.mjs': source }, { access: fullAccess, minimum: '3.1.20' }); + assert.deepEqual(codes(onNew), ['DEPRECATED_API'], source); + assert.equal(onNew[0].level, 'warning'); + assert.match(onNew[0].message, replacement, source); + + const onOld = await run({ 'miniapp/node/legacy.mjs': source }, { access: fullAccess, minimum: '3.1.6' }); + assert.deepEqual(onOld, [], source); + } + + for (const code of ['TOOL_NOT_PERMITTED', 'CONNECTOR_NOT_PERMITTED']) { + const src = `if (err.code === '${code}') return;\n`; + const onNew = await run({ 'miniapp/node/errors.mjs': src }, { access: fullAccess, minimum: '3.1.20' }); + assert.deepEqual(codes(onNew), ['REMOVED_ERROR_CODE'], code); + assert.equal(onNew[0].level, 'warning'); + assert.match(onNew[0].message, /PERMISSION_DENIED/u); + assert.deepEqual(await run({ 'miniapp/node/errors.mjs': src }, { access: fullAccess, minimum: '3.1.6' }), [], code); } + + // Comments and regex literals mentioning old/protected names do not trigger false positives, + // including regexes after control-flow `)` or block `}`, while division after `]` or `fn()` stays code. + assert.deepEqual( + await run( + { + 'miniapp/node/comment.mjs': [ + "const quote = /'/;", + "// don't flag window.mcode.miniapp or TOOL_NOT_PERMITTED here", + 'if (ready) /context.tool.call()/.test(input);', + '{ noop(); } /window.mcode.miniapp/.test(input);', + 'const tpl = `${"inner ` backtick" /* window.mcode.miniapp */}`; // window.mcode.miniapp', + 'export const ok = [quote, tpl];', + ].join('\n'), + }, + { access: { ...NONE }, minimum: '3.1.20' }, + ), + [], + ); + + const betweenDivisions = await run( + { 'miniapp/node/math.mjs': 'const a = items[0] / 2;\ncontext.tool.call(name, {});\nconst b = calc() / 2;\n' }, + { minimum: '3.1.20' }, + ); + assert.deepEqual(codes(betweenDivisions, 'error'), ['ACCESS_UNDECLARED']); +}); + +test('usage: packages below 3.1.20 using 3.1.20 APIs warn unless they include a compatibility fallback', async () => { + const unguarded = await run({ 'miniapp/client/app.js': 'await window.miniapp.host.composer.append(text);\n' }); + assert.deepEqual(codes(unguarded), ['ENGINES_MIN_VERSION_MISSING']); + assert.equal(unguarded[0].level, 'warning'); + assert.match(unguarded[0].message, />=3\.1\.20/u); + + // With engines >=3.1.20 (or permissions), no warning. + assert.deepEqual( + await run({ 'miniapp/client/app.js': 'await window.miniapp.host.composer.append(text);\n' }, { minimum: '3.1.20' }), + [], + ); + + // With dual-version fallback or capabilities.has, no warning even below 3.1.20. + assert.deepEqual( + await run({ + 'miniapp/client/app.js': 'const api = window.miniapp ?? window.mcode?.miniapp;\nawait (api?.host?.composer?.append ?? api?.message?.append)?.(text);\n', + }), + [], + ); + assert.deepEqual( + await run( + { + 'miniapp/node/sessions.mjs': 'export const list = (c) => c.capabilities?.has("session.list") ? c.session.list() : c.agent.sessions();\n', + }, + { access: { ...NONE, session: ['read'] }, minimum: '3.1.6' }, + ), + [], + ); + // A fallback in one file does not silence an unguarded 3.1.20 call in another file. + const crossFile = await run({ + 'miniapp/client/legacy.js': 'const old = window.mcode?.miniapp;\n', + 'miniapp/client/app.js': 'await window.miniapp.host.composer.append(text);\n', + }); + assert.deepEqual(codes(crossFile), ['ENGINES_MIN_VERSION_MISSING']); + assert.equal(crossFile[0].path, 'miniapp/client/app.js'); }); -test('usage: one diagnostic per rule per file, and only payload scripts are scanned', async () => { - const repeated = await run({ 'miniapp/client/app.js': 'context.tool.call(a);\ncontext.tool.call(b);\n' }); +test('usage: one diagnostic per rule per file, HTML prose is ignored, unquoted handlers and <!-- in scripts are scanned, and only payload scripts are scanned', async () => { + const unquoted = await run( + { 'miniapp/client/index.html': '<button onclick=window.miniapp.agent.list()>Run</button>\n' }, + { minimum: '3.1.20' }, + ); + assert.deepEqual(codes(unquoted, 'error'), ['ACCESS_UNDECLARED']); + + const markerInScript = await run( + { 'miniapp/client/index.html': '<script>const s = "<!--"; window.miniapp.agent.list(); const e = "-->";</script>\n' }, + { minimum: '3.1.20' }, + ); + assert.deepEqual(codes(markerInScript, 'error'), ['ACCESS_UNDECLARED']); + + const repeated = await run({ 'miniapp/client/app.js': 'context.tool.call(a);\ncontext.tool.call(b);\n' }, { minimum: '3.1.20' }); assert.equal(repeated.length, 1); assert.equal(repeated[0].path, 'miniapp/client/app.js'); assert.deepEqual( await run({ + 'miniapp/client/index.html': '<p>Runs inside <code>window.miniapp</code>.</p>\n', 'miniapp/client/client-api.ts': '// context.tool.call(name)\n', 'miniapp/node/node_modules/lib/index.js': 'context.tool.call(name);\n', 'tests/agent.test.mjs': 'context.agent.run({ text });\n',