Merge pull request #8168 from deepseek-harness/refactor/tool-errors-mcp

feat(mcp,web,skill,cordis,plugin,ptc): give MCP, web, skill, inspect, plugin, and run_code tool failures error codes
This commit is contained in:
Jiawei Song authored and GitHub committed 2026-11-11 18:16:03 +08:00
commit 0b8ee3b709
156 files changed
+1716 -387

No files matched your search

+4
View File
@@ -43,6 +43,10 @@ describe('dsh badge assembled snapshot', () => {
},
],
"error": {
"info": {
"code": "SKILL_NOT_FOUND",
"name": "SkillError",
},
"message": "skill "dsh-badge" is unknown or no longer available",
},
"isError": true,
+8 -8
View File
@@ -851,7 +851,7 @@ export interface ToolResultPruneConfig {
## `@deepseek-ai/dsh-cordis-host-runner`
- `inject`: `tools`
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:104`](../packages/extensions/cordis-host-runner/src/index.ts)
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts)
```ts config-catalog
/** Runner configuration. */
@@ -2407,7 +2407,7 @@ export interface LspLocalServerConfig {
## `@deepseek-ai/dsh-mcp-client`
- `inject`: `tools`
- `source`: [`packages/mcp/mcp-client/src/index.ts:138`](../packages/mcp/mcp-client/src/index.ts)
- `source`: [`packages/mcp/mcp-client/src/index.ts:140`](../packages/mcp/mcp-client/src/index.ts)
```ts config-catalog
/** Configuration for one stdio or Streamable HTTP MCP server. */
@@ -2711,7 +2711,7 @@ export interface PlanModeConfig {
- `inject`: `loader` · `profileContext`
- `refs`: [`NpmFileSource`](subsystems/boot.md)
- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts)
- `source`: [`packages/boot/plugin-manager/src/index.ts:56`](../packages/boot/plugin-manager/src/index.ts)
```ts config-catalog
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -2761,7 +2761,7 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:43`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
@@ -3406,7 +3406,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill`
- `source`: [`packages/skill/skill/src/index.ts:278`](../packages/skill/skill/src/index.ts)
- `source`: [`packages/skill/skill/src/index.ts:281`](../packages/skill/skill/src/index.ts)
```ts config-catalog
/** Skill registry configuration. */
@@ -3423,7 +3423,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill-filesystem`
- `inject`: `skills`
- `source`: [`packages/skill/skill-filesystem/src/index.ts:48`](../packages/skill/skill-filesystem/src/index.ts)
- `source`: [`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
```ts config-catalog
/** Local filesystem skill provider configuration. */
@@ -4471,7 +4471,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-skill`
- `inject`: `agents` · `tools` · `skills` · `workingDirectory`
- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts)
- `source`: [`packages/skill/tool-skill/src/index.ts:65`](../packages/skill/tool-skill/src/index.ts)
```ts config-catalog
/** Model-facing skill catalog configuration. */
@@ -4682,7 +4682,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-workspace-dependencies`
- `inject`: `tools`
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:15`](../packages/skill/tool-workspace-dependencies/src/index.ts)
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:18`](../packages/skill/tool-workspace-dependencies/src/index.ts)
```ts config-catalog
/** Payload location and optional installation directory. */
+8 -8
View File
@@ -853,7 +853,7 @@ export interface ToolResultPruneConfig {
## `@deepseek-ai/dsh-cordis-host-runner`
- `inject`: `tools`
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:104`](../packages/extensions/cordis-host-runner/src/index.ts)
- `source`: [`packages/extensions/cordis-host-runner/src/index.ts:106`](../packages/extensions/cordis-host-runner/src/index.ts)
```ts config-catalog
/** Runner configuration. */
@@ -2409,7 +2409,7 @@ export interface LspLocalServerConfig {
## `@deepseek-ai/dsh-mcp-client`
- `inject`: `tools`
- `source`: [`packages/mcp/mcp-client/src/index.ts:138`](../packages/mcp/mcp-client/src/index.ts)
- `source`: [`packages/mcp/mcp-client/src/index.ts:140`](../packages/mcp/mcp-client/src/index.ts)
```ts config-catalog
/** Configuration for one stdio or Streamable HTTP MCP server. */
@@ -2713,7 +2713,7 @@ export interface PlanModeConfig {
- `inject`: `loader` · `profileContext`
- `refs`: [`NpmFileSource`](subsystems/boot.zh.md)
- `source`: [`packages/boot/plugin-manager/src/index.ts:54`](../packages/boot/plugin-manager/src/index.ts)
- `source`: [`packages/boot/plugin-manager/src/index.ts:56`](../packages/boot/plugin-manager/src/index.ts)
```ts config-catalog
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -2763,7 +2763,7 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.zh.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:43`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
@@ -3408,7 +3408,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill`
- `source`: [`packages/skill/skill/src/index.ts:278`](../packages/skill/skill/src/index.ts)
- `source`: [`packages/skill/skill/src/index.ts:281`](../packages/skill/skill/src/index.ts)
```ts config-catalog
/** Skill registry configuration. */
@@ -3425,7 +3425,7 @@ export interface Config {
## `@deepseek-ai/dsh-skill-filesystem`
- `inject`: `skills`
- `source`: [`packages/skill/skill-filesystem/src/index.ts:48`](../packages/skill/skill-filesystem/src/index.ts)
- `source`: [`packages/skill/skill-filesystem/src/index.ts:49`](../packages/skill/skill-filesystem/src/index.ts)
```ts config-catalog
/** Local filesystem skill provider configuration. */
@@ -4473,7 +4473,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-skill`
- `inject`: `agents` · `tools` · `skills` · `workingDirectory`
- `source`: [`packages/skill/tool-skill/src/index.ts:64`](../packages/skill/tool-skill/src/index.ts)
- `source`: [`packages/skill/tool-skill/src/index.ts:65`](../packages/skill/tool-skill/src/index.ts)
```ts config-catalog
/** Model-facing skill catalog configuration. */
@@ -4684,7 +4684,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-workspace-dependencies`
- `inject`: `tools`
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:15`](../packages/skill/tool-workspace-dependencies/src/index.ts)
- `source`: [`packages/skill/tool-workspace-dependencies/src/index.ts:18`](../packages/skill/tool-workspace-dependencies/src/index.ts)
```ts config-catalog
/** Payload location and optional installation directory. */
+1 -1
View File
@@ -77,7 +77,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
+1 -1
View File
@@ -79,7 +79,7 @@
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) |
+21 -13
View File
@@ -487,6 +487,7 @@ flowchart TD
subgraph group_workspace["packages/workspace"]
pkg_workspace["workspace"]
end
pkg_atomic_write --> pkg_error
pkg_llm --> pkg_error
pkg_session --> pkg_scope
pkg_api_remotes --> pkg_scope
@@ -494,10 +495,6 @@ flowchart TD
pkg_app_boot --> pkg_home_paths
pkg_app_boot --> pkg_launch_environment
pkg_client_connection --> pkg_scope
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use
pkg_experimental_liveshare --> pkg_scope
pkg_anonymous_user_id --> pkg_brand
@@ -513,6 +510,7 @@ flowchart TD
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_error
pkg_skill --> pkg_llm
pkg_skill --> pkg_scope
pkg_web --> pkg_llm
@@ -525,6 +523,10 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_llm
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_webworker_runtime --> pkg_client_connection
@@ -582,6 +584,7 @@ flowchart TD
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_attachment
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -875,6 +878,7 @@ flowchart TD
pkg_tool_skill --> pkg_skill
pkg_tool_skill --> pkg_tools
pkg_tool_skill --> pkg_working_directory
pkg_tool_workspace_dependencies --> pkg_error
pkg_tool_workspace_dependencies --> pkg_tools
pkg_tool_web --> pkg_llm
pkg_tool_web --> pkg_system_prompt
@@ -992,6 +996,7 @@ flowchart TD
pkg_tool_terminal --> pkg_tools
pkg_tool_terminal --> pkg_working_directory
pkg_cordis_host_runner --> pkg_agent
pkg_cordis_host_runner --> pkg_error
pkg_cordis_host_runner --> pkg_llm
pkg_cordis_host_runner --> pkg_scope
pkg_cordis_host_runner --> pkg_session
@@ -1148,6 +1153,7 @@ flowchart TD
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_mcp_client --> pkg_attachment
pkg_mcp_client --> pkg_credentials
pkg_mcp_client --> pkg_error
pkg_mcp_client --> pkg_llm
pkg_mcp_client --> pkg_mcp_resources
pkg_mcp_client --> pkg_scope
@@ -1243,6 +1249,7 @@ flowchart TD
pkg_acp --> pkg_session_persistence
pkg_acp --> pkg_token_meter
pkg_acp --> pkg_user_approval
pkg_plugin_manager --> pkg_error
pkg_plugin_manager --> pkg_hmr
pkg_plugin_manager --> pkg_host_plugin_inventory
pkg_plugin_manager --> pkg_sandbox
@@ -1371,6 +1378,7 @@ flowchart TD
pkg_api_session_controller --> pkg_util_workspace_path
pkg_api_session_controller --> pkg_working_directory
pkg_api_session_controller --> pkg_workspace
pkg_plugin_market --> pkg_error
pkg_plugin_market --> pkg_plugin_manager
pkg_plugin_market --> pkg_settings
pkg_plugin_market --> pkg_subprocess
@@ -1535,7 +1543,6 @@ flowchart TD
<!-- BEGIN GENERATED module-graph:packages -->
| `package` | `group` | `peerDependencies` |
| --- | --- | --- |
| [`atomic-write`](../packages/util/atomic-write) | `util` | — |
| [`brand`](../packages/util/brand) | `util` | — |
| [`chunked-list`](../packages/util/chunked-list) | `util` | — |
| [`deque`](../packages/util/deque) | `util` | — |
@@ -1685,13 +1692,13 @@ flowchart TD
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — |
| [`typert-generator`](../packages/typert/generator) | `typert` | — |
| [`typert-registry`](../packages/typert/registry) | `typert` | — |
| [`atomic-write`](../packages/util/atomic-write) | `util` | [`error`](../packages/util/error) |
| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) |
| [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) |
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`error`](../packages/util/error) |
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) |
| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
@@ -1704,13 +1711,14 @@ flowchart TD
| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
| [`spill`](../packages/spill/spill) | `spill` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
@@ -1739,7 +1747,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
@@ -1805,7 +1813,7 @@ flowchart TD
| [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) |
| [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`error`](../packages/util/error), [`tools`](../packages/core/tools) |
| [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) |
| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
@@ -1828,7 +1836,7 @@ flowchart TD
| [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) |
| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) |
| [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) |
| [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
@@ -1858,7 +1866,7 @@ flowchart TD
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
@@ -1871,7 +1879,7 @@ flowchart TD
| [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) |
| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) |
| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
@@ -1888,7 +1896,7 @@ flowchart TD
| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
+21 -13
View File
@@ -489,6 +489,7 @@ flowchart TD
subgraph group_workspace["packages/workspace"]
pkg_workspace["workspace"]
end
pkg_atomic_write --> pkg_error
pkg_llm --> pkg_error
pkg_session --> pkg_scope
pkg_api_remotes --> pkg_scope
@@ -496,10 +497,6 @@ flowchart TD
pkg_app_boot --> pkg_home_paths
pkg_app_boot --> pkg_launch_environment
pkg_client_connection --> pkg_scope
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use
pkg_experimental_liveshare --> pkg_scope
pkg_anonymous_user_id --> pkg_brand
@@ -515,6 +512,7 @@ flowchart TD
pkg_util_ripgrep --> pkg_subprocess
pkg_system_prompt --> pkg_llm
pkg_system_prompt --> pkg_scope
pkg_skill --> pkg_error
pkg_skill --> pkg_llm
pkg_skill --> pkg_scope
pkg_web --> pkg_llm
@@ -527,6 +525,10 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_llm
pkg_credentials_local --> pkg_atomic_write
pkg_credentials_local --> pkg_credentials
pkg_credentials_local --> pkg_home_paths
pkg_credentials_local --> pkg_launch_environment
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_webworker_runtime --> pkg_client_connection
@@ -584,6 +586,7 @@ flowchart TD
pkg_host_product_telemetry_otel --> pkg_otel
pkg_persona --> pkg_system_prompt
pkg_ptc_runtime --> pkg_attachment
pkg_ptc_runtime --> pkg_error
pkg_ptc_runtime --> pkg_sandbox
pkg_sandbox_local --> pkg_llm
pkg_sandbox_local --> pkg_sandbox
@@ -877,6 +880,7 @@ flowchart TD
pkg_tool_skill --> pkg_skill
pkg_tool_skill --> pkg_tools
pkg_tool_skill --> pkg_working_directory
pkg_tool_workspace_dependencies --> pkg_error
pkg_tool_workspace_dependencies --> pkg_tools
pkg_tool_web --> pkg_llm
pkg_tool_web --> pkg_system_prompt
@@ -994,6 +998,7 @@ flowchart TD
pkg_tool_terminal --> pkg_tools
pkg_tool_terminal --> pkg_working_directory
pkg_cordis_host_runner --> pkg_agent
pkg_cordis_host_runner --> pkg_error
pkg_cordis_host_runner --> pkg_llm
pkg_cordis_host_runner --> pkg_scope
pkg_cordis_host_runner --> pkg_session
@@ -1150,6 +1155,7 @@ flowchart TD
pkg_host_plugin_inventory --> pkg_typert_protocol
pkg_mcp_client --> pkg_attachment
pkg_mcp_client --> pkg_credentials
pkg_mcp_client --> pkg_error
pkg_mcp_client --> pkg_llm
pkg_mcp_client --> pkg_mcp_resources
pkg_mcp_client --> pkg_scope
@@ -1245,6 +1251,7 @@ flowchart TD
pkg_acp --> pkg_session_persistence
pkg_acp --> pkg_token_meter
pkg_acp --> pkg_user_approval
pkg_plugin_manager --> pkg_error
pkg_plugin_manager --> pkg_hmr
pkg_plugin_manager --> pkg_host_plugin_inventory
pkg_plugin_manager --> pkg_sandbox
@@ -1373,6 +1380,7 @@ flowchart TD
pkg_api_session_controller --> pkg_util_workspace_path
pkg_api_session_controller --> pkg_working_directory
pkg_api_session_controller --> pkg_workspace
pkg_plugin_market --> pkg_error
pkg_plugin_market --> pkg_plugin_manager
pkg_plugin_market --> pkg_settings
pkg_plugin_market --> pkg_subprocess
@@ -1537,7 +1545,6 @@ flowchart TD
<!-- BEGIN GENERATED module-graph:packages -->
| `package` | `group` | `peerDependencies` |
| --- | --- | --- |
| [`atomic-write`](../packages/util/atomic-write) | `util` | — |
| [`brand`](../packages/util/brand) | `util` | — |
| [`chunked-list`](../packages/util/chunked-list) | `util` | — |
| [`deque`](../packages/util/deque) | `util` | — |
@@ -1687,13 +1694,13 @@ flowchart TD
| [`llm-mock-server`](../packages/test-support/llm-mock-server) | `test-support` | — |
| [`typert-generator`](../packages/typert/generator) | `typert` | — |
| [`typert-registry`](../packages/typert/registry) | `typert` | — |
| [`atomic-write`](../packages/util/atomic-write) | `util` | [`error`](../packages/util/error) |
| [`llm`](../packages/llm/llm) | `llm` | [`error`](../packages/util/error) |
| [`session`](../packages/core/session) | `core` | [`scope`](../packages/core/scope) |
| [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) |
| [`attachment`](../packages/attachment/attachment) | `attachment` | [`error`](../packages/util/error) |
| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) |
| [`experimental-liveshare`](../packages/experimental/liveshare) | `experimental` | [`scope`](../packages/core/scope) |
| [`anonymous-user-id`](../packages/identity/anonymous-user-id) | `identity` | [`brand`](../packages/util/brand), [`home-paths`](../packages/util/home-paths) |
@@ -1706,13 +1713,14 @@ flowchart TD
| [`typert-protocol`](../packages/typert/protocol) | `typert` | [`error`](../packages/util/error) |
| [`util-ripgrep`](../packages/util/ripgrep) | `util` | [`subprocess`](../packages/subprocess/subprocess) |
| [`system-prompt`](../packages/core/system-prompt) | `core` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`skill`](../packages/skill/skill) | `skill` | [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) |
| [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) |
| [`spill`](../packages/spill/spill) | `spill` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session) |
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
@@ -1741,7 +1749,7 @@ flowchart TD
| [`skill-badge`](../packages/experimental/skill-badge) | `experimental` | [`skill`](../packages/skill/skill) |
| [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) |
| [`persona`](../packages/preset/persona) | `preset` | [`system-prompt`](../packages/core/system-prompt) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`sandbox`](../packages/sandbox/sandbox) |
| [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime) | `ptc-runtime` | [`attachment`](../packages/attachment/attachment), [`error`](../packages/util/error), [`sandbox`](../packages/sandbox/sandbox) |
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
@@ -1807,7 +1815,7 @@ flowchart TD
| [`tool-fs-search`](../packages/fs/tool-fs-search) | `fs` | [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) | `fs` | [`fs`](../packages/fs/fs), [`output-retention`](../packages/util/output-retention), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tools`](../packages/core/tools) |
| [`tool-skill`](../packages/skill/tool-skill) | `skill` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`tools`](../packages/core/tools) |
| [`tool-workspace-dependencies`](../packages/skill/tool-workspace-dependencies) | `skill` | [`error`](../packages/util/error), [`tools`](../packages/core/tools) |
| [`tool-web`](../packages/web/tool-web) | `web` | [`llm`](../packages/llm/llm), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`web`](../packages/web/web) |
| [`web-deepseek-api`](../packages/web/web-deepseek-api) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-deepseek-account`](../packages/llm/llm-deepseek-account), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`session`](../packages/core/session), [`web`](../packages/web/web) |
| [`tool-todo`](../packages/todo/tool-todo) | `todo` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`tools`](../packages/core/tools) |
@@ -1830,7 +1838,7 @@ flowchart TD
| [`session-title-all-prompts-llm`](../packages/experimental/session-title-all-prompts-llm) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`session-title-llm`](../packages/session/session-title-llm) |
| [`terminal-panel`](../packages/experimental/terminal-panel) | `experimental` | [`api-terminal-controller`](../packages/api/terminal-controller), [`output-retention`](../packages/util/output-retention), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools) |
| [`tool-terminal`](../packages/experimental/tool-terminal) | `experimental` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`system-prompt`](../packages/core/system-prompt), [`terminal`](../packages/terminal/terminal), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`cordis-host-runner`](../packages/extensions/cordis-host-runner) | `extensions` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`message-feedback`](../packages/feedback/message-feedback) | `feedback` | [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`typert-protocol`](../packages/typert/protocol) |
| [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder) | `guard` | [`agent`](../packages/core/agent), [`tools`](../packages/core/tools) |
| [`tool-call-timeout-policy`](../packages/guard/timeout-policy) | `guard` | [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
@@ -1860,7 +1868,7 @@ flowchart TD
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) |
| [`host-plugin-inventory`](../packages/host/plugin-inventory) | `host` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`brand`](../packages/util/brand), [`typert-protocol`](../packages/typert/protocol) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`mcp-client`](../packages/mcp/mcp-client) | `mcp` | [`attachment`](../packages/attachment/attachment), [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`llm`](../packages/llm/llm), [`mcp-resources`](../packages/mcp/mcp-resources), [`scope`](../packages/core/scope), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`agent-preset`](../packages/preset/agent-preset) | `preset` | [`agent-preset-registry`](../packages/preset/agent-preset-registry) |
| [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | `session` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`command-feedback`](../packages/feedback/command-feedback), [`llm`](../packages/llm/llm), [`message-feedback`](../packages/feedback/message-feedback), [`otel`](../packages/telemetry/otel), [`session`](../packages/core/session), [`session-telemetry`](../packages/session/session-telemetry) |
| [`tool-bash`](../packages/shell/tool-bash) | `shell` | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-approval`](../packages/interaction/user-approval), [`working-directory`](../packages/session/working-directory) |
@@ -1873,7 +1881,7 @@ flowchart TD
| [`spill-policy`](../packages/spill/spill-policy) | `spill` | [`attachment`](../packages/attachment/attachment), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`spill`](../packages/spill/spill), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools) |
| [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-query`](../packages/session-query/session-query) |
| [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`llm`](../packages/llm/llm), [`mcp-client`](../packages/mcp/mcp-client), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`token-meter`](../packages/llm/token-meter), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`plugin-manager`](../packages/boot/plugin-manager) | `boot` | [`error`](../packages/util/error), [`hmr`](../packages/boot/hmr), [`host-plugin-inventory`](../packages/host/plugin-inventory), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | `compaction` | [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
@@ -1890,7 +1898,7 @@ flowchart TD
| [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) |
| [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`error`](../packages/util/error), [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) |
| [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) |
| [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) |
| [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) |
+6 -6
View File
@@ -1239,11 +1239,11 @@
en: a7b8c3f842059eec
zh: 4b345faa13cc39f6
/session-persistence-event-catalog/resolved-persistence-types/skillcatalogsource:
en: 2c3148e4a9f0c8f9
zh: dab42cb485067bcd
en: 615f4a7645b94dab
zh: 9e93a88507f2bca4
/session-persistence-event-catalog/resolved-persistence-types/skillinvocationsource:
en: ecc15ebadb77afdf
zh: 97ac27d6a4175f6f
en: 29df35a8cc984e75
zh: 321b4e8bb0ad0850
/session-persistence-event-catalog/resolved-persistence-types/streamchunk:
en: 747e384b3176e0cb
zh: defbff408ea7c97c
@@ -1506,8 +1506,8 @@
en: 10a2d594b106f6fe
zh: 8408379e744ad987
/session-persistence-event-catalog/resolved-persistence-types/description-name:
en: 26072d80c066a334
zh: 48deed5b57fecba4
en: a09e74cd05d03b0e
zh: aa51b3c5db030513
/session-persistence-event-catalog/resolved-persistence-types/description-name~2:
en: a07969828eed2e6f
zh: e06893743af544b5
+3 -3
View File
@@ -4840,7 +4840,7 @@ Sources: [`packages/experimental/liveshare/src/host/viewer-principal.ts:24`](../
SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts)
Sources: [`packages/skill/tool-skill/src/index.ts:36`](../packages/skill/tool-skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
@@ -4860,7 +4860,7 @@ Sources: [`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-sk
SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
Sources: [`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/index.ts)
Sources: [`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
@@ -6278,7 +6278,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:30`](../packages/llm/llm-retry/sr
SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693`
Sources: [`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts)
Sources: [`packages/skill/tool-skill/src/index.ts:44`](../packages/skill/tool-skill/src/index.ts)
| Property | Presence | Type |
|---|---|---|
+3 -3
View File
@@ -4842,7 +4842,7 @@ SHA-256: `4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b`
SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
来源:[`packages/skill/tool-skill/src/index.ts:35`](../packages/skill/tool-skill/src/index.ts)
来源:[`packages/skill/tool-skill/src/index.ts:36`](../packages/skill/tool-skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -4862,7 +4862,7 @@ SHA-256: `65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099`
SHA-256: `672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db`
来源:[`packages/skill/skill/src/index.ts:146`](../packages/skill/skill/src/index.ts)
来源:[`packages/skill/skill/src/index.ts:149`](../packages/skill/skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
@@ -6280,7 +6280,7 @@ SHA-256: `374fdd68aee5ff844e378c0cbdd961d247a0f22e4ade0bb03d800cd2a46a2b8b`
SHA-256: `83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693`
来源:[`packages/skill/tool-skill/src/index.ts:43`](../packages/skill/tool-skill/src/index.ts)
来源:[`packages/skill/tool-skill/src/index.ts:44`](../packages/skill/tool-skill/src/index.ts)
| 属性 | 存在性 | 类型 |
|---|---|---|
+3 -3
View File
@@ -322,9 +322,9 @@
{"digest":"6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f","names":["packages/subagent/subagent/src/descriptor.ts#ContinuableSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:72"]},
{"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]},
{"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:34"]},
{"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]},
{"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:36"]},
{"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]},
{"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:146"]},
{"digest":"672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db","names":["packages/skill/skill/src/index.ts#SkillInvocationSource"],"sources":["packages/skill/skill/src/index.ts:149"]},
{"digest":"67d5f73ceae82f5265258142ad6cf172de2c1fef93ba551b7f0454e0a93bffe0","names":["packages/llm/llm/src/call-config.ts#LlmCallConfig"],"sources":["packages/llm/llm/src/call-config.ts:30"]},
{"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]},
{"digest":"688e853dc149f0d30b31765c12ec7e3be74169bdf1a4c6463a10b945d50cc1b8","names":[],"sources":[]},
@@ -392,7 +392,7 @@
{"digest":"824b1d4d4f007bdaa5eee7994a5db3ede7707c6cd2bf8e2509be176c7609e3bc","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]},
{"digest":"825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8","names":[],"sources":[]},
{"digest":"829a2fb3be6efd4ba36aef8ed2d381a4c6fb2a0aaf50c823a6f3f8290786b809","names":[],"sources":[]},
{"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:43"]},
{"digest":"83079c8a3f733ac3fa603eefa0fbb4737ca4d8b69e7e2e7298b60f9ac4098693","names":[],"sources":["packages/skill/tool-skill/src/index.ts:44"]},
{"digest":"8338ee303e2bd448e9e6144069942f63e3cfd5868962bddc9347d7009e8919d6","names":[],"sources":[]},
{"digest":"83d6916021eede8f2d83a1872716caa1efdec39a3681890996c55147187fdd12","names":[],"sources":[]},
{"digest":"83da72c6857601c75da11212ef847f57d457b9c99f0a82246dcdff3e26700239","names":["packages/context/agent-instructions/src/render.ts#AgentInstructionChange"],"sources":["packages/context/agent-instructions/src/render.ts:62"]},
+4
View File
@@ -233,6 +233,8 @@ Manage profile files and apply their declared reload lifecycle.
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote async listPlugins(): Promise<PluginInfo[]>
@@ -240,6 +242,8 @@ Manage profile files and apply their declared reload lifecycle.
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote listBundles(): Promise<BundleInfo[]>
+4
View File
@@ -233,6 +233,8 @@ Manage profile files and apply their declared reload lifecycle.
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote async listPlugins(): Promise<PluginInfo[]>
@@ -240,6 +242,8 @@ Manage profile files and apply their declared reload lifecycle.
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote listBundles(): Promise<BundleInfo[]>
+3
View File
@@ -48,6 +48,9 @@ list(): CordisInspectProviderView[]
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query( platform: CordisInspectPlatform, providerId: string, methodName: string, input: JsonValue | undefined, agent: Agent, signal: AbortSignal, ): Promise<JsonValue>
+3
View File
@@ -48,6 +48,9 @@ list(): CordisInspectProviderView[]
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query( platform: CordisInspectPlatform, providerId: string, methodName: string, input: JsonValue | undefined, agent: Agent, signal: AbortSignal, ): Promise<JsonValue>
+2 -2
View File
@@ -18,8 +18,8 @@
en: 9aa0df86a35e1a0e
zh: 58f5382ef3f11f06
/mcp/protocol-and-results:
en: 46e9b914f016b636
zh: e1e9ee92a22f2562
en: e935c5aaa53e0e81
zh: c86cea6be89bb1db
/mcp/resources-and-instructions:
en: df9cc13a5d6eb923
zh: 3276d65c19d4c446
+1 -1
View File
@@ -55,7 +55,7 @@ The [native Cua Driver provider](../../packages/experimental/computer-use-cua-dr
Both stdio and Streamable HTTP use the official SDK's negotiation, discovery, protocol validation, and cancellation. Tool-list changes trigger discovery through legacy notifications or a modern subscription. A failed refresh retains the previous tool generation; connection recovery follows the [client lifecycle](../../packages/mcp/mcp-client/README.md#use-this-package).
The result adapter retains canonical MCP JSON for programmatic callers and prepares ordinary tool content. Supported images use the attachment system; unsupported rich content produces explicit text diagnostics. The tool registry remains authoritative for policy failures and replaced results. The [tool contracts](tools.md) own recording and final presentation; the [client result reference](../../packages/mcp/mcp-client/README.md#use-this-package) owns MCP-specific projection details.
The result adapter retains canonical MCP JSON for programmatic callers and prepares ordinary tool content. Supported images use the attachment system; unsupported rich content produces explicit text diagnostics. Server `isError` results and request failures throw `McpToolError` with a code that tells the caller whether the request's outcome is known, such as `MCP_TOOL_ERROR`, `MCP_CONNECTION_CLOSED`, or `MCP_TIMEOUT`; the client README lists every code. The tool registry remains authoritative for policy failures and replaced results. The [tool contracts](tools.md) own recording and final presentation; the [client result reference](../../packages/mcp/mcp-client/README.md#use-this-package) owns MCP-specific projection details.
-----
+1 -1
View File
@@ -55,7 +55,7 @@ Web 与 Desktop profile 还统一挂载一次 [MCP 服务器管理器](../../pac
stdio 和 Streamable HTTP 都使用官方 SDK 的协商、发现、协议校验和取消机制。工具列表变化通过旧版通知或现代订阅触发发现。刷新失败时保留上一代工具;连接恢复遵循[客户端生命周期](../../packages/mcp/mcp-client/README.zh.md#use-this-package)。
结果适配器为程序化调用方保留规范 MCP JSON,并准备普通工具内容。受支持的图像使用附件系统;不受支持的富内容产生明确的文本诊断。工具注册表仍决定策略失败和结果替换。[工具契约](tools.zh.md) 维护记录和最终呈现规则;[客户端结果参考](../../packages/mcp/mcp-client/README.zh.md#use-this-package) 维护 MCP 特有的投影细节。
结果适配器为程序化调用方保留规范 MCP JSON,并准备普通工具内容。受支持的图像使用附件系统;不受支持的富内容产生明确的文本诊断。服务器 `isError` 结果与请求失败抛出 `McpToolError`,其 code 告诉调用方请求结果是否已知,例如 `MCP_TOOL_ERROR`、`MCP_CONNECTION_CLOSED` 或 `MCP_TIMEOUT`;客户端 README 列出全部 code。工具注册表仍决定策略失败和结果替换。[工具契约](tools.zh.md) 维护记录和最终呈现规则;[客户端结果参考](../../packages/mcp/mcp-client/README.zh.md#use-this-package) 维护 MCP 特有的投影细节。
-----
+2 -2
View File
@@ -250,7 +250,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
```ts cordis-catalog
/**
@@ -281,7 +281,7 @@ registerEnvironmentInitializer(program: string): () => Promise<void>
* Resolve supported options and provider defaults before execution.
* @param request - Program, bindings, cancellation and optional execution choices.
* @returns Complete directory, deadline and supported authority for run.
* @throws When an explicit choice is invalid or unsupported by this provider.
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
*/
abstract resolve(request: PtcRunRequest): PtcRunSpec
+2 -2
View File
@@ -250,7 +250,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp
### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam)
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.
```ts cordis-catalog
/**
@@ -281,7 +281,7 @@ registerEnvironmentInitializer(program: string): () => Promise<void>
* Resolve supported options and provider defaults before execution.
* @param request - Program, bindings, cancellation and optional execution choices.
* @returns Complete directory, deadline and supported authority for run.
* @throws When an explicit choice is invalid or unsupported by this provider.
* @throws When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.
*/
abstract resolve(request: PtcRunRequest): PtcRunSpec
+2 -2
View File
@@ -6,8 +6,8 @@
en: ad77015352a17ed6
zh: 5c84933161845393
/skills/provider-registry:
en: abe338b6c6d1ebd1
zh: c604db2de10a23c4
en: 3fe1dff933bdb3f4
zh: b3f21b85a38bfaef
/skills/local-discovery-priority:
en: 390fc00bbccfb777
zh: 96ff7abfbd4b911b
+1 -1
View File
@@ -12,7 +12,7 @@ Source: [`packages/skill/skill/src/index.ts`](../../packages/skill/skill/src/ind
The registry is host+per-scope layered, the shape the [tools registry](tools.md) established over [dsh-scope](../../packages/core/scope): a registration files into the layer of its calling context's scope, so host rows and repository plugins land in the global layer while a plugin mounted by an agent preset's standing composition lands in that preset's layer, and provider names are unique per layer rather than process-wide. A read merges the global layer with the viewing scope's chain — the nearest layer's entry wins a duplicate skill name outright, and the rank order below decides duplicates only within one layer. Discovery caches are keyed by the resolved scope chain, so re-parenting a scope (a blank-session recompose) is visible to the next read without a registry mutation.
Within one layer, duplicate names resolve by rank, provider order, then local order; summaries sort by name. A rejected `list()` is logged and omitted from an incomplete observation, while an explicit incomplete observation contributes usable candidates without making the result cacheable; malformed candidates fail fast. Each provider factory receives a registration-scoped control whose `invalidate()` clears completed catalogs only while that exact registration remains active and whose signal aborts on failed registration or disposal. An in-flight discovery retries once when its provider generation changes; a second change returns the latest candidates incomplete and uncached. Provider and runtime mutations emit the unfiltered `skills/change` invalidation event; it carries no diff, so consumers refetch `snapshot()` with their own lookup options.
Within one layer, duplicate names resolve by rank, provider order, then local order; summaries sort by name. A rejected `list()` is logged and omitted from an incomplete observation, while an explicit incomplete observation contributes usable candidates without making the result cacheable; malformed candidates fail fast as `SkillError` with `SKILL_INVALID_DEFINITION`. Each provider factory receives a registration-scoped control whose `invalidate()` clears completed catalogs only while that exact registration remains active and whose signal aborts on failed registration or disposal. An in-flight discovery retries once when its provider generation changes; a second change returns the latest candidates incomplete and uncached. Provider and runtime mutations emit the unfiltered `skills/change` invalidation event; it carries no diff, so consumers refetch `snapshot()` with their own lookup options.
An array returned by `SkillProvider.list()` is complete-discovery shorthand. `SkillProviderObservation` lets a provider expose candidates that remain directly loadable while reporting that the observation is not authoritative.
+1 -1
View File
@@ -12,7 +12,7 @@
注册表采用宿主 + 按 scope 的分层结构,即[工具注册表](tools.zh.md)在 [dsh-scope](../../packages/core/scope) 之上确立的形态:注册会落入调用方上下文 scope 对应的层——宿主行与 repository 插件落入全局层,由 agent(智能体) preset 常驻组合挂载的插件落入该 preset 的层——提供方名称在每层内唯一,而非进程级唯一。读取时将全局层与观察 scope 的链合并:最近层的条目直接赢得重名 skill,下文的 rank 顺序只在单层内裁决重名。发现缓存以解析后的 scope 链为键,因此重设 scope 父级(空会话重组)无需注册表变更即可被下一次读取看到。
在单层内,重名项依次按 rank、提供方顺序和本地顺序确定优先级;摘要按名称排序。提供方的 `list()` 被拒绝时,系统会记录日志,并从不完整观测中省略该提供方的结果;显式的不完整观测会提供可用候选项,但不会使结果变得可缓存;格式错误的候选项快速失败。每个提供方工厂都会接收一项注册作用域内的控制能力;仅当该精确注册仍处于活动状态时,其 `invalidate()` 才会清除已完成目录;注册失败或 dispose(资源释放)时,其信号会中止。若提供方代次在发现进行期间发生变化,该发现会重试一次;若再次变化,则返回最新候选项,并将结果标为不完整且不予缓存。提供方和运行时变更会发出不带过滤条件的 `skills/change` 失效事件;该事件不携带 diff,因此消费方会使用自身的查找选项重新获取 `snapshot()`。
在单层内,重名项依次按 rank、提供方顺序和本地顺序确定优先级;摘要按名称排序。提供方的 `list()` 被拒绝时,系统会记录日志,并从不完整观测中省略该提供方的结果;显式的不完整观测会提供可用候选项,但不会使结果变得可缓存;格式错误的候选项以带 `SKILL_INVALID_DEFINITION` 的 `SkillError` 快速失败。每个提供方工厂都会接收一项注册作用域内的控制能力;仅当该精确注册仍处于活动状态时,其 `invalidate()` 才会清除已完成目录;注册失败或 dispose(资源释放)时,其信号会中止。若提供方代次在发现进行期间发生变化,该发现会重试一次;若再次变化,则返回最新候选项,并将结果标为不完整且不予缓存。提供方和运行时变更会发出不带过滤条件的 `skills/change` 失效事件;该事件不携带 diff,因此消费方会使用自身的查找选项重新获取 `snapshot()`。
`SkillProvider.list()` 返回的数组是完整发现的简写形式。`SkillProviderObservation` 允许提供方公开仍可直接加载的候选项,同时报告该观测不具权威性。
@@ -39,8 +39,8 @@
en: 1815ec6ce56c80d4
zh: 2d7ac75d3b25eb6b
/deepseek-ai-dsh-plugin-manager/model-experience/management-tool/what-the-model-sees:
en: b1dae91f98350290
zh: 802ae86d923ac6ce
en: 9bb316cf4b47ba60
zh: 1c719feedf36e2f3
/deepseek-ai-dsh-plugin-manager/model-experience/management-tool/token-effect:
en: bc70208bd361dbcd
zh: bb651d6066066c6c
+1 -1
View File
@@ -152,7 +152,7 @@ The `@deepseek-ai/dsh-plugin-manager/diagnostic` entry supplies Desktop Host and
#### What the model sees
The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. A change result that is not plainly applied adds `nextStep`, a sentence derived from its application status, refusal code, package-manager failure kind or restart reason that says what the model does next or tells the user. Management operations do not inject messages into Agents.
The [`plugin_manager` tool](../../../docs/tool-catalog.md#deepseek-aidsh-plugin-manager) lists plugin entries and bundles and performs profile-wide changes. Its results include saved-state changes, application status and package diagnostics. A change result that is not plainly applied adds `nextStep`, a sentence derived from its application status, refusal code, package-manager failure kind or restart reason that says what the model does next or tells the user. Management operations do not inject messages into Agents. A missing or unbounded argument fails as `ToolArgsError` with `INVALID_ARGS`. A failure before a change starts or while reading the profile throws `PluginManagerError`: `PLUGIN_MANAGER_PROFILE_READ_FAILED` when a profile or installation manifest or the profile patches cannot be read, and `PLUGIN_MANAGER_UNAVAILABLE` after the manager is disposed; another writer holding the profile lock past `lockWaitMs` fails with the atomic-write `FileLockError` `FILE_LOCK_TIMEOUT`; other operation failures stay in the change result.
#### Token effect
+1 -1
View File
@@ -152,7 +152,7 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,
#### 模型看到什么
[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。未直接应用的变更结果会增加 `nextStep`,这是一句根据应用状态、拒绝代码、包管理器失败类型或重启原因生成的说明,指出模型下一步做什么或告诉用户什么。管理操作不会向 Agent 注入消息。
[`plugin_manager` 工具](../../../docs/tool-catalog.zh.md#deepseek-aidsh-plugin-manager) 列出插件条目和组合包,并执行影响整个 profile 的改动。结果包含保存状态变化、应用状态和包管理诊断。未直接应用的变更结果会增加 `nextStep`,这是一句根据应用状态、拒绝代码、包管理器失败类型或重启原因生成的说明,指出模型下一步做什么或告诉用户什么。管理操作不会向 Agent 注入消息。缺少参数或参数越界时以带 `INVALID_ARGS` 的 `ToolArgsError` 失败。变更开始前或读取 profile 时的失败抛出 `PluginManagerError`:profile 或安装清单、profile 补丁无法读取时为 `PLUGIN_MANAGER_PROFILE_READ_FAILED`,管理器已卸载时为 `PLUGIN_MANAGER_UNAVAILABLE`;其他写入方持有 profile 锁超过 `lockWaitMs` 时以 atomic-write 的 `FileLockError` `FILE_LOCK_TIMEOUT` 失败;其他操作失败仍记录在变更结果中。
#### Token 影响
@@ -88,6 +88,7 @@
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-hmr": "workspace:*",
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
"@deepseek-ai/dsh-sandbox": "workspace:*",
@@ -113,6 +114,7 @@
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
"@deepseek-ai/dsh-tool-testkit": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-system-prompt": "workspace:*",
"@deepseek-ai/dsh-hmr": "workspace:*",
"@deepseek-ai/cordis-plugin-timer": "workspace:~",
+47
View File
@@ -0,0 +1,47 @@
/** Typed failures thrown by plugin management calls rather than reported in a change result. */
import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every {@link PluginManagerError} code:
* - `PLUGIN_MANAGER_PROFILE_READ_FAILED`: the profile manifest, patches, version exemptions, or
* installation manifest could not be read or parsed; `cause` is the original error. Repair the
* profile files before retrying.
* - `PLUGIN_MANAGER_UNAVAILABLE`: the manager was disposed before the change started.
*/
export const PLUGIN_MANAGER_ERROR_CODES = [
'PLUGIN_MANAGER_PROFILE_READ_FAILED',
'PLUGIN_MANAGER_UNAVAILABLE',
] as const
/** One {@link PluginManagerError} code. */
export type PluginManagerErrorCode = typeof PLUGIN_MANAGER_ERROR_CODES[number]
/** Typed plugin management failure; `code` is one of {@link PLUGIN_MANAGER_ERROR_CODES}. */
export class PluginManagerError extends HarnessError {
override readonly code: PluginManagerErrorCode
constructor(message: string, code: PluginManagerErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginManagerError'
this.code = code
}
}
/**
* Run one synchronous profile read, converting its failure.
* @param read - reads and parses profile files.
* @returns the read value.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` with the original error as `cause`.
*/
export function readProfileState<T>(read: () => T): T {
try {
return read()
} catch (error) {
// Profile readers fail with filesystem, JSON, YAML, or validation Error instances.
throw new PluginManagerError(
`plugin-manager: failed to read the profile: ${(error as Error).message}`,
'PLUGIN_MANAGER_PROFILE_READ_FAILED', { cause: error },
)
}
}
+15 -5
View File
@@ -35,6 +35,7 @@ import { dependencySpec, InvalidInstallSpecError, parseInstallSpec, pinnedGitOri
import { attributeFailure, normalizeRegistry, NPMMIRROR_REGISTRY, registryPlan } from './registry.ts'
import { flatten, writePluginEnabled } from './patch.ts'
import { incompatiblePlugin, ManagementFailure } from './failure.ts'
import { PluginManagerError, readProfileState } from './error.ts'
import { approveBuilds, recordPendingBuilds } from './build-approval.ts'
import { checkGitConnection, checkGithubConnection, type GithubConnectionFailure } from './github-connection.ts'
import { chooseGitTransport, sshGitSpec } from './git-transport.ts'
@@ -48,6 +49,7 @@ import type {
} from './types.ts'
export type * from './types.ts'
export { classifyInstallFailure, type InstallFailureFacts } from './install-failure.ts'
export { PluginManagerError, type PluginManagerErrorCode } from './error.ts'
export { InvalidInstallSpecError, parseInstallSpec, pinnedGitOrigin, type ParsedInstallSpec } from './install-spec.ts'
/** The pnpm executable, registries, and limits for diagnostics, lookups and connection checks. */
@@ -471,10 +473,12 @@ export class PluginManager extends TypertRemoteService {
/** Read current plugins, including why a row cannot be changed through the profile patch.
* @returns Current runtime entries with persistent patch targets.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches
* cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote
async listPlugins(): Promise<PluginInfo[]> {
const rows = flatten(composeEntries([readProfilePatches('dsh', this.profile)]))
const rows = readProfileState(() => flatten(composeEntries([readProfilePatches('dsh', this.profile)])))
const snapshot = await readPluginInventory(this.ctx)
return snapshot.entries.map((entry) => {
const actual = [...this.ctx.loader.entries()].find(row => row.id === entry.entryId)
@@ -495,6 +499,8 @@ export class PluginManager extends TypertRemoteService {
* A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.
* @returns Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional
* display metadata, activation selections, whether the installation offers the bundle, and removal availability.
* @throws {PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or
* installation manifest cannot be read; Remote callers receive `gateway/internal`.
*/
@Remote
listBundles(): Promise<BundleInfo[]> {
@@ -506,12 +512,14 @@ export class PluginManager extends TypertRemoteService {
/** The bundle inventory before update eligibility, which is derived from each listed bundle. */
private readBundles(): Omit<BundleInfo, 'update'>[] {
const manifest = readProfileManifest('dsh', this.profile.dir)
const exemptions = readProfileVersionExemptions(this.profile.dir)
const { manifest, exemptions, installation } = readProfileState(() => ({
manifest: readProfileManifest('dsh', this.profile.dir),
exemptions: readProfileVersionExemptions(this.profile.dir),
installation: JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest,
}))
const selected = bundleSelection(manifest)
const recorded = manifest.dependencies ?? {}
const dependencies = Object.keys(recorded)
const installation = JSON.parse(readFileSync(this.profile.installAnchor, 'utf8')) as InstallationManifest
const catalog = new Map(OFFICIAL_ON_DEMAND_CATALOG.map(entry => [entry.packageName, entry]))
const names = [...new Set([...selected, ...dependencies, ...Object.keys(installation.dependencies ?? {}), ...catalog.keys()])]
const bundles: Omit<BundleInfo, 'update'>[] = []
@@ -1375,7 +1383,9 @@ export class PluginManager extends TypertRemoteService {
let settled: ChangeResult
try {
settled = await withFileLock(join(this.profile.dir, 'package.json'), async () => {
this.abort.signal.throwIfAborted()
if (this.abort.signal.aborted) {
throw new PluginManagerError('plugin-manager: the manager is disposed; retry after the Host reloads it', 'PLUGIN_MANAGER_UNAVAILABLE')
}
const before = this.diskState()
const result: ChangeResult = { ...request, changed: false,
...this.ownerContext.get('hmr') !== undefined ? { application: 'applied' } : { application: 'restart-required', restartReason: 'no-hmr' } }
+6 -6
View File
@@ -6,7 +6,7 @@ import type {} from '@deepseek-ai/dsh-sandbox-policy'
import type {} from '@deepseek-ai/dsh-user-approval'
import { approveEscalation } from '@deepseek-ai/dsh-sandbox'
import type { ChangeResult, ManagementError, PluginEntryId, PluginInstallFailureKind, RestartReason } from './types.ts'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
/** What the model does next for each refusal the manager reports. */
@@ -116,7 +116,7 @@ export function apply(ctx: Context): void {
return JSON.stringify({ runtimeVersion: getDshRuntimeVersion(), ...manager.listVersionExemptions() })
case 'set_version_exemption':
if (args.target === undefined || args.runtimeVersion === undefined || args.enabled === undefined) {
throw new Error('target package-name@version, runtimeVersion, and enabled are required')
throw new ToolArgsError(['target package-name@version, runtimeVersion, and enabled are required'])
}
return JSON.stringify(withNextStep(
await manager.setVersionExemption(args.target, args.runtimeVersion, args.enabled, args.acceptRisk)))
@@ -125,7 +125,7 @@ export function apply(ctx: Context): void {
const offset = args.offset ?? 0
const limit = args.limit ?? 25
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) {
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100')
throw new ToolArgsError(['offset must be a non-negative integer and limit must be an integer from 1 to 100'])
}
const rows = args.action === 'list_plugins' ? await manager.listPlugins() : await manager.listBundles()
const entries = rows.slice(offset, offset + limit).map(({ meta: _meta, ...row }) =>
@@ -140,20 +140,20 @@ export function apply(ctx: Context): void {
}
case 'set_plugin':
case 'set_bundle': {
if (args.target === undefined || args.enabled === undefined) throw new Error('target and enabled are required')
if (args.target === undefined || args.enabled === undefined) throw new ToolArgsError(['target and enabled are required'])
return JSON.stringify(withNextStep(await (args.action === 'set_plugin'
? manager.setPluginEnabled(args.target as PluginEntryId, args.enabled)
: manager.setBundleEnabled(args.target, args.enabled))))
}
case 'install_bundle':
if (args.target === undefined) throw new Error('target package spec is required')
if (args.target === undefined) throw new ToolArgsError(['target package spec is required'])
return JSON.stringify(withNextStep(await manager.installBundle(args.target, {
...args.enabled === undefined ? {} : { enabled: args.enabled },
...args.approvedBuilds === undefined ? {} : { approvedBuilds: args.approvedBuilds },
...args.registry === undefined ? {} : { registry: args.registry },
})))
case 'remove_bundle':
if (args.target === undefined) throw new Error('target bundle name is required')
if (args.target === undefined) throw new ToolArgsError(['target bundle name is required'])
return JSON.stringify(withNextStep(await manager.removeBundle(args.target)))
/* v8 ignore next -- tool JSON validation rejects actions outside the declared enum */
default: return assertNever(args.action)
@@ -2522,3 +2522,27 @@ it('refuses an update whose target does not match where the copy was installed f
expect(view).not.toHaveBeenCalled()
expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before)
})
it('reports profile read, lock, and disposal failures with error codes', async () => {
const { ctx, manager, dir } = await fixture('startup', false, undefined, { lockWaitMs: 0 })
const manifest = join(dir, 'package.json')
const saved = readFileSync(manifest, 'utf8')
writeFileSync(manifest, '{')
const unreadable = Promise.resolve().then(() => manager.listBundles())
await expect(unreadable).rejects.toMatchObject({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_PROFILE_READ_FAILED' })
await expect(unreadable).rejects.toHaveProperty('cause', expect.any(SyntaxError))
writeFileSync(manifest, saved)
writeFileSync(`${manifest}.lock`, `${process.pid}\n`)
await expect(manager.setBundleEnabled('extra', false)).rejects.toMatchObject({
name: 'FileLockError', code: 'FILE_LOCK_TIMEOUT',
})
rmSync(`${manifest}.lock`)
const entry = [...ctx.loader.entries()].find(candidate => candidate.options.name === 'cordis:manager')
await entry?.fiber?.dispose()
await expect(manager.setBundleEnabled('extra', false)).rejects.toMatchObject({
name: 'PluginManagerError', code: 'PLUGIN_MANAGER_UNAVAILABLE',
})
expect(readFileSync(manifest, 'utf8')).toBe(saved)
})
@@ -16,6 +16,8 @@ import { expect, it, onTestFinished, vi } from 'vitest'
import type PluginManager from '../src/index.ts'
import type { BundleInfo } from '../src/types.ts'
import * as tool from '../src/tools.ts'
import { PluginManagerError } from '../src/error.ts'
import { FileLockError } from '@deepseek-ai/dsh-atomic-write'
function resultText(result: ToolExecutionResult): string {
if (typeof result.value !== 'string') throw new Error('Expected a serialized manager result')
@@ -275,7 +277,19 @@ it.each([
{ action: 'set_version_exemption', target: '[email protected]', runtimeVersion: '1.0.0' },
])('rejects incomplete or unbounded tool inputs: %j', async (args) => {
const { call } = await fixture()
expect((await call(args)).isError).toBe(true)
const result = await call(args)
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it('reports profile read, lock, and disposal failures with their error codes', async () => {
const { manager, call } = await fixture()
manager.listBundles.mockRejectedValueOnce(new PluginManagerError('plugin-manager: failed to read the profile: bad JSON', 'PLUGIN_MANAGER_PROFILE_READ_FAILED'))
manager.setBundleEnabled.mockRejectedValueOnce(new FileLockError('/profile/package.json.lock'))
manager.removeBundle.mockRejectedValueOnce(new PluginManagerError('plugin-manager: the manager is disposed', 'PLUGIN_MANAGER_UNAVAILABLE'))
expect((await call({ action: 'list_bundles' })).error?.info).toEqual({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_PROFILE_READ_FAILED' })
expect((await call({ action: 'set_bundle', target: 'bundle', enabled: false })).error?.info).toEqual({ name: 'FileLockError', code: 'FILE_LOCK_TIMEOUT' })
expect((await call({ action: 'remove_bundle', target: 'bundle' })).error?.info).toEqual({ name: 'PluginManagerError', code: 'PLUGIN_MANAGER_UNAVAILABLE' })
})
it('presents reads and changes distinctly and disposes its registration', async () => {
@@ -38,6 +38,9 @@
{
"path": "../../llm/llm"
},
{
"path": "../../util/error"
},
{
"path": "../../subprocess/subprocess"
},
+2 -2
View File
@@ -18,8 +18,8 @@
en: fef9850d643e327f
zh: c6e8cab773cf93b9
/deepseek-ai-dsh-plugin-market/use-this-package/plugin-detail-documents:
en: b5d96ca29cf76f31
zh: e5099b4f694cf4c9
en: 8a49fc923d4ebd95
zh: 44b9f020e8471458
/deepseek-ai-dsh-plugin-market/understand-the-implementation:
en: cb56b9191fc680a1
zh: eee0a1dfee9ea5bb
+1 -1
View File
@@ -80,7 +80,7 @@ A source that exists but cannot be read fails with `plugin-market/detail-unavail
Failures use `plugin-market/invalid-query`, `plugin-market/invalid-index-url`, `plugin-market/unknown-index`, `plugin-market/fetch-failed`, and `plugin-market/invalid-index`; the last carries the JSON path of the offending value.
The `plugin_market` tool lists the configured indexes, pages the plugins of one index in index order or, with a `query`, by best match, or pages one plugin's versions. It requires no approval because it reads only the sources the user configured and changes nothing; each version it returns carries the `target` and `registry` to pass to `plugin_manager`'s `install_bundle`, which keeps its own approval. The tool cannot change index sources. Creator mode keeps its row beside `plugin_manager`, and the row registers the tool only while `pluginMarket` is mounted; other presets keep it disabled.
The `plugin_market` tool lists the configured indexes, pages the plugins of one index in index order or, with a `query`, by best match, or pages one plugin's versions. It requires no approval because it reads only the sources the user configured and changes nothing; each version it returns carries the `target` and `registry` to pass to `plugin_manager`'s `install_bundle`, which keeps its own approval. The tool cannot change index sources. A missing argument or an out-of-range page fails as `ToolArgsError` with `INVALID_ARGS`. Market failures reach the tool registry as `PluginMarketError`, which keeps the service's message and its `RemoteError` as `cause`: for example `plugin-market/unknown-index` becomes `PLUGIN_MARKET_INDEX_NOT_FOUND`, `plugin-market/fetch-failed` becomes `PLUGIN_MARKET_FETCH_FAILED`, and an unlisted plugin is `PLUGIN_MARKET_PLUGIN_NOT_FOUND`; any other failure is `PLUGIN_MARKET_FAILED`. Creator mode keeps its row beside `plugin_manager`, and the row registers the tool only while `pluginMarket` is mounted; other presets keep it disabled.
-----
+1 -1
View File
@@ -81,7 +81,7 @@ Remote 方法如下:
失败使用 `plugin-market/invalid-query`、`plugin-market/invalid-index-url`、`plugin-market/unknown-index`、`plugin-market/fetch-failed` 和 `plugin-market/invalid-index`;最后一种携带违规值的 JSON 路径。
`plugin_market` 工具列出已配置的索引,按索引顺序分页列出某个索引的插件,或在给出 `query` 时按最佳匹配分页列出,或分页列出某个插件的版本。它不需要批准,因为它只读取用户配置的源且不做任何改动;它返回的每个版本都携带要传给 `plugin_manager` 的 `install_bundle` 的 `target` 和 `registry`,`install_bundle` 仍保留自己的批准要求。该工具不能修改索引源。Creator 模式在 `plugin_manager` 旁边保留它的行,该行只在 `pluginMarket` 已挂载时注册工具;其他预设保持禁用。
`plugin_market` 工具列出已配置的索引,按索引顺序分页列出某个索引的插件,或在给出 `query` 时按最佳匹配分页列出,或分页列出某个插件的版本。它不需要批准,因为它只读取用户配置的源且不做任何改动;它返回的每个版本都携带要传给 `plugin_manager` 的 `install_bundle` 的 `target` 和 `registry`,`install_bundle` 仍保留自己的批准要求。该工具不能修改索引源。缺少参数或分页越界时以带 `INVALID_ARGS` 的 `ToolArgsError` 失败。市场失败以 `PluginMarketError` 交给工具注册表,保留服务的 message,并把其 `RemoteError` 保留为 `cause`:例如 `plugin-market/unknown-index` 变为 `PLUGIN_MARKET_INDEX_NOT_FOUND`,`plugin-market/fetch-failed` 变为 `PLUGIN_MARKET_FETCH_FAILED`,未列出的插件为 `PLUGIN_MARKET_PLUGIN_NOT_FOUND`;其他失败为 `PLUGIN_MARKET_FAILED`。Creator 模式在 `plugin_manager` 旁边保留它的行,该行只在 `pluginMarket` 已挂载时注册工具;其他预设保持禁用。
-----
+2
View File
@@ -76,6 +76,7 @@
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*"
},
@@ -92,6 +93,7 @@
"@deepseek-ai/dsh-client-connection": "workspace:*",
"@deepseek-ai/dsh-config-editor": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-plugin-manager": "workspace:*",
"@deepseek-ai/dsh-settings": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
+68
View File
@@ -0,0 +1,68 @@
/** Typed `plugin_market` tool failures converted from the market service's Remote failures. */
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { RemoteErrorCode } from '@deepseek-ai/dsh-typert-protocol'
/**
* Every {@link PluginMarketError} code:
* - `PLUGIN_MARKET_INDEX_NOT_FOUND`: the URL is not a configured index source; call `list_indexes`.
* - `PLUGIN_MARKET_INVALID_INDEX_URL`: a configured index URL is invalid; only the user can fix the source.
* - `PLUGIN_MARKET_FETCH_FAILED`: the index could not be fetched (network, timeout, redirect, status, or size).
* - `PLUGIN_MARKET_INVALID_INDEX`: the fetched index document is invalid.
* - `PLUGIN_MARKET_PLUGIN_NOT_FOUND`: the index lists no plugin with the requested name.
* - `PLUGIN_MARKET_FAILED`: any other market failure; `cause` is the original error.
*/
export const PLUGIN_MARKET_ERROR_CODES = [
'PLUGIN_MARKET_INDEX_NOT_FOUND',
'PLUGIN_MARKET_INVALID_INDEX_URL',
'PLUGIN_MARKET_FETCH_FAILED',
'PLUGIN_MARKET_INVALID_INDEX',
'PLUGIN_MARKET_PLUGIN_NOT_FOUND',
'PLUGIN_MARKET_FAILED',
] as const
/** One {@link PluginMarketError} code. */
export type PluginMarketErrorCode = typeof PLUGIN_MARKET_ERROR_CODES[number]
/** Typed `plugin_market` failure; `code` is one of {@link PLUGIN_MARKET_ERROR_CODES}. */
export class PluginMarketError extends HarnessError {
override readonly code: PluginMarketErrorCode
constructor(message: string, code: PluginMarketErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginMarketError'
this.code = code
}
}
/**
* Remote failure codes `search` and `entry` reject with for a query the tool already validated;
* `invalid-query` cannot occur because the tool checks the same page bounds first.
*/
type ToolRemoteCode = Extract<RemoteErrorCode,
'plugin-market/unknown-index' | 'plugin-market/invalid-index-url' | 'plugin-market/fetch-failed' | 'plugin-market/invalid-index'>
/** Tool code for each Remote failure code the tool's market reads can reject with. */
const REMOTE_CODES: Readonly<Record<ToolRemoteCode, PluginMarketErrorCode>> = {
'plugin-market/unknown-index': 'PLUGIN_MARKET_INDEX_NOT_FOUND',
'plugin-market/invalid-index-url': 'PLUGIN_MARKET_INVALID_INDEX_URL',
'plugin-market/fetch-failed': 'PLUGIN_MARKET_FETCH_FAILED',
'plugin-market/invalid-index': 'PLUGIN_MARKET_INVALID_INDEX',
}
/**
* Convert a market failure for the tool registry. A market `RemoteError` with
* one of the codes `search` and `entry` reject with keeps its message and
* becomes the matching code with the Remote failure as `cause`; any other
* `HarnessError` keeps its identity; anything else is `PLUGIN_MARKET_FAILED`.
* @param error - the rejection of a market service call.
* @returns the failure to throw from the tool body.
*/
export function pluginMarketToolError(error: unknown): HarnessError {
if (error instanceof HarnessError) {
if (!Object.hasOwn(REMOTE_CODES, error.code)) return error
return new PluginMarketError(error.message, REMOTE_CODES[error.code as ToolRemoteCode], { cause: error })
}
const message = error instanceof Error ? error.message : String(error)
return new PluginMarketError(message, 'PLUGIN_MARKET_FAILED', { cause: error })
}
+1
View File
@@ -31,6 +31,7 @@ import type {
} from './types.ts'
export type * from './types.ts'
export { PluginMarketError, type PluginMarketErrorCode } from './error.ts'
declare module '@deepseek-ai/cordis' {
interface Context {
+24 -8
View File
@@ -2,8 +2,9 @@
import { assertNever } from '@deepseek-ai/dsh-util-values'
import type { Context } from '@deepseek-ai/cordis'
import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolArgsError } from '@deepseek-ai/dsh-tools'
import type { MarketListingVersion } from './index.ts'
import { PluginMarketError, pluginMarketToolError } from './error.ts'
/** Required services for the listing tool; `pluginMarket` is awaited inside `apply`. */
export const inject = ['tools']
@@ -17,6 +18,19 @@ function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
})
}
/**
* Await one market read for a tool call: cancellation rethrows the signal's reason, and any other
* rejection becomes a coded {@link PluginMarketError} or keeps its `HarnessError` identity.
*/
async function marketRead<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
try {
return await untilAborted(promise, signal)
} catch (error) {
signal.throwIfAborted()
throw pluginMarketToolError(error)
}
}
/** Longest market-supplied title or description returned to the model, in UTF-16 code units. */
const MAX_TEXT = 300
@@ -46,7 +60,7 @@ interface Page {
function pageOf(offset: number | undefined, limit: number | undefined): Page {
const page = { offset: offset ?? 0, limit: limit ?? 25 }
if (!Number.isInteger(page.offset) || page.offset < 0 || !Number.isInteger(page.limit) || page.limit < 1 || page.limit > 100) {
throw new Error('offset must be a non-negative integer and limit must be an integer from 1 to 100')
throw new ToolArgsError(['offset must be a non-negative integer and limit must be an integer from 1 to 100'])
}
return page
}
@@ -94,11 +108,11 @@ function registerTool(ctx: Context): void {
})),
})
case 'list_plugins': {
if (args.target === undefined) throw new Error('target index URL is required')
if (args.target === undefined) throw new ToolArgsError(['target index URL is required'])
const page = pageOf(args.offset, args.limit)
const text = args.query ?? ''
// The read is shared with other callers, so cancelling this call stops waiting without aborting the fetch.
const result = await untilAborted(market.search(args.target, {
const result = await marketRead(market.search(args.target, {
text, sort: { kind: text.trim() === '' ? 'index' : 'relevance' }, offset: page.offset, limit: page.limit,
}), exec.signal)
const entries = result.entries.map((entry) => {
@@ -121,11 +135,13 @@ function registerTool(ctx: Context): void {
return JSON.stringify({ index: english(result.title), entries, total: result.total, nextOffset: result.nextOffset })
}
case 'list_versions': {
if (args.target === undefined) throw new Error('target index URL is required')
if (args.name === undefined) throw new Error('name is required')
if (args.target === undefined) throw new ToolArgsError(['target index URL is required'])
if (args.name === undefined) throw new ToolArgsError(['name is required'])
const page = pageOf(args.offset, args.limit)
const entry = await untilAborted(market.entry(args.target, args.name), exec.signal)
if (entry === undefined) throw new Error(`${args.name} is not listed in ${args.target}`)
const entry = await marketRead(market.entry(args.target, args.name), exec.signal)
if (entry === undefined) {
throw new PluginMarketError(`${args.name} is not listed in ${args.target}`, 'PLUGIN_MARKET_PLUGIN_NOT_FOUND')
}
const { slice, nextOffset } = paged(entry.versions, page)
return JSON.stringify({
name: entry.name, defaultVersion: entry.defaultVersion ?? null, versions: slice.map(versionResult),
@@ -3,7 +3,7 @@ import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import { Context, Service } from '@deepseek-ai/cordis'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import ToolRuntime, { ToolArgsError } from '@deepseek-ai/dsh-tools'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
@@ -23,7 +23,7 @@ function serve(document: unknown) {
return fetch
}
async function fixture() {
async function fixture(indexes: readonly string[] = [URL_A]) {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
class Manager extends Service {
@@ -32,7 +32,7 @@ async function fixture() {
listVersionExemptions() { return { exemptions: {}, warnings: [] } }
}
await ctx.plugin(Manager)
await ctx.plugin(PluginMarket, { indexes: [URL_A], detailCacheDir: UNUSED_CACHE })
await ctx.plugin(PluginMarket, { indexes: [...indexes], detailCacheDir: UNUSED_CACHE })
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
@@ -128,15 +128,57 @@ it.each([
{ action: 'list_plugins', target: URL_A, limit: 0 },
{ action: 'list_plugins', target: URL_A, limit: 101 },
{ action: 'list_plugins', target: URL_A, offset: 1.5 },
{ action: 'list_plugins', target: 'https://unknown.example/index.json' },
{ action: 'list_versions', name: 'dsh-a' },
{ action: 'list_versions', target: URL_A },
{ action: 'list_versions', target: URL_A, name: 'dsh-a', limit: 101 },
{ action: 'list_versions', target: URL_A, name: 'dsh-missing' },
])('rejects an incomplete, unbounded, or unconfigured request: %j', async (args) => {
])('rejects an incomplete or unbounded request as INVALID_ARGS: %j', async (args) => {
serve(document)
const { call } = await fixture()
expect((await call(args)).isError).toBe(true)
const result = await call(args)
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it.each([
[{ action: 'list_plugins', target: 'https://unknown.example/index.json' }, 'PLUGIN_MARKET_INDEX_NOT_FOUND', 'Not a configured index source: https://unknown.example/index.json'],
[{ action: 'list_versions', target: URL_A, name: 'dsh-missing' }, 'PLUGIN_MARKET_PLUGIN_NOT_FOUND', `dsh-missing is not listed in ${URL_A}`],
] as const)('rejects an unconfigured index or unlisted bundle with a PluginMarketError: %j', async (args, code, message) => {
serve(document)
const { call } = await fixture()
expect((await call(args)).error).toEqual({ message, info: { name: 'PluginMarketError', code } })
})
it.each([
['an unreachable index', () => Promise.reject(new TypeError('fetch failed')), 'PLUGIN_MARKET_FETCH_FAILED'],
['a non-2xx index', () => Promise.resolve(new Response('missing', { status: 404 })), 'PLUGIN_MARKET_FETCH_FAILED'],
['an invalid index document', () => Promise.resolve(new Response(JSON.stringify({ format: 2 }))), 'PLUGIN_MARKET_INVALID_INDEX'],
] as const)('converts the market Remote failure for %s', async (_label, respond, code) => {
vi.stubGlobal('fetch', vi.fn(respond))
const { call } = await fixture()
const result = await call({ action: 'list_plugins', target: URL_A })
expect(result.error?.info).toEqual({ name: 'PluginMarketError', code })
})
it('reports a configured index source with an invalid URL as PLUGIN_MARKET_INVALID_INDEX_URL', async () => {
serve(document)
const invalid = 'https://user:[email protected]/index.json'
const { call } = await fixture([URL_A, invalid])
const result = await call({ action: 'list_plugins', target: invalid })
expect(result.error?.info).toEqual({ name: 'PluginMarketError', code: 'PLUGIN_MARKET_INVALID_INDEX_URL' })
})
it('keeps a HarnessError from the market and classifies any other failure', async () => {
serve(document)
const { call, ctx } = await fixture()
const coded = new ToolArgsError(['limit must be small'])
const search = vi.spyOn(ctx.pluginMarket, 'search').mockRejectedValueOnce(coded)
expect((await call({ action: 'list_plugins', target: URL_A })).error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
search.mockRejectedValueOnce(new Error('index cache broke'))
expect((await call({ action: 'list_plugins', target: URL_A })).error).toEqual({
message: 'index cache broke', info: { name: 'PluginMarketError', code: 'PLUGIN_MARKET_FAILED' },
})
search.mockRejectedValueOnce('bare failure')
expect((await call({ action: 'list_plugins', target: URL_A })).error?.message).toBe('bare failure')
})
it('presents a read and disposes its registration', async () => {
@@ -19,6 +19,7 @@
{ "path": "../../util/values" },
{ "path": "../../settings/settings" },
{ "path": "../../typert/protocol" },
{ "path": "../../util/error" },
{ "path": "../../core/tools" },
{ "path": "../../util/brand" },
{ "path": "../../subprocess/subprocess" },
@@ -21,8 +21,8 @@
en: 78708b3779d999a9
zh: ad6173f9f01630de
/deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation/ptc-mode:
en: 7d0df521ba40881d
zh: 65d4738c69cbe0d4
en: 129e1a149bd42218
zh: 97aec4e64d26dd7f
/deepseek-ai-dsh-tool-executor-ptc/further-exploration:
en: ee69078c38c655a9
zh: fb0873407f23c8c5
+1 -1
View File
@@ -68,7 +68,7 @@ New sub-calls use `<parent>:ptc:<n>` ids. Consumers treat these ids as opaque an
TypeScript bindings for `read_image` and CUA screenshot operations return an `Image` with a readable `path`, `width`, and `height`. Passing it to `inspect` places its durable attachment among the captured text in the `run_code` result. Images nested in arrays and objects are displayed with their containing value. On program failure, inspected output accompanies the original diagnostic; outer result replacements remain authoritative. If an output policy removes a screenshot or read_image image, the binding rejects with ToolCallError and includes the retained text notice. Additional contexts retain their producing tool’s attribution.
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. Cancellation can discard retained runtime state and does not undo completed tool effects.
When the caller cancels and the runtime reports `abort`, `run_code` waits for cleanup and returns the native tool cancellation result: `AbortError` / `ABORTED`, with `Error: tool call aborted` as its content. Retained runtimes append their cancellation diagnostic, including whether variables were preserved or cleared. The Agent records the specific cancellation cause in `turn/end`, including a hook's reason. Other runtime failures retain `CODE_RUN_FAILED` and their diagnostics, even if the caller also cancels. A runtime rejection keeps a `PtcRuntimeError` code and otherwise becomes `CODE_RUN_FAILED` with the rejection as `cause`. A blank `description`, an invalid `timeoutMs`, or `timeoutMs` or `sandbox_permissions` on a runtime that does not support it fails as `ToolArgsError` with `INVALID_ARGS`; a call after executor disposal fails with `CODE_RUN_UNAVAILABLE`; and a missing runtime, `workingDirectory`, or `sandboxPolicy` fails as `ToolContextUnavailableError`. Cancellation can discard retained runtime state and does not undo completed tool effects.
`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in all Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls.
+1 -1
View File
@@ -68,7 +68,7 @@ PTC 执行器公开保留的 `run_code` 传输,以及按所加载运行时语
TypeScript 中的 `read_image` 与 CUA 截图操作返回 `Image`,其中包含可读取的 `path`、`width` 和 `height`。将其传给 `inspect` 后,持久附件会按顺序与文本一起进入 `run_code` 结果。数组和对象内嵌的图片会随所在值一起展示。程序失败时,已 inspect 的输出随原始诊断一起呈现;外层替换的结果保持生效。输出策略移除截图或 read_image 图片时,绑定以 ToolCallError 拒绝,并包含保留的文本提示。额外上下文保留生成工具的归属。
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
调用方取消且运行时报告 `abort` 时,`run_code` 等待清理完成,并返回原生工具的取消结果:`AbortError` / `ABORTED`,内容为 `Error: tool call aborted`。保留状态的运行时会附加取消诊断,包括变量被保留还是清空。Agent 在 `turn/end` 中记录具体取消原因,包括 hook 的理由。其他运行时失败保留 `CODE_RUN_FAILED` 及其诊断,即使调用方同时取消。运行时拒绝保留 `PtcRuntimeError` 的 code,否则变为 `CODE_RUN_FAILED` 并以该拒绝为 `cause`。`description` 为空白、`timeoutMs` 无效,或运行时不支持却传入 `timeoutMs` 或 `sandbox_permissions` 时,以带 `INVALID_ARGS` 的 `ToolArgsError` 失败;执行器释放后的调用以 `CODE_RUN_UNAVAILABLE` 失败;缺少运行时、`workingDirectory` 或 `sandboxPolicy` 时以 `ToolContextUnavailableError` 失败。取消可能丢弃保留的运行时状态,也不会撤销已完成的工具操作。
当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消所有 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。
+22 -8
View File
@@ -21,19 +21,33 @@ export class ToolCallLimitExceededError extends Error {
}
}
/**
* Every {@link CodeRunFailedError} code:
* - `CODE_RUN_FAILED`: the program run failed, or the runtime rejected it without its own error code.
* - `CODE_RUN_UNAVAILABLE`: the executor was disposed before the run started.
*/
export const CODE_RUN_ERROR_CODES = ['CODE_RUN_FAILED', 'CODE_RUN_UNAVAILABLE'] as const
/** One {@link CodeRunFailedError} code. */
export type CodeRunErrorCode = typeof CODE_RUN_ERROR_CODES[number]
/**
* Thrown by `run_code` when the program run itself failed — a program
* exception, a budget expiry, a runtime-local abort, or substrate death. Caller
* cancellation uses the shared `AbortError` / `ABORTED` tool outcome. Extends
* {@link HarnessError} (`code: 'CODE_RUN_FAILED'`); the registry's execution
* pipeline converts it into a structured `isError` result with the failure
* kind. Captured text and images accompany the original diagnostic;
* outer result replacements remain authoritative.
* exception, a budget expiry, a runtime-local abort, or substrate death — or
* could not start. Caller cancellation uses the shared `AbortError` /
* `ABORTED` tool outcome. Extends {@link HarnessError} with a code from
* {@link CODE_RUN_ERROR_CODES}; the registry's execution pipeline converts it
* into a structured `isError` result with the failure kind. Captured text and
* images accompany the original diagnostic; outer result replacements remain
* authoritative.
*/
export class CodeRunFailedError extends HarnessError {
constructor(message: string) {
super(message, 'CODE_RUN_FAILED')
override readonly code: CodeRunErrorCode
constructor(message: string, code: CodeRunErrorCode = 'CODE_RUN_FAILED', options?: ErrorOptions) {
super(message, code, options)
this.name = 'CodeRunFailedError'
this.code = code
}
}
@@ -94,6 +94,7 @@ export class PtcExecutor implements ToolExecutor {
export { Config } from './config.ts'
export { CodeRunFailedError, CodeResetFailedError } from './errors.ts'
export type { CodeRunErrorCode } from './errors.ts'
export type { PtcDispatchLog } from './runtime-types.ts'
export type { PtcDispatchStartEventData, PtcDispatchEventData } from './types.ts'
export { jsonSchemaToTs, renderToolsSdk, type ToolSdkSchema } from './ts-types.ts'
@@ -67,7 +67,7 @@ export class PtcCalls {
await Promise.all(pending.map(call => call.done))
}
signal.throwIfAborted()
if (this.disposed) throw new Error('PTC tool executor disposed')
if (this.disposed) throw new CodeRunFailedError('PTC tool executor disposed', 'CODE_RUN_UNAVAILABLE')
const controller = new AbortController()
const done = Promise.withResolvers<undefined>()
const currentSignal = AbortSignal.any([signal, controller.signal])
+22 -9
View File
@@ -22,7 +22,10 @@ import type {} from '@deepseek-ai/dsh-user-approval'
import type {} from '@deepseek-ai/dsh-working-directory'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
import { defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED } from '@deepseek-ai/dsh-tools'
import {
defineTool, parameterSchemaSpecToJsonSchema, projectToolSchema, RUN_CODE_NAME, TOOL_ABORTED, ToolArgsError,
ToolContextUnavailableError,
} from '@deepseek-ai/dsh-tools'
import type { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline'
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
import { scopeTarget } from '@deepseek-ai/dsh-scope'
@@ -84,7 +87,7 @@ const RUN_CODE_FLAVORS = {
export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
const runtime = ctx.get('ptcRuntime')
if (runtime === undefined) {
throw new Error('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
throw new ToolContextUnavailableError('dsh-tools: mode "ptc" requires a PTC runtime — load a ctx.ptcRuntime implementation (e.g. @deepseek-ai/dsh-ptc-runtime-node) or load @deepseek-ai/dsh-tool-executor-native')
}
return requireRuntimeLanguage(runtime)
}
@@ -93,7 +96,7 @@ export function requirePtcRuntime(ctx: Context): SupportedPtcRuntime {
function requireRuntimeLanguage(runtime: PtcRuntime): SupportedPtcRuntime {
if (!Object.hasOwn(RUN_CODE_FLAVORS, runtime.language)) {
const known = Object.keys(RUN_CODE_FLAVORS).map(name => JSON.stringify(name)).join(', ')
throw new Error(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
throw new ToolContextUnavailableError(`dsh-tools: no SDK renderer registered for runtime language ${JSON.stringify(runtime.language)} (known: ${known})`)
}
return runtime as SupportedPtcRuntime
}
@@ -254,6 +257,11 @@ function renderValue(value: JsonValue): string {
return typeof value === 'string' ? value : renderJsonValue(value)
}
/** Whether a rejection is the caller's cancellation rather than a failure of its own. */
function isCancellation(error: unknown, signal: AbortSignal): boolean {
return signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))
}
/** Canonical value returned by the outer PTC mode transport. */
type RunCodeOutput = { logs: string[]; result?: JsonValue; sandbox?: PtcRunSandbox }
@@ -288,14 +296,14 @@ function renderRunOutput(
async function resolveWorkingDirectory(ctx: Context, exec: ToolRunContext): Promise<string | undefined> {
if (exec.agent === undefined) return undefined
const directories = ctx.get('workingDirectory')
if (directories === undefined) throw new Error('dsh-tools: run_code with an Agent requires workingDirectory')
if (directories === undefined) throw new ToolContextUnavailableError('dsh-tools: run_code with an Agent requires workingDirectory')
return directories.ensure(exec.agent, exec.signal)
}
/** Resolve standing authority for a runtime that enforces file policy. */
function resolveSandboxPolicy(ctx: Context, exec: ToolRunContext): SandboxExecutionPolicy {
const policy = ctx.get('sandboxPolicy')
if (policy === undefined) throw new Error('dsh-tools: confined PTC runtime requires sandboxPolicy')
if (policy === undefined) throw new ToolContextUnavailableError('dsh-tools: confined PTC runtime requires sandboxPolicy')
return policy.resolve(exec.agent === undefined ? {} : { session: exec.agent.session })
}
@@ -391,21 +399,21 @@ export function createRunCodeTransport(
},
async execute(args, exec): Promise<RunCodeOutput> {
if (args.description.trim().length === 0) {
throw new Error('invalid description: expected a non-empty string')
throw new ToolArgsError(['invalid description: expected a non-empty string'])
}
const runtime = getRuntime()
const run = async (callSignal: AbortSignal): Promise<RunCodeOutput> => {
validateEscalationArgs(args.sandbox_permissions, args.justification)
if (args.timeoutMs !== undefined && runtime.timeout === undefined) {
throw new Error('timeoutMs is not available for this PTC runtime')
throw new ToolArgsError(['timeoutMs is not available for this PTC runtime'])
}
if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) {
throw new Error('invalid timeoutMs: expected a positive finite number')
throw new ToolArgsError(['invalid timeoutMs: expected a positive finite number'])
}
const standingPolicy = runtime.sandboxMode === undefined ? undefined : resolveSandboxPolicy(ctx, exec)
let policy = standingPolicy
if (args.sandbox_permissions !== undefined && args.justification !== undefined) {
if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime')
if (standingPolicy === undefined) throw new ToolArgsError(['sandbox_permissions is not available for this PTC runtime'])
const approvedMode = await approveEscalation({
requestedMode: args.sandbox_permissions,
justification: args.justification,
@@ -761,6 +769,11 @@ export function createRunCodeTransport(
maxSubCalls = spec.timeoutMs === null ? Infinity
: Math.floor(spec.timeoutMs / 60_000 * maxSubCallsPerMinute)
result = await runtime.run(spec)
} catch (error) {
// Runtimes reject only contract misuse; a rejection without its own code becomes CODE_RUN_FAILED.
// The cancellation itself passes through for the registry to classify as ABORTED.
if (error instanceof HarnessError || isCancellation(error, callSignal)) throw error
throw new CodeRunFailedError(`code run failed: ${toolErrorMessage(error)}`, 'CODE_RUN_FAILED', { cause: error })
} finally {
// Abort sub-dispatches and drain every in-flight dispatch before
// closing the turn (queued-unstarted ones are abandoned unlogged).
@@ -87,6 +87,9 @@ it('unloads the executor only after calls stop and refuses late admission', asyn
await rejected
await disposed
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toThrow('PTC tool executor disposed')
await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toMatchObject({
name: 'CodeRunFailedError', code: 'CODE_RUN_UNAVAILABLE',
})
} finally { cleanup.resolve(undefined); await first; await disposed }
})
@@ -14,7 +14,7 @@ import type { ToolSchema } from '@deepseek-ai/dsh-llm'
import { createScope } from '@deepseek-ai/dsh-scope'
import type { Scope } from '@deepseek-ai/dsh-scope'
import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
import { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime'
import { PtcRuntime, PtcRuntimeError } from '@deepseek-ai/dsh-ptc-runtime'
import type { PtcRunFailure, PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime'
import ToolRuntime, { RUN_CODE_NAME, TOOL_ABORTED, TOOL_ABORTED_BEFORE_DISPATCH, defineTool } from '@deepseek-ai/dsh-tools'
import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit'
@@ -1945,6 +1945,7 @@ describe('the run_code dispatch bridge', () => {
const result = await runCode(ctx, 'program')
expect(result.isError).toBe(true)
expect((result.content[0] as { text: string }).text).toContain('requires a PTC runtime')
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
})
it('refuses an agent-owned program before dispatch when its directory owner is missing', async () => {
@@ -1968,6 +1969,7 @@ describe('the run_code dispatch bridge', () => {
expect(result.content).toEqual([{
type: 'text', text: 'Error: dsh-tools: run_code with an Agent requires workingDirectory',
}])
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
expect(runtime.lastRequest).toBeUndefined()
expect(calls).toEqual([])
expect(events).toEqual([])
@@ -1989,11 +1991,44 @@ describe('the run_code dispatch bridge', () => {
})
})
it('classifies runtime rejections, keeping a runtime error code', async () => {
const { ctx, runtime } = await setup({ mode: 'ptc' })
const misuse = new TypeError('runtime contract violated')
runtime.behavior = () => Promise.reject(misuse)
const failed = await runCode(ctx, 'return 1')
expect(failed.error).toEqual({
message: 'code run failed: runtime contract violated',
info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' },
})
runtime.behavior = () => Promise.reject(new PtcRuntimeError('ptc-runtime-node: run after disposal', 'PTC_RUNTIME_UNAVAILABLE'))
expect((await runCode(ctx, 'return 1')).error?.info).toEqual({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
})
it('keeps a distinct runtime rejection after cancellation and passes the cancellation through', async () => {
const { ctx, runtime } = await setup({ mode: 'ptc' })
const cancelled = async (rejection: (reason: unknown) => unknown) => {
const controller = new AbortController()
runtime.behavior = () => {
controller.abort(new Error('caller cancelled'))
// The cancellation case rejects with the signal's own reason.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
return Promise.reject(rejection(controller.signal.reason))
}
return (await runCode(ctx, 'return 1', { signal: controller.signal })).error
}
expect((await cancelled(() => new PtcRuntimeError('persistent PTC environment cleanup is incomplete', 'PTC_RUNTIME_UNAVAILABLE')))?.info)
.toEqual({ name: 'PtcRuntimeError', code: 'PTC_RUNTIME_UNAVAILABLE' })
expect((await cancelled(() => new TypeError('cleanup observation failed')))?.info)
.toEqual({ name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' })
expect((await cancelled(reason => reason))?.info).toEqual({ name: 'AbortError', code: 'ABORTED' })
})
it('rejects a whitespace-only description with a structured isError', async () => {
const { ctx } = await setup({ mode: 'ptc' })
const result = await runCode(ctx, 'return 1', { description: ' ' })
expect(result.isError).toBe(true)
expect((result.content[0] as { text: string }).text).toContain('invalid description')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
})
it.each([
@@ -2720,6 +2755,7 @@ describe('PTC standing file policy and sandbox outcomes', () => {
const result = await runCode(ctx, 'return 1')
expect(result.isError).toBe(true)
expect(result.content).toEqual([{ type: 'text', text: 'Error: dsh-tools: confined PTC runtime requires sandboxPolicy' }])
expect(result.error?.info).toEqual({ name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE' })
expect((ctx.ptcRuntime as ConfinedFakeRuntime).lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -2839,6 +2875,7 @@ describe('per-program execution controls', () => {
arguments: { code: 'pass', description: 'Try unsupported timeout', timeoutMs: 5 },
})
expect(rejected.isError).toBe(true)
expect(rejected.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(python.runtime.lastRequest).toBeUndefined()
} finally { await python.ctx.fiber.dispose() }
})
@@ -2846,7 +2883,9 @@ describe('per-program execution controls', () => {
it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY, '1000', null])('rejects invalid timeout %s before runtime execution', async (timeoutMs) => {
const { ctx, runtime, execute } = await controlledSetup()
try {
expect((await execute({ timeoutMs })).isError).toBe(true)
const result = await execute({ timeoutMs })
expect(result.isError).toBe(true)
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(runtime.lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -2860,6 +2899,7 @@ describe('per-program execution controls', () => {
})
expect(result.isError).toBe(true)
expect(JSON.stringify(result.content)).toContain('sandbox_permissions is not available for this PTC runtime')
expect(result.error?.info).toEqual({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
expect(runtime.lastRequest).toBeUndefined()
} finally { await ctx.fiber.dispose() }
})
@@ -21,14 +21,14 @@
en: ca844fa88b307274
zh: da2032bfe3c1b792
/deepseek-ai-dsh-cordis-host-runner/use-this-package/client-inspection:
en: b4a2fe9e7aa9dee7
zh: 56f55558809970da
en: eb3187e43eec0872
zh: 096eef6a6d0c388b
/deepseek-ai-dsh-cordis-host-runner/use-this-package/what-a-run-does:
en: a3c86c081974a710
zh: 180e1b7824c070d4
/deepseek-ai-dsh-cordis-host-runner/use-this-package/what-happens-to-definitions:
en: d1a8777f171d22bb
zh: 7f6aa4c2680557b1
en: 29a5f9735bf562ec
zh: f762571af38fa99a
/deepseek-ai-dsh-cordis-host-runner/use-this-package/trust-stance:
en: af859a1591c02386
zh: 46d3c82713fa9055
@@ -49,6 +49,8 @@ When Gateway is mounted, a Client query with no live event stream fails before d
Client queries accept the first valid page response within `clientInspectTimeoutMs`. A failed page does not prevent another page from answering successfully. If no valid result arrives, the query rejects with the first Client failure or output-validation diagnostic; when no page answers, it asks the caller to open or reconnect the Harness page and retry. Cancellation and registry disposal also end pending queries. Reconnecting a page does not replay a missed request, so retry after the connection is restored. Host queries are unaffected by this timeout.
Query failures throw `InspectError`: `INSPECT_PROVIDER_NOT_FOUND`, `INSPECT_METHOD_NOT_FOUND`, and `INSPECT_INVALID_INPUT` reject the request before dispatch; `INSPECT_INVALID_OUTPUT` rejects a provider value; `INSPECT_CLIENT_UNAVAILABLE` reports a missing page or registry disposal; and `INSPECT_TIMEOUT` reports the Client deadline. A Host provider may throw its own `HarnessError`, such as `INSPECT_TARGET_NOT_FOUND`; any other provider failure becomes `INSPECT_FAILED` with the original error as `cause`. Cancellation rethrows the signal's reason.
### What a run does
Programmatic callers use `define`, `run`, `stop`, and `undefine`; the browser panel operates existing definitions. Host-only packages activate in this process. A package with a browser half waits for approval or cancellation, then loads Host before Client. `mode: "run"` starts the current version; `mode: "update"` replaces it. Stop disposes the live effects and retains the definition; undefine also forgets it.
@@ -57,6 +59,8 @@ Programmatic callers use `define`, `run`, `stop`, and `undefine`; the browser pa
Definitions are session-scoped and process-local: other sessions read them as absent, and restart clears them. Historical logs retain tool arguments and receipts but do not restore the registry. Reloading a browser page requires another explicit run to load its Client half.
A tool defined through `harness.defineTool` fails with `PluginToolError`: `PLUGIN_TOOL_FAILED` when `execute` throws, keeping the thrown message and any string `code` in `message`, and `PLUGIN_TOOL_INVALID_RESULT` when it returns a value that is not lossless JSON data. A thrown `HarnessError` and any failure after cancellation keep their own identity.
### Trust stance
The sandbox isolates globals but is not a security boundary: Node globals are absent or redirect to Cordis services (`ctx.fs`, `ctx.web`, `ctx.bash`, the timer helpers), and a host half receives a façade without framework internals, yet the services it declares reach the live runtime. Treat a dynamic package like bash access — see the [self-referential toolset reference](README.md).
@@ -49,6 +49,8 @@ kind: "package-reference"
Client 查询在 `clientInspectTimeoutMs` 内接受首个有效页面响应。某个页面失败不会阻止其他页面成功回答。若没有有效结果,查询返回首个 Client 错误或输出校验诊断;若没有页面回答,则提示调用方打开或重新连接 Harness 页面后重试。取消和注册表卸载也会结束待处理查询。页面重连不会重放错过的请求,因此需在连接恢复后重试。Host 查询不受此超时影响。
查询失败抛出 `InspectError`:`INSPECT_PROVIDER_NOT_FOUND`、`INSPECT_METHOD_NOT_FOUND` 与 `INSPECT_INVALID_INPUT` 在发送前拒绝请求;`INSPECT_INVALID_OUTPUT` 拒绝提供方返回值;`INSPECT_CLIENT_UNAVAILABLE` 表示没有页面或注册表已卸载;`INSPECT_TIMEOUT` 表示 Client 期限已到。Host 提供方可以抛出自己的 `HarnessError`,例如 `INSPECT_TARGET_NOT_FOUND`;其他提供方失败变为 `INSPECT_FAILED`,原始错误保留为 `cause`。取消时重新抛出信号的 reason。
### run 会做什么
程序调用方使用 `define`、`run`、`stop` 和 `undefine`;浏览器面板操作已有定义。仅含 Host 的包在本进程激活。带浏览器部分的包等待审批或取消,批准后先加载 Host 再加载 Client。`mode: "run"` 启动当前版本,`mode: "update"` 替换版本。Stop 释放运行中的 effect 并保留定义;undefine 还会移除定义。
@@ -57,6 +59,8 @@ Client 查询在 `clientInspectTimeoutMs` 内接受首个有效页面响应。
定义按会话隔离且仅在进程内存在:其他会话无法读取,重启会清空。历史日志保留工具参数和回执,但不会恢复注册表。浏览器页面重载后,需要再次显式运行才能加载 Client 部分。
通过 `harness.defineTool` 定义的工具以 `PluginToolError` 失败:`execute` 抛出时为 `PLUGIN_TOOL_FAILED`,`message` 保留抛出的消息及其字符串 `code`;返回值不是无损 JSON 数据时为 `PLUGIN_TOOL_INVALID_RESULT`。抛出的 `HarnessError` 与取消之后的任何失败保留其自身身份。
### 信任立场
沙箱隔离全局变量,但不是安全边界:Node 全局变量不存在,或重定向到 Cordis 服务(`ctx.fs`、`ctx.web`、`ctx.bash` 与定时器 helper),host 半收到的是不含框架内部机制的 façade,但它声明的服务仍会触达存活运行时。对待动态包要像对待 bash 访问一样,参见[自引用工具集 参考](README.zh.md)。
@@ -59,6 +59,7 @@
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-agent": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-tools": "workspace:*",
@@ -71,6 +72,7 @@
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
"@deepseek-ai/dsh-tool-executor-native": "workspace:*",
@@ -17,7 +17,9 @@ import { Context } from '@deepseek-ai/cordis'
import type { Plugin } from '@deepseek-ai/cordis'
import { scopeOf } from '@deepseek-ai/dsh-scope'
import { assertSupportedJsonSchema, defineTool } from '@deepseek-ai/dsh-tools'
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
import { toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline'
import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools'
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
@@ -539,12 +541,66 @@ function assertRenderedContent(value: JsonValue): ContentBlock[] {
)
}
/**
* Every {@link PluginToolError} code:
* - `PLUGIN_TOOL_FAILED`: a dynamic tool's `execute` threw or rejected with a value other than a
* `HarnessError`; `message` keeps the thrown message and any string `code` it carried, and `cause`
* is the thrown value.
* - `PLUGIN_TOOL_INVALID_RESULT`: `execute` resolved with a value that is not lossless JSON data.
*/
export const PLUGIN_TOOL_ERROR_CODES = ['PLUGIN_TOOL_FAILED', 'PLUGIN_TOOL_INVALID_RESULT'] as const
/** One {@link PluginToolError} code. */
export type PluginToolErrorCode = typeof PLUGIN_TOOL_ERROR_CODES[number]
/** Failure of a tool a dynamic plugin defined; `code` is one of {@link PLUGIN_TOOL_ERROR_CODES}. */
export class PluginToolError extends HarnessError {
override readonly code: PluginToolErrorCode
constructor(message: string, code: PluginToolErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'PluginToolError'
this.code = code
}
}
/**
* Whether a value thrown by sandbox `execute` code is a `HarnessError` or the
* caller's cancellation. A Proxy whose traps throw is neither.
*/
function keepsIdentity(error: unknown, signal: AbortSignal): boolean {
try {
return error instanceof HarnessError
|| (signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError')))
} catch {
// A trapped prototype or `name` read identifies neither a coded failure nor a cancellation.
return false
}
}
/**
* Classify a value thrown by sandbox `execute` code. Sandbox errors come from
* another realm, so their fields are read structurally rather than through `instanceof`.
*/
function pluginToolFailure(error: unknown): PluginToolError {
const message = toolErrorMessage(error)
let code: unknown
try {
code = typeof error === 'object' && error !== null ? (error as { code?: unknown }).code : undefined
} catch (_codeReadTrapped) {
// A trapped `code` read carries no usable code; the message alone describes the failure.
}
return new PluginToolError(typeof code === 'string' ? `${message} (code ${code})` : message, 'PLUGIN_TOOL_FAILED', { cause: error })
}
/**
* The `harness.defineTool` handed into the sandbox: the real DSL, with `parameters` normalized
* into a fresh host-realm ParameterSchemaSpec (raw object wrappers unwrapped,
* required arrays mapped, and explicit DSL object openness enforced) and the tool's `execute` return normalized into the host realm
* via a JSON round-trip. Non-JSON or wrong-shape output fails that call instead of poisoning
* the session log.
* via a JSON round-trip. Non-JSON or wrong-shape output fails that call with
* {@link PluginToolError} `PLUGIN_TOOL_INVALID_RESULT` instead of poisoning the session log, and a
* value thrown by `execute` fails it with `PLUGIN_TOOL_FAILED` unless it is a `HarnessError` or
* the caller's cancellation.
* @param options - the standard `defineTool` options; `parameters` may be the ParameterSchemaSpec DSL or a JSON-Schema-style wrapper.
* @returns the marker-tagged definition `harness.registerTool` (and the guarded `ctx.tools.register`) accepts.
*/
@@ -579,8 +635,21 @@ export function sandboxDefineTool(options: unknown): ToolDefinition {
},
} : {},
},
async execute(args: unknown, exec: unknown): Promise<JsonValue> {
return cloneJson(await rawExecute(args, exec), 'harness.defineTool execute result') as JsonValue
async execute(args: unknown, exec: ToolExecution): Promise<JsonValue> {
let result: unknown
try {
result = await rawExecute(args, exec)
} catch (error) {
// The cancellation and host services' coded failures keep their own identity.
if (keepsIdentity(error, exec.signal)) throw error
throw pluginToolFailure(error)
}
try {
return cloneJson(result, 'harness.defineTool execute result') as JsonValue
} catch (error) {
// Getters and Proxy traps on the returned value run during the clone and may throw any value.
throw new PluginToolError(toolErrorMessage(error), 'PLUGIN_TOOL_INVALID_RESULT', { cause: error })
}
},
})
const parameters = { ...tool.parameters, ...normalized.rootAnnotations }
@@ -44,8 +44,10 @@ export type {
DynamicCordisPackageInspection, DynamicCordisPlugin, DynamicCordisPluginInspection,
DynamicCordisReference, DynamicCordisRun,
} from './registry.ts'
export { CordisInspectRegistryService } from './inspect-registry.ts'
export type { HostCordisInspectProviderRegistration } from './inspect-registry.ts'
export { CordisInspectRegistryService, InspectError } from './inspect-registry.ts'
export type { HostCordisInspectProviderRegistration, InspectErrorCode } from './inspect-registry.ts'
export { PluginToolError } from './guard.ts'
export type { PluginToolErrorCode } from './guard.ts'
/**
* Brand a Host-minted Plugin ID.
@@ -3,6 +3,7 @@
import { Service } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import { HarnessError } from '@deepseek-ai/dsh-error'
import type {} from '@deepseek-ai/dsh-api-gateway'
import { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values'
import { assertSupportedJsonSchema, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools'
@@ -13,6 +14,42 @@ import type {
CordisInspectRequestId, CordisInspectResolveAck,
} from './types.ts'
/**
* Every {@link InspectError} code:
* - `INSPECT_PROVIDER_NOT_FOUND`: no provider with the requested id is registered on the platform.
* - `INSPECT_METHOD_NOT_FOUND`: the provider declares no method with the requested name.
* - `INSPECT_TARGET_NOT_FOUND`: the query names a target, such as a Loader entry, that the provider does not have.
* - `INSPECT_INVALID_INPUT`: the input violates the method's input schema.
* - `INSPECT_INVALID_OUTPUT`: the provider returned a non-JSON value or a value outside its output schema.
* - `INSPECT_CLIENT_UNAVAILABLE`: no Harness page is connected to answer a Client query, or the registry was disposed while it waited.
* - `INSPECT_TIMEOUT`: no valid Client response arrived within the query timeout.
* - `INSPECT_FAILED`: a Host provider failed without its own error code; `cause` is the original error.
*/
export const INSPECT_ERROR_CODES = [
'INSPECT_PROVIDER_NOT_FOUND',
'INSPECT_METHOD_NOT_FOUND',
'INSPECT_TARGET_NOT_FOUND',
'INSPECT_INVALID_INPUT',
'INSPECT_INVALID_OUTPUT',
'INSPECT_CLIENT_UNAVAILABLE',
'INSPECT_TIMEOUT',
'INSPECT_FAILED',
] as const
/** One {@link InspectError} code. */
export type InspectErrorCode = typeof INSPECT_ERROR_CODES[number]
/** Typed Cordis inspect query failure; `code` is one of {@link INSPECT_ERROR_CODES}. */
export class InspectError extends HarnessError {
override readonly code: InspectErrorCode
constructor(message: string, code: InspectErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'InspectError'
this.code = code
}
}
/** Context supplied to a Host inspect query. */
export interface HostCordisInspectQueryContext {
/** Tool-call cancellation. */
@@ -115,6 +152,9 @@ export class CordisInspectRegistryService extends Service {
* @param signal - tool-call cancellation.
* @returns provider JSON data; Client queries fail fast when Gateway has no live Client
* and retain only the first observed failure diagnostic for timeout reporting.
* @throws {InspectError} for an unknown provider or method, invalid input or output, a missing
* Client, a Client timeout, or a Host provider failure without its own `HarnessError`; cancellation
* rethrows the signal's reason.
*/
async query(
platform: CordisInspectPlatform,
@@ -126,11 +166,23 @@ export class CordisInspectRegistryService extends Service {
): Promise<JsonValue> {
if (platform === 'host') {
const registration = this.providers.get(providerId)
if (registration === undefined) throw new Error(`Host Cordis inspect provider "${providerId}" is not registered`)
if (registration === undefined) {
throw new InspectError(`Host Cordis inspect provider "${providerId}" is not registered`, 'INSPECT_PROVIDER_NOT_FOUND')
}
const method = findMethod(registration.manifest, methodName)
validateInput('Host', providerId, method, input)
signal.throwIfAborted()
const data = await registration.query(methodName, input, { agent, signal })
let data: JsonValue
try {
data = await registration.query(methodName, input, { agent, signal })
} catch (error) {
// The cancellation itself passes through for the tool registry to classify as ABORTED.
if (error instanceof HarnessError || isCancellation(error, signal)) throw error
throw new InspectError(
`Host Cordis inspect ${providerId}.${methodName} failed: ${error instanceof Error ? error.message : String(error)}`,
'INSPECT_FAILED', { cause: error },
)
}
signal.throwIfAborted()
return validateOutput('Host', providerId, method, data)
}
@@ -177,13 +229,18 @@ export class CordisInspectRegistryService extends Service {
signal: AbortSignal,
): Promise<JsonValue> {
const provider = this.clientManifest?.find(candidate => candidate.id === providerId)
if (provider === undefined) throw new Error(`Client Cordis inspect provider "${providerId}" is not registered`)
if (provider === undefined) {
throw new InspectError(`Client Cordis inspect provider "${providerId}" is not registered`, 'INSPECT_PROVIDER_NOT_FOUND')
}
const method = findMethod(provider, methodName)
validateInput('Client', providerId, method, input)
signal.throwIfAborted()
const gateway = this.ctx.get('typertGateway')
if (gateway !== undefined && !gateway.hasLiveClient()) {
throw new Error(`Client inspect query ${providerId}.${methodName} has no connected Harness page. Open or reconnect the Harness page, then retry.`)
throw new InspectError(
`Client inspect query ${providerId}.${methodName} has no connected Harness page. Open or reconnect the Harness page, then retry.`,
'INSPECT_CLIENT_UNAVAILABLE',
)
}
const requestId = `inspect-${this.nextRequest++}` as CordisInspectRequestId
const request: CordisInspectQueryRequest = {
@@ -232,7 +289,12 @@ export class CordisInspectRegistryService extends Service {
if (signal.aborted) onAbort()
else this.ctx.emit('cordis/inspect-query', request)
const resolution = await result
if (!resolution.ok) throw new Error(`${providerId}.${methodName}: ${resolution.message}`)
if (!resolution.ok) {
signal.throwIfAborted()
// Locally settled failures: the response deadline, or registry disposal reported as cancellation.
const code = resolution.reason === 'cancelled' ? 'INSPECT_CLIENT_UNAVAILABLE' : 'INSPECT_TIMEOUT'
throw new InspectError(`${providerId}.${methodName}: ${resolution.message}`, code)
}
return resolution.data
} finally {
clearTimeout(timer)
@@ -242,6 +304,11 @@ export class CordisInspectRegistryService extends Service {
}
}
/** Whether a rejection is the caller's cancellation rather than a failure of its own. */
function isCancellation(error: unknown, signal: AbortSignal): boolean {
return signal.aborted && (error === signal.reason || (error instanceof Error && error.name === 'AbortError'))
}
function view(platform: CordisInspectPlatform, manifest: CordisInspectProviderManifest): CordisInspectProviderView {
return { platform, ...manifest, methods: [...manifest.methods] }
}
@@ -264,7 +331,7 @@ function validateManifest(manifest: CordisInspectProviderManifest): CordisInspec
function findMethod(manifest: CordisInspectProviderManifest, name: string): CordisInspectMethodManifest {
const method = manifest.methods.find(candidate => candidate.name === name)
if (method === undefined) throw new Error(`Cordis inspect provider "${manifest.id}" has no method "${name}"`)
if (method === undefined) throw new InspectError(`Cordis inspect provider "${manifest.id}" has no method "${name}"`, 'INSPECT_METHOD_NOT_FOUND')
return method
}
@@ -275,7 +342,9 @@ function validateInput(
input: JsonValue | undefined,
): void {
const violations = validateJsonSchemaValue(method.inputSchema as JsonSchemaNode, input ?? {}, 'input')
if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} rejected input: ${violations.join('; ')}`)
if (violations.length > 0) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} rejected input: ${violations.join('; ')}`, 'INSPECT_INVALID_INPUT')
}
}
function validateOutput(
@@ -285,8 +354,12 @@ function validateOutput(
data: JsonValue,
): JsonValue {
const snapshot = snapshotJsonValue(data)
if (snapshot === undefined) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned a non-JSON value`)
if (snapshot === undefined) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} returned a non-JSON value`, 'INSPECT_INVALID_OUTPUT')
}
const violations = validateJsonSchemaValue(method.outputSchema as JsonSchemaNode, snapshot, 'output')
if (violations.length > 0) throw new Error(`${platform} Cordis inspect ${provider}.${method.name} returned invalid output: ${violations.join('; ')}`)
if (violations.length > 0) {
throw new InspectError(`${platform} Cordis inspect ${provider}.${method.name} returned invalid output: ${violations.join('; ')}`, 'INSPECT_INVALID_OUTPUT')
}
return snapshot
}
@@ -6,7 +6,7 @@ import type { PeerId, PeerScope } from '@deepseek-ai/dsh-typert-protocol'
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import DynamicCordisRunnerService from '../src/index.ts'
import { CordisInspectRegistryService } from '../src/inspect-registry.ts'
import { CordisInspectRegistryService, InspectError } from '../src/inspect-registry.ts'
import type { CordisInspectProviderManifest, CordisInspectQueryRequest, CordisInspectRequestId } from '../src/types.ts'
import { AGENT_A, AGENT_B } from './helpers.ts'
@@ -20,7 +20,7 @@ const manifest: CordisInspectProviderManifest = {
outputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
}],
}
const timeout = 'Error: Service.listService: Client inspect query Service.listService timed out after 100ms. '
const timeout = 'InspectError: Service.listService: Client inspect query Service.listService timed out after 100ms. '
const failure = { ok: false, reason: 'provider-error', message: 'page failed' } as const
let ctx: Context
@@ -67,7 +67,11 @@ function start() {
let settled = false
const result = registry.query('client', 'Service', 'listService', { service: 'remote' }, AGENT_A, controller.signal).then(
(value) => { settled = true; return { value } },
(error: unknown) => { settled = true; return { error: String(error) } },
(error: unknown) => {
settled = true
const code = (error as { code?: unknown }).code
return { error: String(error), ...typeof code === 'string' ? { code } : {} }
},
)
results.push(result)
return { controller, result, request: requests.at(-1)!, settled: () => settled }
@@ -116,7 +120,8 @@ describe('Client inspect completion', () => {
expect(requests).toEqual([])
expect(vi.getTimerCount()).toBe(0)
expect(await query.result).toEqual({
error: 'Error: Client inspect query Service.listService has no connected Harness page. Open or reconnect the Harness page, then retry.',
error: 'InspectError: Client inspect query Service.listService has no connected Harness page. Open or reconnect the Harness page, then retry.',
code: 'INSPECT_CLIENT_UNAVAILABLE',
})
expect(registry.list()).toHaveLength(1)
})
@@ -130,7 +135,7 @@ describe('Client inspect completion', () => {
await vi.advanceTimersByTimeAsync(99)
expect(query.settled()).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
expect(answer(query)).toEqual({ accepted: false })
expect(vi.getTimerCount()).toBe(0)
})
@@ -143,7 +148,7 @@ describe('Client inspect completion', () => {
await vi.advanceTimersByTimeAsync(99)
expect(query.settled()).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: no catalogued Service named "remote"' })
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: no catalogued Service named "remote"', code: 'INSPECT_TIMEOUT' })
expect(resolved).toEqual([query.request.requestId])
expect(answer(query)).toEqual({ accepted: false })
expect(vi.getTimerCount()).toBe(0)
@@ -165,7 +170,7 @@ describe('Client inspect completion', () => {
registry.resolveClientQuery(AGENT_A, query.request.requestId, failure)
registry.resolveClientQuery(AGENT_A, query.request.requestId, { ...failure, message: 'second failure' })
await vi.advanceTimersByTimeAsync(100)
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: page failed' })
expect(await query.result).toEqual({ error: timeout + 'Client failure: provider-error: page failed', code: 'INSPECT_TIMEOUT' })
})
it('retains output validation errors for timeout diagnostics', async () => {
@@ -187,7 +192,7 @@ describe('Client inspect completion', () => {
const query = start()
expect(registry.resolveClientQuery(AGENT_B, query.request.requestId, failure)).toEqual({ accepted: false })
await vi.advanceTimersByTimeAsync(100)
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await query.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
})
it('ends unanswered requests and accepts a fresh retry after manifest publication', async () => {
@@ -195,7 +200,7 @@ describe('Client inspect completion', () => {
registry.syncClientManifest([manifest])
expect(requests).toHaveLength(1)
await vi.advanceTimersByTimeAsync(100)
expect(await first.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.' })
expect(await first.result).toEqual({ error: timeout + 'Open or reconnect the Harness page, then retry.', code: 'INSPECT_TIMEOUT' })
const retry = start()
expect(retry.request.requestId).not.toBe(first.request.requestId)
expect(answer(first)).toEqual({ accepted: false })
@@ -208,7 +213,7 @@ describe('Client inspect completion', () => {
const query = start()
const remove = vi.spyOn(query.controller.signal, 'removeEventListener')
query.controller.abort()
expect(await query.result).toEqual({ error: 'Error: Service.listService: Client inspect query Service.listService was cancelled' })
expect(await query.result).toEqual({ error: 'AbortError: This operation was aborted' })
expect(remove).toHaveBeenCalledWith('abort', expect.any(Function))
expect(vi.getTimerCount()).toBe(0)
expect(answer(query)).toEqual({ accepted: false })
@@ -229,7 +234,7 @@ describe('Client inspect completion', () => {
const second = start()
await fiber.dispose()
for (const query of [first, second]) {
expect(await query.result).toEqual({ error: 'Error: Service.listService: Client inspect registry was disposed' })
expect(await query.result).toEqual({ error: 'InspectError: Service.listService: Client inspect registry was disposed', code: 'INSPECT_CLIENT_UNAVAILABLE' })
expect(answer(query)).toEqual({ accepted: false })
}
expect(resolved).toEqual([first.request.requestId, second.request.requestId])
@@ -262,6 +267,53 @@ describe('Client inspect completion', () => {
})
})
describe('Inspect query failure codes', () => {
const signal = new AbortController().signal
const host = (provider: string, method: string, input: unknown = {}) =>
registry.query('host', provider, method, input as never, AGENT_A, signal)
it('classifies unknown names, schema violations, and Host provider failures', async () => {
let result: unknown = {}
const providerFailure = new Error('provider exploded')
disposers.push(registry.register({ manifest, query: async () => {
if (result === providerFailure) throw providerFailure
return result as never
} }))
await expect(host('Missing', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_PROVIDER_NOT_FOUND' })
await expect(registry.query('client', 'Missing', 'listService', {}, AGENT_A, signal))
.rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_PROVIDER_NOT_FOUND' })
await expect(host('Service', 'missing')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' })
await expect(host('Service', 'listService', { extra: true })).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_INPUT' })
await expect(host('Service', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_OUTPUT' })
result = undefined
await expect(host('Service', 'listService')).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_INVALID_OUTPUT' })
result = providerFailure
await expect(host('Service', 'listService')).rejects.toMatchObject({
name: 'InspectError', code: 'INSPECT_FAILED', message: 'Host Cordis inspect Service.listService failed: provider exploded', cause: providerFailure,
})
})
it('keeps a Host provider HarnessError and its cancellation, and still classifies a distinct late failure', async () => {
const coded = new InspectError('unknown entry id "x"', 'INSPECT_TARGET_NOT_FOUND')
const reason = new Error('caller cancelled')
const late = new Error('cleanup failed')
let controller = new AbortController()
let thrown: unknown = coded
disposers.push(registry.register({ manifest, query: async () => {
if (thrown !== coded) controller.abort(reason)
throw thrown
} }))
await expect(host('Service', 'listService')).rejects.toBe(coded)
thrown = reason
await expect(registry.query('host', 'Service', 'listService', {}, AGENT_A, controller.signal)).rejects.toBe(reason)
controller = new AbortController()
thrown = late
await expect(registry.query('host', 'Service', 'listService', {}, AGENT_A, controller.signal)).rejects.toMatchObject({
name: 'InspectError', code: 'INSPECT_FAILED', cause: late,
})
})
})
describe('Client inspect timeout configuration', () => {
it('defaults to ten seconds and accepts both timer limits', () => {
expect(DynamicCordisRunnerService.Config({}).clientInspectTimeoutMs).toBe(10_000)
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import { HarnessError } from '@deepseek-ai/dsh-error'
import { sandboxDefineTool } from '../src/guard.ts'
import { syntaxErrorContext } from '../src/sandbox.ts'
import { AGENT_A, call, CONTENT_OUTPUT_CODE, mount, setup, text, running } from './helpers.ts'
@@ -41,6 +42,59 @@ describe('dynamic tool declaration boundary', () => {
})
})
describe('dynamic tool execution failures', () => {
const tool = (execute: () => Promise<unknown>) => sandboxDefineTool({
name: 'failing', description: 'failing tool', parameters: {},
output: { schema: { type: 'json' }, render: () => [] },
execute,
})
const run = (execute: () => Promise<unknown>, signal = new AbortController().signal) =>
tool(execute).execute({}, { signal } as never)
it('classifies thrown values and non-JSON results as PluginToolError', async () => {
const thrown = Object.assign(new Error('quota exhausted'), { code: 'QUOTA' })
await expect(run(() => Promise.reject(thrown))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'quota exhausted (code QUOTA)', cause: thrown,
})
// Sandbox code may reject with any value, not only an Error.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject('bare failure'))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'bare failure',
})
const trapped = new Proxy({}, { get: (_target, key) => { if (key === 'code') throw new Error('trap'); return undefined } })
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject(trapped))).rejects.toMatchObject({ name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED' })
await expect(run(() => Promise.resolve(new Map()))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_INVALID_RESULT',
})
})
it('keeps a HarnessError and a failure after cancellation unchanged', async () => {
const coded = new HarnessError('service failed', 'SERVICE_FAILED')
await expect(run(() => Promise.reject(coded))).rejects.toBe(coded)
const controller = new AbortController()
const reason = new Error('cancelled')
controller.abort(reason)
await expect(run(() => Promise.reject(reason), controller.signal)).rejects.toBe(reason)
await expect(run(() => Promise.reject(new Error('cleanup failed')), controller.signal)).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED', message: 'cleanup failed',
})
})
it('classifies hostile thrown values and results that throw during the clone', async () => {
const revocable = Proxy.revocable({}, {})
revocable.revoke()
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
await expect(run(() => Promise.reject(revocable.proxy))).rejects.toMatchObject({ name: 'PluginToolError', code: 'PLUGIN_TOOL_FAILED' })
for (const thrown of ['getter failed', null]) {
const value = { get broken(): never { throw thrown } }
await expect(run(() => Promise.resolve(value))).rejects.toMatchObject({
name: 'PluginToolError', code: 'PLUGIN_TOOL_INVALID_RESULT', message: String(thrown),
})
}
})
})
describe('sandbox isolation and Node-API traps', () => {
it('isolates sandbox globals: no process/Buffer, and globalThis writes do not leak to the host', async () => {
const harness = await setup()
@@ -41,6 +41,9 @@
{
"path": "../../llm/llm"
},
{
"path": "../../util/error"
},
{
"path": "../../typert/protocol"
}
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 3a2f21ff0dc3420d
/deepseek-ai-dsh-tool-cordis/use-this-package:
en: e8c90b0ad037513c
zh: 563454508c30d9b0
en: 5a6ab053010461c6
zh: 4d04f2ff1abb5ffd
/deepseek-ai-dsh-tool-cordis/understand-the-implementation:
en: ff959016d633c6c0
zh: d84dfa7e9d73532f
+1 -1
View File
@@ -25,7 +25,7 @@ Inspect Host and Client runtime APIs before writing plugin code. Creator mode pr
<a id="use-this-package"></a>
## Use this package
Creator mode includes this toolset. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tools; a preset row alone registers no Host providers. Call `cordis_inspect_list` to discover providers, then `cordis_inspect_query` for a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
Creator mode includes this toolset. Other compositions mount `@deepseek-ai/dsh-tool-cordis/host` once in the host composition beside the host runner that provides `cordisInspect`, and `@deepseek-ai/dsh-tool-cordis` in each agent preset that exposes the tools; a preset row alone registers no Host providers. Call `cordis_inspect_list` to discover providers, then `cordis_inspect_query` for a provider's exact methods and types. The Host `Config` provider lists live Loader entries in pages (`offset`, `limit` up to 100, optional exact plugin `name`; `total` and `nextOffset` bound the walk) with each entry's Loader id, the tree-local id patches address, and its Config status (`schema`, `absent`, `unsupported`, `tree` for group and include carriers, `inactive` for disabled, never imported, or disposed entries), and projects one entry's native Config into a self-contained JSON Schema document beside the entry's `packageDir`, the resolved directory holding the package README and built `lib/`, when the profile package lookup resolves it. A call without an Agent, or a `Config` query on a Host without a Loader, fails with `ToolContextUnavailableError`; a malformed `Config` paging field fails with `ToolArgsError`; and an unknown entry id fails with `InspectError` `INSPECT_TARGET_NOT_FOUND`. Use [Plugin Manager](../../boot/plugin-manager/README.md) to install bundles containing plugin code or MCP configuration.
-----
+1 -1
View File
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
创造模式包含这组工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这些工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect_list` 发现 provider,再用 `cordis_inspect_query` 查询其具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
创造模式包含这组工具。其他组合需要在宿主组合里、提供 `cordisInspect` 的 host runner 旁挂载一次 `@deepseek-ai/dsh-tool-cordis/host`,并在每个要暴露这些工具的 agent preset 里挂载 `@deepseek-ai/dsh-tool-cordis`;仅有 preset 行不会注册任何 Host provider。调用 `cordis_inspect_list` 发现 provider,再用 `cordis_inspect_query` 查询其具体方法和类型。Host 的 `Config` provider 分页列出运行中的 Loader entry(`offset`、最多 100 的 `limit`、可选的精确插件 `name`;`total` 与 `nextOffset` 界定遍历),每个 entry 带 Loader id、patch 所寻址的树内 id 及其 Config 状态(`schema`、`absent`、`unsupported`、group 与 include 载体为 `tree`、禁用、未导入或已销毁的 entry 为 `inactive`),并把单个 entry 的原生 Config 投影为自包含的 JSON Schema 文档,同时在 profile 包查找能解析时给出该 entry 的 `packageDir`,即包 README 与构建产物 `lib/` 所在目录。没有 Agent 的调用,或在没有 Loader 的 Host 上的 `Config` 查询,以 `ToolContextUnavailableError` 失败;`Config` 分页字段格式错误时以 `ToolArgsError` 失败;未知 entry id 以 `InspectError` `INSPECT_TARGET_NOT_FOUND` 失败。通过 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 安装包含插件代码或 MCP 配置的组合包。
-----
@@ -2489,12 +2489,14 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
description: 'Read current plugins, including why a row cannot be changed through the profile patch.',
parameters: [],
returns: 'Current runtime entries with persistent patch targets.',
throws: ['{PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when the profile patches cannot be read; Remote callers receive `gateway/internal`.'],
},
{
signature: '@Remote listBundles(): Promise<BundleInfo[]>',
description: 'Read installed, installation-provided, and offline Official catalog bundles, plus selected non-bundle names. A dependency without a bundle patch is listed, as a `not-bundle` problem, only while it is selected.',
parameters: [],
returns: 'Package versions, manifest descriptions, the installable spec of profile dependencies, rows, optional display metadata, activation selections, whether the installation offers the bundle, and removal availability.',
throws: ['{PluginManagerError} `PLUGIN_MANAGER_PROFILE_READ_FAILED` to in-process callers when a profile or installation manifest cannot be read; Remote callers receive `gateway/internal`.'],
},
{
signature: '@Remote async registries(): Promise<PluginRegistries>',
@@ -2692,7 +2694,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
{
key: 'ptcRuntime',
summary: 'Registers one `ctx.ptcRuntime` implementation.',
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
description: 'Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects, with PtcRuntimeError. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal.',
methods: [
{
signature: 'abstract readonly language: string',
@@ -2723,7 +2725,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
description: 'Resolve supported options and provider defaults before execution.',
parameters: [{ name: 'request', description: 'Program, bindings, cancellation and optional execution choices.' }],
returns: 'Complete directory, deadline and supported authority for run.',
throws: ['When an explicit choice is invalid or unsupported by this provider.'],
throws: ['When an explicit choice is invalid or unsupported by this provider; contract misuse throws {@link PtcRuntimeError}.'],
},
{
signature: 'abstract run(spec: PtcRunSpec): Promise<PtcRunResult>',
+12 -6
View File
@@ -5,6 +5,8 @@ import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
// Declares `Context.pluginPackages`, the profile package lookup that resolves an entry's package directory.
import { createConfigProjector, isNativeConfigSchema, LOADER_EXPRESSION_SCHEMA, type NativeConfigSchema } from '@deepseek-ai/dsh-app-boot'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { InspectError } from '@deepseek-ai/dsh-cordis-host-runner'
import { ToolArgsError, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
/**
* `schema`: the running plugin declares a native Schemastery Config. `absent`: it runs without one.
@@ -57,14 +59,14 @@ function parseQuery(input: JsonValue | undefined): ConfigQuery {
const text = (key: string): string | undefined => {
const value = fields[key]
if (value === undefined) return undefined
if (typeof value !== 'string' || value === '') throw new Error(`${key} must be a non-empty string`)
if (typeof value !== 'string' || value === '') throw new ToolArgsError([`${key} must be a non-empty string`])
return value
}
const offset = fields.offset ?? 0
const limit = fields.limit ?? DEFAULT_LIMIT
if (!Number.isInteger(offset) || typeof offset !== 'number' || offset < 0) throw new Error('offset must be a non-negative integer')
if (!Number.isInteger(offset) || typeof offset !== 'number' || offset < 0) throw new ToolArgsError(['offset must be a non-negative integer'])
if (!Number.isInteger(limit) || typeof limit !== 'number' || limit < 1 || limit > MAX_LIMIT) {
throw new Error(`limit must be an integer from 1 to ${MAX_LIMIT}`)
throw new ToolArgsError([`limit must be an integer from 1 to ${MAX_LIMIT}`])
}
return { entry: text('entry'), name: text('name'), offset, limit }
}
@@ -93,11 +95,15 @@ function toJson(value: object): JsonValue {
* @param ctx - Host context; its `loader`, when the profile was mounted by one, owns the entry tree.
* @param input - model-supplied query: `entry` (Loader entry id), or `name`, `offset` (default 0), and `limit` (1 to 100, default 25).
* @returns one directory page, or one entry's status and projected schema.
* @throws when no Loader mounted this Host, when a query field is malformed, or when the entry id matches no live entry.
* @throws {ToolContextUnavailableError} when no Loader mounted this Host.
* @throws {ToolArgsError} when a query field is malformed.
* @throws {InspectError} `INSPECT_TARGET_NOT_FOUND` when the entry id matches no live entry.
*/
export async function queryLiveConfig(ctx: Context, input: JsonValue | undefined): Promise<JsonValue> {
const loader = ctx.get('loader')
if (loader === undefined) throw new Error('Config inspection requires the Loader that mounted this profile; this Host was composed without one')
if (loader === undefined) {
throw new ToolContextUnavailableError('Config inspection requires the Loader that mounted this profile; this Host was composed without one')
}
const query = parseQuery(input)
const entries = [...loader.entries()].map(liveConfig)
if (query.entry === undefined) {
@@ -107,7 +113,7 @@ export async function queryLiveConfig(ctx: Context, input: JsonValue | undefined
return { entries: page, total: matching.length, nextOffset: end < matching.length ? end : null }
}
const entry = entries.find(candidate => candidate.id === query.entry)
if (entry === undefined) throw new Error(`unknown entry id ${JSON.stringify(query.entry)}`)
if (entry === undefined) throw new InspectError(`unknown entry id ${JSON.stringify(query.entry)}`, 'INSPECT_TARGET_NOT_FOUND')
const listed = { ...listing(entry), ...packageDir(ctx, loader.resolve(query.entry)) }
if (entry.native === undefined) return listed
const project = await createConfigProjector()
+2 -2
View File
@@ -2,7 +2,7 @@
import type { Context } from '@deepseek-ai/cordis'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { defineTool, ToolContextUnavailableError } from '@deepseek-ai/dsh-tools'
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
import { presentInspectListCall, presentInspectQueryCall } from './present.ts'
@@ -10,7 +10,7 @@ export const name = 'tool-cordis'
export const inject = ['tools', 'cordisInspect']
function requireAgent(exec: ToolExecution): Agent {
if (exec.agent === undefined) throw new Error('Cordis inspection requires an Agent-backed session')
if (exec.agent === undefined) throw new ToolContextUnavailableError('Cordis inspection requires an Agent-backed session')
return exec.agent
}
@@ -1,7 +1,7 @@
/** First-party Host inspect providers registered by the Cordis tool package. */
import type { Context } from '@deepseek-ai/cordis'
import type { HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner'
import { InspectError, type HostCordisInspectProviderRegistration } from '@deepseek-ai/dsh-cordis-host-runner'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { EVENT_API, queryEventApi, queryServiceApi } from './api-catalog.ts'
import { queryLiveConfig } from './config.ts'
@@ -74,7 +74,7 @@ export function hostInspectProviders(ctx: Context): HostCordisInspectProviderReg
}],
},
query(method, _input, context) {
if (method !== 'listTools') throw new Error(`unknown Tool inspect method "${method}"`)
if (method !== 'listTools') throw new InspectError(`unknown Tool inspect method "${method}"`, 'INSPECT_METHOD_NOT_FOUND')
return Promise.resolve({ tools: ctx.tools.schemas(context.agent) } as unknown as JsonValue)
},
},
@@ -101,7 +101,7 @@ function registration(
}],
},
async query(requested, input) {
if (requested !== method) throw new Error(`unknown ${id} inspect method "${requested}"`)
if (requested !== method) throw new InspectError(`unknown ${id} inspect method "${requested}"`, 'INSPECT_METHOD_NOT_FOUND')
return await query(input)
},
}
@@ -89,6 +89,9 @@ describe('the Config inspect provider', () => {
await expect(queryLiveConfig(ctx, { limit: 0 })).rejects.toThrow('limit must be an integer from 1 to 100')
await expect(queryLiveConfig(ctx, { offset: -1 })).rejects.toThrow('offset must be a non-negative integer')
await expect(queryLiveConfig(ctx, { name: '' })).rejects.toThrow('name must be a non-empty string')
for (const input of [{ limit: 0 }, { offset: -1 }, { name: '' }]) {
await expect(queryLiveConfig(ctx, input)).rejects.toMatchObject({ name: 'ToolArgsError', code: 'INVALID_ARGS' })
}
await ctx.fiber.dispose()
})
@@ -119,10 +122,14 @@ describe('the Config inspect provider', () => {
expect(await queryLiveConfig(ctx, { entry: ids.noConfig })).not.toHaveProperty('packageDir')
expect(await queryLiveConfig(ctx, { entry: ids.group })).toEqual({ id: ids.group, patchId: ids.group, name: 'cordis:group', status: 'tree' })
await expect(queryLiveConfig(ctx, { entry: 'missing' })).rejects.toThrow('unknown entry id "missing"')
await expect(queryLiveConfig(ctx, { entry: 'missing' })).rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_TARGET_NOT_FOUND' })
await ctx.fiber.dispose()
})
it('rejects a Host composed without a Loader', async () => {
await expect(queryLiveConfig(new Context(), undefined)).rejects.toThrow('requires the Loader')
await expect(queryLiveConfig(new Context(), undefined)).rejects.toMatchObject({
name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE',
})
})
})
@@ -6,6 +6,7 @@ import ToolRegistry from '@deepseek-ai/dsh-tools'
import { describe, expect, it } from 'vitest'
import * as CordisInspectProviders from '../src/host.ts'
import * as CordisInspectTools from '../src/index.ts'
import { hostInspectProviders } from '../src/providers.ts'
/**
* The Host inspect providers are one process-global set: the host entry
@@ -35,6 +36,22 @@ describe('the cordis-inspect-providers host entry', () => {
await fiber.dispose()
expect(ctx.cordisInspect.list()).toEqual([])
})
it('reports a missing Agent and an undeclared provider method with error codes', async () => {
const ctx = await host()
await ctx.plugin(CordisInspectProviders)
await ctx.plugin(CordisInspectTools)
const signal = new AbortController().signal
const query = ctx.tools.get('cordis_inspect_query')
await expect(query?.execute({ platform: 'host', provider: 'Tool', method: 'listTools' }, { signal } as never)).rejects.toMatchObject({
name: 'ToolContextUnavailableError', code: 'TOOL_CONTEXT_UNAVAILABLE', message: 'Cordis inspection requires an Agent-backed session',
})
for (const provider of hostInspectProviders(ctx).filter(candidate => ['Service', 'Tool'].includes(candidate.manifest.id))) {
await expect(Promise.resolve().then(() => provider.query('undeclared', undefined, { agent: undefined as never, signal })))
.rejects.toMatchObject({ name: 'InspectError', code: 'INSPECT_METHOD_NOT_FOUND' })
}
await ctx.fiber.dispose()
})
})
describe('the cordis inspect tools', () => {
+4 -4
View File
@@ -30,8 +30,8 @@
en: 213d2d67088beccc
zh: 1e3ff5454c937f11
/deepseek-ai-dsh-mcp-client/use-this-package/runtime-templates-and-credentials:
en: 255e8f48e5981b52
zh: 7b4ad77794c6b7fc
en: fd04dfbe231924e4
zh: ace0b0786bf16d0f
/deepseek-ai-dsh-mcp-client/understand-the-implementation:
en: d33ddd080880b3f5
zh: 64328f5239c26752
@@ -45,8 +45,8 @@
en: 1793a89464c70cec
zh: fcf7b9c2eb343ce3
/deepseek-ai-dsh-mcp-client/understand-the-implementation/tool-execution-internals:
en: bb161208cc002746
zh: 3ab0588ca71effe5
en: c0abd2f870cfeb65
zh: 15b7ba2564dace9a
/deepseek-ai-dsh-mcp-client/understand-the-implementation/environment-scrubbing-stdio:
en: fef482a6f8cc789f
zh: 08f4c594ec83b4a1
+2 -2
View File
@@ -102,7 +102,7 @@ With `expandTemplates: true`, `command`, `args`, `env` values, `cwd`, `url`, and
Credential notifications rebuild the connection only when the resolved values change; same-value notifications preserve the connection and its reconnect budget. The old connection must close and finish local cleanup before a replacement starts. Incomplete cleanup blocks replacement until the Host restarts.
With template expansion enabled, failure diagnostics, tool-call failures, and MCP `isError` tool-result text keep upstream messages but replace every value the instance resolved, including earlier rotations and URL-encoded forms, with `[redacted]`. Successful tool results retain their content.
With template expansion enabled, failure diagnostics, tool-call failures, and MCP `isError` tool-result text keep upstream messages but replace every value the instance resolved, including earlier rotations and URL-encoded forms, with `[redacted]`; the failure keeps its `name` and `code`. Successful tool results retain their content.
-----
@@ -154,7 +154,7 @@ With `expandTemplates` enabled, failure diagnostics name the operation and keep
### Tool execution internals
A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation, advertised output-schema validation, and modern request headers. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws before image persistence. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. For a server that does not advertise `resources`, resource and template lists return empty pages without calling the SDK, whose fallback writes a diagnostic to stdout, where the ACP profile carries JSON-RPC.
A tool call uses the SDK with the raw name, complete tool definition, JSON arguments, abort signal, and configured timeout. The SDK owns protocol validation and modern request headers. The bridge checks structured content against the advertised output schema itself, with the SDK's Node Ajv validator, because the SDK reports its own check as a `ProtocolError` that cannot be told apart from a server's JSON-RPC error. Canonical success is `{ content: JsonValue[], structuredContent? }`, preserving valid MCP JSON blocks for programmatic and PTC mode callers. An MCP `isError` result throws `McpToolError` with `MCP_TOOL_ERROR` before image persistence. Other tool and resource request failures throw `McpToolError`: after `MCP_CONNECTION_CLOSED` or `MCP_TIMEOUT` the request's outcome is unknown, `MCP_SERVER_UNAVAILABLE` means the request was not sent, `MCP_INVALID_RESULT` rejects a result that violates the MCP result schema or the advertised output schema, or an output schema that cannot be compiled, `MCP_UNSUPPORTED_TASK_EXECUTION` rejects the tool, and `MCP_REQUEST_FAILED` carries the JSON-RPC or SDK code in its message. Closure of the connection generation surfaces as `McpLocalError` with `MCP_CONNECTION_CLOSED`, and caller cancellation as the tool registry's `ABORTED`. `McpLocalError` codes also report local connection failures: `MCP_TIMEOUT`, `MCP_CREDENTIALS_UNAVAILABLE`, `MCP_CREDENTIAL_NOT_FOUND`, `MCP_INSTRUCTIONS_TOO_LARGE`, and `MCP_TOOL_REGISTRATION_FAILED`. The bridge validates each image batch before saving it; a refusal projects every image as diagnostic text. For a server that does not advertise `resources`, resource and template lists return empty pages without calling the SDK, whose fallback writes a diagnostic to stdout, where the ACP profile carries JSON-RPC.
### Environment scrubbing (stdio)
+2 -2
View File
@@ -102,7 +102,7 @@ kind: "package-reference"
凭据通知只有在解析值变化时才重建连接;值相同的通知保留连接及其重连预算。替代连接启动前,旧连接必须关闭并完成本地清理。清理未完成会阻止替换,直到宿主重启。
启用模板展开时,失败诊断、工具调用失败与 MCP `isError` 工具结果文本保留上游消息,但会把本实例解析过的每个值(包括此前轮换的值及其 URL 编码形式)替换为 `[redacted]`。成功工具结果保留原始内容。
启用模板展开时,失败诊断、工具调用失败与 MCP `isError` 工具结果文本保留上游消息,但会把本实例解析过的每个值(包括此前轮换的值及其 URL 编码形式)替换为 `[redacted]`,失败的 `name` 与 `code` 保持不变。成功工具结果保留原始内容。
-----
@@ -154,7 +154,7 @@ SDK 通过旧版通知或现代协议订阅接收工具列表变化。监督器
### 工具执行内部细节
工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验、已声明输出 schema 的校验和现代协议请求 header。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。对未声明 `resources` 能力的服务器,资源列表与模板列表直接返回空页而不调用 SDK,因为 SDK 的兜底逻辑会把诊断写到 stdout,而 ACP 配置档在 stdout 上传输 JSON-RPC。
工具调用向 SDK 提供原始名称、完整工具定义、JSON 参数、取消信号及配置的超时。SDK 负责协议校验和现代协议请求 header。结构化内容是否符合已声明的输出 schema 由桥接器自己用 SDK 在 Node 上的 Ajv 校验器检查,因为 SDK 把自己的检查结果报告为 `ProtocolError`,与服务端的 JSON-RPC 错误无法区分。成功结果规范值为 `{ content: JsonValue[], structuredContent? }`,为编程调用方及 PTC 模式保留有效的 MCP JSON 块。MCP `isError` 结果会在图片持久化前抛出带 `MCP_TOOL_ERROR` 的 `McpToolError`。其他工具与资源请求失败抛出 `McpToolError`:`MCP_CONNECTION_CLOSED` 或 `MCP_TIMEOUT` 之后请求结果未知,`MCP_SERVER_UNAVAILABLE` 表示请求未发送,`MCP_INVALID_RESULT` 拒绝违反 MCP 结果 schema 或已声明输出 schema 的结果,以及无法编译的输出 schema,`MCP_UNSUPPORTED_TASK_EXECUTION` 拒绝该工具,`MCP_REQUEST_FAILED` 在 message 中携带 JSON-RPC 或 SDK code。连接代关闭表现为带 `MCP_CONNECTION_CLOSED` 的 `McpLocalError`,调用方取消表现为工具注册表的 `ABORTED`。`McpLocalError` 的 code 也报告本地连接失败:`MCP_TIMEOUT`、`MCP_CREDENTIALS_UNAVAILABLE`、`MCP_CREDENTIAL_NOT_FOUND`、`MCP_INSTRUCTIONS_TOO_LARGE` 与 `MCP_TOOL_REGISTRATION_FAILED`。桥接器在保存前校验整批图片;拒绝时将每张图片投影为诊断文本。对未声明 `resources` 能力的服务器,资源列表与模板列表直接返回空页而不调用 SDK,因为 SDK 的兜底逻辑会把诊断写到 stdout,而 ACP 配置档在 stdout 上传输 JSON-RPC。
### 环境清洗(stdio)
+2
View File
@@ -39,6 +39,7 @@
"peerDependencies": {
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
@@ -58,6 +59,7 @@
"@deepseek-ai/dsh-attachment": "workspace:*",
"@deepseek-ai/dsh-attachment-local": "workspace:*",
"@deepseek-ai/dsh-llm": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-scope": "workspace:*",
"@deepseek-ai/dsh-subprocess": "workspace:*",
"@deepseek-ai/dsh-timeout": "workspace:*",
+5 -5
View File
@@ -21,7 +21,7 @@ import { assertNever, deepEqualJson, type JsonValue } from '@deepseek-ai/dsh-uti
import type { ServerContext } from './server-context.ts'
import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import { withDeadline } from './deadline.ts'
import { McpLocalError } from './diagnostic.ts'
import { McpLocalError, mcpRequestError, McpToolError } from './diagnostic.ts'
import type { McpStatusCell } from './status.ts'
import type { McpCloseResult } from './types.ts'
import { McpGeneration } from './generation.ts'
@@ -316,7 +316,7 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
const text = client.getInstructions()?.trimEnd() ?? ''
const instructions = text ? `### MCP server: ${config.serverName}\n\n${text}` : ''
const maxInstructionBytes = config.maxInstructionBytes ?? DEFAULT_MAX_INSTRUCTION_BYTES
if (Buffer.byteLength(instructions) > maxInstructionBytes) throw new McpLocalError(`${label}: server instructions exceed maxInstructionBytes (${maxInstructionBytes})`)
if (Buffer.byteLength(instructions) > maxInstructionBytes) throw new McpLocalError(`${label}: server instructions exceed maxInstructionBytes (${maxInstructionBytes})`, 'MCP_INSTRUCTIONS_TOO_LARGE')
const sync = enqueueSync(record)
const budget = remaining()
await (budget === undefined ? sync : withDeadline(sync, budget, `${label}: startup timed out`))
@@ -351,7 +351,7 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
resources: {
async request(request, exec): Promise<JsonValue> {
const record = current
if (record?.connectedAt === undefined) throw new Error(`${label}: server is disconnected`)
if (record?.connectedAt === undefined) throw new McpToolError(`${label}: server is disconnected`, 'MCP_SERVER_UNAVAILABLE')
try {
return await record.wire.run(async (signal) => {
const options = { signal: AbortSignal.any([signal, exec.signal]), timeout: config.toolCallTimeoutMs }
@@ -378,8 +378,8 @@ export function startConnection(ctx: Context, config: Config, policy: ResolvedRe
}
})
} catch (error) {
if (config.expandTemplates) throw new Error(diagnostic(error, request.method))
throw error
exec.signal.throwIfAborted()
throw mcpRequestError(error, request.method, config.expandTemplates ? text => binding.redact(text) : undefined)
}
},
},
+2 -2
View File
@@ -21,7 +21,7 @@ export class McpTemplateBinding {
if (config.expandTemplates) {
for (const value of strings) assertTemplateSyntax(value, `mcp-client(${config.serverName})`)
if (this.refs.size > 0 && ctx.get('credentials') === undefined) {
throw new McpLocalError('MCP credential templates require a credentials provider')
throw new McpLocalError('MCP credential templates require a credentials provider', 'MCP_CREDENTIALS_UNAVAILABLE')
}
}
}
@@ -60,7 +60,7 @@ export class McpTemplateBinding {
let value = values.get(ref)
if (value === undefined) {
const provider = this.ctx.get('credentials')
if (provider === undefined) throw new McpLocalError('MCP credential templates require a credentials provider')
if (provider === undefined) throw new McpLocalError('MCP credential templates require a credentials provider', 'MCP_CREDENTIALS_UNAVAILABLE')
value = provider.resolve(ref as CredentialRef).then((result) => {
if (result !== undefined && result.value !== '') this.secrets.add(result.value).add(encodeURIComponent(result.value))
return result?.value
+3 -3
View File
@@ -3,8 +3,8 @@
import { McpLocalError } from './diagnostic.ts'
/**
* Settle with `promise`, or reject with `timeoutMessage` once `remainingMs`
* elapses first. The timer never holds the process open, and a non-Error
* Settle with `promise`, or reject with an `MCP_TIMEOUT` {@link McpLocalError}
* carrying `timeoutMessage` once `remainingMs` elapses first. The timer never holds the process open, and a non-Error
* rejection is wrapped so callers always observe an Error.
* @param promise - operation the deadline bounds.
* @param remainingMs - remaining budget in milliseconds (clamped to at least 1).
@@ -14,7 +14,7 @@ import { McpLocalError } from './diagnostic.ts'
export function withDeadline<T>(promise: Promise<T>, remainingMs: number, timeoutMessage: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new McpLocalError(timeoutMessage))
reject(new McpLocalError(timeoutMessage, 'MCP_TIMEOUT'))
}, Math.max(1, remainingMs))
timer.unref()
promise.then(
+114 -2
View File
@@ -3,8 +3,120 @@
* secrets replace every known secret value before text leaves the instance.
*/
/** Local failure whose message contains no expanded configuration or upstream text. */
export class McpLocalError extends Error {}
import { ProtocolError, SdkError, SdkErrorCode } from '@modelcontextprotocol/client'
import { HarnessError } from '@deepseek-ai/dsh-error'
/**
* Every {@link McpLocalError} code:
* - `MCP_CONNECTION_CLOSED`: the connection generation closed; outcomes of requests in flight are unknown.
* - `MCP_TIMEOUT`: a startup, operation, or cleanup budget elapsed.
* - `MCP_CREDENTIALS_UNAVAILABLE`: credential templates are configured but no credentials provider is mounted.
* - `MCP_CREDENTIAL_NOT_FOUND`: a referenced credential has no configured value.
* - `MCP_INSTRUCTIONS_TOO_LARGE`: server instructions exceed `maxInstructionBytes`.
* - `MCP_TOOL_REGISTRATION_FAILED`: a foreign registration occupies the server's tool namespace.
*/
export const MCP_LOCAL_ERROR_CODES = [
'MCP_CONNECTION_CLOSED',
'MCP_TIMEOUT',
'MCP_CREDENTIALS_UNAVAILABLE',
'MCP_CREDENTIAL_NOT_FOUND',
'MCP_INSTRUCTIONS_TOO_LARGE',
'MCP_TOOL_REGISTRATION_FAILED',
] as const
/** One {@link McpLocalError} code. */
export type McpLocalErrorCode = typeof MCP_LOCAL_ERROR_CODES[number]
/**
* Local failure whose message contains no expanded configuration or upstream
* text; `code` is one of {@link MCP_LOCAL_ERROR_CODES}.
*/
export class McpLocalError extends HarnessError {
override readonly code: McpLocalErrorCode
constructor(message: string, code: McpLocalErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'McpLocalError'
this.code = code
}
}
/**
* Every {@link McpToolError} code:
* - `MCP_TOOL_ERROR`: the server answered the tool call with an `isError` result; the model may adjust its input.
* - `MCP_UNSUPPORTED_TASK_EXECUTION`: the tool requires task-based execution, which the bridge does not support.
* - `MCP_INVALID_RESULT`: the server's result violates the MCP result schema or the tool's advertised output
* schema, or that output schema cannot be compiled.
* - `MCP_CONNECTION_CLOSED`: the connection closed while the request was in flight; its outcome is unknown.
* - `MCP_TIMEOUT`: the request exceeded its deadline; its outcome is unknown.
* - `MCP_SERVER_UNAVAILABLE`: the server was not connected, so the request was not sent.
* - `MCP_REQUEST_FAILED`: any other protocol or SDK failure; `message` carries the JSON-RPC or SDK code.
*/
export const MCP_TOOL_ERROR_CODES = [
'MCP_TOOL_ERROR',
'MCP_UNSUPPORTED_TASK_EXECUTION',
'MCP_INVALID_RESULT',
'MCP_CONNECTION_CLOSED',
'MCP_TIMEOUT',
'MCP_SERVER_UNAVAILABLE',
'MCP_REQUEST_FAILED',
] as const
/** One {@link McpToolError} code. */
export type McpToolErrorCode = typeof MCP_TOOL_ERROR_CODES[number]
/**
* Failure of one MCP tool or resource request; `code` is one of
* {@link MCP_TOOL_ERROR_CODES}. `message` may contain upstream text, redacted
* when the instance resolves credential templates.
*/
export class McpToolError extends HarnessError {
override readonly code: McpToolErrorCode
constructor(message: string, code: McpToolErrorCode, options?: ErrorOptions) {
super(message, code, options)
this.name = 'McpToolError'
this.code = code
}
}
/** Codes for SDK-local failures whose consumer action differs from a generic request failure. */
const SDK_ERROR_CODES: Partial<Record<SdkErrorCode, McpToolErrorCode>> = {
[SdkErrorCode.ConnectionClosed]: 'MCP_CONNECTION_CLOSED',
[SdkErrorCode.RequestTimeout]: 'MCP_TIMEOUT',
[SdkErrorCode.NotConnected]: 'MCP_SERVER_UNAVAILABLE',
[SdkErrorCode.InvalidResult]: 'MCP_INVALID_RESULT',
}
/**
* Classify one failed MCP request. An {@link McpLocalError}, such as the
* generation's closure reason, keeps its identity; any other failure becomes
* an {@link McpToolError} whose `message` carries the JSON-RPC or SDK code.
* Without `redact` the original failure is the `cause`; with `redact` no
* `cause` is attached, because the original text may contain secret values.
* @param error - the request's rejection.
* @param operation - names the request, such as `tool "echo"` or `resources/read`.
* @param redact - removes secret values from the message when templates are enabled.
* @returns the classified failure to throw.
*/
export function mcpRequestError(
error: unknown,
operation: string,
redact?: (text: string) => string,
): HarnessError {
if (error instanceof McpLocalError) return error
let code: McpToolErrorCode = 'MCP_REQUEST_FAILED'
let detail = describeError(error)
if (ProtocolError.isInstance(error)) detail = `JSON-RPC error ${error.code}: ${error.message}`
else if (SdkError.isInstance(error)) {
code = SDK_ERROR_CODES[error.code] ?? code
detail = `${error.code}: ${error.message}`
}
const message = `MCP ${operation} failed: ${detail}`
return redact === undefined
? new McpToolError(message, code, { cause: error })
: new McpToolError(redact(message), code)
}
/** Placeholder written in place of a known secret value. */
const REDACTED = '[redacted]'
+2 -2
View File
@@ -57,7 +57,7 @@ export class McpGeneration {
/** Reject when this generation was cancelled or its transport reported closure. */
assertOpen(): void {
this.lifetime.signal.throwIfAborted()
if (this.closeObserved) throw new McpLocalError('MCP transport closed')
if (this.closeObserved) throw new McpLocalError('MCP transport closed', 'MCP_CONNECTION_CLOSED')
}
/**
@@ -92,7 +92,7 @@ export class McpGeneration {
}
private async finish(): Promise<McpCloseResult> {
this.lifetime.abort(new McpLocalError('MCP connection closed'))
this.lifetime.abort(new McpLocalError('MCP connection closed', 'MCP_CONNECTION_CLOSED'))
let cleanupError: string | undefined
const work = async (): Promise<void> => {
try {
+2
View File
@@ -28,6 +28,8 @@ import type { McpConnectionStatusHandle } from './status.ts'
import type {} from '@deepseek-ai/dsh-tools'
export { createMcpToolDefinition } from './tools.ts'
export { McpLocalError, McpToolError } from './diagnostic.ts'
export type { McpLocalErrorCode, McpToolErrorCode } from './diagnostic.ts'
export type { McpResult, McpToolDefinitionOptions } from './tools.ts'
export type { ReconnectConfig, ResolvedReconnectPolicy } from './connection.ts'
export type { McpConnectionStatusHandle } from './status.ts'
+6 -2
View File
@@ -8,8 +8,12 @@
import { McpLocalError } from './diagnostic.ts'
/** A referenced credential has no configured value. */
export class MissingTemplateValue extends McpLocalError {}
/** A referenced credential has no configured value (`MCP_CREDENTIAL_NOT_FOUND`). */
export class MissingTemplateValue extends McpLocalError {
constructor(message: string) {
super(message, 'MCP_CREDENTIAL_NOT_FOUND')
}
}
const TOKEN = /\$\{credential:([A-Za-z_][A-Za-z0-9_]*)\}/g
+85 -14
View File
@@ -14,7 +14,8 @@
import { createHash } from 'node:crypto'
import { isDeepStrictEqual } from 'node:util'
import { specTypeSchemas, type Client, type ImageContent } from '@modelcontextprotocol/client'
import { specTypeSchemas, type Client, type ImageContent, type JsonSchemaType, type Tool } from '@modelcontextprotocol/client'
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/client/validators/ajv'
import type { Context } from '@deepseek-ai/cordis'
import { isImageAdmissionError } from '@deepseek-ai/dsh-attachment'
import type { AttachmentStore, ImageAttachmentRef, ImageMediaType, SaveImageAttachment } from '@deepseek-ai/dsh-attachment'
@@ -23,7 +24,7 @@ import type { ToolDefinition, ToolExecution, ToolExecutionResult } from '@deepse
import { assertSupportedJsonSchema } from '@deepseek-ai/dsh-tools'
import type { JsonSchemaNode } from '@deepseek-ai/dsh-tools'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import { describeError, McpLocalError } from './diagnostic.ts'
import { describeError, McpLocalError, mcpRequestError, McpToolError } from './diagnostic.ts'
/** Resolved options relevant to tool bridging. */
export interface ToolBridgeOptions {
@@ -32,15 +33,23 @@ export interface ToolBridgeOptions {
/** Generation cancellation combined with each tool execution's signal. */
signal: AbortSignal
/**
* Remove secret values from tool-call failures before they reach callers.
* Remove secret values from tool-call failures before they reach callers;
* a failure keeps its `name` and `code`.
* @param text - transport or protocol failure text, or MCP `isError` result text.
* @returns the text with secret values replaced.
*/
redact?: (text: string) => string
}
/** Registration failed after the prior generation was removed and partial registrations were rolled back. */
export class McpToolRegistrationError extends McpLocalError {}
/**
* Registration failed after the prior generation was removed and partial
* registrations were rolled back (`MCP_TOOL_REGISTRATION_FAILED`).
*/
export class McpToolRegistrationError extends McpLocalError {
constructor(message: string, options?: ErrorOptions) {
super(message, 'MCP_TOOL_REGISTRATION_FAILED', options)
}
}
/** State for one sync generation: the current set of disposers keyed by public name. */
export type ToolDisposers = Map<string, () => void>
@@ -135,6 +144,7 @@ export async function syncTools(
const response = client.getServerCapabilities()?.tools === undefined
? { tools: [] }
: await client.listTools(undefined, { cacheMode: 'refresh', signal: opts.signal })
const outputValidators = new AjvJsonSchemaValidator()
for (const tool of response.tools) {
const publicName = publicToolName(opts.serverName, tool.name)
if (definitions.has(publicName)) {
@@ -142,6 +152,14 @@ export async function syncTools(
`mcp-client(${opts.serverName}): server listed tool "${tool.name}" more than once — invalid tool list`,
)
}
// The bridge checks structured output itself: the SDK reports its local check as a
// ProtocolError indistinguishable from a server's JSON-RPC error.
const { outputSchema: _outputSchema, ...callDefinition } = tool
const outputCheck = compileOutputCheck(outputValidators, tool)
const invalidResult = (reason: string): McpToolError => {
const message = `Tool "${tool.name}" returned an invalid MCP result: ${reason}`
return new McpToolError(opts.redact === undefined ? message : opts.redact(message), 'MCP_INVALID_RESULT')
}
definitions.set(publicName, createMcpToolDefinition(ctx, {
name: publicName,
rawName: tool.name,
@@ -150,18 +168,34 @@ export async function syncTools(
outputSchema: tool.outputSchema,
taskRequired: tool.execution?.taskSupport === 'required',
call: async (args, execution) => {
// The generation closed and its tools await re-sync; the SDK would refuse the request unsent.
if (opts.signal.aborted) {
throw new McpToolError(`mcp-client(${opts.serverName}): server is disconnected`, 'MCP_SERVER_UNAVAILABLE')
}
if (outputCheck !== undefined && 'compileError' in outputCheck) {
throw invalidResult(`its output schema cannot be compiled: ${outputCheck.compileError}`)
}
let result: Awaited<ReturnType<Client['callTool']>>
try {
const result = await client.callTool(
result = await client.callTool(
{ name: tool.name, arguments: args },
{ signal: AbortSignal.any([execution.signal, opts.signal]),
timeout: opts.toolCallTimeoutMs, toolDefinition: tool },
timeout: opts.toolCallTimeoutMs, toolDefinition: callDefinition },
)
if (result.isError !== true || opts.redact === undefined) return result
return { isError: true, content: [{ type: 'text', text: opts.redact(extractText(result.content as JsonValue[], tool.name)) }] }
} catch (error) {
if (opts.redact === undefined) throw error
throw new Error(opts.redact(describeError(error)))
// The SDK reports an aborted signal as a request timeout; cancellation
// and generation closure are reported as their own reasons instead.
execution.signal.throwIfAborted()
opts.signal.throwIfAborted()
throw mcpRequestError(error, `tool "${tool.name}"`, opts.redact)
}
if (result.isError !== true) {
const failure = outputCheck === undefined ? undefined : outputCheck.check(result.structuredContent)
if (failure !== undefined) throw invalidResult(failure)
return result
}
if (opts.redact === undefined) return result
return { isError: true, content: [{ type: 'text', text: opts.redact(extractText(result.content as JsonValue[], tool.name)) }] }
},
}))
}
@@ -187,6 +221,43 @@ export async function syncTools(
return disposers
}
/** A tool's compiled structured-output check, or why its advertised output schema cannot be compiled. */
type OutputCheck = { compileError: string } | {
/**
* @param structured - `structuredContent` of a successful result.
* @returns why the value violates the advertised output schema, or undefined when it conforms.
*/
check(structured: unknown): string | undefined
}
/**
* Compile one tool's advertised output schema with the validator the SDK uses on Node.
* @param validators - validator provider shared by one listing.
* @param tool - listed tool; a tool without `outputSchema` needs no check.
* @returns the check, a compile failure, or undefined without an output schema.
*/
function compileOutputCheck(validators: AjvJsonSchemaValidator, tool: Tool): OutputCheck | undefined {
if (tool.outputSchema === undefined) return undefined
let validate: ReturnType<AjvJsonSchemaValidator['getValidator']>
try {
// The listed schema is the wire object the SDK passes to the same provider; only its optional `$schema` typing differs.
validate = validators.getValidator(tool.outputSchema as JsonSchemaType)
} catch (error) {
return { compileError: describeError(error) }
}
return {
check(structured) {
if (structured === undefined) return 'the tool has an output schema but returned no structured content'
try {
const result = validate(structured)
return result.valid ? undefined : `structured content does not match the output schema: ${result.errorMessage}`
} catch (error) {
return `structured content could not be validated: ${describeError(error)}`
}
},
}
}
/** Fields read from canonical content, including policy-owned value replacements. */
interface McpContentBlock {
type: string
@@ -303,7 +374,7 @@ function createExecutor(
const { rawName, taskRequired } = options
return async (args: unknown, exec: ToolExecution) => {
if (taskRequired) {
throw new Error(`Tool "${rawName}" requires task-based execution, which this bridge does not support`)
throw new McpToolError(`Tool "${rawName}" requires task-based execution, which this bridge does not support`, 'MCP_UNSUPPORTED_TASK_EXECUTION')
}
// The agent loop passes `JSON.parse(model_arguments)` which is usually an
// object, but can be any JSON value if the model misbehaves (outputs a bare
@@ -312,7 +383,7 @@ function createExecutor(
const argsObj = (typeof args === 'object' && args !== null ? args : {}) as Record<string, unknown>
const parsed = specTypeSchemas.CallToolResult['~standard'].validate(await options.call(argsObj, exec))
if (parsed.issues !== undefined) {
throw new Error(`Tool "${rawName}" returned an invalid MCP result: ${parsed.issues.map(issue => issue.message).join('; ')}`)
throw new McpToolError(`Tool "${rawName}" returned an invalid MCP result: ${parsed.issues.map(issue => issue.message).join('; ')}`, 'MCP_INVALID_RESULT')
}
const result = parsed.value
@@ -321,7 +392,7 @@ function createExecutor(
// MCP isError → throw so ToolRuntime produces an isError result for the model.
if (result.isError === true) {
throw new Error(text)
throw new McpToolError(text, 'MCP_TOOL_ERROR')
}
const value: McpResult = {
@@ -492,6 +492,7 @@ describe('server instruction limits', () => {
assert(failure instanceof Error)
assert(failure.cause instanceof Error)
expect(failure.cause.message).toContain('server instructions exceed maxInstructionBytes')
expect(failure.cause).toMatchObject({ name: 'McpLocalError', code: 'MCP_INSTRUCTIONS_TOO_LARGE' })
expect(ctx.tools.schemas()).toEqual([])
} finally {
spy.mockRestore()
@@ -36,6 +36,9 @@ describe('McpTemplateBinding', () => {
it('requires a provider when binding credential templates', async () => {
await providerFiber.dispose()
expect(() => new McpTemplateBinding(ctx, httpConfig())).toThrow('require a credentials provider')
expect(() => new McpTemplateBinding(ctx, httpConfig())).toThrow(expect.objectContaining({
name: 'McpLocalError', code: 'MCP_CREDENTIALS_UNAVAILABLE',
}))
})
it('resolves repeated references once per pass while keeping configuration unexpanded', async () => {
@@ -57,7 +60,9 @@ describe('McpTemplateBinding', () => {
it('reports a provider unloaded after binding creation at the next resolution', async () => {
const binding = new McpTemplateBinding(ctx, httpConfig())
await providerFiber.dispose()
await expect(binding.resolve(new AbortController().signal)).rejects.toThrow('require a credentials provider')
const failure = binding.resolve(new AbortController().signal)
await expect(failure).rejects.toThrow('require a credentials provider')
await expect(failure).rejects.toMatchObject({ name: 'McpLocalError', code: 'MCP_CREDENTIALS_UNAVAILABLE' })
})
it('redacts every resolved value, including rotated and URL-encoded forms', async () => {
@@ -2,7 +2,9 @@
// verbatim, and hostile shapes (cycles, empty messages, bare values) cannot
// break the status text they feed.
import { describe, expect, it } from 'vitest'
import { describeError, redactSecrets } from '@deepseek-ai/dsh-mcp-client/src/diagnostic.ts'
import { describeError, McpLocalError, mcpRequestError, redactSecrets } from '@deepseek-ai/dsh-mcp-client/src/diagnostic.ts'
import { withDeadline } from '@deepseek-ai/dsh-mcp-client/src/deadline.ts'
import { MissingTemplateValue, resolveTemplateString } from '@deepseek-ai/dsh-mcp-client/src/templates.ts'
describe('describeError', () => {
it('keeps a plain error as its own string', () => {
@@ -55,6 +57,35 @@ describe('describeError', () => {
})
})
describe('local failure codes', () => {
it('rejects an elapsed deadline as MCP_TIMEOUT', async () => {
await expect(withDeadline(new Promise(() => {}), 1, 'MCP operation timed out')).rejects.toMatchObject({
name: 'McpLocalError', code: 'MCP_TIMEOUT', message: 'MCP operation timed out',
})
})
it('reports an unconfigured credential as MCP_CREDENTIAL_NOT_FOUND', async () => {
const failure = resolveTemplateString('${credential:MISSING}', 'env.TOKEN', async () => undefined)
await expect(failure).rejects.toBeInstanceOf(MissingTemplateValue)
await expect(failure).rejects.toMatchObject({ name: 'McpLocalError', code: 'MCP_CREDENTIAL_NOT_FOUND' })
})
it('keeps a local failure unchanged when classifying a request failure', () => {
const closed = new McpLocalError('MCP connection closed', 'MCP_CONNECTION_CLOSED')
expect(mcpRequestError(closed, 'resources/read', () => 'replaced')).toBe(closed)
})
it('keeps the original failure as cause only when no redaction applies', () => {
const failure = new Error('rejected secret-value')
expect(mcpRequestError(failure, 'resources/read')).toMatchObject({
message: 'MCP resources/read failed: Error: rejected secret-value', cause: failure,
})
const redacted = mcpRequestError(failure, 'resources/read', text => text.replace('secret-value', '[redacted]'))
expect(redacted.message).toBe('MCP resources/read failed: Error: rejected [redacted]')
expect(redacted.cause).toBeUndefined()
})
})
describe('redactSecrets', () => {
it('replaces every occurrence, longest secret first', () => {
expect(redactSecrets('token token-long token', ['token', 'token-long'])).toBe('[redacted] [redacted] [redacted]')
@@ -117,7 +117,7 @@ it('reports confirmed transport closure when local work outlives cleanup', async
await observedClose.promise
await vi.advanceTimersByTimeAsync(101)
expect(await closing).toEqual({
closeConfirmed: true, cleanupError: 'Error: MCP cleanup did not settle',
closeConfirmed: true, cleanupError: 'McpLocalError: MCP cleanup did not settle',
})
})
@@ -142,5 +142,5 @@ it.each([false, true])('distinguishes local work from unfinished negotiation (tr
await entered.promise
const closing = generation.close()
await vi.advanceTimersByTimeAsync(101)
expect(await closing).toEqual({ closeConfirmed: !created, cleanupError: 'Error: MCP cleanup did not settle' })
expect(await closing).toEqual({ closeConfirmed: !created, cleanupError: 'McpLocalError: MCP cleanup did not settle' })
})
@@ -175,6 +175,7 @@ describe('fixture server — controlled scenarios', () => {
})
expect(result.isError).toBe(true)
expect(result.content[0]).toMatchObject({ type: 'text' })
expect(result.error?.info).toEqual({ name: 'McpToolError', code: 'MCP_TOOL_ERROR' })
})
it('executes image() → ordered durable image content', async () => {
@@ -15,6 +15,7 @@ import ToolRuntime from '@deepseek-ai/dsh-tools'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { PostToolDecision } from '@deepseek-ai/dsh-tools'
import { McpToolRegistrationError, publicToolName, syncTools, type ToolBridgeOptions } from '@deepseek-ai/dsh-mcp-client/src/tools.ts'
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/client/validators/ajv'
import { createTransport } from '@deepseek-ai/dsh-mcp-client/src/transport.ts'
import { Config } from '@deepseek-ai/dsh-mcp-client'
@@ -266,7 +267,9 @@ describe('syncTools', () => {
{ name: 'taken', inputSchema: { type: 'object' } },
])
await expect(syncTools(client as never, ctx, defaultOpts, new Map())).rejects.toBeInstanceOf(McpToolRegistrationError)
const failure = syncTools(client as never, ctx, defaultOpts, new Map())
await expect(failure).rejects.toBeInstanceOf(McpToolRegistrationError)
await expect(failure).rejects.toMatchObject({ name: 'McpLocalError', code: 'MCP_TOOL_REGISTRATION_FAILED' })
// All-or-nothing: the non-conflicting tool is rolled back too.
expect(ctx.tools.get('mcp__srv__free')).toBeUndefined()
@@ -854,9 +857,47 @@ describe('tool execution', () => {
)
await syncTools(invalid as never, invalidCtx, defaultOpts, new Map())
const failure = await executeToolFixture(invalidCtx, { signal: testToolSignal, callId: brandString<ToolCallId>('invalid'), name: 'mcp__srv__structured', arguments: {} })
expect(failure.error).toMatchObject({ info: { code: 'INVALID_TOOL_OUTPUT' } })
expect(failure.content[0]?.type === 'text' ? failure.content[0].text : '')
.toContain('value.structuredContent.answer')
expect(failure.error).toEqual({
message: 'Tool "structured" returned an invalid MCP result: structured content does not match the output schema: data/answer must be integer',
info: { name: 'McpToolError', code: 'MCP_INVALID_RESULT' },
})
// The SDK's own output check is disabled: it would report the failure as a server JSON-RPC error.
expect(invalid.callTool.mock.calls[0]?.[1]).toMatchObject({ toolDefinition: { name: 'structured' } })
expect(invalid.callTool.mock.calls[0]?.[1]).not.toHaveProperty('toolDefinition.outputSchema')
})
it.each([
['omits structuredContent', { name: 'structured', inputSchema: { type: 'object' }, outputSchema: { type: 'object' } },
'the tool has an output schema but returned no structured content', 1],
['advertises an output schema that cannot be compiled', { name: 'structured', inputSchema: { type: 'object' }, outputSchema: { type: 'string', pattern: '(' } },
'its output schema cannot be compiled: SyntaxError: Invalid regular expression: /(/u: Unterminated group', 0],
] as const)('reports a tool that %s as MCP_INVALID_RESULT, redacting the message', async (_label, tool, reason, calls) => {
const client = createMockClient([tool], { content: [{ type: 'text', text: 'no structure' }] })
await syncTools(client as never, ctx, { ...defaultOpts, redact: text => text.replace('structured', '[redacted]') }, new Map())
const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: brandString<ToolCallId>('invalid'), name: 'mcp__srv__structured', arguments: {} })
expect(result.error).toEqual({
message: `Tool "[redacted]" returned an invalid MCP result: ${reason}`,
info: { name: 'McpToolError', code: 'MCP_INVALID_RESULT' },
})
expect(client.callTool).toHaveBeenCalledTimes(calls)
})
it('reports a validator that throws as MCP_INVALID_RESULT', async () => {
const getValidator = vi.spyOn(AjvJsonSchemaValidator.prototype, 'getValidator').mockReturnValue(() => { throw new Error('engine failed') })
try {
const client = createMockClient(
[{ name: 'structured', inputSchema: { type: 'object' }, outputSchema: { type: 'object' } }],
{ content: [], structuredContent: {} },
)
await syncTools(client as never, ctx, defaultOpts, new Map())
const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: brandString<ToolCallId>('throws'), name: 'mcp__srv__structured', arguments: {} })
expect(result.error).toEqual({
message: 'Tool "structured" returned an invalid MCP result: structured content could not be validated: Error: engine failed',
info: { name: 'McpToolError', code: 'MCP_INVALID_RESULT' },
})
} finally {
getValidator.mockRestore()
}
})
it('falls back to JsonValue for unsupported advertised output schemas', async () => {
@@ -866,12 +907,12 @@ describe('tool execution', () => {
inputSchema: { type: 'object' },
outputSchema: { type: 'object', patternProperties: { '^x-': { type: 'string' } } },
}],
{ content: [], structuredContent: ['kept', { nested: true }] },
{ content: [], structuredContent: { 'x-kept': 'kept', nested: { deep: true } } },
)
await syncTools(client as never, ctx, defaultOpts, new Map())
const result = await executeToolFixture(ctx, { signal: testToolSignal, callId: brandString<ToolCallId>('fallback'), name: 'mcp__srv__future-schema', arguments: {} })
if (result.isError) throw new Error('unsupported MCP output schemas must fall back')
expect(result.value).toEqual({ content: [], structuredContent: ['kept', { nested: true }] })
expect(result.value).toEqual({ content: [], structuredContent: { 'x-kept': 'kept', nested: { deep: true } } })
})
it('maps isError to an error result via throw', async () => {
@@ -48,6 +48,27 @@ async function connect(server: McpServer, options?: { resources: true }): Promis
}
describe('modern MCP connections', () => {
it('reports structured output that violates the advertised schema as MCP_INVALID_RESULT', async () => {
// Raw handlers: McpServer validates its own output and would answer with an isError result instead.
const server = new McpServer({ name: 'structured', version: '1' }, { capabilities: { tools: {} } })
server.server.setRequestHandler('tools/list', () => ({ tools: [{
name: 'measure', inputSchema: { type: 'object' },
outputSchema: { type: 'object', properties: { size: { type: 'number' } }, required: ['size'] },
}] }))
server.server.setRequestHandler('tools/call', () => ({
content: [{ type: 'text', text: 'large' }],
structuredContent: { size: 'large' },
}))
const ctx = await connect(server)
const result = await executeToolFixture(ctx, {
name: 'mcp__fixture__measure', arguments: {}, callId: brandString<ToolCallId>('measure'), signal: new AbortController().signal,
})
expect(result.error).toEqual({
message: 'Tool "measure" returned an invalid MCP result: structured content does not match the output schema: data/size must be number',
info: { name: 'McpToolError', code: 'MCP_INVALID_RESULT' },
})
})
it('keeps a resource-only server connected without requesting tools', async () => {
const server = new McpServer({ name: 'resources', version: '1' })
server.registerResource('memo', 'memo://readme', {}, async () => ({
@@ -8,7 +8,7 @@ import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
import { describe, expect, it, vi, beforeEach, onTestFinished } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import type { Transport } from '@modelcontextprotocol/client'
import { ProtocolError, SdkError, SdkErrorCode, type Transport } from '@modelcontextprotocol/client'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRuntime from '@deepseek-ai/dsh-tools'
import McpResources from '@deepseek-ai/dsh-mcp-resources'
@@ -233,6 +233,7 @@ describe('reconnect supervisor', () => {
if (!result.isError) throw new Error('expected transport failure')
expect(result.error.message).toContain('transport rejected [redacted]')
expect(result.error.message).not.toContain('private-token')
expect(result.error.info).toEqual({ name: 'McpToolError', code: 'MCP_REQUEST_FAILED' })
}
} finally {
await handle.dispose()
@@ -252,6 +253,73 @@ describe('reconnect supervisor', () => {
expect(result.isError).toBe(true)
if (!result.isError) throw new Error('expected MCP failure')
expect(result.error.message).toBe(expandTemplates ? 'upstream rejected Bearer [redacted]' : message)
expect(result.error.info).toEqual({ name: 'McpToolError', code: 'MCP_TOOL_ERROR' })
} finally {
await handle.dispose()
}
})
it.each([
[new ProtocolError(-32602, 'unknown window'), 'JSON-RPC error -32602: unknown window', 'MCP_REQUEST_FAILED'],
[new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'), 'CONNECTION_CLOSED: Connection closed', 'MCP_CONNECTION_CLOSED'],
[new SdkError(SdkErrorCode.RequestTimeout, 'Request timed out'), 'REQUEST_TIMEOUT: Request timed out', 'MCP_TIMEOUT'],
[new SdkError(SdkErrorCode.NotConnected, 'Not connected'), 'NOT_CONNECTED: Not connected', 'MCP_SERVER_UNAVAILABLE'],
[new SdkError(SdkErrorCode.InvalidResult, 'bad result'), 'INVALID_RESULT: bad result', 'MCP_INVALID_RESULT'],
[new SdkError(SdkErrorCode.SendFailed, 'write failed'), 'SEND_FAILED: write failed', 'MCP_REQUEST_FAILED'],
[new TypeError('fetch failed'), 'TypeError: fetch failed', 'MCP_REQUEST_FAILED'],
] as const)('classifies a rejected tool call (%s), keeping the code when redacting', async (failure, detail, code) => {
await ctx.plugin(TestCredentials)
;(ctx.credentials as TestCredentials).values.set('MCP_TOKEN', 'test-secret')
for (const expandTemplates of [false, true]) {
const config = { ...stdioConfig({ enabled: false }), env: { TOKEN: '${credential:MCP_TOKEN}' }, expandTemplates }
const handle = startConnection(ctx, config, resolveReconnectPolicy(config.reconnect, 'test'), new McpStatusCell(() => {}))
try {
await handle.ready
mockCallTool.mockRejectedValue(failure)
const result = await executeToolFixture(ctx, { name: 'mcp__srv__remote', arguments: {}, callId: nextCallId(), signal: testToolSignal })
expect(result.error).toEqual({
message: `MCP tool "remote" failed: ${detail}`,
info: { name: 'McpToolError', code },
})
} finally {
await handle.dispose()
}
}
})
it('reports generation closure and caller cancellation during a tool call as their own failures', async () => {
const handle = startConnection(ctx, stdioConfig({ enabled: false }), resolveReconnectPolicy({ enabled: false }, 'test'), new McpStatusCell(() => {}))
try {
await handle.ready
const started: PromiseWithResolvers<void> = Promise.withResolvers()
// The SDK rejects an aborted request as a timeout carrying the abort reason's text.
mockCallTool.mockImplementation((_params, options) => new Promise((_resolve, reject) => {
const { signal } = options as { signal: AbortSignal }
signal.addEventListener('abort', () => { reject(new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason))) })
started.resolve()
}))
const caller = new AbortController()
const cancelled = executeToolFixture(ctx, { name: 'mcp__srv__remote', arguments: {}, callId: nextCallId(), signal: caller.signal })
await started.promise
caller.abort()
expect((await cancelled).error?.info).toEqual({ name: 'AbortError', code: 'ABORTED' })
const closed = executeToolFixture(ctx, { name: 'mcp__srv__remote', arguments: {}, callId: nextCallId(), signal: testToolSignal })
await vi.waitFor(() => { expect(mockCallTool).toHaveBeenCalledTimes(2) })
instances[0]!.transport?.onclose?.()
expect((await closed).error).toEqual({
message: 'MCP connection closed',
info: { name: 'McpLocalError', code: 'MCP_CONNECTION_CLOSED' },
})
// The closed generation's tools stay registered until re-sync; a new call is refused unsent.
const calls = mockCallTool.mock.calls.length
const unsent = await executeToolFixture(ctx, { name: 'mcp__srv__remote', arguments: {}, callId: nextCallId(), signal: testToolSignal })
expect(unsent.error).toEqual({
message: 'mcp-client(srv): server is disconnected',
info: { name: 'McpToolError', code: 'MCP_SERVER_UNAVAILABLE' },
})
expect(mockCallTool).toHaveBeenCalledTimes(calls)
} finally {
await handle.dispose()
}
@@ -321,6 +389,7 @@ describe('reconnect supervisor', () => {
})
expect(result.isError).toBe(true)
expect(JSON.stringify(result.content)).toContain('server is disconnected')
expect(result.error?.info).toEqual({ name: 'McpToolError', code: 'MCP_SERVER_UNAVAILABLE' })
} finally {
reconnectGate.resolve()
await handle.dispose()
+4 -4
View File
@@ -315,7 +315,7 @@ describe('connection status surface', () => {
expect(connectionStatusOf(fiber)).toBe(handle)
expect(handle.closure()).toEqual({
closeConfirmed: mode === 'cleanup-error',
cleanupError: mode === 'cleanup-error' ? 'Error: transport cleanup failed' : 'Error: MCP cleanup did not settle',
cleanupError: mode === 'cleanup-error' ? 'Error: transport cleanup failed' : 'McpLocalError: MCP cleanup did not settle',
})
expect(ctx.tools.schemas()).toEqual([])
} finally {
@@ -383,10 +383,10 @@ describe('connection status surface', () => {
const seen: McpConnectionStatus[] = []
handle.onChange((status) => { seen.push(status) })
await vi.waitFor(() => {
expect(handle.current()).toEqual({ state: 'failed', reason: 'gave-up', lastError: 'Error: MCP transport closed' })
expect(handle.current()).toEqual({ state: 'failed', reason: 'gave-up', lastError: 'McpLocalError: MCP transport closed' })
})
const reconnecting = seen.find(status => status.state === 'reconnecting')
expect(reconnecting).toMatchObject({ lastError: 'Error: MCP transport closed' })
expect(reconnecting).toMatchObject({ lastError: 'McpLocalError: MCP transport closed' })
})
it('reports a reconnect-disabled stop when the transport closes during connect', async () => {
@@ -397,7 +397,7 @@ describe('connection status surface', () => {
})
await apply(ctx, stdioConfig({ reconnect: { enabled: false } }))
await vi.waitFor(() => {
expect(connectionStatusOf(ctx.fiber)!.current()).toEqual({ state: 'failed', reason: 'reconnect-disabled', lastError: 'Error: MCP transport closed' })
expect(connectionStatusOf(ctx.fiber)!.current()).toEqual({ state: 'failed', reason: 'reconnect-disabled', lastError: 'McpLocalError: MCP transport closed' })
})
})
})
@@ -63,9 +63,37 @@ describe('MCP result callback adaptation', () => {
})
expect(result.isError).toBe(true)
expect(result.value).toBeUndefined()
expect(result.error?.info).toEqual({ name: 'McpToolError', code: 'MCP_INVALID_RESULT' })
} finally {
await ctx.fiber.dispose()
}
},
)
it.each([
['an isError result', { isError: true, content: [{ type: 'text', text: 'window is gone' }] }, false,
'window is gone', 'MCP_TOOL_ERROR'],
['a task-required tool', undefined, true,
'Tool "window" requires task-based execution, which this bridge does not support', 'MCP_UNSUPPORTED_TASK_EXECUTION'],
] as const)('classifies %s as an McpToolError', async (_label, raw, taskRequired, message, code) => {
const ctx = new Context()
try {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
const call = vi.fn(async () => raw)
ctx.tools.register(createMcpToolDefinition(ctx, {
name: 'native_window', rawName: 'window', description: 'Read the selected window.',
inputSchema: { type: 'object' }, taskRequired, call,
}))
const result = await executeToolFixture(ctx, {
name: 'native_window', callId: brandString<ToolCallId>('window-call'), arguments: {},
signal: new AbortController().signal,
})
expect(result.error).toEqual({ message, info: { name: 'McpToolError', code } })
expect(call).toHaveBeenCalledTimes(taskRequired ? 0 : 1)
} finally {
await ctx.fiber.dispose()
}
})
})
+3
View File
@@ -20,6 +20,9 @@
{
"path": "../../llm/llm"
},
{
"path": "../../util/error"
},
{
"path": "../../core/tools"
},
+2 -2
View File
@@ -21,8 +21,8 @@
en: ec0195a4ad06b3ab
zh: 0b5c41a4f8ff511e
/deepseek-ai-dsh-mcp-resources/use-this-package/discover-and-read:
en: f7fb6597acd3c5dc
zh: 9c59219fb4ab00d9
en: 303d9d3a0b61cf2d
zh: 10a0a6b07fe97919
/deepseek-ai-dsh-mcp-resources/understand-the-implementation:
en: ab308dbe70e82838
zh: 1eb73edc14c76516
+1 -1
View File
@@ -37,7 +37,7 @@ A caller with no configured MCP server sees no MCP prompt text or resource tools
When system-prompt assembly is mounted, the prompt lists server names visible to the calling agent. Call `list_mcp_resources` or `list_mcp_resource_templates` with one of those names as `server`. Without a cursor, the MCP SDK collects the server’s pages. An explicit `cursor` requests that page; pass a returned `nextCursor` unchanged. Read a listed URI or an expanded template with `read_mcp_resource`, using the same `server` name and an explicit `uri`.
Every operation resolves the server in the calling agent's scope. A missing server argument or unavailable server fails before dispatch. The connection owner handles request cancellation, timeouts, and recovery; a failed request remains a failed tool call.
Every operation resolves the server in the calling agent's scope. A missing server argument or unavailable server fails before dispatch; an unavailable server fails as `ToolArgsError` with `INVALID_ARGS`. The connection owner handles request cancellation, timeouts, and recovery; a failed request remains a failed tool call.
-----
+1 -1
View File
@@ -37,7 +37,7 @@ kind: "package-reference"
挂载系统提示词组装服务时,提示词列出调用 agent 可见的服务器名称。将其中一个名称作为 `server` 调用 `list_mcp_resources` 或 `list_mcp_resource_templates`。未提供游标时,MCP SDK 收集服务器的全部分页;显式提供游标时返回一页;将其中的 `nextCursor` 原样作为 `cursor` 传入,以请求下一页。使用相同的 `server` 名称和显式 `uri`,通过 `read_mcp_resource` 读取已列出的 URI 或展开后的模板。
每个操作都在调用 agent 的作用域中解析服务器。缺少服务器参数或服务器不可用时,会在派发前失败。连接所有者负责请求取消、超时与恢复;失败的请求仍表现为失败的工具调用。
每个操作都在调用 agent 的作用域中解析服务器。缺少服务器参数或服务器不可用时,会在派发前失败;服务器不可用时失败为带 `INVALID_ARGS` 的 `ToolArgsError`。连接所有者负责请求取消、超时与恢复;失败的请求仍表现为失败的工具调用。
-----
+2 -2
View File
@@ -7,7 +7,7 @@
import { Service, type Context } from '@deepseek-ai/cordis'
import { createScope, NamedEntries, ScopedLayers, scopeOf, type ScopeKey, type ScopeLayer } from '@deepseek-ai/dsh-scope'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { ToolExecution } from '@deepseek-ai/dsh-tools'
import { ToolArgsError, type ToolExecution } from '@deepseek-ai/dsh-tools'
import type {} from '@deepseek-ai/dsh-system-prompt'
import { registerResourceTools } from './tools.ts'
@@ -123,7 +123,7 @@ export class McpResourceRuntime extends Service {
/** Resolve the caller-visible server before starting any network operation. */
private request(server: string, request: McpResourceRequest, exec: ToolExecution): Promise<JsonValue> {
const provider = this.layers.merge(exec.agent, layer => layer.servers).get(server)
if (!provider) throw new Error(`MCP resource server "${server}" is unavailable in this agent's scope`)
if (!provider) throw new ToolArgsError([`server: MCP resource server "${server}" is unavailable in this agent's scope`])
return provider.request(request, exec)
}
}
@@ -343,7 +343,10 @@ describe('MCP resource tools', () => {
expect((await call(ctx, 'read_mcp_resource', { uri: 'docs://text' })).isError).toBe(true)
const result = await call(ctx, 'read_mcp_resource', { server: 'missing', uri: 'docs://text' })
expect(result.isError).toBe(true)
expect(JSON.stringify(result.content)).toContain('unavailable in this agent')
expect(result.error).toEqual({
message: 'invalid arguments: server: MCP resource server "missing" is unavailable in this agent\'s scope',
info: { name: 'ToolArgsError', code: 'INVALID_ARGS' },
})
})
it('resolves scoped providers and removes only the disposed registration', async () => {
@@ -1,5 +1,5 @@
/** Validate and capture the binding names available to one program. */
import { PtcImage, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime'
import { PtcImage, DUNDER_MEMBER, PORTABLE_RESERVED_WORDS, PtcRuntimeError, RESERVED_BINDING_GLOBALS, RESERVED_ERROR_MEMBERS } from '@deepseek-ai/dsh-ptc-runtime'
import type { PtcBindingFunction, PtcBindingNamespace, PtcJsonValue, PtcRunRequest } from '@deepseek-ai/dsh-ptc-runtime'
import { snapshotPtcJsonValue, encodePtcJsonWire, type PtcJsonWire, type PtcImageWire } from './json-wire.ts'
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
@@ -12,15 +12,15 @@ export function validateBindings(request: PtcRunRequest): Map<string, PtcBinding
const bindings = new Map<string, PtcBindingNamespace>()
for (const namespace of request.bindings) {
if (!IDENTIFIER.test(namespace.global) || PORTABLE_RESERVED_WORDS.has(namespace.global)) {
throw new Error(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding global ${JSON.stringify(namespace.global)} is not a usable identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
// Shared exclusions keep binding declarations portable across the SDK's
// supported languages, including externally supplied Python runtimes.
if (RESERVED_BINDING_GLOBALS.has(namespace.global)) {
throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(namespace.global)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
if (bindings.has(namespace.global)) {
throw new Error(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate binding global ${JSON.stringify(namespace.global)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
bindings.set(namespace.global, namespace)
}
@@ -30,17 +30,17 @@ export function validateBindings(request: PtcRunRequest): Map<string, PtcBinding
const descriptor = namespace.errorClass
if (!descriptor) continue
if (!IDENTIFIER.test(descriptor.name) || PORTABLE_RESERVED_WORDS.has(descriptor.name)) {
throw new Error(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error class ${JSON.stringify(descriptor.name)} is not a usable identifier`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
if (RESERVED_BINDING_GLOBALS.has(descriptor.name)) {
throw new Error(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: reserved binding global ${JSON.stringify(descriptor.name)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
if (bindings.has(descriptor.name) || errorClassNames.has(descriptor.name)) {
throw new Error(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: duplicate injected global ${JSON.stringify(descriptor.name)}`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
const member = descriptor.memberNameProperty
if (member.length === 0 || RESERVED_ERROR_MEMBERS.has(member) || DUNDER_MEMBER.test(member)) {
throw new Error(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`)
throw new PtcRuntimeError(`dsh-ptc-runtime-node: binding error member property ${JSON.stringify(descriptor.memberNameProperty)} is not usable`, 'PTC_RUNTIME_INVALID_ARGUMENT')
}
errorClassNames.add(descriptor.name)
}
@@ -2,7 +2,7 @@
import { stripTypeScriptTypes } from 'node:module'
import { isAbsolute } from 'node:path'
import type { Context } from '@deepseek-ai/cordis'
import type { PtcProgramFormat, PtcRunRequest, PtcRunResult, PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
import { PtcRuntimeError, type PtcProgramFormat, type PtcRunRequest, type PtcRunResult, type PtcRunSpec } from '@deepseek-ai/dsh-ptc-runtime'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { clampTimeout } from '@deepseek-ai/dsh-timeout'
import type { ResolvedConfig } from './config.ts'
@@ -73,7 +73,7 @@ class NodeExecution {
resolve(request: PtcRunRequest): PtcRunSpec {
const sandboxPolicy = request.sandboxPolicy ?? this.ctx.sandboxPolicy.resolve()
const cwd = request.cwd ?? sandboxPolicy.workspaceRoot
if (!isAbsolute(cwd)) throw new Error(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`)
if (!isAbsolute(cwd)) throw new PtcRuntimeError(`${this.mode.retainsState ? 'persistent PTC' : 'ptc-runtime-node'}: cwd must be absolute`, 'PTC_RUNTIME_INVALID_ARGUMENT')
return { ...request, sandboxPolicy, cwd, timeoutMs: request.timeoutMs === null ? null : clampTimeout(request.timeoutMs, this.config.timeoutMs, this.config.maxTimeoutMs, this.mode.retainsState ? 'persistent PTC timeoutMs' : 'ptc-runtime-node: timeoutMs') }
}
@@ -84,8 +84,8 @@ class NodeExecution {
* @returns Captured logs, JSON completion, or a structured execution failure.
*/
async run(spec: PtcRunSpec, initialization: string | undefined): Promise<PtcRunResult> {
if (spec.sandboxPolicy === undefined) throw new Error('ptc-runtime-node: run requires a resolved sandbox policy')
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new Error('ptc-runtime-node: run requires resolved cwd and timeout')
if (spec.sandboxPolicy === undefined) throw new PtcRuntimeError('ptc-runtime-node: run requires a resolved sandbox policy', 'PTC_RUNTIME_INVALID_ARGUMENT')
if (!isAbsolute(spec.cwd) || (spec.timeoutMs !== null && (!Number.isFinite(spec.timeoutMs) || spec.timeoutMs <= 0 || spec.timeoutMs > this.config.maxTimeoutMs))) throw new PtcRuntimeError('ptc-runtime-node: run requires resolved cwd and timeout', 'PTC_RUNTIME_INVALID_ARGUMENT')
const bindings = validateBindings(spec)
const owner = this.mode.retainsState ? spec.stateOwner : undefined
let worker = owner === undefined ? undefined : this.owners.get(owner)
@@ -93,7 +93,7 @@ class NodeExecution {
if (worker && !worker.closed && (worker.policy.mode !== spec.sandboxPolicy.mode
|| worker.policy.workspaceRoot !== spec.sandboxPolicy.workspaceRoot
|| worker.policy.sessionId !== spec.sandboxPolicy.sessionId)) {
throw new Error('persistent PTC: release the retained environment before changing its sandbox policy')
throw new PtcRuntimeError('persistent PTC: release the retained environment before changing its sandbox policy', 'PTC_RUNTIME_CONFLICT')
}
// Retained processes keep their launch-time directory grants until release.
if (!worker || worker.closed) {
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more