diff --git a/MANIFEST.in b/MANIFEST.in index f29dfedc8..48946cb84 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,6 +4,7 @@ recursive-include src * recursive-include packages/core/src *.py recursive-include apps/api/src *.py recursive-include packages/agent/skills * +include plugins/catalog.json prune packages/core/src/opendirector/_bundled prune node_modules prune dist diff --git a/README.md b/README.md index d9c619258..2b5cce048 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,7 @@ Use Chrome or Edge for MP4 export, and keep the page and editor open while rende - [Troubleshooting](docs/guides/user-guide.md#troubleshooting): Installation, generation, saving, and export issues. - [Business CLI (Chinese)](docs/guides/cli.md): Work with projects through a terminal or Agent Shell. - [DeepSeek Harness plugin](plugins/deepseek-harness/README.md): Generate media from DSH, track jobs, and continue editing in OpenDirector. +- [Optional creative plugins](docs/guides/plugins.md): Install, enable per harness, and create portable Skill packages. - [Documentation index (Chinese)](docs/README.md): Architecture, development, and validation documents. ## Community diff --git a/README.zh-CN.md b/README.zh-CN.md index d11cb383f..227de33e3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -90,6 +90,7 @@ opendirector serve - [故障排查](docs/guides/user-guide.zh-CN.md#故障排查):安装、生成、保存与导出问题。 - [业务 CLI](docs/guides/cli.md):通过终端或 Agent Shell 操作工程。 - [DeepSeek Harness 插件](plugins/deepseek-harness/README.zh-CN.md):从 DSH 生成素材、跟踪任务,再回到 OpenDirector 继续编辑。 +- [可选创作插件](docs/guides/plugins.zh-CN.md):安装插件、按引擎启用,以及制作可移植的技能包。 - [文档索引](docs/README.md):架构、开发与验证文档。 ## 社区交流 diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 7ef36a60b..7bd2952a4 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -315,10 +315,11 @@ async def runtime_models(project_id: UUID, runtime: Literal['opencode', 'codex', return await model_choices(runtime) @router.get('/skills') - async def catalog(project_id: UUID): + async def catalog(project_id: UUID, runtime: Runtime = 'default'): directory = await asyncio.to_thread(conversations.path, project_id) - found = await skills(projects.local.repository, directory) - return [{key: item[key] for key in ('name', 'description', 'source')} for item in found] + found = await skills(projects.local.repository, directory, runtime) + return [{key: item[key] for key in ('name', 'description', 'source', 'pluginId', 'displayName', 'localizedDescription') + if key in item} for item in found] @router.post('/turns/{turn_id}/stop') async def stop(project_id: UUID, turn_id: UUID, x_opendirector_session: UUID = Header()): @@ -356,9 +357,9 @@ async def turn(project_id: UUID, value: Turn, x_opendirector_session: UUID = Hea if value.runtime == 'jiuwenswarm' and value.thinking != 'auto': raise ProjectError('JiuwenSwarm 当前使用原生默认推理强度。', 409) config = await asyncio.to_thread(configs.resolve, str(value.modelId), 'agent') if spec.modelSource == 'settings' else None - available = await skills(projects.local.repository, directory) if spec.supportsSkills else [] + available = await skills(projects.local.repository, directory, value.runtime) if spec.supportsSkills else [] if set(value.skills) - {item['name'] for item in available}: - raise ProjectError('技能已失效,请重新选择。', 409) + raise ProjectError('所选技能对当前引擎已不可用,请从消息中移除并重新选择。', 409, code='agent_skill_unavailable') snapshot = await asyncio.to_thread(projects.snapshot, project_id) assets = {str(asset.id): asset for asset in snapshot.assets} for asset_id in value.assets: diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 0462c5ad1..3e3fefa7b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -10,8 +10,11 @@ from opendirector.domain.timeline_errors import timeline_error_message from opendirector.domain.creation.commands import CommandReceipt +from opendirector.domain.plugins import PLUGIN_ERRORS ENGLISH_BY_CODE = { + **{code: messages[1] for code, messages in PLUGIN_ERRORS.items()}, + 'agent_skill_unavailable': 'A selected skill is unavailable for this harness. Remove it from the message and select an available skill.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', 'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.', diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index bb31390d3..cd0fafbb6 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -27,6 +27,7 @@ from opendirector_api.agent import agent_routes from opendirector_api.library import library_routes from opendirector_api.voices import voice_routes +from opendirector_api.plugins import plugin_routes from opendirector_api.localization import localized_error from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, @@ -70,6 +71,7 @@ async def lifespan(app): app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider)) app.include_router(library_routes(creation_projects)) app.include_router(voice_routes(creation_generation.voices)) + app.include_router(plugin_routes(store.repository)) @app.exception_handler(RequestValidationError) async def invalid_request(request, error): diff --git a/apps/api/src/opendirector_api/plugins.py b/apps/api/src/opendirector_api/plugins.py new file mode 100644 index 000000000..0e781c921 --- /dev/null +++ b/apps/api/src/opendirector_api/plugins.py @@ -0,0 +1,56 @@ +"""Local plugin management; native harnesses retain execution permissions.""" +import asyncio +from typing import Annotated + +from fastapi import APIRouter, Path, Request +from pydantic import BaseModel, ConfigDict, Field + +from opendirector.agent.context import RuntimeId +from opendirector.agent.plugins import MAX_ARCHIVE_BYTES, PluginRegistry, failure +from opendirector.domain.plugins import Digest, PluginId + + +class PluginSource(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True) + source: str = Field(min_length=1, max_length=4096) + + +class PluginChange(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True) + digest: Digest + + +class PluginEnabled(PluginChange): + enabled: bool + + +def plugin_routes(repository): + router = APIRouter(prefix='/api/plugins') + registry = PluginRegistry(repository) + + @router.get('') + def catalog(): + return registry.catalog() + + @router.post('') + def install(value: PluginSource): + return registry.install(value.source) + + @router.post('/upload') + async def upload(request: Request): + content = bytearray() + async for chunk in request.stream(): + content.extend(chunk) + if len(content) > MAX_ARCHIVE_BYTES: + raise failure('plugin_too_large', 413) + return await asyncio.to_thread(registry.install_archive, bytes(content)) + + @router.put('/{plugin_id}/runtimes/{runtime}') + def enable(plugin_id: Annotated[PluginId, Path()], runtime: RuntimeId, value: PluginEnabled): + return registry.change(plugin_id, value.digest, runtime=runtime, enabled=value.enabled) + + @router.delete('/{plugin_id}') + def remove(plugin_id: Annotated[PluginId, Path()], value: PluginChange): + return registry.change(plugin_id, value.digest) + + return router diff --git a/build_backend.py b/build_backend.py index 3120b042a..9afb737b8 100644 --- a/build_backend.py +++ b/build_backend.py @@ -23,6 +23,7 @@ def prepare_resources(): shutil.rmtree(bundled) shutil.copytree(ROOT / 'dist', bundled / 'web') shutil.copytree(ROOT / 'packages/agent/skills', bundled / 'skills') + shutil.copy2(ROOT / 'plugins/catalog.json', bundled / 'plugin-catalog.json') npm_package = ROOT / 'node_modules/opencode-ai' metadata = json.loads((npm_package / 'package.json').read_text()) executable = npm_package / metadata['bin']['opencode'] diff --git a/docs/README.md b/docs/README.md index cc14c4725..ef4d2a6b0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ This directory is the entry point for the repository's shared documentation. The | [Python installation and packaging](development/packaging.md) | Installation, platform wheel builds, and isolated verification | Packaging, resource paths, or build process changes | | [Business CLI](guides/cli.md) | Querying, editing, and generating through a terminal or Agent Shell | Commands, authorization, or receipt semantics change | | [DeepSeek Harness plugin](../plugins/deepseek-harness/README.md) | Installing the DSH bundle and editing an OpenDirector project from DSH | Plugin setup, tools, or creation workflows change | +| [Optional creative plugins](guides/plugins.md) / [可选创作插件](guides/plugins.zh-CN.md) | Installing, enabling and authoring portable Skill packages | Package format, activation or examples change | | [Video model capabilities](guides/video-model-capabilities.md) | Declaring output specifications supported by a service | Configuration fields or capability integration changes | | [OpenAI Images](guides/openai-images.md) | Wiring gpt-image as an optional image service, request shape and failures | Integration fields, capability scope, or the OpenAI interface change | | [Kling video](guides/kling-video.md) ([中文](guides/kling-video.zh-CN.md)) | Optional Kling 4.0 and Flash setup, model-specific inputs, and recovery limits | Kling inputs, model declarations, or recovery behavior change | diff --git a/docs/development/i18n.md b/docs/development/i18n.md index e70dc2355..6c40522da 100644 --- a/docs/development/i18n.md +++ b/docs/development/i18n.md @@ -92,6 +92,7 @@ npm run check:i18n | --- | --- | --- | | 通用、错误 | [common.ts](../../src/i18n/messages/zh-CN/common.ts) | [common.ts](../../src/i18n/messages/en-US/common.ts) | | 设置、主题 | [settings.ts](../../src/i18n/messages/zh-CN/settings.ts) | [settings.ts](../../src/i18n/messages/en-US/settings.ts) | +| 可选插件 | [plugins.ts](../../src/i18n/messages/zh-CN/plugins.ts) | [plugins.ts](../../src/i18n/messages/en-US/plugins.ts) | | 画布与项目 | [canvas.ts](../../src/i18n/messages/zh-CN/canvas.ts) | [canvas.ts](../../src/i18n/messages/en-US/canvas.ts) | | 模型与服务 | [models.ts](../../src/i18n/messages/zh-CN/models.ts) | [models.ts](../../src/i18n/messages/en-US/models.ts) | | 画布外壳 | [canvasShell.ts](../../src/i18n/messages/zh-CN/canvasShell.ts) | [canvasShell.ts](../../src/i18n/messages/en-US/canvasShell.ts) | diff --git a/docs/development/lessons.md b/docs/development/lessons.md index b764df61d..c878d9b8f 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -99,3 +99,17 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Lesson:** [Issue #302](https://github.com/ThinkFlowLab/OpenDirector/issues/302) identified four citation groups whose Unicode private-use delimiters and internal source IDs were displayed as text. The native and persisted replies agreed byte for byte; intact text transport did not establish usable presentation. - **Check:** Verify the source metadata as well as reply text, multiple citations, split streaming markers, history reopening, copying and missing-source fallback. Preserve raw execution evidence and tool offsets; leave literal code examples unchanged and inspect both interface languages in the browser. - **Presentation follow-up:** The source-link UI in #302 initially inherited a library modal's utility classes without the corresponding CSS. Text and click checks passed while the border and close-button positioning failed. Use the supported custom renderer with repository-owned styles, and check computed styles, element geometry, long URLs, keyboard close and focus restoration as well as translated text. + +## Validate every entry returned by native discovery + +- **Trigger:** A package declares one Skill while the native loader scans resource directories recursively. +- **Evidence:** [Issue #114](https://github.com/ThinkFlowLab/OpenDirector/issues/114)'s independent review reproduced nested `SKILL.md` entries being classified as workspace skills, bypassing plugin metadata and colliding during snapshot copying. The regressions in [test_plugins.py](../../tests/test_plugins.py) cover both package rejection and unexpected native discovery results. +- **Check:** Validate all discoverable entry filenames, including case variants. Require the native catalog's exact paths and identities to match registered entries, reject duplicate names before copying, and test the discovery boundary independently of installer validation. + +## Local HTTP requests still need filesystem scope + +- **Trigger:** Accepting a local plugin path from an HTTP request. +- **Evidence:** [PR #371](https://github.com/ThinkFlowLab/OpenDirector/pull/371)'s CodeQL gate flagged unrestricted source paths. An isolated API probe read a valid package outside the backend workspace using only the public local-request header. This demonstrated missing source scope; it did not test a separate OS user or establish a remote-network exploit. +- **Follow-up:** Independent review reproduced replacing a checked resource with an outside symlink during installation, and a hard link bypassed the pathname check without a race. A normalized path check alone does not authorize the object eventually opened. +- **Entry-point follow-up:** Full CodeQL traces exposed a mixed string/bytes installer that skipped source authorization for other types; a direct `Path` call reproduced installation from outside the workspace. Separate source strings from uploaded bytes, reject unexpected types before parsing, and test the shared service boundary as well as HTTP validation. +- **Check:** Authorize the complete normalized candidate against the backend workspace and exclude project/internal storage. Use the existing descriptor/handle reader to pin every path component and reject hard links; do not resolve the package entry after checking it. Test absolute/relative traversal, sibling prefixes, control characters, replacements at the file/directory/ZIP boundaries and bilingual errors. Preserve empty package resources without relaxing execution-artifact defaults, and keep ZIP upload for packages elsewhere. diff --git a/docs/guides/plugins.md b/docs/guides/plugins.md new file mode 100644 index 000000000..78bf59202 --- /dev/null +++ b/docs/guides/plugins.md @@ -0,0 +1,102 @@ +# Optional creative plugins + +[中文](plugins.zh-CN.md) + +Plugins add optional creative Skills to the existing assistant harnesses. Open +**Settings → Plugins**, install a package, then enable the harnesses that may +use it. Every installation starts disabled. The same package can support Default, +OpenCode, Codex, Claude Code, JiuwenSwarm and DeepSeek Harness; switching harnesses +shows only the Skills enabled for that harness. + +This format is an OpenDirector Skill package, with one native Skill entry and +supporting templates or scripts. It is distinct from the [DSH integration +bundle](../../plugins/deepseek-harness/README.md), which lets external DSH call +OpenDirector. Other harnesses' native plugin formats are not accepted as packages. + +## Install and use + +1. In **Settings → Plugins**, choose **Install Creative brief**, select a ZIP, + or enter a local directory/ZIP path or public HTTPS ZIP URL. Paths refer to the + computer running the backend and must stay inside its workspace. Relative paths + start at that workspace; absolute paths inside it also work. Use a package + folder such as `plugins/my-plugin`; the workspace root, `projects/` and + `.opendirector/` are excluded. For packages in other locations, use + **Choose ZIP file**. Only install packages you trust. +2. Enable the desired harness under **Enabled harnesses**. Dependencies must be + installed at their declared versions and enabled for that same harness first. +3. Choose that harness in the assistant and open **Skills**. Select the plugin + and describe your goal in Chinese or English. Existing model configuration and + harness authentication still apply. +4. Inspect the resulting project assets. The official Creative brief example + reads project context, prepares a brief and shot outline, and publishes an + editable Markdown text asset. It does not itself request image/video generation. + +The application includes only the official discovery catalog. Example payloads +are downloaded on explicit installation; source checkouts can use the matching +local example. No optional plugin is activated or added to the default Skill +catalog automatically. Installation validates files and never runs package hooks. +Once enabled, Skill instructions and scripts use the harness's existing tools, +permissions and project business commands; installation does not grant new access. + +## Disable, remove and update + +Changes apply to subsequent turns. Already accepted turns keep their Skill +snapshot. When the enabled package set changes, a new native session starts with +the saved conversation history instead of resuming the old plugin context. +Remove a disabled Skill from any unfinished message before sending it; the server +rejects selected Skills that are no longer available. + +Disable dependent plugins first. To change a package version, disable and uninstall +the old package, install the new one, then enable its harnesses. Installing identical +contents again preserves activation; different contents with the same ID are +rejected until the previous package is removed. Dependencies use exact versions, +not ranges, and there is no automatic dependency download or update. + +The registry and immutable package cache live under the backend workspace's +`.opendirector/plugins/`. They survive restarts and apply across its projects. +Uninstall removes registration and future discovery. Cached package files remain +for in-flight turns; there is no automatic cache deletion. Project assets, +generation configuration, conversation history and execution receipts remain in +the unified project and can still be edited after disabling or removing a plugin. +If a cached package is damaged, uninstall and reinstall from a valid source. +Reinstallation preserves the damaged cache under `.opendirector/plugins/.damaged-*` +before publishing the validated replacement; it does not delete the old files. + +## Make a custom package + +Copy [plugins/template](../../plugins/template) and change the ID, bilingual name, +description, supported runtimes and Skill instructions. Keep these identities equal: + +```text +opendirector-plugin.json → id: my-creative-tool +skills/my-creative-tool/SKILL.md → name: my-creative-tool +``` + +The manifest requires `schemaVersion: 1`, a lowercase hyphenated ID (up to 64 +characters), a `major.minor.patch` version (optional prerelease), `zh-CN` and `en-US` +names/descriptions, and one or more runtime IDs. Runtime IDs are `default`, +`opencode`, `codex`, `claude`, `jiuwenswarm`, `deepseek`. Optional `dependencies` +maps plugin IDs to exact versions, for example `{"studio-brief": "1.0.0"}`. + +The Skill needs YAML frontmatter with matching `name` and a nonempty `description`. +Additional or nested `SKILL.md` files are rejected, regardless of filename case. +Keep templates and scripts under its directory: those resources are copied into +the turn's native Skill directory. Other package files are retained but are not +exposed as Skill resources. Publish outputs through the existing `opendirector` +CLI or business tools, preserving command IDs, version checks, locks and receipts. +Do not maintain a separate editable project or write the project JSON directly. + +Install a directory inside the backend workspace while developing. Parent path +aliases are resolved before checking the workspace boundary. File reads pin every +path component without following links, and reject hard links. Empty resource +files are allowed. To share it, ZIP its **contents**, with +the manifest at the archive root, and use **Choose ZIP file** or a public HTTPS +download URL. A package permits up to 256 files/archive entries, 2 MiB per file, +20 MiB unpacked and 10 MiB compressed. Skill text is limited to 64 KiB. Links, +special files, encrypted archives, ambiguous or escaping paths, private network +URLs and credentials in URLs are rejected. Redirect destinations are also checked. + +Official maintainers edit `packages/agent/plugin-examples/` and run +`python scripts/package-plugin-examples.py` with the project's Python dependencies +installed. Commit the resulting `plugins/catalog.json` and `plugins/examples/` +ZIP together; the catalog pins the expected package content digest. diff --git a/docs/guides/plugins.zh-CN.md b/docs/guides/plugins.zh-CN.md new file mode 100644 index 000000000..1f7f92e1e --- /dev/null +++ b/docs/guides/plugins.zh-CN.md @@ -0,0 +1,78 @@ +# 可选创作插件 + +[English](plugins.md) + +插件向现有助手引擎提供可选的创作技能。打开 **设置 → 插件**,安装插件包, +再选择允许使用它的引擎。安装后默认全部关闭。同一个包可以支持默认引擎、 +OpenCode、Codex、Claude Code、JiuwenSwarm 和 DeepSeek Harness;切换引擎后, +技能列表只显示该引擎已启用的插件。 + +这里的格式是 OpenDirector 技能包,包含一个原生 Skill 入口及配套模板或脚本。 +它与让外部 DSH 调用 OpenDirector 的 [DSH 接入包](../../plugins/deepseek-harness/README.zh-CN.md) +不同;其他引擎的原生插件格式不能直接作为此类包安装。 + +## 安装与使用 + +1. 在 **设置 → 插件** 中安装官方「创作简报」,选择 ZIP 文件,或输入本地目录、 + ZIP 路径、公开 HTTPS ZIP 下载地址。本地路径仅限后端工作目录内,相对路径从该目录解析, + 也可以填写其内部的绝对路径。请使用 `plugins/my-plugin` 等独立包目录,不能使用工作目录 + 本身及其 `projects/`、`.opendirector/` 目录;其他位置的包请通过「选择 ZIP 文件」上传。 + 只安装可信来源。 +2. 在「启用的引擎」中勾选需要的引擎。依赖必须先安装指定版本,并在同一引擎启用。 +3. 在助手中选择对应引擎,打开「技能」,选择插件,再用中文或英文描述目标。 + 模型配置及引擎登录沿用现有设置。 +4. 检查工程中的实际产物。官方「创作简报」读取工程上下文,整理简报与分镜, + 发布为可编辑的 Markdown 文本素材;它自身不发起图片或视频生成。 + +应用只附带官方发现目录。示例包在明确安装时下载;源码环境可使用对应的本地示例。 +可选插件不会自动启用或进入默认技能目录。安装仅校验并保存文件,不执行安装钩子。 +启用后,技能指令和脚本使用引擎已有工具、权限和工程业务命令;安装不会授予额外权限。 + +## 停用、卸载与升级 + +变更从后续对话轮次生效。已接受的任务保留自己的技能快照。启用的插件集合变化后, +后续轮次使用已保存的对话历史启动新的原生会话,不继续复用旧插件上下文。 +如果尚未发送的消息选中了已停用技能,请先移除;后端会拒绝不可用的技能选择。 + +先停用依赖此插件的其他插件。更新版本时,停用并卸载旧包,安装新包,再启用需要的引擎。 +重复安装相同内容会保留启用状态;同一 ID 的不同内容必须先卸载旧包。依赖采用精确版本, +不支持版本范围,也不会自动下载依赖或更新。 + +登记文件和不可变包缓存位于后端工作目录的 `.opendirector/plugins/`,重启后保留, +对该工作目录下的项目生效。卸载移除登记及后续发现入口,为进行中的任务保留包缓存, +不自动清理缓存。工程素材、生成配置、对话历史与执行回执仍保存在统一工程中; +停用或卸载插件后可以继续编辑。 +缓存包损坏时,可以卸载后从有效来源重新安装。重装会先将损坏缓存保留到 +`.opendirector/plugins/.damaged-*`,再发布校验通过的新副本,不删除旧文件。 + +## 制作自定义插件 + +复制 [plugins/template](../../plugins/template),修改 ID、中英文名称和说明、支持的引擎与技能指令。 +以下三个位置的身份必须一致: + +```text +opendirector-plugin.json → id: my-creative-tool +skills/my-creative-tool/SKILL.md → name: my-creative-tool +``` + +清单要求 `schemaVersion: 1`,最长 64 字符的小写连字符 ID,`major.minor.patch` 版本 +(可带预发布后缀),`zh-CN` 和 `en-US` 名称与说明,以及至少一个引擎 ID。 +可用引擎 ID 为 `default`、`opencode`、`codex`、`claude`、`jiuwenswarm`、`deepseek`。 +可选 `dependencies` 将插件 ID 映射到精确版本,例如 `{"studio-brief": "1.0.0"}`。 + +技能需要 YAML frontmatter,含一致的 `name` 和非空 `description`。包内不能有额外或嵌套的 +`SKILL.md`,不区分文件名大小写。模板和脚本放在 +该技能目录内,执行时复制到当轮原生技能目录;包内其他文件仅保留,不作为技能资源暴露。 +通过现有 `opendirector` CLI 或业务工具发布产物,遵守命令 ID、版本检查、锁与回执。 +不要另建可独立编辑的工程副本,也不要直接修改工程 JSON。 + +开发时可以安装后端工作目录内的独立插件目录。检查范围前会解析父目录别名; +读取文件时会固定各级路径句柄,不跟随链接,也不接受硬链接。允许空资源文件。 +分发时压缩目录的**内容**,确保清单位于 ZIP 根目录,再通过 +「选择 ZIP 文件」或公开 HTTPS URL 安装。每包最多 256 个文件/压缩条目,单文件 2 MiB, +解压后总计 20 MiB,压缩包 10 MiB,技能文本 64 KiB。拒绝链接、特殊文件、加密压缩包、 +歧义或越界路径、内网下载地址,以及 URL 中的登录凭证;重定向目标同样检查。 + +维护官方示例时,修改 `packages/agent/plugin-examples/`,在安装项目 Python 依赖的环境运行 +`python scripts/package-plugin-examples.py`,一并提交生成的 `plugins/catalog.json` +和 `plugins/examples/` ZIP。发现目录固定包内容摘要,安装时校验。 diff --git a/packages/agent/plugin-examples/studio-brief/opendirector-plugin.json b/packages/agent/plugin-examples/studio-brief/opendirector-plugin.json new file mode 100644 index 000000000..a80c490ba --- /dev/null +++ b/packages/agent/plugin-examples/studio-brief/opendirector-plugin.json @@ -0,0 +1,9 @@ +{ + "schemaVersion": 1, + "id": "studio-brief", + "version": "1.0.0", + "name": {"zh-CN": "创作简报", "en-US": "Creative brief"}, + "description": {"zh-CN": "结合当前工程整理创作目标、可用素材和分镜草稿,保存为可继续编辑的文本素材。", "en-US": "Turn the current project's goals and assets into a creative brief and shot outline saved as an editable text asset."}, + "runtimes": ["default", "opencode", "codex", "claude", "jiuwenswarm", "deepseek"], + "dependencies": {} +} diff --git a/packages/agent/plugin-examples/studio-brief/skills/studio-brief/SKILL.md b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/SKILL.md new file mode 100644 index 000000000..b02a181b7 --- /dev/null +++ b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/SKILL.md @@ -0,0 +1,16 @@ +--- +name: studio-brief +description: Create a project-aware creative brief and shot outline, then publish it as an editable OpenDirector text asset without generating media. +--- + +# Creative brief / 创作简报 + +Use the user's language for the brief and reply. Work in the current OpenDirector project and preserve existing content. This skill plans creative work; it does not authorize paid generation or publishing to external services. + +1. Discover the `opendirector` CLI on PATH and read its help. Read `opendirector project show` and `opendirector model list` to identify actual project assets and configured capabilities. Do not invent available material or claim to have inspected images that you have not viewed. +2. Read `templates/brief.en.md` for an English request or `templates/brief.zh-CN.md` for a Chinese request. Fill the goal, available material, shot outline and open decisions using the user's requirements and queried facts. Clearly mark creative suggestions and unknown information. Keep actual asset IDs in the material notes when useful for later work. +3. Write the completed Markdown to a new file in the turn's execution directory. Read `opendirector asset import --help`, then register that file with `opendirector asset import ./brief.md --kind text --name "Creative brief.md"` (use a Chinese name ending in `.md` for a Chinese brief). Reuse the operation ID on retries and check the receipt before claiming it was saved. +4. If the user asks to show the brief on the canvas, read the current layout and `opendirector canvas add-material --help`, then add the returned asset at an unoccupied position. Otherwise the registered asset is sufficient; do not create extra displays for inspection. +5. Report the saved brief, how to find it in the project's assets, and any decisions still needed. Uninstalling the plugin must not be described as removing this project content. + +使用用户提问的语言整理目标、已有素材、分镜和待确认事项。通过现有工程 CLI 保存为文本素材,并以实际回执确认结果;不要直接改写工程文件,也不要自行提交图片或视频生成任务。 diff --git a/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.en.md b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.en.md new file mode 100644 index 000000000..2bf423bb7 --- /dev/null +++ b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.en.md @@ -0,0 +1,18 @@ +# Creative brief + +## Goal and constraints + +Describe the audience, message, intended duration and requirements supplied by the user. + +## Available material + +List only assets confirmed in the project, with their identities and proposed use. + +## Shot outline + +| Shot | Visual | Copy or audio | Existing material / new work | +| --- | --- | --- | --- | + +## Decisions to confirm + +Separate missing information from suggested creative choices. No media has been generated by this planning step. diff --git a/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.zh-CN.md b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.zh-CN.md new file mode 100644 index 000000000..9e3d0eca6 --- /dev/null +++ b/packages/agent/plugin-examples/studio-brief/skills/studio-brief/templates/brief.zh-CN.md @@ -0,0 +1,18 @@ +# 创作简报 + +## 目标与约束 + +填写用户提供的受众、核心信息、目标时长及要求。 + +## 已有素材 + +只列出已在工程中确认的素材,记录其身份和建议用途。 + +## 分镜草稿 + +| 镜头 | 画面 | 文案或声音 | 复用素材/新增工作 | +| --- | --- | --- | --- | + +## 待确认事项 + +区分缺失信息与创作建议。本次规划步骤尚未生成媒体。 diff --git a/packages/core/src/opendirector/agent/context.py b/packages/core/src/opendirector/agent/context.py index 1a3a66ef4..168dc4673 100644 --- a/packages/core/src/opendirector/agent/context.py +++ b/packages/core/src/opendirector/agent/context.py @@ -27,7 +27,10 @@ class RunContext: conversation_id: UUID | None = None thinking: str = 'auto' runtime_model: str | None = None - skills: list[dict[str, str]] = field(default_factory=list) + skills: list[dict] = field(default_factory=list) + + def plugin_versions(self) -> dict[str, str]: + return {item['pluginId']: item['pluginDigest'] for item in self.skills if 'pluginId' in item} def native_session_path(self) -> Path | None: if self.conversation_id is None: @@ -39,7 +42,8 @@ def native_session(self, selection: dict) -> dict | None: if directory is None or not (directory / 'session.json').is_file(): return None saved = json.loads((directory / 'session.json').read_text(encoding='utf-8')) - if saved['selection'] == selection and saved['messages'] == len(self.messages) - 1: + if (saved['selection'] == selection and saved['messages'] == len(self.messages) - 1 + and saved.get('plugins', {}) == self.plugin_versions()): return saved return None @@ -81,5 +85,6 @@ def save_native_session(self, session_id: str, selection: dict, *, work_turn_id: directory.mkdir(parents=True, exist_ok=True) write_json(directory / 'session.json', {'sessionId': session_id, 'selection': selection, 'messages': len(self.messages) + 1, + 'plugins': self.plugin_versions(), 'workTurnId': str(work_turn_id) if work_turn_id else None, **({'directory': str(engine_directory)} if engine_directory is not None else {})}) diff --git a/packages/core/src/opendirector/agent/plugins.py b/packages/core/src/opendirector/agent/plugins.py new file mode 100644 index 000000000..a0e8439ab --- /dev/null +++ b/packages/core/src/opendirector/agent/plugins.py @@ -0,0 +1,381 @@ +"""Install optional, portable Skill packages without executing their contents.""" +from contextlib import contextmanager +import errno +from hashlib import sha256 +from io import BytesIO +import json +import os +from pathlib import Path, PurePosixPath, PureWindowsPath +import stat +import time +from tempfile import TemporaryDirectory, mkdtemp +from typing import get_args +from unicodedata import normalize +from zipfile import BadZipFile, ZipFile +from zlib import error as CompressionError + +from filelock import FileLock +import httpx +from pydantic import ValidationError +import yaml + +from opendirector.agent.context import RuntimeId +from opendirector.domain.plugins import PLUGIN_ERRORS, InstalledPlugin, PluginManifest, PluginRegistryRecord +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.execution_files import execution_file +from opendirector.infrastructure.local_projects import read_json, write_json +from opendirector.installation import plugin_catalog, plugin_examples +from opendirector.integrations.http_settings import public_target_sync + +MANIFEST = 'opendirector-plugin.json' +MAX_ARCHIVE_BYTES = 10 * 1024 * 1024 +MAX_PACKAGE_BYTES = 20 * 1024 * 1024 +MAX_FILE_BYTES = 2 * 1024 * 1024 +MAX_FILES = 256 + + +def failure(code, status=400): + return ProjectError(PLUGIN_ERRORS[code][0], status, code=code) + + +def safe_path(name): + path = PurePosixPath(name) + if (not name or any(character in '\\:*?"<>|' or ord(character) < 32 for character in name) or path.is_absolute() + or name != path.as_posix() or any(part in {'.', '..'} or part.endswith((' ', '.')) + or PureWindowsPath(part).is_reserved() for part in path.parts)): + raise failure('plugin_unsafe_path') + return path + + +def is_alias(path): + info = path.lstat() + return stat.S_ISLNK(info.st_mode) or bool(getattr(info, 'st_file_attributes', 0) & 0x400) + + +def read_package_file(path, limit): + try: + with execution_file(path.parent, path.name, allow_empty=True) as stream: + return stream.read(limit + 1) + except ProjectError: + raise failure('plugin_unsafe_path') from None + except OSError as error: + if error.errno in {errno.ELOOP, errno.ENOTDIR} or getattr(error, 'winerror', None) == 1920: + raise failure('plugin_unsafe_path') from None + raise + + +def package_files(source): + files = {} + names = set() + paths = {} + total = 0 + + def unreadable(error): + raise error + + def add(name, content): + nonlocal total + path = safe_path(name) + name = normalize('NFC', name) + for part in (path, *path.parents): + canonical = normalize('NFC', part.as_posix()) + key = canonical.casefold() + if key in paths and paths[key] != canonical: + raise failure('plugin_invalid') + paths[key] = canonical + key = name.casefold() + if key in names: + raise failure('plugin_invalid') + names.add(key) + total += len(content) + if len(names) > MAX_FILES or len(content) > MAX_FILE_BYTES or total > MAX_PACKAGE_BYTES: + raise failure('plugin_too_large', 413) + files[name] = content + + if isinstance(source, Path): + if is_alias(source): + raise failure('plugin_unsafe_path') + # Keep the checked pathname; resolving it could follow a replacement link. + source = Path(os.path.abspath(source)) + if isinstance(source, Path) and source.is_dir(): + for parent, directories, entries in os.walk(source, followlinks=False, onerror=unreadable): + for name in directories + entries: + path = Path(parent) / name + if is_alias(path): + raise failure('plugin_unsafe_path') + safe_path(path.relative_to(source).as_posix()) + if path.is_dir(): + continue + if not stat.S_ISREG(path.stat().st_mode): + raise failure('plugin_unsafe_path') + add(path.relative_to(source).as_posix(), read_package_file(path, MAX_FILE_BYTES)) + else: + if isinstance(source, Path): + if not stat.S_ISREG(source.stat().st_mode): + raise failure('plugin_unsafe_path') + source = read_package_file(source, MAX_ARCHIVE_BYTES) + if len(source) > MAX_ARCHIVE_BYTES: + raise failure('plugin_too_large', 413) + try: + with ZipFile(BytesIO(source)) as archive: + if len(archive.infolist()) > MAX_FILES: + raise failure('plugin_too_large', 413) + for item in archive.infolist(): + safe_path(item.filename.rstrip('/')) + mode = stat.S_IFMT(item.external_attr >> 16) + if mode not in (0, stat.S_IFREG, stat.S_IFDIR) or item.flag_bits & 1: + raise failure('plugin_unsafe_path') + if item.is_dir(): + continue + if item.file_size > MAX_FILE_BYTES: + raise failure('plugin_too_large', 413) + with archive.open(item) as stream: + add(item.filename, stream.read(MAX_FILE_BYTES + 1)) + except (BadZipFile, RuntimeError, ValueError, EOFError, NotImplementedError, CompressionError): + raise failure('plugin_invalid') from None + try: + if any(parent.as_posix().casefold() in names for name in files for parent in PurePosixPath(name).parents): + raise ValueError() + if len(files[MANIFEST]) > 65536: + raise ValueError() + value = json.loads(files[MANIFEST]) + if not isinstance(value, dict) or type(value.get('schemaVersion')) is not int: + raise ValueError() + manifest = PluginManifest.model_validate(value) + if (set(manifest.runtimes) - set(get_args(RuntimeId)) or len(set(manifest.runtimes)) != len(manifest.runtimes) + or manifest.id in manifest.dependencies): + raise ValueError() + raw = files[f'skills/{manifest.id}/SKILL.md'] + entry = raw.decode('utf-8').replace('\r\n', '\n') + if len(raw) > 65536 or not entry.startswith('---\n') or '\n---\n' not in entry[3:]: + raise ValueError() + # Validate the package identity only; native harnesses still discover and load the skill. + metadata = yaml.safe_load(entry[4:].split('\n---\n', 1)[0]) + if (not isinstance(metadata, dict) or metadata.get('name') != manifest.id + or not isinstance(metadata.get('description'), str) or not metadata['description'].strip()): + raise ValueError() + allowed = f'skills/{manifest.id}/' + if any(name.startswith('skills/') and not name.startswith(allowed) for name in files): + raise ValueError() + if any(PurePosixPath(name).name.casefold() == 'skill.md' and name != allowed + 'SKILL.md' for name in files): + raise ValueError() + except (KeyError, ValueError, TypeError, UnicodeError, yaml.YAMLError, ValidationError): + raise failure('plugin_invalid') from None + digest = sha256() + for name, content in sorted(files.items()): + digest.update(name.encode() + b'\0' + str(len(content)).encode() + b'\0' + content) + return manifest, files, digest.hexdigest() + + +def download_package(url): + deadline = time.monotonic() + 60 + try: + current = httpx.URL(url) + with httpx.Client(trust_env=False, timeout=20, follow_redirects=False) as client: + for _ in range(6): + pinned, headers, extensions = public_target_sync(current, schemes=('https',), + unsafe=lambda: failure('plugin_url_unsafe'), unresolved=lambda: failure('plugin_source_unavailable')) + headers['Accept-Encoding'] = 'identity' + if time.monotonic() > deadline: + raise failure('plugin_source_unavailable') + with client.stream('GET', pinned, headers=headers, extensions=extensions) as response: + if response.is_redirect: + if not response.headers.get('location'): + break + current = current.join(response.headers['location']) + continue + response.raise_for_status() + content = bytearray() + for chunk in response.iter_raw(65536): + if time.monotonic() > deadline: + raise failure('plugin_source_unavailable') + content.extend(chunk) + if len(content) > MAX_ARCHIVE_BYTES: + raise failure('plugin_too_large', 413) + return bytes(content) + except (httpx.HTTPError, httpx.InvalidURL, ValueError): + raise failure('plugin_source_unavailable') from None + raise failure('plugin_source_unavailable') + + +class PluginRegistry: + def __init__(self, repository): + self.repository = Path(repository).resolve() + self.directory = self.repository / '.opendirector' / 'plugins' + self.path = self.directory / 'registry.json' + + @contextmanager + def locked(self): + for path in (self.directory.parent, self.directory, self.directory / 'packages'): + if path.is_symlink() or path.exists() and (is_alias(path) or not path.is_dir()): + raise failure('plugin_unsafe_path', 409) + path.mkdir(parents=True, exist_ok=True) + lock = self.directory / 'registry.lock' + if lock.is_symlink(): + raise failure('plugin_unsafe_path', 409) + with FileLock(lock, timeout=15): + yield + + def read(self): + if not self.path.exists() and not self.path.is_symlink(): + return PluginRegistryRecord() + try: + value = read_json(self.path) + if not isinstance(value, dict) or set(value) != {'version', 'plugins'} or type(value['version']) is not int: + raise ValueError() + state = PluginRegistryRecord.model_validate(value) + for key, item in state.plugins.items(): + if (key != item.manifest.id or set(item.manifest.runtimes) - set(get_args(RuntimeId)) + or set(item.enabledRuntimes) - set(item.manifest.runtimes)): + raise ValueError() + return state + except (ValueError, TypeError, ProjectError): + raise failure('plugin_registry_invalid', 409) from None + + def save(self, state): + write_json(self.path, state.model_dump(by_alias=True)) + + def verify(self, item): + try: + digest = package_files(self.directory / 'packages' / item.digest)[2] + except OSError: + raise failure('plugin_invalid', 409) from None + if digest != item.digest: + raise failure('plugin_invalid', 409) + + def catalog(self): + with self.locked(): + installed = [item.model_dump(by_alias=True) for item in self.read().plugins.values()] + examples = [] + if plugin_catalog().is_file(): + for item in read_json(plugin_catalog()): + manifest = PluginManifest.model_validate(item['manifest']) + examples.append({**item, 'manifest': manifest.model_dump(by_alias=True), 'source': f'example:{manifest.id}'}) + return {'installed': installed, 'examples': examples, 'runtimes': list(get_args(RuntimeId))} + + def install(self, source: str): + if not isinstance(source, str): + raise failure('plugin_invalid') + label = source + expected_digest = None + try: + if source.startswith('example:'): + example = next((item for item in self.catalog()['examples'] if item['source'] == source), None) + if example is None: + raise failure('plugin_source_unavailable', 404) + expected_digest = example['digest'] + path = plugin_examples() / example['manifest']['id'] + package = path if path.is_dir() else download_package(example['url']) + elif '://' in source: + package = download_package(source) + label = str(httpx.URL(label).copy_with(query=None, fragment=None)) + else: + windows = PureWindowsPath(source) + if any(ord(character) < 32 for character in source) or windows.drive and not windows.root: + raise failure('plugin_unsafe_path') + requested = os.path.abspath(os.path.join(self.repository, source)) + # Resolve parent aliases before authorizing reads; keep the entry itself for link rejection. + parent = os.path.realpath(os.path.dirname(requested)) + candidate = os.path.normpath(os.path.join(parent, os.path.basename(requested))) + root = os.fspath(self.repository) + if candidate.startswith(os.path.join(root, '')): + package = Path(candidate) + else: + raise failure('plugin_source_outside_workspace', 403) + if (package == self.repository + or package.relative_to(self.repository).parts[0].casefold() in {'projects', '.opendirector'}): + raise failure('plugin_source_outside_workspace', 403) + manifest, files, digest = package_files(package) + if expected_digest is not None and digest != expected_digest: + raise failure('plugin_invalid') + except OSError: + raise failure('plugin_source_unavailable') from None + return self._register(manifest, files, digest, label) + + def install_archive(self, content: bytes): + if not isinstance(content, bytes): + raise failure('plugin_invalid') + try: + manifest, files, digest = package_files(content) + except OSError: + raise failure('plugin_source_unavailable') from None + return self._register(manifest, files, digest, 'upload') + + def _register(self, manifest, files, digest, label): + with self.locked(): + state = self.read() + previous = state.plugins.get(manifest.id) + if previous: + if previous.digest != digest: + raise failure('plugin_conflict', 409) + return previous.model_dump(by_alias=True) + destination = self.directory / 'packages' / digest + reusable = False + if destination.exists() or destination.is_symlink(): + try: + reusable = package_files(destination)[2] == digest + except (ProjectError, OSError): + pass + if not reusable: + with TemporaryDirectory(prefix='.install-', dir=self.directory) as temporary: + staging = Path(temporary) / 'package' + staging.mkdir() + for name, content in files.items(): + path = staging / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + if destination.exists() or destination.is_symlink(): + # Preserve a damaged cache for diagnosis; never delete its uncertain contents. + preserved = Path(mkdtemp(prefix='.damaged-', dir=self.directory)) / 'package' + os.replace(destination, preserved) + os.replace(staging, destination) + record = InstalledPlugin(manifest=manifest, digest=digest, source=label) + state.plugins[manifest.id] = record + self.save(state) + return record.model_dump(by_alias=True) + + def change(self, plugin_id, digest, *, runtime=None, enabled=None): + with self.locked(): + state = self.read() + item = state.plugins.get(plugin_id) + if item is None: + raise failure('plugin_missing', 404) + if item.digest != digest: + raise failure('plugin_changed', 409) + if runtime is not None and runtime not in item.manifest.runtimes: + raise failure('plugin_runtime_unsupported', 409) + if enabled: + self.verify(item) + for dependency, version in item.manifest.dependencies.items(): + other = state.plugins.get(dependency) + if other is None or other.manifest.version != version or runtime not in other.enabledRuntimes: + raise failure('plugin_dependency_missing', 409) + else: + for other in state.plugins.values(): + if plugin_id in other.manifest.dependencies and (runtime in other.enabledRuntimes + if runtime is not None else other.enabledRuntimes): + raise failure('plugin_required', 409) + if runtime is None: + # Retain immutable package files: already accepted turns may still be taking their snapshot. + del state.plugins[plugin_id] + else: + item.enabledRuntimes = [value for value in item.enabledRuntimes if value != runtime] + if enabled: + item.enabledRuntimes.append(runtime) + self.save(state) + return self.catalog() + + def skills(self, runtime): + with self.locked(): + items = list(self.read().plugins.values()) + result = [] + for item in items: + if runtime not in item.enabledRuntimes: + continue + path = self.directory / 'packages' / item.digest + self.verify(item) + result.append({'name': item.manifest.id, 'pluginId': item.manifest.id, 'pluginDigest': item.digest, + 'filePath': str(path / 'skills' / item.manifest.id / 'SKILL.md'), + 'displayName': item.manifest.name.model_dump(by_alias=True), + 'localizedDescription': item.manifest.description.model_dump(by_alias=True)}) + return result diff --git a/packages/core/src/opendirector/agent/skills.py b/packages/core/src/opendirector/agent/skills.py index b0555b320..dec052e68 100644 --- a/packages/core/src/opendirector/agent/skills.py +++ b/packages/core/src/opendirector/agent/skills.py @@ -7,16 +7,15 @@ from opendirector.agent.native import BUNDLED_INSTALL_ERROR, executable from opendirector.agent.process import terminate +from opendirector.agent.plugins import PluginRegistry, failure from opendirector.installation import builtin_skills from opendirector.domain.projects import ProjectError -async def skills(repository: Path, directory: Path) -> list[dict[str, str]]: +async def native_catalog(roots: list[Path]) -> list[dict]: binary = executable('default') if binary is None: raise ProjectError(BUNDLED_INSTALL_ERROR, 503, code='agent_dependency_unavailable') - roots = [path.resolve() for path in [directory / '.opendirector/skills', - repository / '.opendirector/skills', builtin_skills()] if path.is_dir()] with TemporaryDirectory(prefix='od-skills-') as temporary: env = {**os.environ, 'XDG_CONFIG_HOME': temporary, 'OPENCODE_DISABLE_EXTERNAL_SKILLS': '1', 'OPENCODE_DISABLE_CLAUDE_CODE_SKILLS': '1', @@ -32,15 +31,42 @@ async def skills(repository: Path, directory: Path) -> list[dict[str, str]]: if process.returncode: raise ProjectError(BUNDLED_INSTALL_ERROR, 503, code='agent_dependency_unavailable') try: - catalog = json.loads(data) + return json.loads(data) except json.JSONDecodeError: raise ProjectError("OpenCode 返回了无效的技能目录,请检查 CLI 版本。", 503) from None - found = [] - for item in catalog: - path = Path(item['location']).resolve() - if any(path.is_relative_to(root) for root in roots) and path.is_file() and path.stat().st_size <= 65536: - source = 'builtin' if path.is_relative_to(builtin_skills()) else 'project' if path.is_relative_to(directory / '.opendirector/skills') else 'workspace' - found.append({'name': item['name'], 'description': item['description'], 'filePath': str(path), 'source': source}) - return found finally: await terminate(process) + + +async def skills(repository: Path, directory: Path, runtime: str = 'default') -> list[dict]: + roots = [path.resolve() for path in [directory / '.opendirector/skills', + repository / '.opendirector/skills', builtin_skills()] if path.is_dir()] + plugins = await asyncio.to_thread(PluginRegistry(repository).skills, runtime) + catalog = await native_catalog(roots) + entries = {Path(item['filePath']).resolve(): item for item in plugins} + if plugins: + # Native discovery deduplicates names; keep plugins from silently replacing ordinary skills. + if {item['name'] for item in plugins} & {item['name'] for item in catalog}: + raise failure('plugin_skill_conflict', 409) + plugin_roots = [path.parent.parent for path in entries] + # Native virtual skills have no file to expose or copy into the project. + discovered = [item for item in await native_catalog(plugin_roots) if Path(item['location']).is_absolute()] + if (len(discovered) != len(entries) + or {Path(item['location']).resolve() for item in discovered} != set(entries)): + raise failure('plugin_skill_conflict', 409) + catalog += discovered + roots += plugin_roots + found = [] + for item in catalog: + path = Path(item['location']).resolve() + if any(path.is_relative_to(root) for root in roots) and path.is_file() and path.stat().st_size <= 65536: + plugin = entries.get(path) + if plugin and plugin['name'] != item['name']: + raise failure('plugin_skill_conflict', 409) + source = 'plugin' if plugin else 'builtin' if path.is_relative_to(builtin_skills()) else 'project' if path.is_relative_to(directory / '.opendirector/skills') else 'workspace' + found.append({'name': item['name'], 'description': item['description'], 'filePath': str(path), 'source': source, + **(plugin or {})}) + if (set(entries) != {Path(item['filePath']).resolve() for item in found if item['source'] == 'plugin'} + or len({item['name'] for item in found}) != len(found)): + raise failure('plugin_skill_conflict', 409) + return found diff --git a/packages/core/src/opendirector/domain/plugins.py b/packages/core/src/opendirector/domain/plugins.py new file mode 100644 index 000000000..7f3a8987a --- /dev/null +++ b/packages/core/src/opendirector/domain/plugins.py @@ -0,0 +1,57 @@ +"""Optional plugin packages: declarative metadata, never installation hooks.""" +from typing import Annotated, Literal + +from pydantic import BaseModel, ConfigDict, Field, StringConstraints + +PluginId = Annotated[str, StringConstraints(pattern=r'^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', max_length=64)] +PluginVersion = Annotated[str, StringConstraints(pattern=r'^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$', max_length=64)] +Digest = Annotated[str, StringConstraints(pattern=r'^[a-f0-9]{64}$')] + + +class LocalizedPluginText(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True, str_strip_whitespace=True) + zh: str = Field(alias='zh-CN', min_length=1, max_length=500) + en: str = Field(alias='en-US', min_length=1, max_length=500) + + +class PluginManifest(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True) + schemaVersion: Literal[1] + id: PluginId + version: PluginVersion + name: LocalizedPluginText + description: LocalizedPluginText + runtimes: list[str] = Field(min_length=1, max_length=6) + dependencies: dict[PluginId, PluginVersion] = Field(default_factory=dict, max_length=32) + + +class InstalledPlugin(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True) + manifest: PluginManifest + digest: Digest + source: str + enabledRuntimes: list[str] = Field(default_factory=list) + + +class PluginRegistryRecord(BaseModel): + model_config = ConfigDict(extra='forbid', strict=True) + version: Literal[1] = 1 + plugins: dict[PluginId, InstalledPlugin] = Field(default_factory=dict) + + +PLUGIN_ERRORS = { + 'plugin_invalid': ('插件包无效:请检查清单、技能入口及文件格式。', 'Invalid plugin package. Check its manifest, skill entry and files.'), + 'plugin_unsafe_path': ('插件包不能包含链接、特殊文件或不安全的路径及文件名。', 'Plugin packages cannot contain links, special files or unsafe paths and filenames.'), + 'plugin_too_large': ('插件包超过文件数量或大小限制。', 'The plugin package exceeds the file count or size limit.'), + 'plugin_source_unavailable': ('无法读取插件来源,请检查文件路径或下载地址。', 'Cannot read the plugin source. Check the file path or download URL.'), + 'plugin_source_outside_workspace': ('本地插件必须位于后端工作目录内的独立文件夹,不能使用工程或内部数据目录;其他位置的插件请上传 ZIP 文件。', 'Local plugins must be inside the backend workspace, outside project and internal data directories. Upload a ZIP file to install from elsewhere.'), + 'plugin_url_unsafe': ('插件下载地址必须是公开 HTTPS 地址,且不能包含登录凭证。', 'Plugin downloads require a public HTTPS URL without embedded credentials.'), + 'plugin_registry_invalid': ('插件登记文件损坏或格式不受支持,原文件已保留。', 'The plugin registry is damaged or unsupported. The original file was preserved.'), + 'plugin_conflict': ('已安装不同内容的同名插件,请先停用并卸载旧包。', 'A different package with this plugin ID is installed. Disable and uninstall it first.'), + 'plugin_missing': ('插件尚未安装,请刷新插件列表。', 'This plugin is not installed. Refresh the plugin list.'), + 'plugin_changed': ('插件版本已经变化,请刷新后重试。', 'The installed plugin has changed. Refresh and try again.'), + 'plugin_runtime_unsupported': ('此插件不支持所选引擎。', 'This plugin does not support the selected harness.'), + 'plugin_dependency_missing': ('请先在此引擎安装并启用清单要求的依赖版本。', 'Install and enable the declared dependency versions for this harness first.'), + 'plugin_required': ('其他已启用插件依赖此插件,请先停用它们。', 'Other enabled plugins depend on this plugin. Disable them first.'), + 'plugin_skill_conflict': ('插件技能与已有技能重名或入口不匹配,请修正插件包。', 'The plugin skill conflicts with an existing skill or its entry does not match. Correct the package.'), +} diff --git a/packages/core/src/opendirector/infrastructure/execution_files.py b/packages/core/src/opendirector/infrastructure/execution_files.py index 6a587b6ad..7a472a5e9 100644 --- a/packages/core/src/opendirector/infrastructure/execution_files.py +++ b/packages/core/src/opendirector/infrastructure/execution_files.py @@ -8,7 +8,7 @@ @contextmanager -def _posix_file(work, parts, create): +def _posix_file(work, parts, create, *, allow_empty=False): if os.open not in os.supports_dir_fd or not hasattr(os, 'O_NOFOLLOW'): raise ProjectError('当前平台不支持安全的执行产物文件读取。', 501) with ExitStack() as stack: @@ -24,7 +24,7 @@ def _posix_file(work, parts, create): fd = os.open(parts[-1], flags | os.O_NOFOLLOW, 0o600, dir_fd=parent) stack.callback(os.close, fd) facts = os.fstat(fd) - if not stat.S_ISREG(facts.st_mode) or (not create and facts.st_size == 0): + if not stat.S_ISREG(facts.st_mode) or (not create and not allow_empty and facts.st_size == 0): raise ProjectError('发布产物必须是非空普通文件。') duplicate = os.dup(fd) try: @@ -42,7 +42,7 @@ def _posix_file(work, parts, create): @contextmanager -def execution_file(execution_directory: Path, path: str, *, create=False): +def execution_file(execution_directory: Path, path: str, *, create=False, allow_empty=False): """The host supplies the root; callers may only open descendants of it. Pin the execution root and user directory components for the operation. @@ -50,6 +50,7 @@ def execution_file(execution_directory: Path, path: str, *, create=False): root Windows releases lookup-only ancestors to permit project commits. Outputs are created exclusively. Failed POSIX writes may leave a partial file; inspect it and use a new output name rather than overwriting on retry. + Empty input is allowed only when the caller's format explicitly supports it. """ # Do not resolve the execution root: it is a lexical authorization boundary, # not permission to follow a replacement symlink/junction. Both backends @@ -70,11 +71,12 @@ def execution_file(execution_directory: Path, path: str, *, create=False): parts = candidate.relative_to(work).parts if os.name == 'nt': from opendirector.infrastructure.windows_execution_files import open_file + opened = open_file(work, parts, create) else: - open_file = _posix_file - with open_file(work, parts, create) as stream: + opened = _posix_file(work, parts, create, allow_empty=allow_empty) + with opened as stream: facts = os.fstat(stream.fileno()) - if not stat.S_ISREG(facts.st_mode) or (not create and facts.st_size == 0): + if not stat.S_ISREG(facts.st_mode) or (not create and not allow_empty and facts.st_size == 0): raise ProjectError('发布产物必须是非空普通文件。') if facts.st_nlink != 1: raise ProjectError('执行文件不能包含硬链接。', 403, code='execution_file_link') diff --git a/packages/core/src/opendirector/installation.py b/packages/core/src/opendirector/installation.py index ec0729660..5f90100c9 100644 --- a/packages/core/src/opendirector/installation.py +++ b/packages/core/src/opendirector/installation.py @@ -21,5 +21,13 @@ def builtin_skills() -> Path: return SOURCE_ROOT / 'packages/agent/skills' if SOURCE_ROOT else BUNDLED / 'skills' +def plugin_examples() -> Path: + return SOURCE_ROOT / 'packages/agent/plugin-examples' if SOURCE_ROOT else BUNDLED / 'plugin-examples' + + +def plugin_catalog() -> Path: + return SOURCE_ROOT / 'plugins/catalog.json' if SOURCE_ROOT else BUNDLED / 'plugin-catalog.json' + + def default_timeline_font() -> Path: return (SOURCE_ROOT / 'public/fonts' if SOURCE_ROOT else web_root() / 'fonts') / 'NotoSansCJKsc-Regular.otf' diff --git a/plugins/catalog.json b/plugins/catalog.json new file mode 100644 index 000000000..cb9090e07 --- /dev/null +++ b/plugins/catalog.json @@ -0,0 +1,28 @@ +[ + { + "manifest": { + "schemaVersion": 1, + "id": "studio-brief", + "version": "1.0.0", + "name": { + "zh-CN": "创作简报", + "en-US": "Creative brief" + }, + "description": { + "zh-CN": "结合当前工程整理创作目标、可用素材和分镜草稿,保存为可继续编辑的文本素材。", + "en-US": "Turn the current project's goals and assets into a creative brief and shot outline saved as an editable text asset." + }, + "runtimes": [ + "default", + "opencode", + "codex", + "claude", + "jiuwenswarm", + "deepseek" + ], + "dependencies": {} + }, + "digest": "5c3c2e798a7fdc1ce55c74315349b621d54a7ed21170060d4394af74b79900d5", + "url": "https://raw.githubusercontent.com/ThinkFlowLab/OpenDirector/main/plugins/examples/studio-brief.zip" + } +] diff --git a/plugins/examples/studio-brief.zip b/plugins/examples/studio-brief.zip new file mode 100644 index 000000000..1154622a5 Binary files /dev/null and b/plugins/examples/studio-brief.zip differ diff --git a/plugins/template/opendirector-plugin.json b/plugins/template/opendirector-plugin.json new file mode 100644 index 000000000..4ebac7758 --- /dev/null +++ b/plugins/template/opendirector-plugin.json @@ -0,0 +1,9 @@ +{ + "schemaVersion": 1, + "id": "my-creative-tool", + "version": "1.0.0", + "name": {"zh-CN": "我的创作工具", "en-US": "My creative tool"}, + "description": {"zh-CN": "根据工程素材整理创作笔记。", "en-US": "Prepare creative notes from project assets."}, + "runtimes": ["default", "opencode", "codex", "claude", "jiuwenswarm", "deepseek"], + "dependencies": {} +} diff --git a/plugins/template/skills/my-creative-tool/SKILL.md b/plugins/template/skills/my-creative-tool/SKILL.md new file mode 100644 index 000000000..84f194379 --- /dev/null +++ b/plugins/template/skills/my-creative-tool/SKILL.md @@ -0,0 +1,19 @@ +--- +name: my-creative-tool +description: Prepare project-aware creative notes and save them as an editable text asset. 根据工程素材整理并保存可编辑的创作笔记。 +--- + +# My creative tool / 我的创作工具 + +Use the user's language. Read `opendirector --help` and `opendirector project show` +to learn the current project and available operations. Read `templates/notes.md`, +then write `notes.md` in the execution directory using the user's requirements +and actual project facts. Label unknowns; do not invent assets or model results. + +Read `opendirector asset import --help` and publish with +`opendirector asset import ./notes.md --kind text --name notes.md`. +Report success only after an applied receipt. Reuse the command ID for retries. +Do not write project storage directly or start generation without authorization. + +使用用户提问的语言,通过工程查询获取真实素材,再填写笔记模板。用现有 CLI +将笔记发布为文本素材,以实际回执确认保存;保留原有素材和配置。 diff --git a/plugins/template/skills/my-creative-tool/templates/notes.md b/plugins/template/skills/my-creative-tool/templates/notes.md new file mode 100644 index 000000000..cdfaf0cc4 --- /dev/null +++ b/plugins/template/skills/my-creative-tool/templates/notes.md @@ -0,0 +1,9 @@ +# Creative notes / 创作笔记 + +## Goal / 目标 + +## Existing assets / 已有素材 + +## Proposed next steps / 建议步骤 + +## Open decisions / 待确认事项 diff --git a/scripts/package-plugin-examples.py b/scripts/package-plugin-examples.py new file mode 100644 index 000000000..b15bdddb5 --- /dev/null +++ b/scripts/package-plugin-examples.py @@ -0,0 +1,26 @@ +"""Build the optional example ZIPs and metadata-only discovery catalog.""" +import json +from pathlib import Path +import sys +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +root = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(root / 'packages/core/src')) +from opendirector.agent.plugins import package_files + +output = root / 'plugins/examples' +output.mkdir(parents=True, exist_ok=True) +catalog = [] +for source in sorted((root / 'packages/agent/plugin-examples').iterdir()): + if not source.is_dir(): + continue + manifest, files, digest = package_files(source) + with ZipFile(output / f'{manifest.id}.zip', 'w') as archive: + for name, content in sorted(files.items()): + info = ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0)) + info.compress_type = ZIP_DEFLATED + info.external_attr = 0o100644 << 16 + archive.writestr(info, content) + catalog.append({'manifest': manifest.model_dump(by_alias=True), 'digest': digest, + 'url': f'https://raw.githubusercontent.com/ThinkFlowLab/OpenDirector/main/plugins/examples/{manifest.id}.zip'}) +(root / 'plugins/catalog.json').write_text(json.dumps(catalog, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') diff --git a/src/backend/chat.ts b/src/backend/chat.ts index f935df4c8..50cce4865 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -2,6 +2,7 @@ import type { ReferenceContent } from "../canvas/chatReferenceContent.ts"; import { defaultTranslate } from "../canvas/assistantTranslate.ts"; import type { Translate } from "../i18n/I18nProvider.tsx"; import { headers, json, request, responseError } from "./api.ts"; +import type { Locale } from "../i18n/types.ts"; export type AgentRuntime = | "default" @@ -28,9 +29,12 @@ export interface RuntimeInfo { supportsSkills?: boolean; } export interface ChatSkill { - source?: "builtin" | "workspace" | "project"; + source?: "builtin" | "workspace" | "project" | "plugin"; name: string; description: string; + pluginId?: string; + displayName?: Record; + localizedDescription?: Record; } export interface ChatTool { @@ -196,8 +200,8 @@ export async function conversation( } export const saveChatDraft = (id: string, draft: ChatDraft) => request(path(id) + "/draft", json("PUT", draft)); -export const chatSkills = (id: string, signal?: AbortSignal) => - request(path(id) + "/skills", { signal }); +export const chatSkills = (id: string, signal?: AbortSignal, runtime: AgentRuntime = "default") => + request(path(id) + `/skills?runtime=${runtime}`, { signal }); export const stopChat = (id: string, turn: string) => request(path(id) + `/turns/${turn}/stop`, json("POST", {})); export async function streamChat( diff --git a/src/backend/plugins.ts b/src/backend/plugins.ts new file mode 100644 index 000000000..841d814f5 --- /dev/null +++ b/src/backend/plugins.ts @@ -0,0 +1,37 @@ +import type { AgentRuntime } from "./chat.ts"; +import type { Locale } from "../i18n/types.ts"; +import { json, request } from "./api.ts"; + +export interface PluginManifest { + schemaVersion: 1; + id: string; + version: string; + name: Record; + description: Record; + runtimes: AgentRuntime[]; + dependencies: Record; +} +export interface InstalledPlugin { + manifest: PluginManifest; + digest: string; + source: string; + enabledRuntimes: AgentRuntime[]; +} +export interface PluginCatalog { + installed: InstalledPlugin[]; + examples: { manifest: PluginManifest; source: string }[]; + runtimes: AgentRuntime[]; +} + +export const PLUGINS_CHANGED = "opendirector:plugins-changed"; +export const pluginCatalog = (signal?: AbortSignal) => request("/plugins", { signal }); +export const installPlugin = (source: string | File) => + request("/plugins" + (typeof source === "string" ? "" : "/upload"), + typeof source === "string" ? json("POST", { source }) : { + method: "POST", headers: { "Content-Type": "application/zip" }, body: source, + }); +export const enablePlugin = (plugin: InstalledPlugin, runtime: AgentRuntime, enabled: boolean) => + request(`/plugins/${plugin.manifest.id}/runtimes/${runtime}`, + json("PUT", { digest: plugin.digest, enabled })); +export const removePlugin = (plugin: InstalledPlugin) => + request(`/plugins/${plugin.manifest.id}`, json("DELETE", { digest: plugin.digest })); diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 1da3e8e12..aef0badd6 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -710,6 +710,7 @@ export function AssistantPanel({ /> item.id === value.runtime)?.supportsSkills === false} diff --git a/src/canvas/PluginSettings.tsx b/src/canvas/PluginSettings.tsx new file mode 100644 index 000000000..3a8563657 --- /dev/null +++ b/src/canvas/PluginSettings.tsx @@ -0,0 +1,120 @@ +import { useEffect, useRef, useState } from "react"; +import { errorMessage } from "../backend/api"; +import { enablePlugin, installPlugin, PLUGINS_CHANGED, pluginCatalog, removePlugin, type PluginCatalog } from "../backend/plugins"; +import { useI18n } from "../i18n/I18nProvider"; +import { CanvasIcon } from "./CanvasIcon"; +import "./plugin-settings.css"; + +export function PluginSettings() { + const { t, locale } = useI18n(); + const [catalog, setCatalog] = useState(null); + const [source, setSource] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [status, setStatus] = useState<"plugins.saved" | "plugins.installedHint" | "">(""); + const saving = useRef(false); + const upload = useRef(null); + + useEffect(() => { + const controller = new AbortController(); + void pluginCatalog(controller.signal).then(setCatalog).catch((reason) => { + if (!controller.signal.aborted) setError(errorMessage(reason)); + }); + return () => controller.abort(); + }, []); + + async function change(action: () => Promise, installed = false) { + if (saving.current) return; + saving.current = true; + setBusy(true); + setError(""); + setStatus(""); + try { + await action(); + window.dispatchEvent(new Event(PLUGINS_CHANGED)); + setStatus(installed ? "plugins.installedHint" : "plugins.saved"); + setCatalog(await pluginCatalog()); + } catch (reason) { + setError(errorMessage(reason)); + } finally { + saving.current = false; + setBusy(false); + } + } + + return
+

{t("plugins.intro")}

+
{ + event.preventDefault(); + if (source.trim()) void change(() => installPlugin(source.trim()), true); + }}> + +
+ setSource(event.target.value)} + placeholder={t("plugins.sourcePlaceholder")} disabled={busy} autoComplete="off" /> + +
+ { + const file = event.target.files?.[0]; + event.target.value = ""; + if (file) void change(() => installPlugin(file), true); + }} /> + +

