The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
feat: continue installed OpenMotion tools in the current agent chat
罗高d5d1d4a6924e
diff --git a/docs/install.md b/docs/install.mdindex 77a8f06b..1ceadf22 100644--- a/docs/install.md+++ b/docs/install.md@@ -9,7 +9,7 @@ If you are reading this file in the source repository and see `{{...}}`, it is a1. Collect OS/CPU, Node.js/npm versions and the current Agent identity together, using the host's supplied context where available. Node.js 22.18+ with npm and the Agent must already be installed. Supported native targets: {{TARGETS}}. If a macOS target has no declared minimum version, proceed with setup and native executable checks; do not infer a minimum from the build/test machine's OS version. Do not claim support for another target from package-download success.2. Select the current host explicitly: `codex` (Codex), `claude` (Claude Code), `deepseek` (DeepSeek Harness) or `workbuddy` (WorkBuddy). An explicit user selection takes precedence. Do not infer the current host from which CLIs happen to be installed. Ask only when the current host or required profile cannot be established. Configure only that host; preserve projects, credentials and unrelated MCP/Skills settings.3. For a test candidate, use a separate host profile, application home, project data and Skills directory. Keep those paths and reuse them for prepare and future reconnects. The [platform installation recipes]({{DETAILS_URL}}) describe the actual supported options. Do not run a test candidate into the user's daily profile by default.-4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. When the current host can discover the eleven public Tools and five Skills, verify the version/environment and make an actual `openmotion_get_project` call. If the current chat has not loaded them, report that limitation; registration alone does not prove loading. Do not postpone the installation reply or invitation until a new chat or the first MCP call.+4. Choose exactly one setup command below, applying the test isolation paths first when required. Setup starts checked video-component downloads in the background. Do not wait for prepare to connect MCP, create/edit projects or open ordinary preview. Studio shows preparation status and retry; media import, automated capture and export require their respective components. Compatible phase-one updates can keep existing connections; reconnect closed or incompatible transports. When the current host can discover the eleven public Tools and five Skills, verify the version/environment and make an actual `openmotion_get_project` call. If this chat has not loaded them or still points at another installation, use `onboarding.directAccess` below; registration alone does not prove native loading. Do not postpone the installation reply or invitation until a new chat or the first MCP call.5. On successful setup, follow the installation-success reply below in this same conversation, using the returned `onboarding.catalog` summaries. Installation does not authorize creating a project, downloading template assets, rendering or calling a paid model. Report a failed installation honestly; do not issue a success invitation until it is fixed.For npm network failures, automatically try `https://registry.npmjs.org` then `https://registry.npmmirror.com`, at most once per registry, counting the initial failed attempt. Respect an explicitly selected registry and host policy. Set `npm_config_registry` and `npm_config_fetch_retries=0` only for that attempt, including setup's npm child process. Keep the exact version; verify any mirrored tgz against the matching immutable guide's SHA256 before executing it. If both fail, follow [npm download recovery]({{DETAILS_URL}}#npm-download-failures) for network checks and a terminal handoff. Permission or checksum failures stop immediately. A local tgz still needs npm access for setup's production dependencies.@@ -33,7 +33,7 @@ Reply structure, in the user's language:2. Directly invite the user to try one selected template with its appeal, or three numbered candidates with concise differences and confirmed durations where available. Keep each ID mapped to its displayed number/name in this conversation.3. A yes/no question for one template, or a number/name choice for three, with an option to defer. Then stop and wait.-Do not ask the user to refresh/reconnect, restart the host or open a new chat by default. Only when an actual tool call or requested operation is blocked, attempt supported recovery within the current chat when available. If user action is still necessary, briefly explain the specific blocker and the minimum supported next step. Mention video-component preparation only when it blocks the requested operation. Preserve the accepted template choice and existing work across recovery.+Do not ask the user to refresh/reconnect, restart the host or open a new chat by default. When native tools are missing or stale, use setup’s `onboarding.directAccess`: run its `command` with `toolsArgs`, read the public input schemas, then run `callArgs` with the selected Tool and a JSON arguments file. It uses this installation’s actual registered MCP transport, version and data directory, so the current chat can continue without restarting or opening another chat. It does not refresh native discovery. Keep these technical details internal. Never bypass disabled tools, permission denials or host policy. Attempt supported host recovery only if direct access is unavailable or fails. If user action is still necessary, briefly explain the specific blocker and the minimum supported next step. Mention video-component preparation only when it blocks the requested operation. Preserve the accepted template choice and existing work across recovery.After acceptance, use openmotion-template-to-video with the exact offered template ID and unchanged sample content. A single-template “yes/体验” accepts that template; a three-candidate “yes” is ambiguous, so ask which one. Do not reshuffle, re-query just to change the offer, or silently substitute a failed template. Create one independent project, preserving existing work; reuse the same experience project on continuation. Do not repeat optional material/brand/style questions. Open the actual editable project and check loading/playback when the host supports it; otherwise give its real link and state the limitation. Export only on request. A refusal/deferment stops the experience. If creation is blocked by unavailable tools, follow the recovery rule above. No invitation-state service or “invitation sent/seen” telemetry is implied; only the host controls its actual reply.diff --git a/docs/npm-installation.md b/docs/npm-installation.mdindex 9c32f508..7396c483 100644--- a/docs/npm-installation.md+++ b/docs/npm-installation.md@@ -111,21 +111,34 @@ For a non-Codex test, keep the isolated application/data paths from the examplesHarness callers should pass the actual current profile from their host context, such as `DSH_PROFILE`, rather than assuming `web` or `desktop`. On macOS, setup already detects the standard Desktop CLI at `/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh`; it need not be on PATH. Keep that host-specific lookup in the Harness adapter. Other executable locations use `--dsh`; do not unpack the host or invent a wrapper for ordinary installation.-After setup, use each host's supported discovery/reload action to load the Tools and Skills. Confirm all eleven public Tools and five Skills, and call `openmotion_get_project` to verify the expected data directory. Do not impose another host's restart or refresh procedure, or substitute an on-disk registration for host loading evidence.+After setup, use working native tools or the direct commands below to continue in the same chat. Refresh native discovery only when needed. Confirm all eleven public Tools and five Skills, and call `openmotion_get_project` to verify the expected data directory. Do not impose another host's restart or refresh procedure, or substitute an on-disk registration for host loading evidence.The internal ownership marker remains stable across the npm package rename so earlier local installations can be upgraded in place. An installation can serve multiple hosts using the same home/data. `install.json.hosts` retains each host. Skill documentation links are rewritten for flat layouts; Codex/Harness retain bundle-relative links. Re-run setup for each installed host when upgrading Skills. Unowned same-name MCP/Skills are refused. Unrelated settings/Skills and existing projects are retained. Registration failure restores the prior install state and Skills; checked application caches remain available for retry.Compatible phase-one updates do not require closing existing MCP connections or stopping the same workspace's backend. Connections negotiate the API protocol and requested Tool, retaining running exports and completed results; see [shared editor recovery](shared-editor.md). The installer does not terminate existing processes. Incompatible protocols or internal legacy ABIs still require updating the connection and idle backend together. Refresh the host to discover new Tools or reload changed Skills; an already-closed transport needs host reconnection.+## Continue in the current Agent chat++Setup returns `onboarding.directAccess` with the exact Node executable and argument arrays for the selected installation and host. Prefer native tools when their workspace matches setup. If native tools are absent or still use an old installation, the Agent runs these commands itself in the same chat; no new Codex chat, separate Agent profile or host restart is required when shell execution is permitted:++```sh+node /absolute/appRoot/scripts/npm-installer.mjs tools --host codex --home /absolute/installHome+node /absolute/appRoot/scripts/npm-installer.mjs call openmotion_get_project --args-file /absolute/arguments.json --host codex --home /absolute/installHome+```++Use the actual paths from setup, preserving host/profile and CLI overrides. `tools` returns the public schemas and verified data directory. Write a JSON object to the arguments file using host file tools; do not interpolate user content into shell commands. `call` sends one request unchanged through the registered stdio MCP transport, including its cwd/environment. It validates installation ownership, enabled state, public tool contract, version and workspace before sending the requested operation. Host tool allow/deny lists apply. Server-side schema validation, stable request IDs, revision/version guards and export ownership remain unchanged. Tool failures return their evidence with a nonzero exit; the client never retries mutations. On timeout, inspect the original request/project/job state before retrying with the same request ID. Export calls queue jobs; poll the returned job rather than keeping a CLI call open.++This is an installed MCP client, not native host discovery or reconnection. It starts only its owned transport process, closes it after each command and leaves the shared backend/projects/jobs intact. It cannot override host policy or permission denials. If shell execution is unavailable or neither access path works, diagnose the actual blocker and use the host's supported recovery, preserving this chat's template/project choice. Ask the user for action only when needed. Never report `hostSessionVerified:false` as an installation failure.+## Versions, upgrades and publication boundaryExplicit builds accept `MAJOR.MINOR.PATCH-test.N[.N]` or `MAJOR.MINOR.PATCH`. CI-generated candidates use next-patch `test.<run>.<attempt>`; manually assigned candidates can use `test.1`, `test.2`. Every artifact has one identity across the installer, app package/lock and plugin metadata. Build numbers never overwrite old output; source versions are not bumped by packaging.Source package manifests remain `private:true`. Only an explicit test/DEV or stable/prod build produces publishable tgz metadata. Test artifacts default to `candidate`; the manual publisher advances `test` only after matching Mac/Windows registry installation checks. Stable artifacts default to `stage`; stable publication and `latest` promotion are separate follow-ups. Local/default and channel/environment-mismatched artifacts remain private. No command here publishes or changes npm tags. See [test and stable acceptance](release-guide.md) for separate maintainer authorization and gates.-After publication, the intended user entry is `npx --yes --package @openmotion/app@<exact-version> -- openmotion setup --host codex`, followed by host discovery/reload; `prepare` is optional when an explicit wait or retry is needed. `@test` and `@latest` select channels; acceptance always records the exact resolved version. Installing/running npx alone, publishing a new package or moving a tag does not update an existing managed app.+After publication, the intended user entry is `npx --yes --package @openmotion/app@<exact-version> -- openmotion setup --host codex`, followed by native discovery or direct installed access in the same chat; `prepare` is optional when an explicit wait or retry is needed. `@test` and `@latest` select channels; acceptance always records the exact resolved version. Installing/running npx alone, publishing a new package or moving a tag does not update an existing managed app.-Before upgrading, back up projects/configuration, run setup with the new exact tgz and the **same** home/data/Skills paths, then reconnect while preparation runs (or explicitly wait with prepare). Compatible phase-one connections and active exports can continue. Refresh host discovery for new Tools or Skills; reconnect a closed transport. For an incompatible protocol, finish active exports before updating only the owned connection and idle backend together. Do not terminate unrelated services. Older app directories may remain, but rollback requires a compatible old package and data; back up before an irreversible format change. There is no automatic update or arbitrary-version rollback promise.+Before upgrading, back up projects/configuration, run setup with the new exact tgz and the **same** home/data/Skills paths, then continue through native tools or direct access while preparation runs (or explicitly wait with prepare). Compatible phase-one connections and active exports can continue. Refresh host discovery for new Tools or Skills; reconnect a closed transport. For an incompatible protocol, finish active exports before updating only the owned connection and idle backend together. Do not terminate unrelated services. Older app directories may remain, but rollback requires a compatible old package and data; back up before an irreversible format change. There is no automatic update or arbitrary-version rollback promise.## Native tools and diagnosticsdiff --git a/docs/product/architecture.md b/docs/product/architecture.mdindex 98f0eb84..b127ea79 100644--- a/docs/product/architecture.md+++ b/docs/product/architecture.md@@ -128,7 +128,7 @@ README 参考 OpenDesign 的产品导览和 HTML Anything 的贡献、来源表## 核心用户流程1. The user creates a blank project or opens an existing one from the sidebar, asks an external Agent to create a project, or chooses a template in the editor. Bundled templates create independent project copies; external references require Agent reconstruction.-2. The Agent uses the existing MCP integration and verifies the selected project, revision and workflow. Integration setup remains available outside the MVP editor. Successful Agent-led installation returns the canonical reply rules from `docs/install.md` plus bounded real catalog summaries in the setup result, without waiting for the first MCP use. The Agent defaults to one eligible template; explicit comparison requests can receive three confirmed candidates. Acceptance preserves that exact choice and creates one independent editable project; refusal stops. Registration does not prove active-chat loading or that an invitation was actually displayed. No invitation telemetry/state service is introduced. Follow the [first-run defaults](../../skills/openmotion-production/references/templates.md#first-run-experience-defaults) for creation and delivery.+2. The Agent uses the existing MCP integration and verifies the selected project, revision and workflow. Integration setup remains available outside the MVP editor. Successful Agent-led installation returns the canonical reply rules from `docs/install.md` plus bounded real catalog summaries in the setup result, without waiting for the first MCP use. The user-facing reply only confirms installation and invites an experience; technical verification stays internal. When native discovery is missing or stale, setup returns direct installed MCP commands that let the same chat continue without a new chat or restart. The client reads the selected host configuration and enforces ownership, enabled/tool policy, version and workspace before public calls; it preserves request deduplication and revision/version guards and does not claim to reload native discovery. User recovery instructions appear only when permitted access paths fail. The Agent defaults to one eligible template; explicit comparison requests can receive three confirmed candidates. Acceptance preserves that exact choice and creates one independent editable project; refusal stops. Registration does not prove active-chat loading or that an invitation was actually displayed. No invitation telemetry/state service is introduced. Follow the [first-run defaults](../../skills/openmotion-production/references/templates.md#first-run-experience-defaults) for creation and delivery.3. `openmotion_open_preview({projectId})` opens the project directly. Project switching waits for pending saves and reloads the document to release the previous edit session. Opening a bookmark warms only its scoped native context without switching other editor tabs. Rendering and write conflicts continue to block unsafe switches. Original creation, reference recreation and template production automatically open the saved project before delivery; the open editor is the deliverable, and video files are handed over only when requested (video-to-template still delivers its template ZIP). Continued edits and restores return a project/revision/version-bound previewHandoff. Reuse the native project tab: present it when the calling chat is active, otherwise queue it without switching chats and resolve the latest version when the user returns. Only this turn's explicit `presentation=now` request permits switching back; explicit background requests suppress presentation. Codex IAB synchronizes visibility within the calling chat. A queued acknowledgment is separate from observed visibility and live-content freshness; `record_display` rejects stale content identities, and stored previewDisplay remains historical host-reported evidence. The shared [editable preview handoff](../../skills/openmotion-production/references/native.md#editable-preview-handoff) defines readiness, host checks and capability limitations.4. Agent 根据本轮目标直接选择 Skill:openmotion-director 负责原创、局部/整体叙事动作声音重新设计和创作审片;openmotion-template-to-video 负责已有模板出片;openmotion-recreate 负责参考作品重建(已接入实际流程、独立参考与测量脚本);openmotion-video-to-template 负责可复用模板生产;openmotion-production 承接既定决定下的工程操作、预览、技术检查、排错和导出。共享规则同源引用,已有 production/start 保留导航,无需前置总路由。项目来源与画面锁定不固定入口;保持项和已完成操作继续有效。5. The Agent imports or generates media through the existing backend. In the editor, the user imports assets, edits text/solid color/opacity, previews, and edits clips on the timeline. Element, clip, time-range and official animation-library Ask Agent entry points are hidden in the MVP; users can continue requesting edits through their external Agent. Text controls include headings with explicit line breaks and preserve those breaks when edited. The MVP omits the layer-count heading and Add text field controls. Unselected off-canvas elements have no dashed markers in the MVP preview; selecting an element, including from Layers, retains its selection boundary. Text selections omit the separate Style group and background-fill control; element opacity remains in Text. For opacity-animated elements, the MVP opacity control saves an independent CSS filter multiplier, retaining the authored fade and existing static filters rather than writing over the animated opacity channel. The multiplier is part of project source, so preview and export use the same value. Other element types retain their Style controls. Generation, image replacement, advanced style/animation controls, code and inspector Layout settings are hidden without rewriting existing source content or removing Agent capabilities.@@ -172,7 +172,7 @@ MCP version availability is derived from readable, hash-verified native or retaiMCP restore refusals also reach the owning editor through its existing project-status polling and shared error toast. Toasts summarize the unavailable historical files without exposing paths or diagnostic controls, and remain dismissible; repeated polls do not repeat a request's notice. The latest refusal is transient backend state, cleared on successful restoration or restart, and is separate from project source and history. Native history panel action failures reuse the same toast.-Preview/export preflight and the bundled OpenMotion lint command use the pinned native linter's Studio policy in an isolated, cancellable process. A structurally invalid project is rejected before editor opening or rendering; non-blocking warnings remain warnings. The npm CLI's `diagnose` command reads the installed host configuration and probes initialization, tool discovery and the expected workspace through an independent MCP process. It does not mutate configuration, create projects or prove active-chat connectivity. Host reconnection and a subsequent real host read remain separate completion conditions; see [connection diagnosis](../npm-installation.md#missing-mcp-tools-or-a-failed-connection).+Preview/export preflight and the bundled OpenMotion lint command use the pinned native linter's Studio policy in an isolated, cancellable process. A structurally invalid project is rejected before editor opening or rendering; non-blocking warnings remain warnings. The npm CLI's `diagnose` command reads the installed host configuration and probes initialization, tool discovery and the expected workspace through an independent MCP process. It does not mutate configuration, create projects or prove active-chat connectivity. The direct installed client can continue the task without refreshing native discovery; native host reconnection and a subsequent host read remain separate proof of native loading; see [connection diagnosis](../npm-installation.md#missing-mcp-tools-or-a-failed-connection).| 能力 | 负责模块 | 当前边界 || --- | --- | --- |diff --git a/docs/templates/candidate-install.md b/docs/templates/candidate-install.mdindex 1d8b1b4e..49ac80af 100644--- a/docs/templates/candidate-install.md+++ b/docs/templates/candidate-install.md@@ -20,7 +20,7 @@ This is a **local candidate installation guide**. It installs the complete `{{TG```Replace `HOST` with `codex`, `claude`, `deepseek` or `workbuddy`. Carry the explicit `--home`, `--data-dir`, `--skills-dir` and host-specific options from the platform recipe. Setup starts checked video-component downloads in the background. Do not run or wait for prepare to connect MCP, create/edit projects or open ordinary preview. Keep using this local package; no sidecar application/manifest download or source build is required.-4. Follow this host's discovery/reload action. Verify the actual application version, **{{TEMPLATE_ENVIRONMENT}} template environment**, eleven MCP Tools, resources and five Skills, including a `openmotion_get_project` call against the isolated data directory. Registration or installation success alone is not host loading or creative acceptance.+4. Keep verification internal. Use working native tools or setup's `onboarding.directAccess` commands in this same chat; do not default to a new chat or restart. Verify the actual application version, **{{TEMPLATE_ENVIRONMENT}} template environment**, eleven MCP Tools, resources and five Skills, including a `openmotion_get_project` call against the isolated data directory. Direct access verifies the installed MCP, not native host discovery or creative acceptance. Follow setup's installation-success reply: confirm installation, then invite an eligible experience.Keep installation/host loading and video-component readiness as separate internal evidence; include those details only in an explicitly requested acceptance report or when needed to resolve a blocked operation. Installation alone does not authorize creating a video or exporting an MP4.diff --git a/scripts/check-installed-mcp.mjs b/scripts/check-installed-mcp.mjsindex 7b9b3b04..c46dff43 100644--- a/scripts/check-installed-mcp.mjs+++ b/scripts/check-installed-mcp.mjs@@ -12,7 +12,7 @@ export function redact(message, environment) {.replace(/([\w-]*(?:token|secret|password|authorization|api.?key)[\w-]*["']?\s*[:=]\s*)("(?:\\.|[^"\\])*"|'[^']*'|[^\s,;}]+)/gi, '$1[redacted]').slice(-1500);}-export function checkTransport(config, expectedVersion, { expectedTools, dataDirectory } = {}) {+export function validateTransport(config) {if (!config) throw failure('MCP_NOT_REGISTERED', 'OpenMotion MCP is not registered in this host. Run setup for the selected host.');if (config.enabled === false) throw failure('MCP_DISABLED', 'OpenMotion MCP is disabled. Enable it in the selected host before reconnecting.');if (config.transport?.type !== 'stdio') throw failure('MCP_CONFIG_INVALID', 'OpenMotion requires a local stdio MCP connection.');@@ -22,6 +22,11 @@ export function checkTransport(config, expectedVersion, { expectedTools, dataDirif (JSON.stringify([transport.command, transport.cwd, transport.args]).includes('${')) throw failure('MCP_CONFIG_INVALID', 'The resolved MCP command contains an unexpanded placeholder. Fix the host configuration.');if (typeof transport.command !== 'string' || !transport.command || !Array.isArray(transport.args) || transport.args.some(arg => typeof arg !== 'string')) throw failure('MCP_CONFIG_INVALID', 'MCP requires an executable command and string arguments.');if (transport.cwd && (!path.isAbsolute(transport.cwd) || !fs.existsSync(transport.cwd) || !fs.statSync(transport.cwd).isDirectory())) throw failure('MCP_CONFIG_INVALID', 'The resolved MCP working directory does not exist or is not absolute.');+ return transport;+}++export function checkTransport(config, expectedVersion, { expectedTools, dataDirectory } = {}) {+ const transport = validateTransport(config);const messages = [{ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'openmotion-install-check', version: '1' } } },{ jsonrpc: '2.0', method: 'notifications/initialized' },diff --git a/scripts/distribution.ts b/scripts/distribution.tsindex 1fdb3f5f..a241d437 100644--- a/scripts/distribution.ts+++ b/scripts/distribution.ts@@ -496,7 +496,7 @@ export async function distributionFiles(profile: string): Promise<string[]> {'phase1.ts', 'phase1-versions.ts', 'preview.ts', 'hyperframes.ts', 'template-library.ts','template-catalog.ts', 'prism-templates.ts', 'editor-server.ts','scripts/runtime-assets.mjs', 'scripts/npm-runtime.mjs', 'scripts/runtime-lock.json', 'scripts/lint-project.mjs',- 'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/check-installed-mcp.mjs',+ 'scripts/npm-installer.mjs', 'scripts/npm-hosts.mjs', 'scripts/check-installed-mcp.mjs', 'scripts/mcp-client.mjs','scripts/install-onboarding.mjs', 'scripts/onboarding-catalog.ts', 'scripts/install-library-skill.mjs','scripts/diagnostics.mjs', 'scripts/diagnostic-redaction.mjs', 'scripts/zip.mjs','scripts/verify-export.ts', 'scripts/export-adapters.ts', 'scripts/package.ts', 'scripts/distribution.ts',diff --git a/scripts/mcp-client.mjs b/scripts/mcp-client.mjsnew file mode 100644index 00000000..9a4186d9--- /dev/null+++ b/scripts/mcp-client.mjs@@ -0,0 +1,60 @@+import { spawn } from 'node:child_process';+import { createInterface } from 'node:readline';+import assert from 'node:assert/strict';+import path from 'node:path';+import { readFile } from 'node:fs/promises';+import { validateTransport, redact } from './check-installed-mcp.mjs';++function protocolClient(transport, env, timeout) {+ const child = spawn(transport.command, transport.args, { cwd: transport.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });+ let seq = 0, stderr = ''; const pending = new Map();+ child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });+ const failPending = error => {+ for (const { reject, timer } of pending.values()) { clearTimeout(timer); reject(error); }+ pending.clear();+ };+ child.on('error', failPending);+ child.on('close', code => failPending(new Error(`MCP exited ${code}: ${stderr}`)));+ child.stdin.on('error', failPending);+ createInterface({ input: child.stdout }).on('line', line => {+ try { const value = JSON.parse(line); if (value.jsonrpc !== '2.0') throw new Error('Invalid MCP response'); pending.get(value.id)?.resolve(value); }+ catch (error) { failPending(error); }+ });+ const rpc = (method, params) => new Promise((resolve, reject) => {+ if (child.exitCode !== null || child.signalCode !== null || child.stdin.destroyed) return reject(new Error('MCP transport is closed'));+ const id = ++seq, timer = setTimeout(() => { pending.delete(id); reject(new Error(`${method} timed out; an operation may still be running. Read its state before retrying. ${stderr}`)); }, timeout);+ pending.set(id, { reject, timer, resolve: reply => { clearTimeout(timer); pending.delete(id); reply.error ? reject(new Error(JSON.stringify(reply.error))) : resolve(reply.result); } });+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');+ });+ return { child, rpc };+}++// Use the installed transport and public contract; never a second implementation of project operations.+export async function installedTool(state, connection, name, args = {}, timeout = 180_000) {+ assert(args && typeof args === 'object' && !Array.isArray(args), 'Tool arguments must be a JSON object');+ const transport = validateTransport(connection);+ const allowed = tool => (!connection.enabled_tools || connection.enabled_tools.includes(tool)) && !connection.disabled_tools?.includes(tool);+ assert(allowed('openmotion_get_project') && (name === undefined || allowed(name)), 'MCP_TOOL_DISABLED: requested tool or workspace read is disabled in this host');+ const expected = JSON.parse(await readFile(path.join(state.appRoot, 'shared/mcp-profiles.json'), 'utf8')).phase1.tools;+ assert(name === undefined || expected.includes(name), 'MCP_TOOL_NOT_EXPOSED: ' + name);+ const { child, rpc } = protocolClient(transport, { ...process.env, ...(transport.env || {}) }, timeout);+ try {+ const hello = await rpc('initialize', { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'openmotion-cli', version: '1' } });+ assert.equal(hello.serverInfo?.version, state.version, 'Installed MCP version mismatch');+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');+ const { tools } = await rpc('tools/list', {});+ assert(Array.isArray(tools) && tools.length === expected.length && expected.every(name => tools.some(tool => tool.name === name)), 'Installed MCP tool contract mismatch');+ const read = await rpc('tools/call', { name: 'openmotion_get_project', arguments: {} });+ assert(!read.isError && typeof read.structuredContent?.dataDirectory === 'string'+ && path.resolve(read.structuredContent.dataDirectory) === path.resolve(state.dataDirectory), 'Installed MCP data directory mismatch; no requested operation was applied');+ if (name === undefined) return { serverInfo: hello.serverInfo, dataDirectory: state.dataDirectory, tools: tools.filter(tool => allowed(tool.name)) };+ return name === 'openmotion_get_project' && Object.keys(args).length === 0 ? read : await rpc('tools/call', { name, arguments: args });+ } catch (error) {+ throw new Error(redact(error.message, { ...process.env, ...(transport.env || {}) }));+ } finally {+ const timer = setTimeout(() => child.kill(), 2000);+ child.stdin.end();+ if (child.exitCode === null && child.signalCode === null) await new Promise(resolve => child.once('close', resolve));+ clearTimeout(timer);+ }+}diff --git a/scripts/npm-installer.mjs b/scripts/npm-installer.mjsindex 0c04c482..1cdb4daa 100644--- a/scripts/npm-installer.mjs+++ b/scripts/npm-installer.mjs@@ -9,6 +9,7 @@ import { parseArgs } from 'node:util';import { canonical, extractArchive, nativeComponents, obtainAsset, readJSON, relativePath, runFile, withLock, writeAtomic, writeJSON } from './runtime-assets.mjs';import { ensureNativeRuntime, startNativePreparation } from './npm-runtime.mjs';import { hosts, hostPlan, skillTargets, obsoleteSkills, checkSkillOwner, copyHostSkills } from './npm-hosts.mjs';+import { installedTool } from './mcp-client.mjs';import { checkTransport, redact } from './check-installed-mcp.mjs';import { exportDiagnostics, recordDiagnostic } from './diagnostics.mjs';@@ -21,6 +22,8 @@ const usage = `Usage:openmotion setup --host <${hosts.join('|')}> [options]openmotion prepare [--home DIR]openmotion diagnose --host <${hosts.join('|')}> [--home DIR] [host options]+ openmotion tools --host HOST [--home DIR]+ openmotion call TOOL --args-file FILE.json --host HOST [--home DIR]openmotion diagnostics [--home DIR] [--data-dir DIR] [--output FILE.zip]openmotion --version@@ -43,6 +46,8 @@ Diagnose checks the installed host configuration and probes its MCP command withIt does not reconnect the host; follow its recovery guidance and verify a read in the active Agent chat.Diagnostics saves a redacted local ZIP without contacting hosts or uploading anything.Reuse the original --home; --data-dir also works when setup has not completed. Output files are never overwritten.+tools lists the installed public MCP schemas. call sends one JSON-object file unchanged through the registered transport.+Use these in the current Agent chat when native tools are missing or still point at an older installation; no new chat or host restart is required.Use separate host configuration, home, data and Skills paths for test candidates.-h, --help Show this help without installing or changing configuration--version Show this package's version`;@@ -145,7 +150,7 @@ export async function setup(options) {await plan.register();for (const item of directories) await rm(item.backup, { recursive: true, force: true }).catch(error => console.error('Old instruction backup retained: ' + error.message));await startNativePreparation(appRoot).catch(error => console.error('OpenMotion: background preparation could not start; retry in Studio or run prepare. ' + error.message));- return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'background-preparation; status and retry available in Studio', onboarding };+ return { ...state, host: plan.host, hostInstallation: plan.metadata, nativeDependencies: 'background-preparation; status and retry available in Studio', onboarding: { ...onboarding, directAccess: directAccess(home, plan.host, appRoot, options) } };} catch (error) {if (wroteLauncher && !previous) await rm(launcher, { force: true });if (wroteState) { if (previous) await writeJSON(stateFile, previous); else await rm(stateFile, { force: true }); }@@ -159,6 +164,35 @@ export async function setup(options) {});}+export function directAccess(home, host, appRoot, options = {}) {+ const flags = ['--home', home, '--host', host];+ for (const key of ['codex', 'claude', 'dsh', 'profile']) if (options[key]) flags.push('--' + key, options[key]);+ const cli = path.join(appRoot, 'scripts/npm-installer.mjs');+ return { command: process.execPath, toolsArgs: [cli, 'tools', ...flags],+ callArgs: [cli, 'call', 'TOOL', '--args-file', 'FILE.json', ...flags],+ instructions: 'Use working native tools for this installation first. Otherwise execute toolsArgs with command in this same chat, read the returned inputSchema, then execute callArgs after replacing TOOL and FILE.json. Write arguments as a JSON object in a local file, without shell interpolation. Reuse the chosen template, project and request IDs; revision/version guards still apply. This is direct installed MCP access, not native host discovery or reconnection. Do not ask the user to restart or open a new chat to use it. Do not bypass disabled tools, permission denials or host policy. If shell execution is unavailable, use supported host recovery; ask for user action only when no permitted path works.' };+}++async function installedConnection(options) {+ const host = options.host || 'codex';+ const environment = (await readJSON(bundledManifest))?.templateEnvironment;+ const home = await canonical(options.home || defaultHome(environment));+ const state = await readJSON(path.join(home, 'install.json'));+ assert(state?.managedBy === managedBy, 'Run setup for the selected host and installation home first.');+ assert(state.hosts?.[host] || host === 'codex' && state.skillsDirectory, 'This installation is not registered for the selected host.');+ const saved = state.hosts?.[host];+ try {+ const plan = await hostPlan({ ...options, skillsDirectory: saved?.skillsDirectory, profile: options.profile || saved?.profile }, home, state.launcher, state);+ const connection = plan.readConnection ? await plan.readConnection() : plan.connection;+ return { state, connection, home, host };+ } catch (error) { error.stage = 'host_configuration'; throw error; }+}++export async function callInstalled(options, name, args = {}) {+ const { state, connection } = await installedConnection(options);+ return installedTool(state, connection, name, args);+}+export async function diagnose(options) {let stage = 'installation';const host = options.host || 'codex';@@ -166,22 +200,14 @@ export async function diagnose(options) {? 'After correcting the reported cause, open /mcp in the current Claude Code session and select Reconnect for openmotion.': `After correcting the reported cause, refresh or reconnect openmotion in the current ${host} host${options.profile ? ' profile ' + options.profile : ''}.`;try {- const environment = (await readJSON(bundledManifest))?.templateEnvironment;- const home = await canonical(options.home || defaultHome(environment));- const state = await readJSON(path.join(home, 'install.json'));- assert(state?.managedBy === managedBy, 'Run setup for the selected host and installation home first.');- assert(state.hosts?.[host] || host === 'codex' && state.skillsDirectory, 'This installation is not registered for the selected host.');- stage = 'host_configuration';- const saved = state.hosts?.[host];- const plan = await hostPlan({ ...options, skillsDirectory: saved?.skillsDirectory, profile: options.profile || saved?.profile }, home, state.launcher, state);- const connection = plan.readConnection ? await plan.readConnection() : plan.connection;+ const { state, connection, home } = await installedConnection(options);stage = 'mcp_probe';const expectedTools = (await readJSON(path.join(state.appRoot, 'shared/mcp-profiles.json'))).phase1.tools;const checked = checkTransport(connection, state.version, { expectedTools, dataDirectory: state.dataDirectory });- return { status: 'passed', host, ...checked, hostSessionVerified: false,- nextAction: 'Call openmotion_get_project through the active host connection and verify the original project and version. This independent probe does not verify the active chat connection. If that chat still lacks OpenMotion tools: ' + recovery };+ return { status: 'passed', host, ...checked, hostSessionVerified: false, directAccess: directAccess(home, host, state.appRoot, options),+ nextAction: 'Use working native tools for this installation, otherwise use directAccess in this same chat. Verify openmotion_get_project and the original project/version before continuing. This probe does not refresh native discovery. Request host recovery only if permitted direct access also fails.' };} catch (error) {- return { status: 'failed', host, stage, code: error.code || 'MCP_DIAGNOSIS_FAILED', message: redact(error.message, process.env),+ return { status: 'failed', host, stage: error.stage || stage, code: error.code || 'MCP_DIAGNOSIS_FAILED', message: redact(error.message, process.env),hostSessionVerified: false, nextAction: recovery + ' Keep existing projects and exports; do not create replacement work or blindly replay a mutation.' };}}@@ -189,12 +215,12 @@ export async function diagnose(options) {async function main() {const { positionals, values } = parseArgs({ allowPositionals: true, options: {manifest: { type: 'string' }, home: { type: 'string' }, 'data-dir': { type: 'string' }, 'skills-dir': { type: 'string' }, host: { type: 'string' }, codex: { type: 'string' }, claude: { type: 'string' }, dsh: { type: 'string' }, profile: { type: 'string' },- help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' }, output: { type: 'string' },+ help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' }, output: { type: 'string' }, 'args-file': { type: 'string' },} });if (values.help) { console.log(usage); return; }if (values.version) { console.log((await readJSON(new URL('../package.json', import.meta.url))).version); return; }const [command] = positionals;- assert(positionals.length === 1, usage);+ assert(positionals.length === (command === 'call' ? 2 : 1), usage);if (command === 'setup') {try {console.log(JSON.stringify(await setup({ manifest: values.manifest, home: values.home, dataDirectory: values['data-dir'], skillsDirectory: values['skills-dir'], host: values.host, codex: values.codex, claude: values.claude, dsh: values.dsh, profile: values.profile }), null, 2));@@ -203,6 +229,12 @@ async function main() {await recordDiagnostic(values.home || defaultHome(environment), { kind: 'installation_failed', message: error.message });throw error;}+ } else if (command === 'tools' || command === 'call') {+ assert(command !== 'call' || values['args-file'], 'call requires --args-file FILE.json');+ const result = await callInstalled(values, command === 'call' ? positionals[1] : undefined,+ command === 'call' ? JSON.parse(await readFile(values['args-file'], 'utf8')) : {});+ console.log(JSON.stringify(result, null, 2));+ if (result.isError) process.exitCode = 1;} else if (command === 'prepare') {const environment = (await readJSON(bundledManifest))?.templateEnvironment;const state = await readJSON(path.join(values.home || defaultHome(environment), 'install.json'));@@ -219,6 +251,6 @@ async function main() {const state = await readJSON(path.join(home, 'install.json')).catch(() => null);const dataDirectory = values['data-dir'] || state?.dataDirectory || path.join(home, 'data');console.log(JSON.stringify(await exportDiagnostics({ appRoot: state?.appRoot || fileURLToPath(new URL('../', import.meta.url)), installHome: home, dataDirectory, output: values.output }), null, 2));- } else throw new Error('Supported commands: setup, prepare, diagnose, diagnostics');+ } else throw new Error('Supported commands: setup, prepare, tools, call, diagnose, diagnostics');}if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) main().catch(error => { console.error(error.message + '\nRun openmotion --help for supported hosts and installation options.'); process.exitCode = 1; });diff --git a/scripts/package-npm.mjs b/scripts/package-npm.mjsindex 7dca5ab4..0d09cf65 100644--- a/scripts/package-npm.mjs+++ b/scripts/package-npm.mjs@@ -98,7 +98,7 @@ export async function packageNpm(output = path.join(root, 'dist/npm-local'), verawait writeJSON(path.join(application, 'shared/template-config.json'), templateConfig);await writeJSON(path.join(application, 'shared/build-info.json'), { commit });const skills = (await readdir(path.join(application, 'skills'))).sort();- for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));+ for (const name of ['runtime-assets.mjs', 'npm-runtime.mjs', 'npm-hosts.mjs', 'npm-installer.mjs', 'check-installed-mcp.mjs', 'mcp-client.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) await cp(path.join(root, 'scripts', name), path.join(installer, 'scripts', name));await chmod(path.join(installer, 'scripts/npm-installer.mjs'), 0o755);const installerPkg = JSON.parse(await readFile(path.join(root, 'packages/npm/package.json'), 'utf8'));assert.equal(installerPkg.private, true, 'Keep the source package protected; publish only an explicitly versioned artifact');diff --git a/skills/openmotion-production/references/context.md b/skills/openmotion-production/references/context.mdindex 980e73b1..72e48ca4 100644--- a/skills/openmotion-production/references/context.md+++ b/skills/openmotion-production/references/context.md@@ -17,7 +17,7 @@ Agent 结合当前目标、保持项与工程状态选择本轮入口;工程For a video task, identify OpenMotion as the intended execution path in the first relevant response. Discover the host's connected OpenMotion tools, using its tool search when discovery is lazy. Reading a Skill establishes workflow guidance. Report actual tool use only after a host MCP call. A concept-only request may finish with a plan without creating a project. When the user proceeds to production, reuse that plan and use the connected tools for the project and editable preview.-If OpenMotion tools are unavailable or fail, disclose the connection status and recovery action as soon as it is observed, including during planning. Apply the [connection diagnosis and recovery rules](production.md#tool-transport-and-workspace-readiness) before creating or importing work. Use the installed host/home identity, retain the actual connection error and verify recovery through a real host MCP read. A separate CLI probe cannot confirm the current chat connection. Continue independent planning within the requested scope while connection recovery is pending.+If OpenMotion tools are unavailable or fail, disclose the connection status and recovery action as soon as it is observed, including during planning. Apply the [connection diagnosis and recovery rules](production.md#tool-transport-and-workspace-readiness) before creating or importing work. Use the installed host/home identity, retain the actual connection error and verify recovery through a real read. For npm installs, setup's directAccess commands can call the same registered MCP in the current chat when native discovery is missing or stale; this does not prove native host reconnection. A separate CLI probe cannot confirm the current chat connection. Continue independent planning within the requested scope while connection recovery is pending.## 先补齐阅读缺口,再执行当前范围diff --git a/skills/openmotion-production/references/production.md b/skills/openmotion-production/references/production.mdindex 6e8832aa..7e9b1608 100644--- a/skills/openmotion-production/references/production.md+++ b/skills/openmotion-production/references/production.md@@ -29,7 +29,7 @@ When OpenMotion tools are missing or a connection fails:1. Read the selected host's server status and startup output. An empty tool search does not distinguish an unregistered server, a disabled connection, startup failure or discovery still in progress. Keep the actual error; do not infer the cause from a browser URL or a running backend.2. For an npm installation, read `runtimeRoot`, `installHome` and `host` from the installed Skill's `openmotion-install.json` or `scope.json`. Run `node <runtimeRoot>/scripts/npm-installer.mjs diagnose --host <host> --home <installHome>` with argument-safe paths; preserve the selected profile and CLI overrides where needed. It checks that host's owned configuration, initializes an independent MCP process, checks the installed tool list and reads the expected data directory. It does not verify or reconnect the current chat. For a source/plugin installation without `installHome`, inspect the host's actual registered command and output; do not guess an npm home or run setup over an unrelated installation.-3. Correct the reported cause before retrying. Missing runtimes, invalid paths, disabled servers and incompatible versions need their specific fix. Use the host's supported refresh/reconnect action; in Claude Code's interactive session use the server's Reconnect action in `/mcp`. If the host exposes no recovery capability, give that concrete user action. Do not claim to reconnect by starting a separate shell process or repeatedly reinstalling. Allow one safe read retry after a transient failure or completed recovery; if it still fails, report the error and recovery action rather than looping.+3. For an npm installation with permitted shell access, use the returned `directAccess` commands to continue in this chat before requesting a host handoff. A successful direct call proves installed access only; do not claim native host reconnection. If direct access is unavailable or fails, correct the reported cause before retrying. Missing runtimes, invalid paths, disabled servers and incompatible versions need their specific fix. Use the host's supported refresh/reconnect action; in Claude Code's interactive session use the server's Reconnect action in `/mcp`. If the host exposes no recovery capability, give that concrete user action. Do not claim to reconnect by starting a separate shell process or repeatedly reinstalling. Allow one safe read retry after a transient failure or completed recovery; if it still fails, report the error and recovery action rather than looping.4. Through the recovered host MCP connection, call `openmotion_get_project`, confirm its data directory and the original project's identity/current version, then resume this task. A passed independent probe is not host recovery. Query existing jobs and preserve request IDs before deciding whether a mutation needs retrying; never create replacement work to hide a connection failure.If only an independent folder can be produced, state that the editable Studio handoff is unavailable. Continue that delivery only within the user's accepted scope; do not report the project as open or directly editable in Studio without observing it.diff --git a/tests/mcp-client.test.ts b/tests/mcp-client.test.tsnew file mode 100644index 00000000..666ca8ea--- /dev/null+++ b/tests/mcp-client.test.ts@@ -0,0 +1,89 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { installedTool } from '../scripts/mcp-client.mjs';++async function fixture(t: any, options: { version?: string; wrongDirectory?: boolean; toolError?: boolean } = {}) {+ const directory = await mkdtemp(path.join(tmpdir(), 'motion-direct-'));+ t.after(() => rm(directory, { recursive: true, force: true }));+ await mkdir(path.join(directory, 'shared'));+ const names = ['openmotion_get_project', 'openmotion_edit_project'], log = path.join(directory, 'calls.jsonl');+ await writeFile(path.join(directory, 'shared/mcp-profiles.json'), JSON.stringify({ phase1: { tools: names } }));+ const state = { version: '1.2.3', appRoot: directory, dataDirectory: path.join(directory, 'data'), launcher: path.join(directory, 'run-mcp.mjs') };+ await writeFile(state.launcher, `+ import { createInterface } from 'node:readline';+ import { appendFileSync } from 'node:fs';+ let initialized = false;+ for await (const line of createInterface({ input: process.stdin })) {+ const m = JSON.parse(line);+ appendFileSync(${JSON.stringify(log)}, JSON.stringify(m) + '\\n');+ if (m.method === 'notifications/initialized') { initialized = true; continue; }+ let result;+ if (m.method === 'initialize') result = { serverInfo: { version: ${JSON.stringify(options.version || state.version)} } };+ else if (!initialized) { console.log(JSON.stringify({ jsonrpc: '2.0', id: m.id, error: { code: -1, message: 'Not initialized' } })); continue; }+ else if (m.method === 'tools/list') result = { tools: ${JSON.stringify(names.map(name => ({ name, inputSchema: { type: 'object' } })))} };+ else if (m.params.name === 'openmotion_get_project') result = { structuredContent: { dataDirectory: ${JSON.stringify(options.wrongDirectory ? directory : state.dataDirectory)} } };+ else result = ${JSON.stringify(options.toolError ? { isError: true, structuredContent: { error: { code: 'VERSION_CONFLICT', applied: false } } } : { structuredContent: { received: 'tool arguments' } })};+ console.log(JSON.stringify({ jsonrpc: '2.0', id: m.id, result }));+ }+ `);+ return { state, connection: { transport: { type: 'stdio', command: process.execPath, args: [state.launcher], cwd: directory, env: { FIXTURE_ENV: 'registered' } } }, calls: async () => (await readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)) };+}++test('direct access lists schemas and verifies the saved workspace before each requested operation', async t => {+ const { state, connection, calls } = await fixture(t);+ assert.deepEqual((await installedTool(state, connection)).tools.map(tool => tool.name), ['openmotion_get_project', 'openmotion_edit_project']);+ const args = { projectId: 'original-project', expectedRevision: 'original-revision', files: [{ path: 'index.html', content: '用户内容 $() `literal`' }] };+ await installedTool(state, connection, 'openmotion_edit_project', args);+ const messages = await calls(), requested = messages.filter(message => message.method === 'tools/call');+ assert.deepEqual(requested.map(message => message.params.name), ['openmotion_get_project', 'openmotion_get_project', 'openmotion_edit_project']);+ assert.deepEqual(requested[2].params.arguments, args);+});++test('version and workspace mismatches stop before a mutation is sent', async t => {+ for (const options of [{ version: 'wrong' }, { wrongDirectory: true }]) {+ const { state, connection, calls } = await fixture(t, options);+ await assert.rejects(installedTool(state, connection, 'openmotion_edit_project'), /mismatch/);+ assert(!(await calls()).some(message => message.params?.name === 'openmotion_edit_project'));+ }+});++test('hidden tools and invalid arguments are rejected, while tool failures keep their evidence without retrying', async t => {+ const { state, connection, calls } = await fixture(t, { toolError: true });+ await assert.rejects(installedTool(state, connection, 'motion_write_files'), /MCP_TOOL_NOT_EXPOSED/);+ await assert.rejects(installedTool(state, connection, 'openmotion_edit_project', []), /JSON object/);+ const failure = await installedTool(state, connection, 'openmotion_edit_project', { requestId: 'keep-me' });+ assert.equal(failure.isError, true);+ assert.equal(failure.structuredContent.error.code, 'VERSION_CONFLICT');+ assert.equal((await calls()).filter(message => message.params?.name === 'openmotion_edit_project').length, 1);+});++test('an unresponsive runtime fails within the check deadline and closes its owned transport', async t => {+ const { state, connection } = await fixture(t);+ await writeFile(state.launcher, 'process.stdin.resume();');+ await assert.rejects(installedTool(state, connection, 'openmotion_get_project', {}, 50), /timed out/);+});+++test('disabled servers/tools are refused before starting the transport', async t => {+ const { state, connection } = await fixture(t);+ for (const restricted of [{ ...connection, enabled: false },+ { ...connection, disabled_tools: ['openmotion_edit_project'] },+ { ...connection, enabled_tools: ['openmotion_edit_project'] }]) {+ await assert.rejects(installedTool(state, restricted, 'openmotion_edit_project'), /disabled/i);+ }+ await assert.rejects(readFile(path.join(state.appRoot, 'calls.jsonl')), { code: 'ENOENT' });+});++test('registered cwd/env are used and startup secrets are redacted', async t => {+ const { state, connection } = await fixture(t);+ await writeFile(state.launcher, "console.error(process.env.API_TOKEN + ' ' + process.env.FIXTURE_ENV + ' ' + process.cwd());process.exit(1)");+ await assert.rejects(installedTool(state, { ...connection, transport: { ...connection.transport, env: { ...connection.transport.env, API_TOKEN: 'private-test-secret' } } }), error => {+ assert.match(error.message, /registered/);+ assert(error.message.includes(state.appRoot));+ assert.doesNotMatch(error.message, /private-test-secret/);+ return true;+ });+});diff --git a/tests/npm-installer.test.ts b/tests/npm-installer.test.tsindex 47d5aec6..395cf9f7 100644--- a/tests/npm-installer.test.ts+++ b/tests/npm-installer.test.ts@@ -54,6 +54,7 @@ test('successful setup hands the current Agent an invitation before any MCP use,const options = await setupFixture(t);const installed = await setup(options);assert.equal(installed.onboarding.hostSessionVerified, false);+ assert.deepEqual(installed.onboarding.directAccess.toolsArgs, [path.join(installed.appRoot, 'scripts/npm-installer.mjs'), 'tools', '--home', installed.launcher.replace(/[/\\]run-mcp.mjs$/, ''), '--host', 'codex', '--codex', options.codex]);const examples = [...installed.onboarding.instructions.matchAll(/```text\n([\s\S]*?)```/g)].map(([, text]) => text);assert.equal(examples.length, 2);for (const example of examples) {@@ -95,7 +96,7 @@ test('a flat-host upgrade replaces an owned legacy Skill with an explicit aliastest('bundled CLI installs without a sidecar manifest, isolates DEV defaults and rejects a mixed-environment home', async t => {const options = await setupFixture(t), bundle = path.join(options.directory, 'bundle');await mkdir(path.join(bundle, 'scripts'), { recursive: true }); await mkdir(path.join(bundle, 'payload'));- for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) {+ for (const file of ['npm-installer.mjs', 'npm-hosts.mjs', 'npm-runtime.mjs', 'runtime-assets.mjs', 'check-installed-mcp.mjs', 'mcp-client.mjs', 'diagnostics.mjs', 'diagnostic-redaction.mjs', 'zip.mjs']) {await cp(new URL('../scripts/' + file, import.meta.url), path.join(bundle, 'scripts', file));}await writeJSON(path.join(bundle, 'package.json'), { version: '1.2.3', type: 'module' });@@ -502,3 +503,26 @@ test('registration failure restores obsolete flat Skills, and malformed installawait assert.rejects(setup(options), /belongs to another/);assert.equal(JSON.parse(await readFile(state, 'utf8')), false);});+++test('installed CLI uses the selected host transport and keeps failed tool results nonzero', async t => {+ const options = await setupFixture(t), installed = await setup(options);+ const tools = (JSON.parse(await readFile(path.join(installed.appRoot, 'shared/mcp-profiles.json'), 'utf8'))).phase1.tools;+ await writeFile(installed.launcher, `import { createInterface } from 'node:readline';+ for await (const line of createInterface({ input: process.stdin })) {+ const q=JSON.parse(line); if(q.id===undefined) continue;+ const result=q.method==='initialize'?{serverInfo:{version:'1.2.3'}}:q.method==='tools/list'?{tools:${JSON.stringify(tools.map(name => ({name,inputSchema:{type:'object'}})))}}:q.params.name==='openmotion_get_project'?{structuredContent:{dataDirectory:${JSON.stringify(installed.dataDirectory)}}}:{isError:true,structuredContent:{error:{code:'VERSION_CONFLICT',applied:false}}};+ console.log(JSON.stringify({jsonrpc:'2.0',id:q.id,result}));+ }`);+ const cli = fileURLToPath(new URL('../scripts/npm-installer.mjs', import.meta.url));+ const flags = ['--home', options.home, '--host', 'codex', '--codex', options.codex];+ const listed = JSON.parse(await runFile(process.execPath, [cli, 'tools', ...flags]));+ assert.equal(listed.dataDirectory, installed.dataDirectory);+ assert.equal(listed.tools.length, tools.length);+ const argsFile=path.join(options.directory, 'arguments 中文.json'); await writeJSON(argsFile, {requestId:'stable-request'});+ await assert.rejects(runFile(process.execPath, [cli, 'call', 'openmotion_edit_project', '--args-file', argsFile, ...flags]), /VERSION_CONFLICT/);+ await writeFile(argsFile, '[]');+ await assert.rejects(runFile(process.execPath, [cli, 'call', 'openmotion_edit_project', '--args-file', argsFile, ...flags]), /JSON object/);+ const config=JSON.parse(await readFile(options.config,'utf8')); config.openmotion.enabled=false; await writeJSON(options.config,config);+ await assert.rejects(runFile(process.execPath, [cli, 'tools', ...flags]), /disabled/);+});diff --git a/tests/npm-package.test.ts b/tests/npm-package.test.tsindex e612f912..bd905352 100644--- a/tests/npm-package.test.ts+++ b/tests/npm-package.test.ts@@ -143,7 +143,7 @@ test('test npm artifacts contain their application, locked manifest and no bundlassert(entries.includes('skills/openmotion-recreate/references/verify.md'));assert(entries.includes('studio/build/index.html'));assert(entries.includes('shared/editor-launch.pl'), 'macOS shared editor launcher must ship');- for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'diagnostics.mjs', 'zip.mjs', 'diagnostic-redaction.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);+ for (const script of ['lint-project.mjs', 'npm-installer.mjs', 'npm-hosts.mjs', 'check-installed-mcp.mjs', 'mcp-client.mjs', 'diagnostics.mjs', 'zip.mjs', 'diagnostic-redaction.mjs', 'install-onboarding.mjs', 'onboarding-catalog.ts']) assert(entries.includes('scripts/' + script), 'Runtime diagnostic and lint entry must ship: ' + script);await readFile(path.join(installer, 'package/scripts/check-installed-mcp.mjs'));const diagnosticFile = path.join(directory, 'packaged-diagnostics.zip');await runFile(process.execPath, [cli, 'diagnostics', '--home', path.join(directory, 'not-installed'), '--output', diagnosticFile]);