{t("plugins.trust")}

+
+ {busy &&

{t("plugins.working")}

} + {status &&

{t(status)}

} + {error &&
{error} + +
} + {!catalog && !error &&

{t("plugins.loading")}

} + {catalog && <> +
+

{t("plugins.installed")}

+ {!catalog.installed.length &&

{t("plugins.empty")}

} + {catalog.installed.map((plugin) =>
+

{plugin.manifest.name[locale]}

+ {plugin.manifest.id} · {plugin.manifest.version}
+ +
+

{plugin.manifest.description[locale]}

+ {Object.keys(plugin.manifest.dependencies).length > 0 &&

+ {t("plugins.dependencies")}: {Object.entries(plugin.manifest.dependencies).map(([id, version]) => `${id} ${version}`).join(", ")} +

} +
+ {t("plugins.enableFor")} + {plugin.manifest.runtimes.map((runtime) => )} +
+
)} +
+
+

{t("plugins.examples")}

+

{t("plugins.examplesHint")}

+ {catalog.examples.map((example) =>
+

{example.manifest.name[locale]}

{example.manifest.version}
+ +

{example.manifest.description[locale]}

+
)} +
+ } +
; +} diff --git a/src/canvas/SettingsDialog.tsx b/src/canvas/SettingsDialog.tsx index 45a89f57f..97bf29ae7 100644 --- a/src/canvas/SettingsDialog.tsx +++ b/src/canvas/SettingsDialog.tsx @@ -1,6 +1,7 @@ import { useLayoutEffect, useRef, useState } from "react"; import { CanvasIcon } from "./CanvasIcon"; import { ModelSettings } from "./ModelSettings"; +import { PluginSettings } from "./PluginSettings"; import { errorMessage } from "../backend/api"; import type { BackendModels } from "../backend/models"; import type { Theme, ThemeControls } from "./theme"; @@ -10,6 +11,7 @@ import type { Locale } from "../i18n/types"; const categories = [ { id: "models", labelKey: "settings.models", icon: "model" }, { id: "general", labelKey: "settings.general", icon: "settings" }, + { id: "plugins", labelKey: "plugins.title", icon: "sparkle" }, ] as const; function GeneralSettings({ @@ -136,7 +138,7 @@ export function SettingsDialog({ const { t } = useI18n(); const dialog = useRef(null); const backdropPressed = useRef(false); - const [category, setCategory] = useState<"general" | "models">( + const [category, setCategory] = useState<"general" | "models" | "plugins">( initialCategory, ); useLayoutEffect(() => { @@ -210,9 +212,7 @@ export function SettingsDialog({ >

- {category === "general" - ? t("settings.general") - : t("settings.models")} + {t(categories.find((item) => item.id === category)!.labelKey)}

@@ -227,7 +227,7 @@ export function SettingsDialog({
)} - {category === "general" ? ( + {category === "plugins" ? : category === "general" ? ( ) : ( diff --git a/src/canvas/SkillPicker.tsx b/src/canvas/SkillPicker.tsx index 31361d505..e7d350586 100644 --- a/src/canvas/SkillPicker.tsx +++ b/src/canvas/SkillPicker.tsx @@ -1,6 +1,7 @@ import { useEffect, useLayoutEffect, useId, useRef, useState } from "react"; -import { chatSkills, type ChatSkill } from "../backend/chat.ts"; -import { useT } from "../i18n/I18nProvider.tsx"; +import { chatSkills, type AgentRuntime, type ChatSkill } from "../backend/chat.ts"; +import { PLUGINS_CHANGED } from "../backend/plugins.ts"; +import { useI18n } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; import { CanvasIcon } from "./CanvasIcon.tsx"; @@ -8,22 +9,25 @@ const SOURCE_LABELS: Record, MessageKey> = { builtin: "assistant.skills.source.builtin", workspace: "assistant.skills.source.workspace", project: "assistant.skills.source.project", + plugin: "plugins.skillSource", }; export function SkillPicker({ projectId, + runtime = "default", selected, slashQuery, disabled, onChange, }: { projectId: string; + runtime?: AgentRuntime; selected: string[]; slashQuery: string | null; disabled: boolean; onChange: (names: string[], fromSlash: boolean) => void; }) { - const t = useT(); + const { t, locale } = useI18n(); const [skills, setSkills] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); @@ -39,7 +43,7 @@ export function SkillPicker({ const open = !disabled && (manual || slash); const search = slash ? (slashQuery ?? "") : query; const shown = skills.filter((skill) => - `${skill.name} ${skill.description}` + `${skill.name} ${skill.displayName?.[locale] ?? ""} ${skill.localizedDescription?.[locale] ?? skill.description}` .toLowerCase() .includes(search.toLowerCase()), ); @@ -50,7 +54,12 @@ export function SkillPicker({ setQuery(""); setSkills([]); setError(""); - }, [projectId]); + }, [projectId, runtime]); + useEffect(() => { + const refresh = () => setAttempt((value) => value + 1); + window.addEventListener(PLUGINS_CHANGED, refresh); + return () => window.removeEventListener(PLUGINS_CHANGED, refresh); + }, []); useEffect(() => { setDismissed(false); setActive(0); @@ -61,8 +70,9 @@ export function SkillPicker({ useEffect(() => { const abort = new AbortController(); setLoading(true); + setSkills([]); setError(""); - void chatSkills(projectId, abort.signal) + void chatSkills(projectId, abort.signal, runtime) .then((value) => { if (!abort.signal.aborted) setSkills(value); }) @@ -78,7 +88,7 @@ export function SkillPicker({ if (!abort.signal.aborted) setLoading(false); }); return () => abort.abort(); - }, [projectId, attempt]); + }, [projectId, runtime, attempt]); useLayoutEffect(() => { if (!open || !root.current) return; @@ -233,8 +243,8 @@ export function SkillPicker({ > - {skill.name}{skill.source && {t(SOURCE_LABELS[skill.source])}} - {skill.description} + {skill.displayName?.[locale] ?? skill.name}{skill.source && {t(SOURCE_LABELS[skill.source])}} + {skill.localizedDescription?.[locale] ?? skill.description} {selected.includes(skill.name) && ( diff --git a/src/canvas/plugin-settings.css b/src/canvas/plugin-settings.css new file mode 100644 index 000000000..231af95e5 --- /dev/null +++ b/src/canvas/plugin-settings.css @@ -0,0 +1,20 @@ +.cw-plugin-settings { display: grid; gap: 20px; } +.cw-plugin-settings p { line-height: 1.6; margin: 8px 0; } +.cw-plugin-intro, .cw-plugin-empty, .cw-plugin-card small, .cw-plugin-install p { color: var(--settings-muted); } +.cw-plugin-settings h3 { margin: 0 0 10px; font-size: 14px; } +.cw-plugin-settings h4 { margin: 0; font-size: 14px; font-weight: 600; } +.cw-plugin-install { display: grid; gap: 8px; } +.cw-plugin-install > button { justify-self: start; } +.cw-plugin-source-row { display: flex; gap: 8px; } +.cw-plugin-source-row input { + min-width: 0; flex: 1; padding: 8px 10px; border: 1px solid var(--settings-border); + border-radius: 8px; background: var(--settings-input); color: var(--settings-text); font: inherit; +} +.cw-plugin-card { padding: 16px; margin-top: 10px; border: 1px solid var(--settings-border); border-radius: 10px; } +.cw-plugin-card header { display: flex; justify-content: space-between; align-items: start; gap: 12px; } +.cw-plugin-card header > div { min-width: 0; overflow-wrap: anywhere; } +.cw-plugin-card fieldset { display: flex; flex-wrap: wrap; gap: 10px 18px; border: 0; margin: 12px 0 0; padding: 0; } +.cw-plugin-card legend { padding: 0; margin-bottom: 10px; color: var(--settings-muted); } +.cw-plugin-card label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; } +.cw-plugin-card input { accent-color: var(--cw-control-accent); } +.cw-plugin-settings button:disabled { cursor: default; opacity: .5; } diff --git a/src/i18n/messages/en-US/index.ts b/src/i18n/messages/en-US/index.ts index 29898459a..839d8179a 100644 --- a/src/i18n/messages/en-US/index.ts +++ b/src/i18n/messages/en-US/index.ts @@ -15,6 +15,7 @@ import { generation } from "./generation.ts"; import { library } from "./library.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; +import { plugins } from "./plugins.ts"; import { timeline } from "./timeline.ts"; import { tools } from "./tools.ts"; @@ -25,6 +26,7 @@ export const enUS: Record = { ...common, ...voiceLibrary, ...settings, + ...plugins, ...modelSetup, ...trace, ...canvas, diff --git a/src/i18n/messages/en-US/plugins.ts b/src/i18n/messages/en-US/plugins.ts new file mode 100644 index 000000000..a463b4d5b --- /dev/null +++ b/src/i18n/messages/en-US/plugins.ts @@ -0,0 +1,25 @@ +export const plugins = { + "plugins.title": "Plugins", + "plugins.intro": "Install optional creative capabilities and choose which agent harnesses can use them. Outputs stay in the current project.", + "plugins.source": "Workspace plugin path or download URL", + "plugins.sourcePlaceholder": "plugins/my-plugin or https://…/plugin.zip", + "plugins.install": "Install", + "plugins.installName": "Install {name}", + "plugins.upload": "Choose ZIP file", + "plugins.trust": "Use a package folder inside the backend workspace, outside project and internal data folders, or upload a ZIP. Only install trusted plugins. Installation does not run scripts; enabled skills use the agent's existing permissions.", + "plugins.working": "Updating plugins…", + "plugins.loading": "Loading plugins…", + "plugins.saved": "Plugin settings saved for the next turn. Existing tasks and project outputs are preserved.", + "plugins.installedHint": "Installed. Enable a harness below, then use the assistant's Skills menu.", + "plugins.installed": "Installed", + "plugins.empty": "No optional plugins installed. Choose an example below or install a custom package.", + "plugins.uninstall": "Uninstall", + "plugins.uninstallName": "Uninstall {name}", + "plugins.dependencies": "Dependencies", + "plugins.enableFor": "Enabled harnesses", + "plugins.defaultRuntime": "Default", + "plugins.examples": "Official examples", + "plugins.examplesHint": "Examples require manual installation and activation. They stay out of the agent's skill catalog until enabled.", + "plugins.alreadyInstalled": "Installed", + "plugins.skillSource": "Plugin", +} as const; diff --git a/src/i18n/messages/zh-CN/index.ts b/src/i18n/messages/zh-CN/index.ts index 3561f1e89..5fc8175be 100644 --- a/src/i18n/messages/zh-CN/index.ts +++ b/src/i18n/messages/zh-CN/index.ts @@ -14,6 +14,7 @@ import { generation } from "./generation.ts"; import { library } from "./library.ts"; import { models } from "./models.ts"; import { settings } from "./settings.ts"; +import { plugins } from "./plugins.ts"; import { timeline } from "./timeline.ts"; import { tools } from "./tools.ts"; @@ -22,6 +23,7 @@ export const zhCN = { ...common, ...voiceLibrary, ...settings, + ...plugins, ...modelSetup, ...trace, ...canvas, diff --git a/src/i18n/messages/zh-CN/plugins.ts b/src/i18n/messages/zh-CN/plugins.ts new file mode 100644 index 000000000..bf61e76e8 --- /dev/null +++ b/src/i18n/messages/zh-CN/plugins.ts @@ -0,0 +1,25 @@ +export const plugins = { + "plugins.title": "插件", + "plugins.intro": "按需安装创作能力,并选择在哪些 Agent 引擎中启用。插件产物保存在当前工程。", + "plugins.source": "工作目录内的插件路径或下载地址", + "plugins.sourcePlaceholder": "plugins/my-plugin 或 https://…/plugin.zip", + "plugins.install": "安装", + "plugins.installName": "安装 {name}", + "plugins.upload": "选择 ZIP 文件", + "plugins.trust": "本地包请放在后端工作目录内的独立文件夹,不能使用工程或内部数据目录;也可上传 ZIP。仅安装可信插件;安装不会执行脚本,启用的技能沿用 Agent 现有权限。", + "plugins.working": "正在处理插件,请稍候…", + "plugins.loading": "正在读取插件…", + "plugins.saved": "插件设置已保存,下轮对话生效。已有任务和工程产物保留。", + "plugins.installedHint": "已安装。请选择要启用的引擎,再到助手的技能菜单使用。", + "plugins.installed": "已安装", + "plugins.empty": "尚未安装可选插件。可以选择下方示例,或安装自定义插件包。", + "plugins.uninstall": "卸载", + "plugins.uninstallName": "卸载 {name}", + "plugins.dependencies": "依赖", + "plugins.enableFor": "启用引擎", + "plugins.defaultRuntime": "默认引擎", + "plugins.examples": "官方示例", + "plugins.examplesHint": "示例需要手动安装和启用,未启用时不会进入 Agent 的技能目录。", + "plugins.alreadyInstalled": "已安装", + "plugins.skillSource": "插件", +} as const; diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 34341e02f..8a519620d 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -1,5 +1,11 @@ { "scripts": [ + { + "file": "plugins.mjs", + "lanes": ["extended", "production"], + "previewSafe": true, + "note": "Real package install, per-harness activation, native Skill discovery, disable, reload and uninstall in both languages; no model calls." + }, { "file": "heif_upload_recovery.mjs", "lanes": ["extended", "production"], diff --git a/tests/browser/plugins.mjs b/tests/browser/plugins.mjs new file mode 100644 index 000000000..fd96a8b6a --- /dev/null +++ b/tests/browser/plugins.mjs @@ -0,0 +1,141 @@ +/** Real plugin storage, native Skill discovery and bilingual settings; no model calls. */ +import assert from "node:assert/strict"; +import { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; +async function api(path, method = "GET", body) { + const response = await fetch(base + "/api" + path, { + method, headers, ...(body ? { body: JSON.stringify(body) } : {}), + }); + assert.ok(response.ok, await response.clone().text()); + return response.json(); +} +const health = await api("/creation-test-health"); +assert.equal(health.isolated, true); +assert.ok(!(await api("/plugins")).installed.some((item) => item.manifest.id === "studio-brief")); +const projectId = crypto.randomUUID(); +await api(`/creation/projects/${projectId}/commands`, "POST", { + type: "project.create", projectId, commandId: crypto.randomUUID(), + payload: { name: `Plugin UI ${projectId.slice(0, 8)}` }, +}); +const skillPath = `/creation/projects/${projectId}/assistant/skills`; +const pluginSkills = async (runtime) => (await api(`${skillPath}?runtime=${runtime}`)).filter((row) => row.source === "plugin"); +const browser = await launchBrowser(); +const screenshots = await mkdtemp(join(tmpdir(), "opendirector-plugins-ui-")); +const page = await browser.newPage({ locale: "en-US", viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(15000); +await page.addInitScript(() => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + if (!localStorage.getItem("opendirector.locale.v1")) localStorage.setItem("opendirector.locale.v1", "en-US"); +}); +const errors = []; +page.on("pageerror", (error) => errors.push(error.message)); +const settings = page.locator("#settings-dialog"); +const plugins = page.locator(".cw-plugin-settings"); +const installed = plugins.locator("section").first(); +async function saved() { + await page.waitForFunction(() => document.querySelector(".cw-plugin-settings")?.getAttribute("aria-busy") === "false"); + assert.equal(await plugins.getByRole("alert").count(), 0); +} +try { + await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`); + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await settings.getByRole("button", { name: "Plugins", exact: true }).click(); + await plugins.getByRole("button", { name: "Install Creative brief", exact: true }).click(); + await installed.getByRole("heading", { name: "Creative brief", exact: true }).waitFor(); + await saved(); + assert.equal(await installed.locator('input:checked').count(), 0); + assert.deepEqual(await pluginSkills("default"), []); + await plugins.locator("#plugin-source").fill("../outside-plugin"); + await plugins.getByRole("button", { name: "Install", exact: true }).click(); + await plugins.getByRole("alert").filter({ hasText: "inside the backend workspace" }).waitFor(); + await page.screenshot({ path: join(screenshots, "plugin-source-error-en.png") }); + await installed.getByRole("checkbox", { name: "DeepSeek Harness", exact: true }).click(); + await saved(); + assert.equal((await pluginSkills("deepseek"))[0].pluginId, "studio-brief"); + assert.deepEqual(await pluginSkills("default"), []); + await installed.getByRole("checkbox", { name: "Default", exact: true }).click(); + await saved(); + assert.equal(/[\u3400-\u9fff]/.test(await plugins.innerText()), false); + await page.screenshot({ path: join(screenshots, "plugins-en.png") }); + await page.keyboard.press("Escape"); + const trigger = page.getByRole("button", { name: "Use skills", exact: true }); + if (!(await trigger.isVisible())) await page.getByRole("button", { name: "Chat with AI", exact: true }).click(); + await page.getByRole("textbox", { name: "Message content", exact: true }).fill("Prepare a creative brief"); + await trigger.click(); + await page.getByRole("option", { name: /Creative brief/ }).click(); + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await settings.getByRole("button", { name: "Plugins", exact: true }).click(); + await installed.getByRole("checkbox", { name: "Default", exact: true }).click(); + await saved(); + await page.keyboard.press("Escape"); + await trigger.click(); + await page.waitForFunction(() => !document.querySelector('.cw-skill-popover [role="status"]')); + assert.equal(await page.getByRole("option", { name: /Creative brief/ }).count(), 0); + await page.keyboard.press("Escape"); + let [rejected] = await Promise.all([ + page.waitForResponse((response) => response.request().method() === "POST" && response.url().endsWith("/assistant/turns")), + page.getByRole("button", { name: "Send message", exact: true }).click(), + ]); + assert.equal(rejected.status(), 409); + await page.getByText("A selected skill is unavailable for this harness. Remove it from the message and select an available skill.", { exact: true }).waitFor(); + await page.screenshot({ path: join(screenshots, "skill-error-en.png") }); + await page.getByRole("button", { name: "Settings", exact: true }).click(); + await settings.getByRole("button", { name: "Plugins", exact: true }).click(); + await plugins.locator('input[type="file"]').setInputFiles({ name: "invalid.zip", mimeType: "application/zip", buffer: Buffer.from("invalid") }); + await plugins.getByRole("alert").filter({ hasText: "Invalid plugin package" }).waitFor(); + await settings.getByRole("button", { name: "General", exact: true }).click(); + await settings.locator("#settings-language").selectOption("zh-CN"); + await settings.getByRole("button", { name: "插件", exact: true }).click(); + await installed.getByRole("heading", { name: "创作简报", exact: true }).waitFor(); + assert.equal(await installed.getByRole("checkbox", { name: "DeepSeek Harness", exact: true }).isChecked(), true); + await page.screenshot({ path: join(screenshots, "plugins-zh.png") }); + await plugins.locator("#plugin-source").fill("../outside-plugin"); + await plugins.getByRole("button", { name: "安装", exact: true }).click(); + await plugins.getByRole("alert").filter({ hasText: "后端工作目录内" }).waitFor(); + await page.screenshot({ path: join(screenshots, "plugin-source-error-zh.png") }); + await plugins.locator('input[type="file"]').setInputFiles({ name: "invalid.zip", mimeType: "application/zip", buffer: Buffer.from("invalid") }); + await plugins.getByRole("alert").filter({ hasText: "插件包无效" }).waitFor(); + await plugins.locator('input[type="file"]').setInputFiles(fileURLToPath(new URL("../../plugins/examples/studio-brief.zip", import.meta.url))); + await saved(); + assert.equal(await installed.getByRole("checkbox", { name: "DeepSeek Harness", exact: true }).isChecked(), true); + await page.reload(); + await page.getByRole("button", { name: "设置", exact: true }).click(); + await settings.getByRole("button", { name: "插件", exact: true }).click(); + await installed.getByRole("heading", { name: "创作简报", exact: true }).waitFor(); + assert.equal(await installed.getByRole("checkbox", { name: "DeepSeek Harness", exact: true }).isChecked(), true); + await page.keyboard.press("Escape"); + const send = page.getByRole("button", { name: "发送消息", exact: true }); + if (!(await send.isVisible())) await page.getByRole("button", { name: "与 AI 对话", exact: true }).click(); + [rejected] = await Promise.all([ + page.waitForResponse((response) => response.request().method() === "POST" && response.url().endsWith("/assistant/turns")), + send.click(), + ]); + assert.equal(rejected.status(), 409); + await page.getByText("所选技能对当前引擎已不可用,请从消息中移除并重新选择。", { exact: true }).waitFor(); + await page.screenshot({ path: join(screenshots, "skill-error-zh.png") }); + await page.getByRole("button", { name: "设置", exact: true }).click(); + await settings.getByRole("button", { name: "插件", exact: true }).click(); + await installed.getByRole("button", { name: "卸载 创作简报", exact: true }).click(); + await saved(); + assert.deepEqual(await pluginSkills("deepseek"), []); + assert.equal((await api("/creation-test-health")).calls.length, health.calls.length); + assert.deepEqual(errors, []); + console.log(`Plugins: install, per-harness activation, native discovery, disable, ZIP replay, reload, bilingual errors and uninstall passed. Screenshots: ${screenshots}`); +} catch (error) { + await page.screenshot({ path: join(screenshots, "failure.png") }); + console.error(`Failure screenshot: ${screenshots}`); + throw error; +} finally { + try { + const plugin = (await api("/plugins")).installed.find((item) => item.manifest.id === "studio-brief"); + if (plugin) await api("/plugins/studio-brief", "DELETE", { digest: plugin.digest }); + } finally { + await browser.close(); + } +} diff --git a/tests/test_execution_files.py b/tests/test_execution_files.py index 19ce39b08..14993694c 100644 --- a/tests/test_execution_files.py +++ b/tests/test_execution_files.py @@ -86,6 +86,12 @@ def test_empty_files_and_directories_are_rejected(tmp_path): with execution_file(tmp_path, name): pytest.fail('Not a nonempty ordinary file') + with execution_file(tmp_path, 'empty', allow_empty=True) as stream: + assert stream.read() == b'' + with pytest.raises(ProjectError): + with execution_file(tmp_path, 'folder', allow_empty=True): + pytest.fail('Allowing empty files must not allow directories') + def test_symbolic_links_are_not_followed(tmp_path): work = tmp_path / 'work'; work.mkdir() diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 000000000..a63f4be95 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,674 @@ +"""Optional packages preserve native loading, project content and filesystem boundaries.""" +import asyncio +from dataclasses import replace +from io import BytesIO +import json +from pathlib import Path +import shutil +import stat +from uuid import uuid4 +from zipfile import ZIP_DEFLATED, ZipFile, ZipInfo + +from fastapi.testclient import TestClient +import httpx +import pytest + +from opendirector.agent.context import RunContext +from opendirector.agent.plugins import PluginRegistry, package_files, download_package, MAX_FILE_BYTES +from opendirector.agent.skills import skills +from opendirector.agent.skill_snapshot import prepare_skills +from opendirector.domain.projects import ProjectError +from opendirector.domain.creation.commands import parse_command +from opendirector.application.creation_canvas import asset_ref +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector.installation import plugin_examples +from opendirector_api.main import create_app +from test_agent_artifacts import publication +from test_assistant_conversations import assistant +from process_helpers import directory_link + +pytestmark = pytest.mark.ready +HEADERS = {'X-OpenDirector-Request': '1', 'Accept-Language': 'en-US'} + + +def custom_package(tmp_path, plugin_id='custom-brief', **changes): + root = tmp_path / plugin_id + shutil.copytree(plugin_examples() / 'studio-brief', root) + manifest = json.loads((root / 'opendirector-plugin.json').read_text()) + manifest.update(id=plugin_id, **changes) + (root / 'opendirector-plugin.json').write_text(json.dumps(manifest), encoding='utf-8') + (root / 'skills/studio-brief').rename(root / 'skills' / plugin_id) + entry = root / 'skills' / plugin_id / 'SKILL.md' + entry.write_text(entry.read_text().replace('name: studio-brief', f'name: {plugin_id}'), encoding='utf-8') + return root + + +def zipped(root, extra=()): + output = BytesIO() + with ZipFile(output, 'w', compression=ZIP_DEFLATED) as archive: + for path in sorted(root.rglob('*')): + if path.is_file(): + archive.writestr(path.relative_to(root).as_posix(), path.read_bytes()) + for name, value in extra: + archive.writestr(name, value) + return output.getvalue() + + +def test_install_enable_restart_disable_and_uninstall(tmp_path): + repository = tmp_path / 'workspace' + source = custom_package(repository) + registry = PluginRegistry(repository) + assert registry.catalog()['installed'] == [] + assert registry.catalog()['examples'][0]['manifest']['id'] == 'studio-brief' + item = registry.install(str(source)) + assert item['enabledRuntimes'] == [] + assert registry.skills('default') == [] + registry.change('custom-brief', item['digest'], runtime='codex', enabled=True) + replay = registry.install_archive(zipped(source)) + assert replay['digest'] == item['digest'] + assert replay['enabledRuntimes'] == ['codex'] + restarted = PluginRegistry(repository) + assert restarted.skills('default') == [] + loaded = restarted.skills('codex') + assert loaded[0]['pluginId'] == 'custom-brief' + work = tmp_path / 'work' + prepare_skills(work, loaded) + saved = (work / '.agents/skills/custom-brief/SKILL.md').read_bytes() + restarted.change('custom-brief', item['digest'], runtime='codex', enabled=False) + assert restarted.skills('codex') == [] + restarted.change('custom-brief', item['digest']) + assert restarted.catalog()['installed'] == [] + assert (work / '.agents/skills/custom-brief/SKILL.md').read_bytes() == saved + assert Path(loaded[0]['filePath']).read_bytes() == saved + assert not (repository / 'projects').exists() + + +def test_dependencies_versions_and_conflicts_preserve_state(tmp_path): + registry = PluginRegistry(tmp_path / 'workspace') + base = registry.install('example:studio-brief') + extra = registry.install(str(custom_package(tmp_path / 'workspace', dependencies={'studio-brief': '1.0.0'}))) + with pytest.raises(ProjectError) as error: + registry.change('custom-brief', extra['digest'], runtime='codex', enabled=True) + assert error.value.code == 'plugin_dependency_missing' + registry.change('studio-brief', base['digest'], runtime='default', enabled=True) + with pytest.raises(ProjectError): + registry.change('custom-brief', extra['digest'], runtime='codex', enabled=True) + registry.change('studio-brief', base['digest'], runtime='codex', enabled=True) + registry.change('custom-brief', extra['digest'], runtime='codex', enabled=True) + before = registry.path.read_bytes() + for kwargs in ({}, {'runtime': 'codex', 'enabled': False}): + with pytest.raises(ProjectError) as error: + registry.change('studio-brief', base['digest'], **kwargs) + assert error.value.code == 'plugin_required' + assert registry.path.read_bytes() == before + with pytest.raises(ProjectError) as error: + registry.change('studio-brief', '0' * 64, runtime='codex', enabled=False) + assert error.value.code == 'plugin_changed' + source = custom_package(tmp_path / 'workspace', 'new-brief', runtimes=['codex']) + newer = registry.install(str(source)) + with pytest.raises(ProjectError) as error: + registry.change('new-brief', newer['digest'], runtime='default', enabled=True) + assert error.value.code == 'plugin_runtime_unsupported' + (source / 'skills/new-brief/SKILL.md').write_text((source / 'skills/new-brief/SKILL.md').read_text() + '\nchanged') + with pytest.raises(ProjectError) as error: + registry.install(str(source)) + assert error.value.code == 'plugin_conflict' + + +@pytest.mark.parametrize('name', ['../outside', '/outside', 'skills/../../outside', 'C:/outside', + 'skills\\outside', 'a//b', './outside', 'con.txt', 'name.', + 'a*b', 'a?b', 'a"b', 'ab', 'a|b', 'a\nb', 'a\rb', 'a\tb', 'a\x01b']) +def test_archive_paths_cannot_escape_or_alias(tmp_path, name): + registry = PluginRegistry(tmp_path / 'workspace') + source = custom_package(tmp_path) + with pytest.raises(ProjectError) as error: + registry.install_archive(zipped(source, [(name, b'bad')])) + assert error.value.code == 'plugin_unsafe_path' + assert registry.catalog()['installed'] == [] + assert not (tmp_path / 'outside').exists() + + +def test_links_special_files_duplicate_paths_and_bombs_are_rejected(tmp_path): + source = custom_package(tmp_path) + link = ZipInfo('link') + link.create_system = 3 + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + fifo = ZipInfo('pipe') + fifo.create_system = 3 + fifo.external_attr = (stat.S_IFIFO | 0o600) << 16 + for extra in ([(link, b'/etc/passwd')], [(fifo, b'')], [('README', b'a'), ('readme', b'b')], + [('dir/a', b'a'), ('DIR/b', b'b')], [('file', b'a'), ('file/child', b'b')], + [('é.txt', b'a'), ('e\u0301.txt', b'b')], + [('large.txt', b'x' * (MAX_FILE_BYTES + 1))]): + with pytest.raises(ProjectError): + package_files(zipped(source, extra)) + unsupported = bytearray(zipped(source)) + for signature, offset in ((b'PK\x03\x04', 8), (b'PK\x01\x02', 10)): + position = unsupported.index(signature) + offset + unsupported[position:position + 2] = (99).to_bytes(2, 'little') + with pytest.raises(ProjectError) as error: + package_files(bytes(unsupported)) + assert error.value.code == 'plugin_invalid' + (source / 'alias').symlink_to(tmp_path, target_is_directory=True) + with pytest.raises(ProjectError) as error: + package_files(source) + assert error.value.code == 'plugin_unsafe_path' + + +@pytest.mark.parametrize('changes', [{'schemaVersion': 2}, {'schemaVersion': True}, {'runtimes': ['unknown']}, + {'runtimes': ['default', 'default']}, {'hooks': {'install': 'touch dangerous'}}, + {'dependencies': {'custom-brief': '1.0.0'}}, {'name': {'en-US': 'Missing Chinese'}}, + {'name': {'zh-CN': ' ', 'en-US': 'Blank Chinese'}}]) +def test_invalid_manifest_never_runs_or_registers(tmp_path, changes): + registry = PluginRegistry(tmp_path / 'workspace') + source = custom_package(tmp_path / 'workspace', **changes) + with pytest.raises(ProjectError) as error: + registry.install(str(source)) + assert error.value.code == 'plugin_invalid' + assert registry.catalog()['installed'] == [] + + +def test_frontmatter_delimiters_unicode_paths_and_byte_limit(tmp_path): + source = custom_package(tmp_path) + entry = source / 'skills/custom-brief/SKILL.md' + entry.write_bytes(b'---\r\nname: custom-brief\r\ndescription: "Use --- within text"\r\n---\r\nBody') + first = package_files(zipped(source, [('skills/custom-brief/é.md', b'notes')])) + second = package_files(zipped(source, [('skills/custom-brief/e\u0301.md', b'notes')])) + assert first[2] == second[2] + entry.write_text('---\nname: custom-brief\ndescription: Brief\n---\n' + '字' * 22000, encoding='utf-8') + with pytest.raises(ProjectError) as error: + package_files(source) + assert error.value.code == 'plugin_invalid' + + +def test_broken_registry_and_failed_commit_preserve_original(tmp_path, monkeypatch): + from opendirector.agent import plugins + registry = PluginRegistry(tmp_path / 'workspace') + original = registry.install('example:studio-brief') + before = registry.path.read_bytes() + def fail(*args): + raise OSError('simulated disk failure') + with monkeypatch.context() as patch: + patch.setattr(plugins, 'write_json', fail) + with pytest.raises(OSError): + registry.change('studio-brief', original['digest'], runtime='default', enabled=True) + with pytest.raises(OSError): + registry.install(str(custom_package(tmp_path / 'workspace'))) + assert registry.path.read_bytes() == before + assert registry.install(str(tmp_path / 'workspace/custom-brief'))['manifest']['id'] == 'custom-brief' + registry.path.write_text('{broken') + with pytest.raises(ProjectError) as error: + registry.install('example:studio-brief') + assert error.value.code == 'plugin_registry_invalid' + assert registry.path.read_text() == '{broken' + + +def test_http_optional_installation_and_bilingual_errors(tmp_path): + root = custom_package(tmp_path) + with TestClient(create_app(LocalProjects(tmp_path / 'workspace')), headers=HEADERS) as client: + assert client.get('/api/plugins', headers={'Origin': 'https://evil.example'}).status_code == 403 + assert client.post('/api/plugins', json={'source': str(root)}, headers={'X-OpenDirector-Request': ''}).status_code == 403 + installed = client.post('/api/plugins/upload', content=zipped(root), headers={'Content-Type': 'application/zip'}) + assert installed.status_code == 200, installed.text + row = installed.json() + assert row['source'] == 'upload' + assert row['enabledRuntimes'] == [] + assert client.put('/api/plugins/custom-brief/runtimes/codex', json={'digest': row['digest'], 'enabled': True}).status_code == 200 + invalid = {'digest': '0' * 64, 'enabled': False} + english = client.put('/api/plugins/custom-brief/runtimes/codex', json=invalid) + chinese = client.put('/api/plugins/custom-brief/runtimes/codex', json=invalid, headers={'Accept-Language': 'zh-CN'}) + assert english.status_code == chinese.status_code == 409 + assert english.json()['code'] == chinese.json()['code'] == 'plugin_changed' + assert 'Refresh' in english.json()['detail'] + assert '刷新' in chinese.json()['detail'] + assert client.request('DELETE', '/api/plugins/custom-brief', json={'digest': row['digest']}).status_code == 200 + assert client.get('/api/plugins').json()['installed'] == [] + + +def test_public_download_rejects_private_hosts_and_rechecks_redirects(tmp_path, monkeypatch): + from opendirector.agent import plugins + package = zipped(custom_package(tmp_path)) + requests = [] + mode = 'zip' + def serve(request): + requests.append(request) + return httpx.Response(302, headers={'Location': 'https://127.0.0.1/private'}) if mode == 'redirect' else httpx.Response(200, stream=httpx.ByteStream(package)) + original = httpx.Client + monkeypatch.setattr(plugins.httpx, 'Client', lambda **kwargs: original(**kwargs, transport=httpx.MockTransport(serve))) + assert download_package('https://8.8.8.8/package.zip') == package + assert requests[0].headers['host'] == '8.8.8.8' + assert 'authorization' not in requests[0].headers + installed = PluginRegistry(tmp_path / 'workspace').install('https://8.8.8.8/package.zip?token=secret#section') + assert installed['manifest']['id'] == 'custom-brief' + assert installed['source'] == 'https://8.8.8.8/package.zip' + mode = 'redirect' + with pytest.raises(ProjectError) as error: + download_package('https://8.8.8.8/package.zip') + assert error.value.code == 'plugin_url_unsafe' + assert len(requests) == 3 + for url in ('http://8.8.8.8/package.zip', 'https://127.0.0.1/a', 'https://user:secret@8.8.8.8/a', 'https://[::1]/a'): + with pytest.raises(ProjectError) as error: + download_package(url) + assert error.value.code == 'plugin_url_unsafe' + assert len(requests) == 3 + + +def test_native_skill_discovery_respects_harness_and_disable(tmp_path): + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + baseline = asyncio.run(skills(tmp_path, tmp_path / 'project')) + assert all(row['source'] != 'plugin' for row in baseline) + registry.change('studio-brief', item['digest'], runtime='default', enabled=True) + found = asyncio.run(skills(tmp_path, tmp_path / 'project')) + plugin = next(row for row in found if row['name'] == 'studio-brief') + assert plugin['source'] == 'plugin' + assert plugin['displayName']['zh-CN'] == '创作简报' + assert all(row['source'] != 'plugin' for row in asyncio.run(skills(tmp_path, tmp_path / 'project', 'codex'))) + registry.change('studio-brief', item['digest'], runtime='default', enabled=False) + assert asyncio.run(skills(tmp_path, tmp_path / 'project')) == baseline + + +def test_plugin_change_starts_new_native_session_without_erasing_history(tmp_path): + plugin = {'pluginId': 'studio-brief', 'pluginDigest': '1' * 64} + run = RunContext(runtime='codex', project_id=uuid4(), turn_id=uuid4(), session=str(uuid4()), + directory=tmp_path, conversation_id=uuid4(), config=None, messages=[{'role': 'user', 'content': 'first'}], + selected_skills=[], skills=[plugin]) + run.save_native_session('session-one', {}) + record = run.native_session_path() / 'session.json' + before = record.read_bytes() + next_run = replace(run, messages=[*run.messages, {'role': 'assistant', 'content': 'done'}, {'role': 'user', 'content': 'next'}]) + assert next_run.native_session_id({}) == 'session-one' + assert replace(next_run, skills=[]).native_session_id({}) is None + assert replace(next_run, skills=[{**plugin, 'pluginDigest': '2' * 64}]).native_session_id({}) is None + assert record.read_bytes() == before + + +def test_uninstall_preserves_published_editable_brief(publication): + business, run, work = publication + registry = PluginRegistry(run.directory.parent.parent) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest'], runtime='codex', enabled=True) + prepare_skills(work, registry.skills('codex')) + template = work / '.agents/skills/studio-brief/templates/brief.en.md' + content = template.read_text().replace('Describe the audience, message, intended duration and requirements supplied by the user.', + 'A 15-second studio introduction for new customers.') + (work / 'brief.md').write_text(content, encoding='utf-8') + result = asyncio.run(business.execute(run.project_id, run.turn_id, run.session, 'publish-brief', + 'execute_command', {'type': 'artifact.publish', 'payload': {'path': 'brief.md', 'name': 'Creative brief', 'expectedKind': 'text'}}, + roots=[], config=None, native_runtime='codex')) + assert result['status'] == 'applied' + asset_id = result['changed'][0]['id'] + saved = business.assets.get(run.project_id, asset_id) + assert saved.kind == 'text' + registry.change('studio-brief', item['digest']) + assert business.assets.get(run.project_id, asset_id) == saved + stream, _ = business.assets.open_media(run.project_id, saved.id) + with stream: + assert stream.read() == content.encode() + edited = business.projects.execute(parse_command(dict(type='asset.writeText', projectId=run.project_id, + commandId=uuid4(), payload=dict(name='Revised brief.md', text='User revision', previousAsset=asset_ref(saved).model_dump(mode='json')), + expectedVersions=[dict(objectType='asset', id=saved.id, revision=saved.revision)])), session=run.session) + assert edited.status == 'applied' + revised = business.assets.get(run.project_id, edited.changed[0].id) + assert revised.provenance.sources == (asset_ref(saved),) + stream, _ = business.assets.open_media(run.project_id, revised.id) + with stream: + assert stream.read() == b'User revision' + assert registry.skills('codex') == [] + + +def test_plugin_cannot_shadow_builtin_skill(tmp_path): + registry = PluginRegistry(tmp_path) + item = registry.install(str(custom_package(tmp_path, 'character-replacement'))) + registry.change('character-replacement', item['digest'], runtime='default', enabled=True) + with pytest.raises(ProjectError) as error: + asyncio.run(skills(tmp_path, tmp_path / 'project')) + assert error.value.code == 'plugin_skill_conflict' + registry.change('character-replacement', item['digest'], runtime='default', enabled=False) + assert any(row['source'] == 'builtin' for row in asyncio.run(skills(tmp_path, tmp_path / 'project'))) + + +@pytest.mark.parametrize('entry', ['skills/custom-brief/sub/SKILL.md', 'skills/custom-brief/sub/skill.md', + 'skills/custom-brief/sub/SkIlL.Md', 'docs/SKILL.md']) +def test_package_rejects_every_extra_native_skill_entry(tmp_path, entry): + registry = PluginRegistry(tmp_path / 'workspace') + source = custom_package(tmp_path) + with pytest.raises(ProjectError) as error: + registry.install_archive(zipped(source, [(entry, b'---\nname: character-replacement\ndescription: Hidden\n---\nHidden')])) + assert error.value.code == 'plugin_invalid' + assert registry.catalog()['installed'] == [] + + +@pytest.mark.parametrize('unexpected', ['nested', 'duplicate', 'renamed', 'outside']) +def test_discovery_rejects_untracked_plugin_entries(tmp_path, monkeypatch, unexpected): + import importlib + discovery = importlib.import_module('opendirector.agent.skills') + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest'], runtime='default', enabled=True) + entry = Path(registry.skills('default')[0]['filePath']) + plugin = dict(name='studio-brief', description='Brief', location=str(entry)) + location = entry.parent / 'nested/SKILL.md' if unexpected == 'nested' else tmp_path / '.opendirector/skills/hidden/SKILL.md' + location.parent.mkdir(parents=True, exist_ok=True) + location.write_text('Untracked skill', encoding='utf-8') + # The catalog boundary must reject a native-loader surprise independently of package validation. + monkeypatch.setattr(PluginRegistry, 'verify', lambda *_: None) + async def catalog(roots): + if entry.parent.parent not in roots: + return [] + if unexpected == 'renamed': + return [{**plugin, 'name': 'untracked'}] + return [plugin, plugin if unexpected == 'duplicate' else dict(name='untracked', description='Hidden', location=str(location))] + monkeypatch.setattr(discovery, 'native_catalog', catalog) + with pytest.raises(ProjectError) as error: + asyncio.run(discovery.skills(tmp_path, tmp_path / 'project')) + assert error.value.code == 'plugin_skill_conflict' + + +def test_local_directory_uses_canonical_root_without_accepting_package_links(tmp_path): + workspace = tmp_path / 'workspace' + source = custom_package(workspace) + registry = PluginRegistry(workspace) + item = registry.install(str(source / '..' / source.name)) + parent_alias = tmp_path / 'parent-alias' + directory_link(parent_alias, workspace) + assert registry.install(str(parent_alias / source.name))['digest'] == item['digest'] + root_alias = workspace / 'root-alias' + directory_link(root_alias, source) + with pytest.raises(ProjectError) as error: + registry.install(str(root_alias)) + assert error.value.code == 'plugin_unsafe_path' + directory_link(source / 'nested-link', source / 'skills') + with pytest.raises(ProjectError) as error: + registry.install(str(parent_alias / source.name)) + assert error.value.code == 'plugin_unsafe_path' + + +@pytest.mark.parametrize('source_kind', ['absolute', 'traversal', 'prefix-sibling', 'parent-link']) +def test_http_local_install_rejects_outside_workspace_before_reading(tmp_path, monkeypatch, source_kind): + from opendirector.agent import plugins + workspace = tmp_path / 'workspace' + workspace.mkdir() + outside = custom_package(tmp_path / ('workspace-private' if source_kind == 'prefix-sibling' else 'private')) + source = str(outside) + if source_kind == 'traversal': + source = '../private/custom-brief' + elif source_kind == 'parent-link': + directory_link(workspace / 'linked-parent', outside.parent) + source = 'linked-parent/custom-brief' + def unexpected_read(*args): + raise AssertionError('Out-of-scope input reached the package reader') + monkeypatch.setattr(plugins, 'package_files', unexpected_read) + with TestClient(create_app(LocalProjects(workspace)), headers=HEADERS) as client: + for language, message in [('en-US', 'inside the backend workspace'), ('zh-CN', '后端工作目录内')]: + response = client.post('/api/plugins', json={'source': source}, headers={'Accept-Language': language}) + assert response.status_code == 403 + assert response.json()['code'] == 'plugin_source_outside_workspace' + assert message in response.json()['detail'] + assert client.get('/api/plugins').json()['installed'] == [] + + +def test_workspace_paths_and_uploaded_external_packages_remain_available(tmp_path): + workspace = tmp_path / 'workspace' + source = custom_package(workspace) + registry = PluginRegistry(workspace) + item = registry.install(source.name) + assert registry.install(str(source))['digest'] == item['digest'] + assert registry.install(str(source / '..' / source.name))['digest'] == item['digest'] + (workspace / 'source.zip').write_bytes(zipped(source)) + assert registry.install('source.zip')['digest'] == item['digest'] + outside_alias = tmp_path / 'workspace-alias' + directory_link(outside_alias, workspace) + assert registry.install(str(outside_alias / source.name))['digest'] == item['digest'] + external = custom_package(tmp_path / 'external', 'external-brief') + with TestClient(create_app(LocalProjects(workspace)), headers=HEADERS) as client: + uploaded = client.post('/api/plugins/upload', content=zipped(external), headers={'Content-Type': 'application/zip'}) + assert uploaded.status_code == 200 + assert uploaded.json()['manifest']['id'] == 'external-brief' + assert uploaded.json()['enabledRuntimes'] == [] + + +@pytest.mark.parametrize('entry, kind', [ + ('install', 'path'), ('install', 'archive'), ('install', 'missing'), + ('install_archive', 'path'), ('install_archive', 'text'), ('install_archive', 'missing'), +]) +def test_install_entry_types_cannot_bypass_source_scope(tmp_path, entry, kind): + source = custom_package(tmp_path / 'outside') + registry = PluginRegistry(tmp_path / 'workspace') + value = {'path': source, 'archive': zipped(source), 'text': str(source), 'missing': None}[kind] + with pytest.raises(ProjectError) as error: + getattr(registry, entry)(value) + assert error.value.code == 'plugin_invalid' + assert not registry.path.exists() + assert not (registry.directory / 'packages').exists() + + +@pytest.mark.parametrize('source', ['bad\x00path', 'bad\npath', 'bad\tpath', 'C:relative']) +def test_http_local_source_rejects_invalid_path_text(tmp_path, source): + with TestClient(create_app(LocalProjects(tmp_path)), headers=HEADERS, raise_server_exceptions=False) as client: + response = client.post('/api/plugins', json={'source': source}) + assert response.status_code == 400 + assert response.json()['code'] == 'plugin_unsafe_path' + assert client.get('/api/plugins').json()['installed'] == [] + + +@pytest.mark.parametrize('folder', ['projects', '.opendirector', '.']) +def test_local_source_excludes_project_storage_and_workspace_root(tmp_path, monkeypatch, folder): + from opendirector.agent import plugins + registry = PluginRegistry(tmp_path) + def unexpected_read(*args): + raise AssertionError('Internal storage reached the package reader') + monkeypatch.setattr(plugins, 'package_files', unexpected_read) + with pytest.raises(ProjectError) as error: + registry.install(folder if folder == '.' else folder + '/custom-brief') + assert error.value.code == 'plugin_source_outside_workspace' + + +@pytest.mark.parametrize('kind', ['resource', 'zip']) +def test_local_package_rejects_hardlinked_files(tmp_path, kind): + workspace = tmp_path / 'workspace' + source = custom_package(workspace) + outside = tmp_path / 'outside' + if kind == 'zip': + outside.write_bytes(zipped(source)) + source = workspace / 'source.zip' + source.hardlink_to(outside) + else: + outside.write_bytes(b'outside secret') + (source / 'skills/custom-brief/private.txt').hardlink_to(outside) + registry = PluginRegistry(workspace) + with pytest.raises(ProjectError) as error: + registry.install(str(source)) + assert error.value.code == 'plugin_unsafe_path' + assert registry.catalog()['installed'] == [] + + +@pytest.mark.parametrize('kind', ['resource', 'directory', 'zip']) +def test_local_package_rejects_link_replacement_after_inspection(tmp_path, monkeypatch, kind): + from opendirector.agent import plugins + workspace = tmp_path / 'workspace' + source = custom_package(workspace) + outside = custom_package(tmp_path / 'private') + (outside / 'skills/custom-brief/private.txt').write_bytes(b'outside secret') + target = source + if kind == 'zip': + source = target = workspace / 'source.zip' + source.write_bytes(zipped(outside)) + archive = tmp_path / 'private.zip' + archive.write_bytes(zipped(outside)) + outside = archive + elif kind == 'resource': + target = source / 'skills/custom-brief/private.txt' + target.write_bytes(b'public resource') + outside = outside / 'skills/custom-brief/private.txt' + original = plugins.is_alias + replaced = [] + def inspect_then_replace(path): + result = original(path) + if path == target and not replaced: + path.rename(path.with_name(path.name + '-saved')) + if kind == 'directory': + directory_link(path, outside) + else: + try: + path.symlink_to(outside) + except OSError as error: + if getattr(error, 'winerror', None) == 1314: + pytest.skip('Windows file symlink privilege unavailable; directory junction case runs separately') + raise + replaced.append(path) + return result + monkeypatch.setattr(plugins, 'is_alias', inspect_then_replace) + registry = PluginRegistry(workspace) + with pytest.raises(ProjectError) as error: + registry.install(str(source)) + assert replaced == [target] + assert error.value.code == 'plugin_unsafe_path' + assert registry.catalog()['installed'] == [] + + +def test_local_package_preserves_empty_resource_files(tmp_path): + source = custom_package(tmp_path) + empty = 'skills/custom-brief/empty.txt' + (source / empty).touch() + assert package_files(source)[1][empty] == b'' + assert package_files(source)[2] == package_files(zipped(source))[2] + + +@pytest.mark.parametrize('damage', ['missing', 'changed', 'unreadable']) +def test_reinstall_preserves_damaged_cache_and_existing_turn_snapshot(tmp_path, monkeypatch, damage): + from opendirector.agent import plugins + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest'], runtime='default', enabled=True) + work = tmp_path / 'work' + prepare_skills(work, registry.skills('default')) + snapshot = work / '.agents/skills/studio-brief/SKILL.md' + before = snapshot.read_bytes() + cached = registry.directory / 'packages' / item['digest'] + entry = cached / 'skills/studio-brief/SKILL.md' + if damage == 'missing': + entry.unlink() + elif damage == 'changed': + entry.write_bytes(before + b'\nChanged') + else: + original = plugins.os.scandir + unreadable = [True] + def read(source): + if not isinstance(source, int) and Path(source) == cached / 'skills/studio-brief/templates' and unreadable: + unreadable.pop() + raise PermissionError('Unreadable cache') + return original(source) + monkeypatch.setattr(plugins.os, 'scandir', read) + registry.change('studio-brief', item['digest']) + repaired = registry.install('example:studio-brief') + assert repaired['enabledRuntimes'] == [] + assert package_files(cached)[2] == repaired['digest'] == item['digest'] + assert snapshot.read_bytes() == before + preserved = list(registry.directory.glob('.damaged-*/package')) + assert len(preserved) == 1 + saved_entry = preserved[0] / 'skills/studio-brief/SKILL.md' + if damage == 'missing': + assert not saved_entry.exists() + else: + assert saved_entry.read_bytes() == before + (b'\nChanged' if damage == 'changed' else b'') + + +def test_failed_cache_repair_preserves_old_files_and_can_retry(tmp_path, monkeypatch): + from opendirector.agent import plugins + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest']) + cached = registry.directory / 'packages' / item['digest'] + (cached / 'opendirector-plugin.json').write_bytes(b'Corrupt original') + original = plugins.os.replace + def fail_publication(source, target): + if target == cached: + raise OSError('Replacement failed') + return original(source, target) + with monkeypatch.context() as patch: + patch.setattr(plugins.os, 'replace', fail_publication) + with pytest.raises(OSError, match='Replacement failed'): + registry.install('example:studio-brief') + assert registry.catalog()['installed'] == [] + preserved = list(registry.directory.glob('.damaged-*/package/opendirector-plugin.json')) + assert len(preserved) == 1 and preserved[0].read_bytes() == b'Corrupt original' + assert not cached.exists() + assert registry.install('example:studio-brief')['digest'] == item['digest'] + assert package_files(cached)[2] == item['digest'] + + +def test_catalog_archives_template_and_wheel_install(tmp_path, monkeypatch): + from opendirector import installation + from opendirector.agent import plugins + root = Path(__file__).resolve().parents[1] + package_files(root / 'plugins/template') + catalog = json.loads((root / 'plugins/catalog.json').read_text()) + for entry in catalog: + archive = root / 'plugins/examples' / (entry['manifest']['id'] + '.zip') + assert package_files(archive)[2] == entry['digest'] + assert package_files(plugin_examples() / entry['manifest']['id'])[2] == entry['digest'] + bundled = tmp_path / 'bundled' + bundled.mkdir() + shutil.copy(root / 'plugins/catalog.json', bundled / 'plugin-catalog.json') + monkeypatch.setattr(installation, 'SOURCE_ROOT', None) + monkeypatch.setattr(installation, 'BUNDLED', bundled) + requests = [] + def download(url): + requests.append(url) + return (root / 'plugins/examples/studio-brief.zip').read_bytes() + monkeypatch.setattr(plugins, 'download_package', download) + registry = PluginRegistry(tmp_path / 'workspace') + assert registry.catalog()['installed'] == [] + assert requests == [] + assert registry.install('example:studio-brief')['enabledRuntimes'] == [] + assert requests == [catalog[0]['url']] + assert not (bundled / 'plugin-examples').exists() + + +def test_corrupt_installed_package_can_be_disabled_and_removed(tmp_path): + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest'], runtime='default', enabled=True) + shutil.rmtree(registry.directory / 'packages' / item['digest']) + with pytest.raises(ProjectError) as error: + registry.skills('default') + assert error.value.code == 'plugin_invalid' + registry.change('studio-brief', item['digest'], runtime='default', enabled=False) + before = registry.path.read_bytes() + with pytest.raises(ProjectError): + registry.change('studio-brief', item['digest'], runtime='default', enabled=True) + assert registry.path.read_bytes() == before + registry.change('studio-brief', item['digest']) + assert registry.skills('default') == [] + + +@pytest.mark.parametrize('runtime', ['default', 'opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek']) +def test_turn_catalog_and_disabled_selection_use_same_runtime(assistant, monkeypatch, tmp_path, runtime): + from opendirector_api import agent + client, path, _ = assistant + monkeypatch.setattr(agent, 'skills', skills) + registry = PluginRegistry(tmp_path) + item = registry.install('example:studio-brief') + registry.change('studio-brief', item['digest'], runtime=runtime, enabled=True) + found = client.get(path + '/skills', params={'runtime': runtime}).json() + assert any(row.get('pluginId') == 'studio-brief' for row in found) + assert all('filePath' not in row and 'pluginDigest' not in row for row in found) + accepted = [] + async def stream(self, run): + accepted.append(run) + yield {'type': 'delta', 'text': 'Fixture only'} + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + request = {'id': str(uuid4()), 'conversationId': client.get(path).json()['conversationId'], + 'text': 'Create a brief', 'runtime': runtime, 'skills': ['studio-brief']} + assert client.post(path + '/turns', json=request).status_code == 200 + assert accepted[0].selected_skills == ['studio-brief'] + assert accepted[0].plugin_versions() == {'studio-brief': item['digest']} + registry.change('studio-brief', item['digest'], runtime=runtime, enabled=False) + assert all(row.get('pluginId') != 'studio-brief' for row in client.get(path + '/skills', params={'runtime': runtime}).json()) + for language, expected in [('en-US', 'Remove it from the message'), ('zh-CN', '从消息中移除')]: + rejected = client.post(path + '/turns', json={**request, 'id': str(uuid4())}, headers={'Accept-Language': language}) + assert rejected.status_code == 409 + assert rejected.json()['code'] == 'agent_skill_unavailable' + assert expected in rejected.json()['detail'] + assert len(accepted) == 1