diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a23b72b..63cb2e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,18 +27,21 @@ jobs: cache: npm - name: Install Zstandard CLI for Node 20 compression and codec checks run: sudo apt-get update && sudo apt-get install -y zstd - - name: Install deps (cordis/react/react-dom for the host+client suites) - run: npm ci - - name: Test suite (reader + host smoke + client render; hermetic, no dsh install needed) + - name: Install dependencies without lifecycle scripts + run: npm ci --ignore-scripts + - name: Existing and live-sync regression suites plus actual-tarball privacy gate run: npm test - name: CLI smoke run: node bin/dsh-codex-sync.js --help - # Real DSH host boot: a harness release that breaks the plugin contract - # fails here instead of on the user's machine. + # Composition only: a successful dump is not host boot or GUI acceptance. dsh-boot-smoke: runs-on: ubuntu-latest timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + dsh: [0.2.0-rc.2, 0.2.1-rc.2, 0.2.1-rc.3] steps: - uses: actions/checkout@v4 with: @@ -46,13 +49,13 @@ jobs: persist-credentials: false - uses: actions/setup-node@v4 with: - node-version: 22 - - run: npm ci + node-version: 24 + - run: npm ci --ignore-scripts - run: npm install -g pnpm - - name: pack plugin and add to a scratch web profile + - name: Pack exact source and add to a scratch web profile run: | export DSH_HOME="$RUNNER_TEMP/dsh-home" - npm pack --json > pack.json + npm pack --ignore-scripts --json > pack.json TGZ="$(node -p 'JSON.parse(require("fs").readFileSync("pack.json"))[0].filename')" mkdir "$RUNNER_TEMP/packed-plugin" tar -xzf "$TGZ" -C "$RUNNER_TEMP/packed-plugin" @@ -62,9 +65,50 @@ jobs: cmp docs/COMPATIBILITY.md "$RUNNER_TEMP/packed-plugin/package/docs/COMPATIBILITY.md" git rev-parse HEAD sha256sum "$TGZ" - pnpm dlx @deepseek-ai/dsh@0.2.0-rc.2 plugin --profile web add "$PWD/$TGZ" + pnpm dlx @deepseek-ai/dsh@${{ matrix.dsh }} plugin --profile web add "$PWD/$TGZ" echo "DSH_HOME=$DSH_HOME" >> "$GITHUB_ENV" - - name: composed config mentions this plugin + - name: Composed config mentions this plugin run: | - pnpm dlx @deepseek-ai/dsh@0.2.0-rc.2 --profile web --dump-config > composed.txt + pnpm dlx @deepseek-ai/dsh@${{ matrix.dsh }} --profile web --dump-config > composed.txt grep -E "dsh-codex-sync|codex-sync" composed.txt + + current-skills-contract: + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + node: [20, 22] + fixture: [current-runtime, current-runtime-rc3] + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + - run: npm ci --ignore-scripts + - name: Locked Skills contract for one supported runtime + run: npm run test:current -- test/${{ matrix.fixture }} + + native-mcp-contract: + runs-on: ${{ matrix.os }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + fixture: [native-runtime, native-runtime-rc3, native-runtime-020-rc2] + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: npm ci --ignore-scripts + - name: Locked native MCP contract for one supported runtime + run: npm run test:native -- test/${{ matrix.fixture }} diff --git a/.gitignore b/.gitignore index a1127ae..001e59f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,12 @@ node_modules/ *.tgz .DS_Store +runtime-status*.json +*.log +.env +.env.* +!.env.example +.npmrc +.release-artifacts/ +pack.json +composed.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 5837f7d..ef419da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## Unreleased + +- Admit the DSH MCP client 0.2.1-rc.2 without compatibility exemptions; resolve shipped clients through the Host Loader with an npm fallback. +- Make Codex Skills cache invalidation registration-owned and watched, including late-created roots and master/per-item changes; parse real YAML invocation policies and fix flat-file resource bases. +- Use complete TOML parsing and portable field validation; keep unsupported tool policies fail-closed and diagnostics free of source excerpts/credential values. +- Retain actual Cordis Fibers, cancel the full startup pipeline, join namespace retirement before replacement, and admit revocations independently of unrelated starts/teardowns. Preserve explicit native reconnect and late dependency activation. +- Add hermetic lifecycle/cache/native-protocol suites and actual-tarball privacy gates; exclude local deployment notes/runtime artifacts and export localized metadata plus an original MIT icon. + + ## 1.6.2 โ€” 2026-10-05 - Import sessions in the installed DSH current format and support handle-based persistence, incremental assistant replies, new turns, and idempotent re-imports (PR #3). diff --git a/README.md b/README.md index f07b8eb..6bde831 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,9 @@ When adopting or exploring **DeepSeek Harness (DSH)**, developers typically face ### 2. โšก Live First-Class Skills Mounting - Mounts `~/.codex/skills/*/SKILL.md` directly into DSH's native skill catalog; - Full support for nested directory resources and multi-file skill bundles; -- **Zero-restart updates**: Edit a skill file on disk, and DSH recognizes the change on the next turn. +- **Zero-restart updates**: additions, deletion, rename and YAML metadata changes invalidate the owning registry cache; bodies are reread on load. Master/per-item switches also update cached catalogs. + +For the bounded 0.2 upgrade policy (including 0.2.1-rc.3), native API checks, supported fields, trust boundary and synthetic release checks, see [Live sync compatibility](docs/LIVE-SYNC.md). No user-specific profiles, service inventories or runtime snapshots are included. ### 3. ๐Ÿ”Œ Automated Bidirectional MCP Mirroring - **Codex โ†’ DSH**: Watches `~/.codex/config.toml` live, dynamically mirroring `[mcp_servers.*]` to DSH with conflict avoidance and stderr silencing; diff --git a/README.zh-CN.md b/README.zh-CN.md index 83cc6d3..21f3e51 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -82,7 +82,9 @@ ### 2. โšก Skills ๅฎžๆ—ถไธ€็ญ‰ๅ…ฌๆฐ‘ๆŒ‚่ฝฝ - ็›ดๆŽฅๅฐ† `~/.codex/skills/*/SKILL.md` ๆณจๅ†Œไธบ DSH ๅŽŸ็”Ÿไธ€็ญ‰ๅ…ฌๆฐ‘ๆŠ€่ƒฝ๏ผ› - ๆ”ฏๆŒๅฎŒๆ•ด็š„ๅญ็›ฎๅฝ•่ต„ๆบๅผ•็”จไธŽๅคšๆ–‡ไปถๆžถๆž„๏ผ› -- **ๆ”นๅฎŒๅณ็”จ**๏ผšๅœจๆœฌๅœฐไฟฎๆ”น `SKILL.md`๏ผŒDSH ไธ‹ๆฌก่ฐƒ็”จๅณๆ—ถ็”Ÿๆ•ˆ๏ผŒๆ— ้œ€้‡ๅฏ DSH ๆœๅŠกใ€‚ +- **ๆ”นๅฎŒๅณ็”จ**๏ผšๆ–ฐๅขžใ€ๅˆ ้™คใ€้‡ๅ‘ฝๅๅ’Œ YAML ๅ…ƒๆ•ฐๆฎๅ˜ๅŒ–ไฝฟๆ‰€ๅฑžๆณจๅ†Œ็ผ“ๅญ˜ๅคฑๆ•ˆ๏ผ›ๆญฃๆ–‡ๆŒ‰้œ€้‡่ฏปใ€‚ๆ€ปๅผ€ๅ…ณๅŠ้€้กนๅŒๆญฅๅผ€ๅ…ณๅŒๆ ทๆ›ดๆ–ฐๅทฒๆœ‰็ผ“ๅญ˜ใ€‚ + +0.2 ็ณปๅˆ—็š„ๆœ‰็•Œๅ‡็บง็ญ–็•ฅ๏ผˆๅซ 0.2.1-rc.3๏ผ‰ใ€ๅŽŸ็”ŸๆŽฅๅฃ่ƒฝๅŠ›ๆฃ€ๆŸฅใ€ๅญ—ๆฎตๆ”ฏๆŒใ€ๆ‰ง่กŒไฟกไปป่พน็•ŒๅŠๅˆๆˆๅ‘ๅธƒๆต‹่ฏ•่ง [ๅฎžๆ—ถๅŒๆญฅๅ…ผๅฎน่ฏดๆ˜Ž](docs/LIVE-SYNC.md)ใ€‚ไธๅŒ…ๅซไธชไบบ profileใ€ๆœๅŠกๅบ“ๅญ˜ๆˆ–่ฟ่กŒๅฟซ็…งใ€‚ ### 3. ๐Ÿ”Œ MCP ่‡ชๅŠจๅŒๅ‘้•œๅƒ - **Codex โ†’ DSH**๏ผšๅŽๅฐ่‡ชๅŠจ็›‘ๅฌ `~/.codex/config.toml`๏ผŒๅฐ† `[mcp_servers.*]` ๅŠจๆ€้•œๅƒๅˆฐ DSH๏ผŒๆ”ฏๆŒ็ƒญ้‡่ฝฝ๏ผŒๅนถๅ†…็ฝฎๅธธ็”จๆœๅŠก็š„้™้ŸณไธŽๅ†ฒ็ชๆŽ’้™ค็ญ–็•ฅ๏ผ› diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cb5f773..458295d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -124,18 +124,21 @@ Two sources (lib/mcp.js): server (`@deepseek-ai/dsh-mcp-client`, optional peer; graceful warning if missing). - **Auto-mirror** (`mcpMirror`, default on) โ€” parses `~/.codex/config.toml` - `[mcp_servers.*]` (TOML-lite parser: command/args/env/cwd + url/ - bearer_token_env_var + enabled), maps: + `[mcp_servers.*]` (complete TOML parser; command/args/env/env_vars/cwd, + URL/static/environment headers, bearer references, timeouts and enabled), maps: - stdio โ†’ `{ transport: 'stdio', serverName, command, args, env }` - url โ†’ `{ transport: 'streamable-http', url, headers: { Authorization: 'Bearer ' } }` - skips `enabled = false`; **always excludes `dsh-plugins`** (the reverse bridge โ€” would recurse); `mcpMirrorDeny`/`mcpMirrorOnly` filter; names in explicit `mcpServers` win. - - `fs.watch(config.toml)` + 500 ms debounce โ†’ diff mount/unmount, so - editing codex's config live-syncs dsh's MCP servers. - - `failOnStartupError: false` on every instance: a failing server logs and - continues. + - Parent-directory observation plus bounded polling handles missing roots and + repeated atomic replacements; only changed generations are replaced. + - Per-generation cancellation and same-name retirement barriers do not block + later revocations behind another server's startup or teardown. + - Mirrored clients require initial readiness and own bounded initial retries; + explicit clients retain native dependency waiting and reconnect behavior. + See [live-sync contracts](LIVE-SYNC.md) for limits and synthetic tests. ## 6. Client bundle (lib/client.js) diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index 652fd00..5e833bc 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -5,11 +5,31 @@ The PR #3 local follow-up was tested with the official npm/CLI and session-format catalog v4. Desktop version numbers are independent and are not substitutes for npm package versions. -The optional MCP client peer admits `0.2.0-rc.2` explicitly, alongside the -existing `^0.0.1-rc.1` range. This does not claim compatibility with every -future 0.2 release or prove full MCP mirroring acceptance. Session import -requires the host's production migration/catalog packages; development-only -migration packages must not be installed into a production profile as a fix. +Host admission now uses `engines.dsh: ^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0`, +retaining the legacy declaration while admitting later 0.2 patch and prerelease +versions, including `0.2.1-rc.3`. DSH matches this range with +`includePrerelease: true`; the `-0` upper bound also excludes **0.3 prereleases**. +This is a bounded candidate family, not certification of every future release. +No version exemption or exact RC comparison is used at runtime. + +The optional native MCP peer likewise uses bounded ranges; a 0.2.1 lower tuple +is retained because npm's own peer matcher does not enable `includePrerelease`. +Host admission is explicitly separate from that npm peer hint: DSH gives +`engines.dsh` precedence rather than treating every SDK peer as a core-version +pin. A new patch-level SDK prerelease may still need a peer-hint update for +standalone npm installations, but cannot by itself block Host Loader admission. + +Isolated real SkillRegistry fixtures cover `0.2.1-rc.2` and `0.2.1-rc.3`. +Native MCP protocol/lifecycle fixtures cover `0.2.0-rc.2`, `0.2.1-rc.2` and +`0.2.1-rc.3`. Native config-field checks and independently owned Skills +registration provide a fail-closed boundary when an admitted runtime changes +an interface. See [LIVE-SYNC.md](LIVE-SYNC.md) for exact scope and reproducible +commands. These checks do not prove full Desktop GUI acceptance or every +historical/future implementation's semantics. + +Session import requires the host's production migration/catalog packages; +development-only migration packages must not be installed into a production +profile as a fix. Use a profile dependency plus the bundle patch insert, as in `examples/web-profile.cordis.patch.yml`. Do not also add the same bundle to diff --git a/docs/LIVE-SYNC.md b/docs/LIVE-SYNC.md new file mode 100644 index 0000000..d39df3d --- /dev/null +++ b/docs/LIVE-SYNC.md @@ -0,0 +1,71 @@ +# Live Skills and MCP compatibility + +## Scope + +The compatibility update admits a **bounded DSH 0.2 patch/prerelease family, including 0.2.1-rc.3**, without a version exemption or exact-RC checks. It keeps the existing package identity, commands, UI response shapes, per-item state schema and within-layer Codex skill rank (800). The import/export and reverse-installer implementations are not redesigned by this update. + +Home resolution is `config.codexHome`, then a nonempty `CODEX_HOME`, then `~/.codex`. Directory overrides are generic configuration, not application-installation or user-specific paths. No runtime inventory, credentials, personal acceptance record or profile configuration belongs in the package or PR. + +## Upgrade resilience + +- `engines.dsh` admits `^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0`. The legacy branch is retained, not newly certified; the 0.3 boundary includes its prereleases. An allowed version is only a candidate for the runtime API checks, not a guarantee of future implementation semantics. +- Only enabled MCP servers load the native client. Before any executable lookup, child creation or network operation, verify the plugin/Config exports, the selected transport's explicitly declared fields (including nested reconnect), and every supplied setting after native validation. +- Schemastery passes through unknown keys, so successful validation or a simple round trip is insufficient. Missing fields or unfamiliar schema forms reject the affected server. New native defaults are allowed; supplied env/header maps cannot acquire extra entries. Never return native validation errors that could embed configuration values. +- Skills still use this plugin's watched provider, priorities and preferencesโ€”not a replacement native filesystem provider. Unsupported registry/control contracts stop that optional registration, clean partial registrations/watchers and leave commands/MCP active. Service replacement retries via the existing owned injection scope. +- When the optional subprocess service exists, stdio requires its supported resolver method. In standalone/legacy deployments without it, the native SDK retains its own executable resolution. A changed stdio resolver does not disable HTTP clients. Native reconnect, dependency waiting, startup deadlines and late-child cleanup remain independently owned. +- Native API failure is a static, credential-free per-server/feature diagnostic. Actual breaking changes still require adaptation; the range is not a promise of indefinite compatibility. The npm peer hint is separate from DSH Host admission; see [COMPATIBILITY.md](COMPATIBILITY.md). + +## Skills + +- Discover one level of `/skills//SKILL.md` or `/skills/.md`; hidden roots and nested example skills are not recursively imported. +- YAML descriptions and invocation controls are parsed as YAML. Empty/invalid metadata, invalid names/policies, empty bodies and files larger than 1 MiB are omitted; malformed invocation policies never default to granting access. A missing name retains the directory/filename fallback when it is a valid skill name. +- Changes call the owning registration's `control.invalidate()`, which clears the current DSH registry cache. There is no call to a nonexistent shared `skills.invalidate()` method. +- Watch additions, deletion, rename and frontmatter changes. A fixed-root probe recovers missing/recreated roots, and a two-second metadata-only signature fallback covers watcher startup races or lost OS events; resource subtrees are not recursively watched. Bodies are reread on load. The Node-20-compatible watcher does not require native addons. +- Keep master/default/per-item/select-all preferences and raw entry identities. A renamed directory is a new item. Registration unload aborts observation and awaits watcher closure. Flat Markdown resources resolve relative to the skills directory, not the Markdown file. +- Within one registration layer, rank 800 remains below DSH's own providers; nearer Agent/preset layers still win regardless of rank. Already-logged skill content is not rewritten. + +## MCP + +The optional native client is loaded through the Host Loader when available, with the npm peer fallback for other deployments. No application or executable path is embedded. Explicit clients retain dependency waiting and native reconnect after initial errors. Mirrored clients report `mounted` only after their initial activation/discovery succeeds, then rely on native reconnect; initial failures retry at a bounded interval. + +A complete TOML parser supports quoted keys, comments, literal strings, multiline/comma-containing arrays and inline/subtable maps. A read/parse failure keeps the last-good generation and reports a redacted diagnostic. An authoritative valid configuration that removes/disables a server revokes it. + +| Codex field | Mapping / constraint | +| --- | --- | +| `command`, `args`, `env` | stdio; env values are literal, matching Codex rather than interpolating `${VAR}` | +| `env_vars` | whitelist: copy only named variables present in the Host environment; explicit env wins | +| `cwd` | absolute or `~/` path; relative paths are rejected instead of guessing a cross-application base | +| `url` | HTTP/HTTPS Streamable HTTP, without URL userinfo | +| `http_headers`, `env_http_headers` | static/environment headers with case-insensitive override semantics | +| `bearer_token_env_var` | explicit in-memory bearer header; missing references fail closed | +| `startup_timeout_sec` / `startup_timeout_ms` | full executable-lookup + activation deadline; default 20 seconds, maximum 5 minutes | +| `tool_timeout_sec` | native tool timeout; default 60 seconds, maximum 5 minutes | +| `enabled_tools`, nonempty `disabled_tools`, `tool_approval` | unsupported by the native client: skip/report rather than broaden tool access | +| `enabled = false` | never start | + +A native server namespace must match `[A-Za-z0-9_-]{1,32}`; invalid names are reported per server, not normalized into ambiguous aliases. Reverse-bridge exclusions check known bridge identities and launch entrypoints, not arbitrary data path substrings. Existing deny/only, explicit-wins and per-item policies remain in force. POSIX stderr silencing preserves argument boundaries; on Windows it is not applied, so the plugin never assumes `/bin/sh` exists. + +Parent-directory observation plus a bounded 2-second fallback detects atomic replacement, repeated edits and late-created homes. Configure `mcpMirrorPollIntervalMs` (50โ€“60000 ms) or `mcpStartupTimeoutMs` (1โ€“300000 ms) when needed. Each generation owns an AbortController and its actual Cordis Fiber. New configuration admission is independent of unrelated handshakes **and teardowns**. Only same-namespace replacement startup waits for its prior generation's closure; global unload joins all active/retiring generations. + +**Trust boundary:** enabling mirroring trusts enabled commands/endpoints in the current and future Codex configuration. MCP commands run with plugin privileges and may invoke package managers; this is not per-tool approval. The bridge does not read Codex authentication/OAuth stores or inherit every secret-shaped environment variable. Logged status can contain the configured local path and server names, so treat those existing user-requested status outputs as private. The plugin creates no persistent runtime-status artifact in its source or install tree. + +## Reproducible verification + +All new fixtures are synthetic; tests never read a personal Codex directory or use a real service/account. Keep the historical migration fixture dependency graph separate from current DSH peers. + +```sh +npm ci --ignore-scripts +npm test +npm run test:current +# Use Node 24 for the locked current SDK/transitive engine requirements: +npm run test:native +npm run test:package +``` + +- Main suite: existing session/client/command regressions plus actual Cordis lifecycle, full-TOML mapping, full-pipeline cancellation, independent revocation, atomic-save and upgrade-contract tests. SemVer boundary tables distinguish the Host's prerelease policy from npm peer matching; negative native-schema cases prove unknown/nested fields cannot bypass the guard. +- `test:current`: isolated locked DSH SkillRegistry 0.2.1-rc.2 and 0.2.1-rc.3 / Cordis 4.0.5; populate real caches, then test commands/HTTP toggles and external file changes, missing roots and unload. +- `test:native`: isolated locked native MCP clients 0.2.0-rc.2, 0.2.1-rc.2 and 0.2.1-rc.3. A hermetic stdio fixture answers initialize/list/call; verify discover/call/dispose/re-add, recovery after initial failure and late arrival of the tools service. No network endpoint is used. +- Both contract runners install each selected locked fixture with `npm ci --ignore-scripts`, then execute tests using the same Node executable. For one graph, pass its allowlisted directory, e.g. `npm run test:current -- test/current-runtime-rc3` or `npm run test:native -- test/native-runtime-rc3`; the equivalent environment selector is `DSH_CONTRACT_FIXTURE`. Unknown/path-traversal/cross-suite selections fail before installation. +- Packaging gate: inspect the **actual tarball**, require runtime/schema/locale/icon/license resources, and reject runtime artifacts, private paths, credential-shaped literals and local deployment documents. + +CI exercises the portable contract suites on Node 20/22 and current native SDK fixtures on Node 24. Composition checks are separate from lifecycle/protocol tests; a successful `--dump-config` is not a boot or visual acceptance claim. No full Desktop GUI, restart, or all-host/all-platform certification follows merely from these tests. The unchanged legacy peer range is not a claim that every historical/future runtime has been newly verified. diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000..64c4855 --- /dev/null +++ b/icon.svg @@ -0,0 +1 @@ + diff --git a/lib/index.js b/lib/index.js index c532b48..abc4420 100644 --- a/lib/index.js +++ b/lib/index.js @@ -30,9 +30,10 @@ */ import { homedir } from 'node:os' import { existsSync } from 'node:fs' -import { join } from 'node:path' +import { join, resolve } from 'node:path' import { bridgeInstructionsSection, bridgeConfigSection } from './bridge.js' import { registerCodexSkillProvider, registerPluginSkillProvider } from './skill-provider.js' +import { assertSkillControl, RuntimeCompatibilityError } from './runtime-compat.js' import { importCodex, attachAllImported, listImportCatalog } from './import-service.js' import { exportToCodex, listExportCatalog } from './export-codex.js' import { repairSessionStore } from './session-repair.mjs' @@ -69,7 +70,7 @@ const SETTING_META = { autoImport: { label: '่‡ชๅŠจๅฏผๅ…ฅ', default: (c) => c.autoImport === true, apply: 'startup' }, enableInstructions: { label: 'ๆŒ‡ไปคๆณจๅ…ฅ', default: (c) => c.enableInstructions !== false, apply: 'next-session' }, enableConfig: { label: '้…็ฝฎๆ‘˜่ฆ', default: (c) => c.enableConfig !== false, apply: 'next-session' }, - enableSkills: { label: 'ๆŠ€่ƒฝๆณจๅ†Œ', default: (c) => c.enableSkills !== false, apply: 'next-session' }, + enableSkills: { label: 'ๆŠ€่ƒฝๆณจๅ†Œ', default: (c) => c.enableSkills !== false, apply: 'hot' }, mcpMirror: { label: 'MCP ้•œๅƒ', default: (c) => c.mcpMirror !== false, apply: 'hot' }, skillSyncDefault: { label: 'ๆ–ฐๆŠ€่ƒฝ้ป˜่ฎคๅŒๆญฅ', default: () => readSyncGroup('skill').default, apply: 'hot' }, mcpSyncDefault: { label: 'ๆ–ฐ MCP ้ป˜่ฎคๅŒๆญฅ', default: () => readSyncGroup('mcp').default, apply: 'hot' }, @@ -115,20 +116,27 @@ export const inject = ['systemPrompt', 'commands'] * fallback โ€” overrides this when set) */ export function apply(ctx, config = {}) { - const codexHome = config.codexHome ?? join(homedir(), '.codex') + const configuredHome = config.codexHome || process.env.CODEX_HOME || join(homedir(), '.codex') + const codexHome = resolve(configuredHome.startsWith('~/') ? join(homedir(), configuredHome.slice(2)) : configuredHome) const store = autoImportStore(config.autoImport === true) /** Effective persisted value for a setting key, config default as fallback. */ const ef = (key, configDefault) => effectiveSetting(key, configDefault) let mirrorHandle = null + let mirrorTransition = Promise.resolve() + let stopping = false + const codexProviders = new Set() const setMirror = (on) => { - if (on) { - if (mirrorHandle) return - mirrorHandle = startMcpMirror(ctx, codexHome, config) - return - } - try { mirrorHandle?.dispose?.() } catch { /* ignore */ } - mirrorHandle = null + mirrorTransition = mirrorTransition.then(async () => { + if (on && !stopping) { + if (!mirrorHandle) mirrorHandle = startMcpMirror(ctx, codexHome, config) + } else { + const old = mirrorHandle + mirrorHandle = null + await old?.dispose() + } + }).catch(() => { ctx.logger?.warn?.('dsh-codex-sync: MCP mirror transition failed') }) + return mirrorTransition } /** Raw names under ~/.codex/skills (SKILL.md folders or flat .md files). */ @@ -162,13 +170,9 @@ export function apply(ctx, config = {}) { } } - /** Nudge skill consumers to rescan after a per-item toggle. */ + /** Invalidation belongs to each registration, not the shared Skills service. */ const invalidateSkills = () => { - try { - ctx.get('skills')?.invalidate?.() - } catch { - /* older dsh builds rescan on their own schedule */ - } + for (const provider of codexProviders) provider.invalidate() } const runImport = async () => { @@ -193,20 +197,52 @@ export function apply(ctx, config = {}) { // โ”€โ”€ 1. first-class skills from ~/.codex/skills โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // Provider stays mounted; its list() consults the persisted toggle so the // Switch in Sync settings takes effect without re-applying the plugin. - const skills = ctx.get('skills') - if (skills !== undefined) { - ctx.effect( - () => skills.registerProvider((control) => registerPluginSkillProvider(codexHome, config, control)), - 'codex-sync.plugin-skills()', - ) - ctx.effect( - () => skills.registerProvider((control) => registerCodexSkillProvider( - codexHome, config, control, - () => ef('enableSkills', config.enableSkills !== false), - )), - 'codex-sync.skills()', - ) + const mountSkills = async (inner) => { + const skills = inner.get('skills') + if (typeof skills?.registerProvider !== 'function') { + ctx.logger?.warn?.('dsh-codex-sync: skills-registry-api-unsupported; other features remain active') + return + } + const registrations = [] + const providers = [] + const register = (create, label) => { + const dispose = inner.effect(() => { + const release = skills.registerProvider(control => { + assertSkillControl(control) + const provider = create(control) + providers.push(provider) + return provider + }) + if (typeof release !== 'function') throw new RuntimeCompatibilityError('skills-registration-api-unsupported') + return release + }, label) + registrations.push(dispose) + } + try { + register(control => registerPluginSkillProvider(codexHome, config, control), 'codex-sync.plugin-skills()') + register(control => { + const provider = registerCodexSkillProvider(codexHome, config, control, + () => ef('enableSkills', config.enableSkills !== false)) + codexProviders.add(provider) + inner.effect(() => async () => { + codexProviders.delete(provider) + await provider.dispose() + }, 'codex-sync.skill-watchers()') + return provider + }, 'codex-sync.skills()') + } catch (error) { + await Promise.allSettled(registrations.map(dispose => Promise.resolve().then(dispose))) + await Promise.allSettled(providers.map(provider => { + codexProviders.delete(provider) + return provider.dispose?.() + })) + const reason = error instanceof RuntimeCompatibilityError ? error.code : 'skills-registration-failed' + ctx.logger?.warn?.(`dsh-codex-sync: ${reason}; other features remain active`) + } } + // Late/replaced Skills services get a fresh, independently-owned registration. + if (typeof ctx.inject === 'function') ctx.inject(['skills'], mountSkills) + else if (ctx.get('skills') !== undefined) mountSkills(ctx) // โ”€โ”€ 2. system-prompt sections (instructions + config summary) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ // Sections always mount; their text() is gated by the persisted toggle, so @@ -372,9 +408,10 @@ export function apply(ctx, config = {}) { } else { writeState({ [key]: next }) } - if (key === 'mcpMirror') setMirror(next) + if (key === 'enableSkills') invalidateSkills() ctx.logger?.info?.(`dsh-codex-sync: setting ${key}=${val}`) - return { kind: 'success', text: `${key}=${val} ${meta.label} ๅทฒ${next ? 'ๅผ€ๅฏ' : 'ๅ…ณ้—ญ'}๏ผˆ${APPLY_NOTE[meta.apply]}๏ผ‰` } + const report = { kind: 'success', text: `${key}=${val} ${meta.label} ๅทฒ${next ? 'ๅผ€ๅฏ' : 'ๅ…ณ้—ญ'}๏ผˆ${APPLY_NOTE[meta.apply]}๏ผ‰` } + return key === 'mcpMirror' ? setMirror(next).then(() => report) : report } const on = ef(key, meta.default(config)) return { kind: 'success', text: `${key}=${on ? 'on' : 'off'} ${meta.label}๏ผˆ${APPLY_NOTE[meta.apply]}๏ผ‰` } @@ -509,7 +546,12 @@ export function apply(ctx, config = {}) { } } if (ef('mcpMirror', config.mcpMirror !== false)) setMirror(true) - ctx.effect(() => () => { try { mirrorHandle?.dispose?.() } catch { /* ignore */ } }, 'codex-sync.mcp-mirror()') + ctx.effect(() => async () => { + stopping = true + await mirrorTransition + await mirrorHandle?.dispose() + mirrorHandle = null + }, 'codex-sync.mcp-mirror()') // Silent JSON API for the import picker. Nested so we WAIT for webServer // (ctx.get at apply-time is often undefined and the SPA fallback ate GET). @@ -701,7 +743,8 @@ export function apply(ctx, config = {}) { } else { writeState({ [key]: value }) } - if (key === 'mcpMirror') setMirror(value) + if (key === 'enableSkills') invalidateSkills() + if (key === 'mcpMirror') await setMirror(value) inner.logger?.info?.(`dsh-codex-sync: setting ${key}=${value ? 'on' : 'off'}`) sendJson(res, 200, { ok: true, key, value }) return diff --git a/lib/mcp-config.js b/lib/mcp-config.js new file mode 100644 index 0000000..530d4c6 --- /dev/null +++ b/lib/mcp-config.js @@ -0,0 +1,107 @@ +/** Portable Codex TOML mapping. No credential files or machine-specific paths. */ +import { parse } from 'smol-toml' +import { RuntimeCompatibilityError } from './runtime-compat.js' +import { homedir } from 'node:os' +import { isAbsolute, join } from 'node:path' + +export class McpConfigError extends Error { + constructor(code, field) { super(field ? `${code}: ${field}` : code); this.code = code } +} +const record = value => value !== null && typeof value === 'object' && !Array.isArray(value) +export const HARD_DENY = new Set(['dsh-plugins', 'dsh-plugins-runtime']) +export function parseCodexMcpServers(text) { + let doc + try { doc = parse(text) } catch { throw new McpConfigError('invalid-toml') } + if (doc.mcp_servers !== undefined && !record(doc.mcp_servers)) throw new McpConfigError('invalid-mcp-servers') + return new Map(Object.entries(doc.mcp_servers ?? {}).map(([name, srv]) => { + if (!record(srv)) throw new McpConfigError('invalid-server') + return [name, { args: [], env: {}, ...srv, name }] + })) +} +function strings(value, field) { + if (!Array.isArray(value) || value.some(v => typeof v !== 'string')) throw new McpConfigError('invalid-field', field) + return [...value] +} +function dictionary(value, field) { + if (!record(value) || Object.values(value).some(v => typeof v !== 'string')) throw new McpConfigError('invalid-field', field) + return { ...value } +} +function envValue(name, env) { + if (typeof name !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)) throw new McpConfigError('invalid-env-name') + if (typeof env[name] !== 'string' || !env[name]) throw new McpConfigError('missing-env', name) + return env[name] +} +function timeout(value, fallback, field) { + if (value === undefined) return fallback + if (typeof value !== 'number' || !Number.isFinite(value) || value < 1 || value > 300000) throw new McpConfigError('invalid-timeout', field) + return Math.ceil(value) +} +export function startupTimeout(srv, config = {}) { + if (srv.startup_timeout_sec !== undefined && typeof srv.startup_timeout_sec !== 'number') throw new McpConfigError('invalid-timeout', 'startup_timeout_sec') + const ms = srv.startup_timeout_sec === undefined ? srv.startup_timeout_ms : srv.startup_timeout_sec * 1000 + return timeout(ms, timeout(config.mcpStartupTimeoutMs, 20000, 'mcpStartupTimeoutMs'), 'startup_timeout_sec') +} +export function toMcpClientConfig(name, srv, env = process.env) { + if (!record(srv)) throw new McpConfigError('invalid-server') + if (srv.enabled !== undefined && typeof srv.enabled !== 'boolean') throw new McpConfigError('invalid-field', 'enabled') + if (srv.enabled === false) return null + if (!/^[A-Za-z0-9_-]{1,32}$/u.test(name)) throw new McpConfigError('invalid-server-name') + for (const field of ['enabled_tools', 'disabled_tools', 'tool_approval']) { + if (srv[field] !== undefined && !(field === 'disabled_tools' && Array.isArray(srv[field]) && srv[field].length === 0)) throw new McpConfigError('unsupported-tool-policy', field) + } + if (srv.tool_timeout_sec !== undefined && typeof srv.tool_timeout_sec !== 'number') throw new McpConfigError('invalid-timeout', 'tool_timeout_sec') + const toolMs = srv.tool_timeout_sec === undefined ? 60000 : srv.tool_timeout_sec * 1000 + const common = { serverName: name, toolCallTimeoutMs: timeout(toolMs, 60000, 'tool_timeout_sec') } + if (srv.command !== undefined) { + if (typeof srv.command !== 'string' || !srv.command.trim() || srv.url !== undefined) throw new McpConfigError('invalid-field', 'command/url') + const extra = dictionary(srv.env ?? {}, 'env') + for (const key of strings(srv.env_vars ?? [], 'env_vars')) { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) throw new McpConfigError('invalid-env-name') + if (!Object.hasOwn(extra, key) && typeof env[key] === 'string') extra[key] = env[key] + } + let cwd + if (srv.cwd !== undefined) { + if (typeof srv.cwd !== 'string' || !srv.cwd) throw new McpConfigError('invalid-field', 'cwd') + cwd = srv.cwd.startsWith('~/') ? join(homedir(), srv.cwd.slice(2)) : srv.cwd + if (!isAbsolute(cwd)) throw new McpConfigError('relative-cwd-not-portable') + } + return { ...common, transport: 'stdio', command: srv.command, args: strings(srv.args ?? [], 'args'), env: extra, ...(cwd ? { cwd } : {}) } + } + if (typeof srv.url === 'string') { + let url + try { url = new URL(srv.url) } catch { throw new McpConfigError('invalid-field', 'url') } + if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) throw new McpConfigError('invalid-field', 'url') + const headers = {} + const setHeader = (name, value) => { + for (const key of Object.keys(headers)) if (key.toLowerCase() === name.toLowerCase()) delete headers[key] + headers[name] = value + } + for (const [name, value] of Object.entries(dictionary(srv.http_headers ?? {}, 'http_headers'))) setHeader(name, value) + for (const [name, variable] of Object.entries(dictionary(srv.env_http_headers ?? {}, 'env_http_headers'))) setHeader(name, envValue(variable, env)) + if (srv.bearer_token_env_var !== undefined) setHeader('Authorization', `Bearer ${envValue(srv.bearer_token_env_var, env)}`) + return { ...common, transport: 'streamable-http', url: srv.url, headers } + } + throw new McpConfigError('unsupported-transport') +} +export function isReverseBridge(name, srv) { + if (HARD_DENY.has(name)) return true + const base = value => String(value).split(/[\\/]/u).at(-1).replace(/\.(?:exe|cmd)$/iu, '') + const command = base(srv.command ?? '') + const args = Array.isArray(srv.args) ? srv.args.filter(v => typeof v === 'string') : [] + const bridge = /^(?:dsh-codex-sync(?:\.js)?|dsh-plugins-runtime)(?:@[^/\\]+)?$/u + if (bridge.test(command)) return true + if (/^node(?:js)?$/u.test(command)) return bridge.test(base(args[0] ?? '')) + if (/^(?:npx|npm|pnpm|bunx)$/u.test(command)) { + const entry = args.filter(value => !value.startsWith('-') && !['exec', 'dlx'].includes(value))[0] + return entry !== undefined && bridge.test(entry) + } + return false +} +/** Never serialize upstream error.message/cause: it can contain URLs, headers or TOML. */ +export function safeMcpError(error) { + if (error instanceof McpConfigError || error instanceof RuntimeCompatibilityError) return error.message + if (error?.name === 'AbortError') return 'cancelled' + if (error?.code === 'ENOENT') return 'config-missing (last-good connections retained)' + if (error?.code === 'EACCES' || error?.code === 'EPERM') return 'config-unreadable (last-good connections retained)' + return 'MCP connection failed' +} diff --git a/lib/mcp-lifecycle.js b/lib/mcp-lifecycle.js new file mode 100644 index 0000000..1e3ff72 --- /dev/null +++ b/lib/mcp-lifecycle.js @@ -0,0 +1,99 @@ +/** Cordis lifecycle adapter shared by explicit and mirrored MCP clients. */ +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { McpConfigError } from './mcp-config.js' +import { prepareNativeMcp, RuntimeCompatibilityError } from './runtime-compat.js' + +export async function loadMcpClient(ctx) { + // Desktop bundles live inside ASAR; linked plugins must resolve shipped + // modules through the Host Loader, not an application-specific absolute path. + const fixture = process.env.DSH_CX_SYNC_MCP_CLIENT_DIR + if (!fixture) { + const loader = ctx.get?.('loader') + if (loader && typeof loader.import !== 'function') throw new RuntimeCompatibilityError('host-loader-api-unsupported') + if (loader) { + try { + return await loader.import('@deepseek-ai/dsh-mcp-client') + } catch { /* npm/non-Loader installations can still use the optional peer */ } + } + } + try { + const require = createRequire(fixture ? join(fixture, 'package.json') : import.meta.url) + return await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-mcp-client')).href) + } catch { return undefined } +} + +/** + * Bound the entire startup pipeline, including dependency/executable lookup. + * Keep the Fiber immediately; cancellation must close a negotiating transport. + * The optional loader argument is a same-process test seam, never profile data. + */ +export async function launchMcp(ctx, config, { signal, timeoutMs = 20000, load = loadMcpClient, allowWaiting = false } = {}) { + const controller = new AbortController() + let child + let closing + let disposedChild + let rejectCancelled + const cancelled = new Promise((_, reject) => { rejectCancelled = reject }) + const abortError = () => new DOMException('MCP startup cancelled', 'AbortError') + const check = () => { if (controller.signal.aborted) throw abortError() } + const disposeChild = () => { + if (!child) return Promise.resolve() + if (child === disposedChild) return closing ?? Promise.resolve() + const target = child + disposedChild = target + closing = (async () => { + if (typeof target === 'function') await target() + else if (typeof target.dispose === 'function') await target.dispose() + // Repeated Cordis effect disposers can return undefined while teardown is + // already running; Fiber.await still joins that in-flight lifecycle. + if (typeof target.await === 'function') await target.await().catch(() => {}) + })() + return closing + } + const cancel = (error = abortError()) => { + controller.abort() + void disposeChild().catch(() => {}) + rejectCancelled(error) + } + const onAbort = () => cancel() + signal?.addEventListener('abort', onAbort, { once: true }) + if (signal?.aborted) cancel() + const timer = setTimeout(() => cancel(new McpConfigError('startup-timeout')), timeoutMs) + timer.unref?.() + const setup = (async () => { + check() + const module = await load(ctx) + check() + if (!module) throw new McpConfigError('mcp-client-unavailable') + const native = prepareNativeMcp(module, config) + let prepared = native.config + const subprocess = ctx.get?.('subprocess') + if (config.transport === 'stdio' && subprocess !== undefined) { + if (typeof subprocess?.resolveExecutable !== 'function') throw new RuntimeCompatibilityError('subprocess-api-unsupported') + prepared = { ...prepared, command: await subprocess.resolveExecutable(config.command, config.env, controller.signal) } + } + check() + child = ctx.plugin(native.plugin, prepared) + if (typeof child !== 'function' && typeof child?.dispose !== 'function' && typeof child?.then !== 'function') throw new RuntimeCompatibilityError('mcp-lifecycle-unsupported') + if (typeof child?.await === 'function') await child.await() + else if (typeof child?.then === 'function') child = await child + if (controller.signal.aborted) { await disposeChild(); throw abortError() } + // Explicit clients may stand waiting for tools to arrive later. Retain that + // dependency-owned Fiber; only the mirror requires immediate readiness. + if (child?.state !== undefined && child.state !== 2 && !(allowWaiting && child.state === 0)) throw new McpConfigError('mcp-client-inactive') + })() + try { + await Promise.race([setup, cancelled]) + check() + return { dispose: async () => { controller.abort(); await disposeChild() } } + } catch (error) { + controller.abort() + await disposeChild().catch(() => {}) + throw error + } finally { + clearTimeout(timer) + signal?.removeEventListener('abort', onAbort) + } +} diff --git a/lib/mcp.js b/lib/mcp.js index 5b761a6..38a2e2a 100644 --- a/lib/mcp.js +++ b/lib/mcp.js @@ -1,430 +1,266 @@ /** - * MCP mounting for dsh-codex-sync. - * - * Two sources of MCP servers: - * - * A. EXPLICIT โ€” config.mcpServers from the plugin row (see the plugin - * README). Each entry becomes one @deepseek-ai/dsh-mcp-client instance. - * - * B. AUTO MIRROR โ€” read ~/.codex/config.toml's [mcp_servers.*] sections - * (the single source of truth Codex itself uses), mount every portable - * server in dsh, and watch the file for live add/remove/change sync. - * Mapping rules: - * - stdio entries โ†’ transport 'stdio' (command/args/env/cwd) - * - url entries โ†’ transport 'streamable-http' (url + optional - * Authorization header from bearer_token_env_var) - * - enabled=false โ†’ skipped - * - the reverse bridge 'dsh-plugins' is ALWAYS denied (it would - * otherwise recurse: dsh spawning a server that talks back to dsh) - * - names already provided by explicit mcpServers are not mirrored - * (explicit config wins; duplicate serverName fails the later mount) - * - * The client package is an optional peerDependency; if it is missing, both - * sources degrade to a warning instead of failing the plugin. - * - * @module dsh-codex-sync/mcp + * One-way Codex MCP mirroring with per-generation, awaited Cordis ownership. + * Configuration stays in Codex; no profile rewrites or persistent snapshots. */ - -import { readFileSync, watch } from 'node:fs' +import { readFile } from 'node:fs/promises' +import { watch } from 'node:fs' import { join } from 'node:path' import { homedir } from 'node:os' -import { pathToFileURL } from 'node:url' -import { createRequire } from 'node:module' import { effectiveItemSync } from './state.js' +import { HARD_DENY, parseCodexMcpServers, toMcpClientConfig, startupTimeout, isReverseBridge, safeMcpError } from './mcp-config.js' +import { launchMcp } from './mcp-lifecycle.js' +export { parseCodexMcpServers, toMcpClientConfig } from './mcp-config.js' -/** @type {Promise | undefined} */ -let mcpClientModulePromise - -/** - * Load the mcp-client package once (peer optional). - * - * Deliberately NOT a bare-specifier dynamic import: Node negatively caches a - * failed specifier resolution for the whole process, so a package installed - * later (runtime repair, test fixtures) would never be found again. Resolving - * through createRequire().resolve() on every attempt and importing the file - * URL keeps retry semantics; the successful MODULE is still cached. - */ -const requireResolve = createRequire(import.meta.url).resolve -function loadMcpClient() { - if (mcpClientModulePromise === undefined) { - mcpClientModulePromise = Promise.resolve() - .then(() => { - let resolved - if (process.env.DSH_CX_SYNC_MCP_CLIENT_DIR !== undefined) { - // Test seam: resolve from an explicit fixture directory (node --test - // runs test FILES concurrently; each file owns its own fixture). - resolved = createRequire(join(process.env.DSH_CX_SYNC_MCP_CLIENT_DIR, 'package.json')) - .resolve('@deepseek-ai/dsh-mcp-client') - } else { - resolved = requireResolve('@deepseek-ai/dsh-mcp-client') - } - return import(pathToFileURL(resolved).href) - }) - .then( - (mod) => mod.default ?? mod, - () => undefined, - ) - // A failed load resolves to `undefined`; reset so later syncs can retry. - mcpClientModulePromise.then((mod) => { - if (mod === undefined) mcpClientModulePromise = undefined - }, () => { mcpClientModulePromise = undefined }) +export function hardDenyNames() { return new Set(HARD_DENY) } +const shq = token => `'${String(token).replace(/'/gu, `'\\''`)}'` +/** POSIX-only compatibility option; never require /bin/sh on Windows. */ +export function silenceStdio(cfg, platform = process.platform) { + if (cfg.transport !== 'stdio' || platform === 'win32') return cfg + const command = [cfg.command, ...(cfg.args ?? [])].map(shq).join(' ') + return { ...cfg, command: '/bin/sh', args: ['-c', `exec ${command} 2>/dev/null`] } +} +function canonical(value) { + if (Array.isArray(value)) return value.map(canonical) + if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])) + return value +} +function nativeConfig(cfg, requireReady = true) { + return { + ...cfg, failOnStartupError: requireReady, + reconnect: cfg.reconnect ?? { enabled: true, initialDelayMs: 1000, maxDelayMs: 30000, maxAttempts: 2147483647 }, } - return mcpClientModulePromise } -/* โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - * A. Explicit servers (config.mcpServers) - * โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */ - -/** - * Mount one dsh-mcp-client instance per explicitly configured server. - * @param {import('@deepseek-ai/cordis').Context} ctx - * @param {Array<[string, object]>} servers - [serverName, dshMcpClientConfig][]. - */ +/** Explicit clients share the same cancellation/ownership rules as the mirror. */ export async function mountMcpServers(ctx, servers) { - const McpClient = await loadMcpClient() - if (McpClient === undefined) { - ctx.logger?.warn?.('dsh-codex-sync: @deepseek-ai/dsh-mcp-client not installed; skipping mcpServers') - return + const controller = new AbortController() + const handles = new Set() + const timers = new Set() + let stopped = false + const dispose = async () => { + stopped = true + controller.abort() + for (const timer of timers) clearTimeout(timer) + timers.clear() + await Promise.allSettled([...handles].map(handle => handle.dispose())) } - for (const [serverName, cfg] of servers) { + ctx.effect?.(() => dispose, 'codex-sync.explicit-mcp()') + const mountOne = async ([serverName, cfg]) => { + if (stopped) return try { - await ctx.plugin(McpClient, { serverName, ...cfg, failOnStartupError: false }) - ctx.logger?.info?.(`dsh-codex-sync: mounted explicit MCP server "${serverName}"`) + if (!cfg || typeof cfg !== 'object' || isReverseBridge(serverName, cfg)) return + // Explicit clients retain the native supervisor after an initial failure. + // Mirrored clients instead require readiness and own their retry state. + const handle = await launchMcp(ctx, nativeConfig({ ...cfg, serverName }, false), { signal: controller.signal, timeoutMs: 20000, allowWaiting: true }) + if (stopped) await handle.dispose() + else handles.add(handle) } catch (error) { - ctx.logger?.warn?.(`dsh-codex-sync: failed to mount MCP server "${serverName}": ${error?.message ?? error}`) - } - } -} - -/* โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - * B. Auto mirror of ~/.codex/config.toml [mcp_servers.*] - * โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ */ - -/** One server entry parsed from codex config.toml. */ -function newServer(name) { - return { name, args: [], env: {} } -} - -/** - * Minimal TOML-lite parser for codex's [mcp_servers.*] schema. - * @param {string} text - config.toml content. - * @returns {Map} server name โ†’ entry. - */ -export function parseCodexMcpServers(text) { - const servers = new Map() - let current = null - let inEnv = false - for (const rawLine of text.split(/\r?\n/)) { - const line = rawLine.trim() - if (!line || line.startsWith('#')) continue - const header = line.match(/^\[([^\]]+)\]$/) - if (header) { - const path = header[1].trim() - const top = path.match(/^mcp_servers\.([^.]+)$/) - const env = path.match(/^mcp_servers\.([^.]+)\.env$/) - if (top) { - current = servers.get(top[1]) ?? newServer(top[1]) - if (!servers.has(top[1])) servers.set(top[1], current) - inEnv = false - } else if (env) { - current = servers.get(env[1]) ?? newServer(env[1]) - if (!servers.has(env[1])) servers.set(env[1], current) - inEnv = true - } else { - current = null - inEnv = false + if (!stopped) { + ctx.logger?.warn?.(`dsh-codex-sync: explicit MCP ${serverName}: ${safeMcpError(error)}`) + if (['startup-timeout', 'mcp-client-unavailable'].includes(error.code) && cfg?.reconnect?.enabled !== false) { + const timer = setTimeout(() => { timers.delete(timer); void mountOne([serverName, cfg]) }, 30000) + timer.unref?.() + timers.add(timer) + } } - continue - } - if (!current) continue - const kv = line.match(/^([A-Za-z0-9_-]+)\s*=\s*(.*)$/) - if (!kv) continue - const key = kv[1] - const value = kv[2].trim() - let parsed - if (value.startsWith('"')) { - const m = value.match(/^"((?:[^"\\]|\\.)*)"/) - parsed = m ? m[1].replace(/\\(.)/gu, '$1') : value - } else if (value.startsWith('[')) { - const m = value.match(/^\[(.*)\]$/) - parsed = m - ? m[1] - .split(',') - .map((s) => s.trim().replace(/^"(.*)"$/u, '$1').replace(/\\(.)/gu, '$1')) - .filter(Boolean) - : value - } else if (value === 'true' || value === 'false') { - parsed = value === 'true' - } else { - parsed = value.replace(/\s+#.*$/u, '') - } - if (inEnv) current.env[key] = parsed - else current[key] = parsed - } - return servers -} - -/** Interpolate ${VAR} inside a string from process.env. */ -function interpolate(value) { - return String(value).replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu, (_all, name) => process.env[name] ?? '') -} - -/** Map one codex mcp_servers entry to a dsh-mcp-client Config, or null. */ -export function toMcpClientConfig(name, srv) { - if (srv.enabled === false) return null - if (srv.command !== undefined) { - const env = {} - for (const [k, v] of Object.entries(srv.env ?? {})) env[k] = interpolate(v) - return { - transport: 'stdio', - serverName: name, - command: srv.command, - args: Array.isArray(srv.args) ? srv.args : [], - ...(Object.keys(env).length > 0 ? { env } : {}), - ...(typeof srv.cwd === 'string' && srv.cwd.length > 0 ? { cwd: interpolate(srv.cwd) } : {}), - } - } - if (srv.url !== undefined) { - const headers = {} - if (typeof srv.bearer_token_env_var === 'string' && srv.bearer_token_env_var.length > 0) { - const token = process.env[srv.bearer_token_env_var] - if (token) headers.Authorization = `Bearer ${token}` - } - return { - transport: 'streamable-http', - serverName: name, - url: srv.url, - headers, } } - return null -} - -/** Names that must never be mirrored (recursion guard + known-private servers). */ -const HARD_DENY = new Set(['dsh-plugins', 'dsh-plugins-runtime']) - -/** Read-only view of the hard-deny set for UI/command layers. */ -export function hardDenyNames() { - return new Set(HARD_DENY) -} - -/** POSIX single-quote a shell token (safe for any byte sequence). */ -function shq(token) { - return `'${String(token).replace(/'/gu, `'\\''`)}'` + await Promise.all(servers.map(mountOne)) + return { dispose } } -/** - * Re-run a stdio MCP config through `sh -c 'โ€ฆ 2>/dev/null'` so the child's - * stderr (chatty stdio servers like mcp-remote) no longer leaks into the - * host console. The MCP protocol runs on stdin/stdout, so discarding stderr - * is safe; env and cwd propagate through the wrapper. - * @param {object} cfg - dsh-mcp-client stdio config. - * @returns {object} wrapped config, or the input when it is not stdio. - */ -export function silenceStdio(cfg) { - if (cfg.transport !== 'stdio') return cfg - const command = `${shq(cfg.command)}${(cfg.args ?? []).map(shq).join(' ')}` - return { - ...cfg, - command: '/bin/sh', - args: ['-c', `${command} 2>/dev/null`], - } -} - -/** - * Render a mirror status snapshot (from `startMcpMirror().getStatus()`) as - * the /mcp-status command text. Pure function โ€” shared by the handler and - * the test suite. - * @param {{configPath: string, enabled: boolean, lastSyncAt: string|null, servers: Array}} status - * @returns {string} - */ export function formatMcpStatus(status) { const lines = [ `MCP mirror: ${status.enabled ? 'on' : 'off'} ยท ${status.configPath}`, - ...(status.lastSyncAt ? [`last sync: ${status.lastSyncAt}`] : ['last sync: (initial mount in progressโ€ฆ)']), - '', + status.lastSyncAt ? `last sync: ${status.lastSyncAt}` : 'last sync: (initial mount in progressโ€ฆ)', + ...(status.issue ? [`config: ${status.issue}`] : []), '', ] - const byName = [...status.servers].sort((a, b) => a.name.localeCompare(b.name)) - for (const s of byName) { - const flags = [ - s.silent ? 'silent' : null, - s.reason === 'mounted' ? 'โœ“' : null, - ].filter(Boolean).join(' ') - const detail = s.reason === 'failed' ? ` (${s.error ?? 'unknown error'})` : '' - lines.push(`${s.name.padEnd(16)} ${s.transport.padEnd(15)} ${s.reason}${flags ? ' ' + flags : ''}${detail}`) + const rows = [...status.servers].sort((a, b) => a.name.localeCompare(b.name)) + for (const server of rows) { + const flags = [server.silent ? 'silent' : null, server.reason === 'mounted' ? 'โœ“' : null].filter(Boolean).join(' ') + const detail = server.reason === 'failed' ? ` (${server.error ?? 'MCP connection failed'})` : '' + lines.push(`${server.name.padEnd(16)} ${server.transport.padEnd(15)} ${server.reason}${flags ? ' ' + flags : ''}${detail}`) } - lines.push('', `servers: ${byName.length}`, 'hint: /codex-mcp <ๅ> on|off ยท codex config edits live-sync') + lines.push('', `servers: ${rows.length}`, 'hint: /codex-mcp <ๅ> on|off ยท codex config edits live-sync') return lines.join('\n') } /** - * Start the codex MCP auto-mirror: mount portable servers now and live-sync - * on config.toml changes. Returns a disposer that unmounts everything. - * @param {import('@deepseek-ai/cordis').Context} ctx - * @param {object} config - plugin config (mcpMirrorDeny / mcpMirrorOnly / - * mcpMirrorSilent / mcpServers). - * @param {string} codexHome - codex config dir. - * @returns {() => void} disposer. + * Reconcile configuration independently of connection handshakes. A slow beta + * must never postpone revocation of an already-ready alpha. refresh() waits for + * the current generation's starts, but those waits are NOT the reconcile queue. */ -export function startMcpMirror(ctx, codexHome = join(homedir(), '.codex'), config = {}) { +export function startMcpMirror(ctx, codexHome = process.env.CODEX_HOME || join(homedir(), '.codex'), config = {}) { const configPath = join(codexHome, 'config.toml') - const deny = new Set(HARD_DENY) - for (const name of config.mcpMirrorDeny ?? []) deny.add(name) + const deny = new Set([...HARD_DENY, ...(config.mcpMirrorDeny ?? [])]) const only = config.mcpMirrorOnly ? new Set(config.mcpMirrorOnly) : null - const silent = config.mcpMirrorSilent ? new Set(config.mcpMirrorSilent) : null - const explicitNames = new Set(Object.keys(config.mcpServers ?? {})) - - const mounted = new Map() // name โ†’ { cfgJson, dispose } - const status = new Map() // name โ†’ { name, transport, silent, reason, error? } - let lastSyncAt = null - let watcher = null - let debounce = null + const silent = new Set(config.mcpMirrorSilent ?? []) + const explicit = new Set(Object.keys(config.mcpServers ?? {})) + const entries = new Map() + const retiring = new Map() + let status = new Map() let stopped = false + let stopping + let queue = Promise.resolve() + let queued = false + let forceRetry = false + let lastSyncAt = null + let issue = null + let watcher + let debounce + const pollMs = Number.isFinite(config.mcpMirrorPollIntervalMs) ? Math.max(50, Math.min(60000, config.mcpMirrorPollIntervalMs)) : 2000 + const retryMs = 30000 + const isCurrent = entry => !stopped && entries.get(entry.name) === entry && !entry.controller.signal.aborted - function describeTransport(srv) { - if (srv.command !== undefined) return 'stdio' - if (srv.url !== undefined) return 'streamable-http' - return '?' + async function remove(entry) { + entry.controller.abort() + await entry.handle?.dispose() + await entry.task?.catch(() => {}) } - - async function sync() { + function retire(entry) { + entry.controller.abort() + const prior = retiring.get(entry.name) + const task = Promise.all([prior, remove(entry)]) + retiring.set(entry.name, task) + task.then(() => { + if (retiring.get(entry.name) === task) retiring.delete(entry.name) + }, () => { issue = 'MCP teardown failed; replacement namespace remains blocked' }) + return task + } + async function waitForRetirement(entry) { + const barrier = retiring.get(entry.name) + const signal = entry.controller.signal + if (signal.aborted) throw new DOMException('Cancelled', 'AbortError') + if (!barrier) return + let abort + const cancelled = new Promise((_, reject) => { + abort = () => reject(new DOMException('Cancelled', 'AbortError')) + signal.addEventListener('abort', abort, { once: true }) + }) + try { await Promise.race([barrier, cancelled]) } + finally { signal.removeEventListener('abort', abort) } + } + function start(entry) { + entry.row.reason = 'mounting' + delete entry.row.error + entry.task = (async () => { + await waitForRetirement(entry) + return launchMcp(ctx, nativeConfig(entry.cfg), { signal: entry.controller.signal, timeoutMs: entry.timeoutMs }) + })() + .then(async handle => { + if (!isCurrent(entry)) { await handle.dispose(); return } + entry.handle = handle + entry.row.reason = 'mounted' + entry.retryAt = 0 + }, error => { + if (!isCurrent(entry)) return + entry.row.reason = 'failed' + entry.row.error = safeMcpError(error) + entry.retryAt = Date.now() + retryMs + }) + .finally(() => { entry.pending = false }) + entry.pending = true + } + async function reconcile(force) { + let parsed + try { parsed = parseCodexMcpServers(await readFile(configPath, 'utf8')) } + catch (error) { issue = safeMcpError(error); return } if (stopped) return - const McpClient = await loadMcpClient() - if (McpClient === undefined) { - ctx.logger?.warn?.('dsh-codex-sync: @deepseek-ai/dsh-mcp-client not installed; MCP mirror disabled') - return - } - let text - try { - text = readFileSync(configPath, 'utf8') - } catch { - return // config not readable; keep current state - } - const parsed = parseCodexMcpServers(text) const wanted = new Map() - const seen = new Set() + const nextStatus = new Map() for (const [name, srv] of parsed) { - seen.add(name) - const base = { name, transport: describeTransport(srv), silent: silent?.has(name) ?? false } - if (srv.enabled === false) { - status.set(name, { ...base, reason: 'disabled' }) - continue - } - if (deny.has(name)) { - status.set(name, { ...base, reason: 'denied' }) - continue - } - if (only && !only.has(name)) { - status.set(name, { ...base, reason: 'only-filtered' }) - continue - } - // Per-server sync preference (UI / /codex-mcp): user-off hides the - // mirror without touching codex config. Read live so toggles hot-apply. - if (!effectiveItemSync('mcp', name)) { - status.set(name, { ...base, reason: 'user-disabled' }) - continue - } - if (explicitNames.has(name)) { - status.set(name, { ...base, reason: 'explicit-wins' }) - continue - } - let cfg = toMcpClientConfig(name, srv) - if (!cfg) { - status.set(name, { ...base, reason: 'unmapped' }) - continue - } - if (silent?.has(name)) cfg = silenceStdio(cfg) - wanted.set(name, cfg) - // Only brand not-yet-mounted servers as 'mounting'; an already-mounted - // server that survives this pass must keep its 'mounted' status even - // though the mount loop below skips it. - if (!mounted.has(name)) status.set(name, { ...base, reason: 'mounting' }) - } - // drop status rows for servers that disappeared from the config - for (const name of [...status.keys()]) { - if (!seen.has(name)) status.delete(name) - } - - // unmount removed or changed - for (const [name, entry] of mounted) { - const next = wanted.get(name) - if (!next || JSON.stringify(next) !== entry.cfgJson) { + const row = { name, transport: srv.command !== undefined ? 'stdio' : srv.url !== undefined ? 'streamable-http' : '?', silent: silent.has(name) && process.platform !== 'win32' } + if (srv.enabled === false) row.reason = 'disabled' + else if (deny.has(name) || isReverseBridge(name, srv)) row.reason = 'denied' + else if (only && !only.has(name)) row.reason = 'only-filtered' + else if (!effectiveItemSync('mcp', name)) row.reason = 'user-disabled' + else if (explicit.has(name)) row.reason = 'explicit-wins' + else { try { - entry.dispose() - } catch { - /* already disposed */ - } - mounted.delete(name) - ctx.logger?.info?.(`dsh-codex-sync: unmounted mirrored MCP "${name}"`) + let cfg = toMcpClientConfig(name, srv) + if (!cfg) row.reason = 'unmapped' + else { + const timeoutMs = startupTimeout(srv, config) + if (row.silent) cfg = silenceStdio(cfg) + const key = JSON.stringify(canonical([cfg, timeoutMs])) + const old = entries.get(name) + if (old?.key === key) { + wanted.set(name, old) + nextStatus.set(name, old.row) + continue + } + const entry = { name, cfg, key, row, timeoutMs, controller: new AbortController(), retryAt: 0 } + wanted.set(name, entry) + row.reason = 'mounting' + } + } catch (error) { row.reason = 'failed'; row.error = safeMcpError(error) } } + nextStatus.set(name, row) } - // mount new - for (const [name, cfg] of wanted) { - if (mounted.has(name)) continue - try { - const dispose = await ctx.plugin(McpClient, { ...cfg, failOnStartupError: false }) - mounted.set(name, { cfgJson: JSON.stringify(cfg), dispose }) - status.set(name, { name, transport: cfg.transport, silent: silent?.has(name) ?? false, reason: 'mounted' }) - ctx.logger?.info?.(`dsh-codex-sync: mirrored MCP "${name}" from ~/.codex/config.toml`) - } catch (error) { - status.set(name, { name, transport: cfg.transport, silent: silent?.has(name) ?? false, reason: 'failed', error: error?.message ?? String(error) }) - ctx.logger?.warn?.(`dsh-codex-sync: failed to mirror MCP "${name}": ${error?.message ?? error}`) - } + status = nextStatus + // Admit later revisions immediately, even while an unrelated name closes. + // Only replacement startup waits for its own namespace retirement barrier. + for (const [name, old] of entries) if (wanted.get(name) !== old) { + entries.delete(name) + void retire(old) } + if (stopped) return + for (const [name, entry] of wanted) { + entries.set(name, entry) + if (!entry.handle && !entry.pending && (force || entry.retryAt <= Date.now())) start(entry) + } + issue = null lastSyncAt = new Date().toISOString() } - - let syncChain = Promise.resolve() - /** Serialize sync() calls: the initial mount races refresh() calls otherwise. */ - function enqueueSync() { - const run = syncChain.then(() => sync()) - // keep the chain alive regardless of individual failures - syncChain = run.catch(() => {}) - return run - } - - void enqueueSync() - try { - watcher = watch(configPath, () => { - clearTimeout(debounce) - debounce = setTimeout(() => void enqueueSync(), 500) - }) - } catch { - // config.toml does not exist (yet); mirror resumes on the next restart - } - - /** Snapshot of the mirror state for /mcp-status. */ - function getStatus() { - return { - configPath, - enabled: !stopped, - lastSyncAt, - servers: [...status.values()], + function enqueue(force = false) { + if (stopped) return queue + forceRetry ||= force + if (!queued) { + queued = true + queue = queue.then(async () => { + queued = false + const force = forceRetry + forceRetry = false + if (!stopped) await reconcile(force) + }).catch(error => { issue = safeMcpError(error) }) } + return queue.then(() => Promise.allSettled([...entries.values()].map(entry => entry.task).concat([...retiring.values()]))) } - + function armWatcher() { + if (stopped || watcher) return + try { + watcher = watch(codexHome, (_event, file) => { + if (file && String(file) !== 'config.toml') return + clearTimeout(debounce) + debounce = setTimeout(() => { void enqueue() }, 150) + debounce.unref?.() + }) + watcher.on('error', () => { watcher?.close(); watcher = undefined }) + watcher.unref?.() + } catch { /* bounded polling recovers a missing parent or failed watch */ } + } + const interval = setInterval(() => { armWatcher(); void enqueue() }, pollMs) + interval.unref?.() + armWatcher() + void enqueue() return { + refresh: () => enqueue(true), + getStatus: () => ({ configPath, enabled: !stopped, lastSyncAt, issue, servers: [...status.values()].map(row => ({ ...row })) }), dispose() { + if (stopping) return stopping stopped = true + clearInterval(interval) clearTimeout(debounce) - try { - watcher?.close() - } catch { - /* watcher already closed */ - } - for (const [, entry] of mounted) { - try { - entry.dispose() - } catch { - /* ignore */ - } - } - mounted.clear() - status.clear() + watcher?.close() + for (const entry of entries.values()) entry.controller.abort() + stopping = (async () => { + await queue + await Promise.allSettled([...entries.values()].map(remove).concat([...retiring.values()])) + entries.clear() + retiring.clear() + status.clear() + })() + return stopping }, - getStatus, - /** Re-run sync immediately (serialized) โ€” per-item toggles hot-apply. */ - refresh: () => enqueueSync(), } } diff --git a/lib/runtime-compat.js b/lib/runtime-compat.js new file mode 100644 index 0000000..f08cecd --- /dev/null +++ b/lib/runtime-compat.js @@ -0,0 +1,67 @@ +/** Runtime contracts, independent of DSH patch/RC strings. No runtime snapshots. */ +import { isDeepStrictEqual } from 'node:util' + +export class RuntimeCompatibilityError extends Error { + constructor(code) { super(code); this.name = 'RuntimeCompatibilityError'; this.code = code } +} +const record = value => value !== null && typeof value === 'object' && !Array.isArray(value) +const incompatible = () => { throw new RuntimeCompatibilityError('mcp-config-contract-changed') } + +function shape(schema, value) { + if (schema?.type !== 'union') return schema + // The native MCP union is discriminated by transport. Do not guess how a + // future lazy/transform/intersection schema interprets security settings. + if (!Array.isArray(schema.list)) incompatible() + const branches = schema.list.filter(branch => branch.type === 'object' && branch.dict?.transport?.type === 'const' && branch.dict.transport.value === value?.transport) + if (branches.length !== 1) incompatible() + return branches[0] +} +function declared(schema, value, depth = 0) { + schema = shape(schema, value) + if (!schema || depth > 12) incompatible() + if (schema.type === 'object') { + if (!record(value) || !record(schema.dict)) incompatible() + for (const [key, item] of Object.entries(value)) { + if (!Object.hasOwn(schema.dict, key)) incompatible() + declared(schema.dict[key], item, depth + 1) + } + } else if (schema.type === 'dict') { + if (!record(value)) incompatible() + for (const item of Object.values(value)) declared(schema.inner, item, depth + 1) + } else if (schema.type === 'array') { + if (!Array.isArray(value)) incompatible() + for (const item of value) declared(schema.inner, item, depth + 1) + } else if (!['string', 'number', 'boolean', 'const'].includes(schema.type)) incompatible() +} +function preserved(schema, input, output) { + schema = shape(schema, input) + if (schema.type === 'object' && record(output)) { + // Native defaults may grow; every supplied setting must remain effective. + return Object.keys(input).every(key => Object.hasOwn(output, key) && preserved(schema.dict[key], input[key], output[key])) + } + // Opaque env/header maps must not gain ambient credentials. Arrays preserve order. + return isDeepStrictEqual(input, output) +} + +/** Fail before spawning/network I/O if native Config silently stops recognizing a field. */ +export function prepareNativeMcp(module, config) { + const plugin = module?.default ?? module + const Config = plugin?.Config ?? module?.Config + if (!plugin || (typeof plugin !== 'function' && typeof plugin.apply !== 'function') || typeof Config !== 'function') { + throw new RuntimeCompatibilityError('mcp-client-api-unsupported') + } + // Schemastery preserves unknown fields, even nested fields. Successful + // validation/round-trip equality alone therefore cannot establish support. + declared(Config, config) + let prepared + try { prepared = Config(structuredClone(config)) } + catch { throw new RuntimeCompatibilityError('mcp-config-rejected') } + if (!preserved(Config, config, prepared)) incompatible() + return { plugin, config: prepared } +} + +export function assertSkillControl(control) { + if (typeof control?.invalidate !== 'function' || typeof control?.signal?.aborted !== 'boolean' || typeof control.signal.addEventListener !== 'function') { + throw new RuntimeCompatibilityError('skills-provider-control-unsupported') + } +} diff --git a/lib/skill-provider.js b/lib/skill-provider.js index b78e614..d4f8958 100644 --- a/lib/skill-provider.js +++ b/lib/skill-provider.js @@ -1,193 +1,220 @@ /** - * First-class DSH skill provider backed by ~/.codex/skills. - * - * Registers via ctx.skills.registerProvider() so Codex skills appear in the - * normal DSH skill catalog (the `skill` tool can load full SKILL.md bodies, - * and scripts/ under each skill dir resolve through a directory resource - * base). The provider deliberately ranks BELOW dsh's own filesystem provider - * (800 > BUNDLED_SKILL_RANK 600), so a same-named dsh skill always wins. + * Portable, watched DSH skill providers. Codex skills remain lower priority + * within their registration layer (rank 800); nearer Agent layers still win. */ -import { join, dirname } from 'node:path' +import { join, dirname, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { readdirSync, readFileSync } from 'node:fs' -import { parseFrontmatter, sanitizeName } from './bridge.js' -import { effectiveItemSync } from './state.js' +import { readdir, readFile, realpath, stat } from 'node:fs/promises' +import chokidar from 'chokidar' +import { parseDocument } from 'yaml' +import { readSyncGroup, statePath } from './state.js' -/** Provider rank: higher number = lower precedence on name collisions. */ const CODEX_SKILL_RANK = 800 -/** Bundled plugin skill (this package's skills/ dir) โ€” ahead of Codex user skills. */ const PLUGIN_SKILL_RANK = 500 const PLUGIN_SKILLS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'skills') +const MAX_SKILL_BYTES = 1024 * 1024 +const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u -/** - * @param {string} codexHome - Codex config dir. - * @param {object} config - plugin config (maxSkills). - * @param {object} control - SkillProviderControl (signal/invalidate). - * @param {() => boolean} [enabled] - live gate; the provider reports no skills - * while it returns false (Sync settings toggle, hot on next catalog scan). - * @returns {import('@deepseek-ai/dsh-skill').SkillProvider} - */ -export function registerCodexSkillProvider(codexHome, config, control, enabled = () => true) { - const maxSkills = config.maxSkills ?? 100 +function invocationBoolean(value, fallback) { + if (value === undefined) return fallback + if (typeof value === 'boolean') return value + if (typeof value !== 'string' && typeof value !== 'number') throw new Error('invalid skill invocation policy') + const token = String(value).toLowerCase() + if (['true', 'yes', 'on', '1'].includes(token)) return true + if (['false', 'no', 'off', '0'].includes(token)) return false + throw new Error('invalid skill invocation policy') +} - /** Scan ~/.codex/skills: SKILL.md folders or flat .md files. */ - function scan() { - let entries - try { - entries = readdirSync(join(codexHome, 'skills')) - } catch { - return [] - } - const found = [] - for (const entry of entries) { - if (found.length >= maxSkills) break - if (entry.startsWith('.')) continue - // Per-skill sync preference: an explicit off hides the skill entirely. - // Checked on the raw entry name; state keys use the same raw string the - // UI lists, so renamed folders start fresh under the group default. - if (!effectiveItemSync('skill', entry)) continue - const skillFile = join(codexHome, 'skills', entry, 'SKILL.md') - let file = skillFile - try { - readFileSync(file, 'utf8') - } catch { - if (!entry.endsWith('.md')) continue - file = join(codexHome, 'skills', entry) - try { - readFileSync(file, 'utf8') - } catch { - continue - } - } - found.push({ entry, file }) +/** Parse actual YAML, not a line-oriented subset; rejected policies never grant invocation. */ +async function readSkill(file, fallbackName, signal) { + if (signal?.aborted) return undefined + try { + if ((await stat(file)).size > MAX_SKILL_BYTES) return undefined + const text = await readFile(file, { encoding: 'utf8', ...(signal ? { signal } : {}) }) + const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u) + if (!match) return undefined + const document = parseDocument(match[1], { uniqueKeys: true }) + if (document.errors.length) return undefined + const meta = document.toJS({ maxAliasCount: 100 }) + if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return undefined + const name = meta.name ?? fallbackName + if (typeof name !== 'string' || !NAME.test(name)) return undefined + if (typeof meta.description !== 'string' || !meta.description.trim()) return undefined + if (!match[2].trim()) return undefined + return { + name, description: meta.description, + ...(typeof meta.whenToUse === 'string' ? { whenToUse: meta.whenToUse } : {}), + invocation: { + modelInvocable: !invocationBoolean(meta['disable-model-invocation'], false), + userInvocable: invocationBoolean(meta['user-invocable'], true), + }, + metadata: meta, content: match[2], path: await realpath(file), } - return found + } catch (error) { + if (signal?.aborted || ['EACCES', 'EPERM', 'EIO', 'EMFILE', 'ENFILE'].includes(error.code)) throw error + // Invalid YAML, disappeared files and oversized skills are not candidates. + return undefined } +} +async function discover(root) { + let entries + try { entries = await readdir(root, { withFileTypes: true }) } + catch (error) { + if (error.code === 'ENOENT') return [] + throw error // let the registry retain its last-good view on unexpected I/O + } + const files = [] + for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) { + if (entry.name.startsWith('.')) continue + const base = join(root, entry.name) + const isDirectory = entry.isDirectory() || (entry.isSymbolicLink() && await stat(base).then(s => s.isDirectory(), () => false)) + if (isDirectory) files.push({ entry: entry.name, file: join(base, 'SKILL.md'), dir: base }) + else if (entry.name.endsWith('.md')) files.push({ entry: entry.name, file: base, dir: root }) + } + return files +} + +function relevantSkillEvent(root, file) { + const parts = relative(resolve(root), resolve(file)).split(/[\\/]/u) + return parts.length === 1 || (parts.length === 2 && parts[1] === 'SKILL.md') +} + +/** Existing exported factory stays synchronous as required by registerProvider. */ +export function registerCodexSkillProvider(codexHome, config = {}, control, enabled = () => true) { + const root = join(codexHome, 'skills') + const limit = Number.isInteger(config.maxSkills) && config.maxSkills >= 0 ? config.maxSkills : 100 + let closed = false + let closing + let rootWatcher + let stateWatcher + let probe + let checking + let catalogStamp + let nextStampAt = 0 + const state = resolve(statePath()) + const notify = () => { + if (!closed && !control.signal.aborted) control.invalidate?.() + } + const invalidate = () => { + // An observed edit can return to the same stat signature before the next + // probe (add then delete). Re-baseline once so a missed final event heals. + catalogStamp = undefined + notify() + } + const watchOptions = { + depth: 1, ignoreInitial: true, persistent: false, + awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 25 }, + } + const attach = watcher => { + watcher.on('ready', invalidate) + watcher.on('error', invalidate) + return watcher + } + const ensureRoot = () => { + if (closed) return Promise.resolve() + if (checking) return checking + checking = (async () => { + const exists = await stat(root).then(info => info.isDirectory(), error => { + if (error.code === 'ENOENT') return false + throw error + }) + if (closed) return + if (exists && !rootWatcher) { + rootWatcher = attach(chokidar.watch(root, watchOptions)) + rootWatcher.on('all', (_event, file) => { if (relevantSkillEvent(root, file)) invalidate() }) + invalidate() + } else if (!exists && rootWatcher) { + const old = rootWatcher + rootWatcher = undefined + await old.close() + invalidate() + } + // Watch startup and OS event delivery can race with an editor save. A + // metadata-only fallback closes that gap without copying/reading bodies. + if (Date.now() >= nextStampAt) { + nextStampAt = Date.now() + 2000 + const files = [state, ...(await discover(root)).map(entry => entry.file)] + const marks = await Promise.all(files.map(async file => { + const info = await stat(file).catch(error => { if (error.code === 'ENOENT') return undefined; throw error }) + return [file, info?.mtimeMs, info?.ctimeMs, info?.size, info?.ino] + })) + const stamp = JSON.stringify(marks) + if (stamp !== catalogStamp) { catalogStamp = stamp; notify() } + } + })().catch(invalidate).finally(() => { checking = undefined }) + return checking + } + const dispose = () => { + if (closing) return closing + closed = true + clearInterval(probe) + control.signal.removeEventListener?.('abort', dispose) + closing = (async () => { + await checking + await Promise.all([rootWatcher?.close(), stateWatcher?.close()]) + })() + return closing + } + if (!control.signal.aborted && config.watchSkills !== false) { + stateWatcher = attach(chokidar.watch(state, watchOptions)) + stateWatcher.on('all', invalidate) + // A root may not have any existing parent below the home directory yet. + // Probe that fixed root; a slower metadata signature recovers lost events. + probe = setInterval(() => { void ensureRoot() }, 500) + probe.unref?.() + void ensureRoot() + control.signal.addEventListener?.('abort', dispose, { once: true }) + } return { - name: 'codex', - async list() { - if (enabled() === false) return [] + name: 'codex', invalidate, dispose, + async list(options = {}) { + if (closed || control.signal.aborted || enabled() === false) return [] + const group = readSyncGroup('skill') const candidates = [] - for (const { entry, file } of scan()) { - if (control.signal.aborted) return candidates - let content - try { - content = readFileSync(file, 'utf8') - } catch { - continue - } - const { meta, body } = parseFrontmatter(content) - if (body.trim().length === 0) continue - const rawName = meta.name ?? entry.replace(/\.md$/u, '') - const name = sanitizeName(rawName) - candidates.push({ - name, - description: typeof meta.description === 'string' ? meta.description : '', - whenToUse: typeof meta.whenToUse === 'string' ? meta.whenToUse : undefined, - invocation: { modelInvocable: true, userInvocable: true }, - source: 'custom', - provider: 'codex', - rank: CODEX_SKILL_RANK, - locator: { file, dir: join(codexHome, 'skills', entry) }, - path: file, - metadata: meta, - }) + for (const { entry, file, dir } of await discover(root)) { + if (closed || control.signal.aborted || options.signal?.aborted) break + const selected = typeof group.items[entry] === 'boolean' ? group.items[entry] : group.default + if (!selected || candidates.length >= limit) continue + const skill = await readSkill(file, entry.replace(/\.md$/u, ''), options.signal) + if (!skill) continue + const { content, ...summary } = skill + candidates.push({ ...summary, source: 'custom', provider: 'codex', rank: CODEX_SKILL_RANK, locator: { file, dir, entry } }) } return candidates }, - async get(candidate) { - if (control.signal.aborted) return undefined - let content - try { - content = readFileSync(candidate.locator.file, 'utf8') - } catch { - return undefined - } - const { body } = parseFrontmatter(content) - const { locator, ...summary } = candidate - return { - ...summary, - content: body, - resourceBase: { kind: 'directory', path: candidate.locator.dir }, - } + async get(candidate, options = {}) { + if (closed || control.signal.aborted || enabled() === false) return undefined + const { file, dir, entry } = candidate.locator + const group = readSyncGroup('skill') + if (!(typeof group.items[entry] === 'boolean' ? group.items[entry] : group.default)) return undefined + const skill = await readSkill(file, entry.replace(/\.md$/u, ''), options.signal) + if (!skill) return undefined + return { ...skill, source: 'custom', provider: 'codex', resourceBase: { kind: 'directory', path: dir } } }, } } -/** - * Skills shipped inside this npm package (skills//SKILL.md). Always on - * while the plugin is loaded so the agent can operate import / settings / MCP - * without the user opening the Sync menu. - */ +/** Bundled plugin instructions do not need mutable-user-directory watchers. */ export function registerPluginSkillProvider(_codexHome, _config, control) { - function scan() { - let entries - try { - entries = readdirSync(PLUGIN_SKILLS_DIR) - } catch { - return [] - } - const found = [] - for (const entry of entries) { - if (entry.startsWith('.')) continue - const dir = join(PLUGIN_SKILLS_DIR, entry) - const file = join(dir, 'SKILL.md') - try { - readFileSync(file, 'utf8') - } catch { - continue - } - found.push({ entry, file, dir }) - } - return found - } - return { name: 'dsh-codex-sync', - async list() { + async list(options = {}) { const candidates = [] - for (const { entry, file, dir } of scan()) { - if (control.signal.aborted) return candidates - let content - try { - content = readFileSync(file, 'utf8') - } catch { - continue - } - const { meta, body } = parseFrontmatter(content) - if (body.trim().length === 0) continue - const name = sanitizeName(meta.name ?? entry) - candidates.push({ - name, - description: typeof meta.description === 'string' ? meta.description : '', - whenToUse: typeof meta.whenToUse === 'string' ? meta.whenToUse : undefined, - invocation: { modelInvocable: true, userInvocable: true }, - source: 'custom', - provider: 'dsh-codex-sync', - rank: PLUGIN_SKILL_RANK, - locator: { file, dir }, - path: file, - metadata: meta, - }) + for (const { entry, file, dir } of await discover(PLUGIN_SKILLS_DIR)) { + if (control.signal.aborted) break + const skill = await readSkill(file, entry, options.signal) + if (!skill) continue + const { content, ...summary } = skill + candidates.push({ ...summary, source: 'custom', provider: 'dsh-codex-sync', rank: PLUGIN_SKILL_RANK, locator: { file, dir } }) } return candidates }, - async get(candidate) { + async get(candidate, options = {}) { if (control.signal.aborted) return undefined - let content - try { - content = readFileSync(candidate.locator.file, 'utf8') - } catch { - return undefined - } - const { body } = parseFrontmatter(content) - const { locator, ...summary } = candidate - return { - ...summary, - content: body, - resourceBase: { kind: 'directory', path: candidate.locator.dir }, - } + const { file, dir } = candidate.locator + const skill = await readSkill(file, candidate.name, options.signal) + return skill ? { ...skill, source: 'custom', provider: 'dsh-codex-sync', resourceBase: { kind: 'directory', path: dir } } : undefined }, } } diff --git a/locale/en.json b/locale/en.json new file mode 100644 index 0000000..7951ba7 --- /dev/null +++ b/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Codex Sync", + "description": "Mount Codex skills live, mirror enabled MCP servers, and manage Codex/DSH conversation import and export." + } +} diff --git a/locale/zh.json b/locale/zh.json new file mode 100644 index 0000000..04d2043 --- /dev/null +++ b/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Codex ๅŒๆญฅ", + "description": "ๅฎžๆ—ถๆŒ‚่ฝฝ Codex ๆŠ€่ƒฝใ€้•œๅƒๅฏ็”จ็š„ MCP๏ผŒๅนถ็ฎก็† Codex ไธŽ DSH ๅฏน่ฏ็š„ๅฏผๅ…ฅๅฏผๅ‡บใ€‚" + } +} diff --git a/package-lock.json b/package-lock.json index 9fa46e1..86614ac 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,11 @@ "name": "dsh-codex-sync", "version": "1.6.2", "license": "MIT", + "dependencies": { + "chokidar": "4.0.3", + "smol-toml": "1.9.1", + "yaml": "2.9.1" + }, "bin": { "dsh-codex-sync": "bin/dsh-codex-sync.js" }, @@ -18,15 +23,18 @@ "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2", "@deepseek-ai/dsh-session-format-v2-to-v3": "0.1.7-rc.2", "@deepseek-ai/dsh-session-format-v3-to-v4": "0.1.7-rc.2", + "@deepseek-ai/schemastery": "~3.18.5", "react": "^18.3.1", - "react-dom": "^18.3.1" + "react-dom": "^18.3.1", + "semver": "^7.7.2" }, "engines": { + "dsh": "^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0", "node": ">=20" }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2" + "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0 || >=0.2.1-rc.2 <0.3.0-0" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-mcp-client": { @@ -61,9 +69,9 @@ } }, "node_modules/@deepseek-ai/cosmokit": { - "version": "1.8.5", - "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.5.tgz", - "integrity": "sha512-LXsrlem9z8dq4sLflj2yuCuYX7KqhdzF5hZly3eZyuTo8d6oDSOXuEgC5DbQWKW+lksm6zmOutQLsP/ma6wR6A==", + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", "dev": true, "license": "MIT" }, @@ -399,13 +407,13 @@ } }, "node_modules/@deepseek-ai/schemastery": { - "version": "3.18.4", - "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.4.tgz", - "integrity": "sha512-SSXO6tYuyrIqKVbmOnIq0s+riUywYzouFMcnBluHF9n4KMo2G8HvEzhCYj6pj2617/glOjbJuVInJ9hfONsjkg==", + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", "dev": true, "license": "MIT", "dependencies": { - "@deepseek-ai/cosmokit": "~1.8.5", + "@deepseek-ai/cosmokit": "~1.8.6", "@standard-schema/spec": "^1.1.0" } }, @@ -416,6 +424,21 @@ "dev": true, "license": "MIT" }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -463,6 +486,19 @@ "react": "^18.3.1" } }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/scheduler": { "version": "0.23.2", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", @@ -473,6 +509,46 @@ "loose-envify": "^1.1.0" } }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/smol-toml": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", + "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, "node_modules/zod": { "version": "4.6.5", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", diff --git a/package.json b/package.json index ff2f500..26db25a 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,8 @@ "default": "./lib/index.js" }, "./client": "./lib/client.js", + "./locale/*.json": "./locale/*.json", + "./icon": "./icon.svg", "./package.json": "./package.json" }, "files": [ @@ -44,12 +46,18 @@ "cordis.patch.yml", "examples", "docs", + "!docs/*.local.md", + "locale", + "icon.svg", "lib", "skills", "CHANGELOG.md" ], "scripts": { - "test": "node scripts/run-tests.mjs" + "test": "node scripts/run-tests.mjs", + "test:current": "node scripts/run-contract-tests.mjs skills", + "test:native": "node scripts/run-contract-tests.mjs native", + "test:package": "node --test test/package-contents.test.mjs" }, "bin": { "dsh-codex-sync": "bin/dsh-codex-sync.js" @@ -68,19 +76,27 @@ } }, "engines": { - "node": ">=20" + "node": ">=20", + "dsh": "^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0" }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || 0.2.0-rc.2" + "@deepseek-ai/dsh-mcp-client": "^0.0.1-rc.1 || >=0.2.0-rc.2 <0.3.0-0 || >=0.2.1-rc.2 <0.3.0-0" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-mcp-client": { "optional": true } }, + "dependencies": { + "chokidar": "4.0.3", + "smol-toml": "1.9.1", + "yaml": "2.9.1" + }, "devDependencies": { "@deepseek-ai/cordis": "^4.0.1", + "@deepseek-ai/schemastery": "~3.18.5", + "semver": "^7.7.2", "@deepseek-ai/dsh-session-format-catalog": "0.1.7-rc.2", "@deepseek-ai/dsh-session-format-v0-to-v1": "0.1.7-rc.2", "@deepseek-ai/dsh-session-format-v1-to-v2": "0.1.7-rc.2", diff --git a/scripts/run-contract-tests.mjs b/scripts/run-contract-tests.mjs new file mode 100644 index 0000000..400dc87 --- /dev/null +++ b/scripts/run-contract-tests.mjs @@ -0,0 +1,78 @@ +#!/usr/bin/env node +// npm run test:current -- test/current-runtime-rc3 +// npm run test:native -- test/native-runtime-rc3 +// DSH_CONTRACT_FIXTURE selects one known directory; without a selector, run all. +import { execFileSync } from 'node:child_process' +import { existsSync, realpathSync, statSync } from 'node:fs' +import { createRequire } from 'node:module' +import { delimiter, dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = realpathSync(fileURLToPath(new URL('..', import.meta.url))) +const contracts = { + skills: { suite: 'skills-current.test.mjs', fixtures: ['current-runtime', 'current-runtime-rc3'] }, + native: { suite: 'mcp-native.test.mjs', fixtures: ['native-runtime', 'native-runtime-rc3', 'native-runtime-020-rc2'] }, +} + +function contract(kind) { + const definition = Object.hasOwn(contracts, kind) ? contracts[kind] : undefined + if (!definition) throw new Error('Choose a contract suite: skills or native') + return definition +} + +function fixtureDirectory(kind, selector) { + const { fixtures } = contract(kind) + const name = selector === undefined ? fixtures[0] : fixtures.find(name => + selector === name || resolve(root, selector) === join(root, 'test', name)) + if (!name) throw new Error(`Unknown ${kind} fixture: ${selector}. Choose ${fixtures.map(name => `test/${name}`).join(', ')}`) + const directory = join(root, 'test', name) + // npm ci replaces node_modules, so verify the canonical, allowlisted target. + if (realpathSync(directory) !== directory) throw new Error(`Contract fixture must not be a symlink: test/${name}`) + return directory +} + +// Test files use the same allowlist as the runner, not arbitrary module roots. +export function runtimeRequire(kind, selector = process.env.DSH_CONTRACT_FIXTURE) { + return createRequire(join(fixtureDirectory(kind, selector), 'package.json')) +} + +function npmCli() { + if (process.env.npm_execpath) return process.env.npm_execpath + const directories = [dirname(process.execPath), ...(process.env.PATH ?? '').split(delimiter).filter(Boolean)] + for (const directory of directories) { + const candidates = [join(directory, 'node_modules', 'npm', 'bin', 'npm-cli.js'), join(directory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')] + // POSIX npm is normally a symlink to npm-cli.js. Windows npm.cmd is not + // executable without a shell, so use its adjacent npm-cli.js above instead. + if (process.platform !== 'win32' && existsSync(join(directory, 'npm'))) candidates.push(realpathSync(join(directory, 'npm'))) + for (const candidate of candidates) { + if (/\.[cm]?js$/i.test(candidate) && existsSync(candidate) && statSync(candidate).isFile()) return candidate + } + } + throw new Error('Cannot locate the npm CLI; run this contract through npm run test:current or npm run test:native') +} + +function run(kind, selectors) { + const { suite, fixtures } = contract(kind) + if (kind === 'native' && Number(process.versions.node.split('.')[0]) < 24) throw new Error('Native MCP contracts require Node.js 24 or newer') + const selected = selectors.length ? selectors : process.env.DSH_CONTRACT_FIXTURE ? [process.env.DSH_CONTRACT_FIXTURE] : fixtures + // Validate every selector before installing any fixture. + const directories = [...new Set(selected.map(selector => fixtureDirectory(kind, selector)))] + const cli = npmCli() + for (const directory of directories) { + console.log(`[contract:${kind}] ${directory.slice(root.length + 1)}`) + execFileSync(process.execPath, [cli, 'ci', '--ignore-scripts', '--no-audit', '--no-fund', '--registry=https://registry.npmjs.org'], { cwd: directory, stdio: 'inherit' }) + execFileSync(process.execPath, ['--test', join(root, 'test', suite)], { + cwd: root, stdio: 'inherit', env: { ...process.env, DSH_CONTRACT_FIXTURE: directory }, + }) + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { + const [kind, ...selectors] = process.argv.slice(2) + run(kind, selectors) + } catch (error) { + console.error(`[run-contract-tests] ${error.message}`) + process.exitCode = error.status ?? 1 + } +} diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjs index 9bac80a..f5dadcd 100644 --- a/scripts/run-tests.mjs +++ b/scripts/run-tests.mjs @@ -14,6 +14,9 @@ const suites = [ 'test/plugin-skill.test.mjs', 'test/export-codex.test.mjs', 'test/item-sync.test.mjs', + 'test/mcp-live.test.mjs', + 'test/runtime-compat.test.mjs', + 'test/package-contents.test.mjs', 'test/convert-order.test.mjs', 'test/session-repair.test.mjs', 'test/zstd-frame.test.mjs', diff --git a/test/current-runtime-rc3/package-lock.json b/test/current-runtime-rc3/package-lock.json new file mode 100644 index 0000000..64b30b6 --- /dev/null +++ b/test/current-runtime-rc3/package-lock.json @@ -0,0 +1,168 @@ +{ + "name": "codex-sync-current-runtime-rc3-contract", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-sync-current-runtime-rc3-contract", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-skill": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/cordis": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.5.tgz", + "integrity": "sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + }, + "bin": { + "cordis": "bin.js" + }, + "peerDependencies": { + "@deepseek-ai/cordis-plugin-include": "~1.0.10", + "@deepseek-ai/cordis-plugin-loader": "~1.0.6" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis-plugin-include": { + "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/cosmokit": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", + "license": "MIT" + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.1-rc.3.tgz", + "integrity": "sha512-bPpKuu05gZj7gdW15z6PL2dz4+A4MDEafgWOrhexFO7f08g1NeI4fhE4YNOxd8N2ua+tZJjsKCMAIobFMAaGOw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.1-rc.3.tgz", + "integrity": "sha512-7Fq7zS3yQb1J1PsaNmahQ1gHDdsb338UhTkmZCexlNecmc5I44c/PbkHcT5pJ5SO4hnLplJOdDhiIMFpvvyAaw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.3", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-crypto": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.2.1-rc.3.tgz", + "integrity": "sha512-3oCu1zZhbJTzV9TtYXjVUyxc9yOaQOYzxSGQvMuZ/q/O7/1Y1ofIS2j2GETfc79mCoiQIoQAjr2gu/ncXSgALw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-skill": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-skill/-/dsh-skill-0.2.1-rc.3.tgz", + "integrity": "sha512-jQrGCS0D5zg7g4mB95ly1yvWglMUJYx0OMIdxjHqe4X3VRt8TKwVH2Yy0WORI+22w965zZPly39c3teFwWrE2Q==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.1-rc.3.tgz", + "integrity": "sha512-DOuGjmY5dMlXqXqhuXlHNgEVajTLTYuj/EabS5b8IIBC5VN36YDOtyPgaT8aq1+LI7XoReDMUYQRUHCI3SOXqw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.1-rc.3.tgz", + "integrity": "sha512-ycKq2jF0h/iE/gwQFXn7Fx/pdKsVnPe6rkaA8F0SIZ8QfbAK8KcYmpG1Kn9zjwZAWPyb6pLMhD2GI/gXlM7f0Q==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.1-rc.3.tgz", + "integrity": "sha512-AKznKjQmc2JHDQO+DV2Z68zwGrr3+0qAkxNqZE3SnuBTpO7TeTaS7v2cOzQi81EhZUlYFArmKEbmjcsCrsQvvw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.1-rc.3.tgz", + "integrity": "sha512-YyHu30xQBdp7sIr4ZNUliNxm2S9yRNOwdUPiBvfQZ+KaRtekI2j+T8+TFy7qgyBiGM7YYiG0xzJVibS894WIrg==", + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/test/current-runtime-rc3/package.json b/test/current-runtime-rc3/package.json new file mode 100644 index 0000000..a26c72e --- /dev/null +++ b/test/current-runtime-rc3/package.json @@ -0,0 +1,10 @@ +{ + "name": "codex-sync-current-runtime-rc3-contract", + "private": true, + "type": "module", + "description": "Isolated DSH 0.2.1-rc.3 Skills contract fixture; never distributed with the plugin.", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-skill": "0.2.1-rc.3" + } +} diff --git a/test/current-runtime/package-lock.json b/test/current-runtime/package-lock.json new file mode 100644 index 0000000..5a089cd --- /dev/null +++ b/test/current-runtime/package-lock.json @@ -0,0 +1,168 @@ +{ + "name": "codex-sync-current-runtime-contract", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-sync-current-runtime-contract", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-skill": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/cordis": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.5.tgz", + "integrity": "sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + }, + "bin": { + "cordis": "bin.js" + }, + "peerDependencies": { + "@deepseek-ai/cordis-plugin-include": "~1.0.10", + "@deepseek-ai/cordis-plugin-loader": "~1.0.6" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis-plugin-include": { + "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/cosmokit": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", + "license": "MIT" + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.1-rc.2.tgz", + "integrity": "sha512-T2kcygikRS8rv8cKjgho2x381EgGprv5yQmvHl4/iYbuHE19OW+SLGtHWbV27PGdSHz5U8CJxasYzFosKW4e2A==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.1-rc.2.tgz", + "integrity": "sha512-3xfoMDHEpUJGcH2Lu+lNXUJYRBclYfBkdCG9Au02VzIjYAm9BrFmc/MNuaVTg0vwgvPpTsd6Fx1IeGtfmQFvlg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-crypto": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.2.1-rc.2.tgz", + "integrity": "sha512-CVGPI4lzmUy7O3zg8X1LavUSmD3JKFkUdykfHN7VkyWXG5oAXSvig9s5PLnIb+sxRItmSpiqPXGnT/48X1T1qg==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-skill": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-skill/-/dsh-skill-0.2.1-rc.2.tgz", + "integrity": "sha512-lB9mB0zG+H6oUSvDllF3QJ5yHIm+QAlCu8/nsWdvQV0APAjBJDrwH/u7A0n9La5T2VbsoGEIjWivmLcJmMFg7w==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.1-rc.2.tgz", + "integrity": "sha512-R75r+GkYP+ZhtIsIfn8MMuRXPkugJr0OyQ1Y+rauoTae2sdVfnE8v5zvQORRCHdh7MiOcmh10dQN70KjHh7qhQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.1-rc.2.tgz", + "integrity": "sha512-rtsHJHGE9SWX+zOgtDbPUqz3h7r+qFm3h1WASzRJxDnULqo7JaBdIiGshNTFPmetsX+r1T69CKFdTZAJmHwMug==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.1-rc.2.tgz", + "integrity": "sha512-V4SxvXL4ZbY5RYJckVtmo3qz4YsA52pYKvDF13+8hsDCEmQIv9YfmLRMA61pjK/i05pGMe3p1pPhAB6L+NOIEA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.1-rc.2.tgz", + "integrity": "sha512-mgnByPadOgZtoBxbwMI184li494O6sNn66/NvdqN0RIrzAJmFGpFxpjFkQtQN/yetwWhlx7Ic17+6p7eKl8DNg==", + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/test/current-runtime/package.json b/test/current-runtime/package.json new file mode 100644 index 0000000..c56d611 --- /dev/null +++ b/test/current-runtime/package.json @@ -0,0 +1,10 @@ +{ + "name": "codex-sync-current-runtime-contract", + "private": true, + "type": "module", + "description": "Isolated current-DSH contract fixtures; never distributed with the plugin.", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-skill": "0.2.1-rc.2" + } +} diff --git a/test/host.smoke.mjs b/test/host.smoke.mjs index f714a99..0c41a42 100644 --- a/test/host.smoke.mjs +++ b/test/host.smoke.mjs @@ -44,25 +44,31 @@ test('state: persisted settings override config defaults (DSH_HOME temp)', async assert.equal(raw.autoImport, true) assert.equal(raw.enableInstructions, false) } finally { - process.env.DSH_HOME = prevHome ?? '' + if (prevHome === undefined) delete process.env.DSH_HOME + else process.env.DSH_HOME = prevHome rmSync(tempHome, { recursive: true, force: true }) } }) -const FAKE = join(PROJECT, 'node_modules', '@deepseek-ai', 'dsh-mcp-client') - +let fakeRoot +let FAKE function installFakeMcpClient() { + fakeRoot = mkdtempSync(join(tmpdir(), 'cx-sync-host-mcp-')) + FAKE = join(fakeRoot, 'node_modules', '@deepseek-ai', 'dsh-mcp-client') + process.env.DSH_CX_SYNC_MCP_CLIENT_DIR = fakeRoot mkdirSync(FAKE, { recursive: true }) writeFileSync(join(FAKE, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-mcp-client', version: '0.0.0-fake', type: 'module', main: 'index.js' })) - writeFileSync(join(FAKE, 'index.js'), 'export default class FakeMcpClient { constructor() {} }\n') + writeFileSync(join(FAKE, 'index.js'), `export { Config } from ${JSON.stringify(new URL('./mcp-schema-fixture.mjs', import.meta.url).href)};\nexport default class FakeMcpClient { constructor() {} }\n`) } function removeFakeMcpClient() { - // remove ONLY the fake fixture package โ€” never the whole @deepseek-ai scope - // (it also contains real deps like cordis / schemastery) - rmSync(FAKE, { recursive: true, force: true }) + // Only the uniquely-created OS-temporary fixture; never an installed peer. + assert.ok(fakeRoot?.startsWith(join(tmpdir(), 'cx-sync-host-mcp-'))) + rmSync(fakeRoot, { recursive: true, force: true }) } test('host plugin: commands, invocation args, auto-import persistence, mirror status', async (t) => { + const previous = { home: process.env.DSH_HOME, fixture: process.env.DSH_CX_SYNC_MCP_CLIENT_DIR, token: process.env.CODEX_SYNC_FIXTURE_TOKEN } process.env.DSH_HOME = mkdtempSync(join(tmpdir(), 'cx-sync-test-')) + process.env.CODEX_SYNC_FIXTURE_TOKEN = 'synthetic-test-token' installFakeMcpClient() // Hermetic mirror fixture: a throwaway codex config so the mirror never // reads the real ~/.codex/config.toml (which changes as the user adds MCP @@ -74,7 +80,7 @@ test('host plugin: commands, invocation args, auto-import persistence, mirror st [mcp_servers.cloudflare-api] type = "streamable-http" url = "https://mcp.cloudflare.com/mcp" -bearer_token_env_var = "CLOUDFLARE_API_TOKEN" +bearer_token_env_var = "CODEX_SYNC_FIXTURE_TOKEN" [mcp_servers.exa] type = "stdio" command = "exa" @@ -228,8 +234,15 @@ command = "computer" assert.equal(typeof getMcpStatus.data.autoImport, 'boolean') } finally { // closing the mirror's fs.watch lets the event loop drain (no runner hang) - try { mirror?.dispose?.() } catch { /* ignore */ } + await mirror?.dispose?.() removeFakeMcpClient() + const testHome = process.env.DSH_HOME + assert.ok(testHome.startsWith(join(tmpdir(), 'cx-sync-test-'))) + rmSync(testHome, { recursive: true, force: true }) + for (const [key, value] of [['DSH_HOME', previous.home], ['DSH_CX_SYNC_MCP_CLIENT_DIR', previous.fixture], ['CODEX_SYNC_FIXTURE_TOKEN', previous.token]]) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } } }) diff --git a/test/item-sync.test.mjs b/test/item-sync.test.mjs index 6f450b1..450453a 100644 --- a/test/item-sync.test.mjs +++ b/test/item-sync.test.mjs @@ -99,6 +99,7 @@ command = "echo" mkdirSync(fakeDir, { recursive: true }) writeFileSync(join(fakeDir, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-mcp-client', version: '0.0.0-fake', type: 'module', main: 'index.js' })) writeFileSync(join(fakeDir, 'index.js'), ` +export { Config } from ${JSON.stringify(new URL('./mcp-schema-fixture.mjs', import.meta.url).href)}; export default class FakeMcpClient { constructor(opts) { this.opts = opts; FakeMcpClient.instances.push(this) } } diff --git a/test/live-helpers.mjs b/test/live-helpers.mjs new file mode 100644 index 0000000..26e42b1 --- /dev/null +++ b/test/live-helpers.mjs @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict' +import { mkdtemp, realpath, rm } from 'node:fs/promises' +import { basename, dirname, join } from 'node:path' +import { tmpdir } from 'node:os' + +export const delay = ms => new Promise(resolve => setTimeout(resolve, ms)) +export function deferred() { let resolve; const promise = new Promise(r => { resolve = r }); return { promise, resolve } } +export async function eventually(check, timeout = 5000) { + const deadline = Date.now() + timeout + while (!await check()) { if (Date.now() > deadline) throw new Error('fixture condition timed out'); await delay(15) } +} +export async function temporary(t) { + const root = await realpath(await mkdtemp(join(tmpdir(), 'codex-sync-contract-'))) + const disposers = [] + t.after(async () => { + for (const dispose of disposers.reverse()) await dispose() + // Verify canonical ownership immediately before removing a computed path. + assert.equal(await realpath(root), root) + assert.equal(dirname(root), await realpath(tmpdir())) + assert.ok(basename(root).startsWith('codex-sync-contract-')) + await rm(root, { recursive: true, force: true }) + }) + return { root, own: dispose => disposers.push(dispose) } +} +export function environment(t, patch) { + const before = Object.fromEntries(Object.keys(patch).map(key => [key, process.env[key]])) + Object.assign(process.env, patch) + t.after(() => { for (const [key, value] of Object.entries(before)) { + if (value === undefined) delete process.env[key] + else process.env[key] = value + } }) +} diff --git a/test/mcp-live.test.mjs b/test/mcp-live.test.mjs new file mode 100644 index 0000000..d7d37cd --- /dev/null +++ b/test/mcp-live.test.mjs @@ -0,0 +1,173 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdir, writeFile, rename } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import { parseCodexMcpServers, toMcpClientConfig, silenceStdio, startMcpMirror } from '../lib/mcp.js' +import { startupTimeout, safeMcpError, isReverseBridge } from '../lib/mcp-config.js' +import { launchMcp } from '../lib/mcp-lifecycle.js' +import { Config } from './mcp-schema-fixture.mjs' +import { temporary, environment, eventually, deferred, delay } from './live-helpers.mjs' + +const server = (name, argument = 'ok') => `[mcp_servers.${name}]\ncommand='synthetic-executable'\nargs=['${argument}']\n` +function runtime() { + const ctx = new Context() + const active = new Set() + const calls = [] + const entered = new Map() + const closures = new Map() + const plugin = { name: 'mcp-contract-fixture', Config, async apply(inner, cfg) { + if (active.has(cfg.serverName)) throw new Error('duplicate fixture namespace') + active.add(cfg.serverName); calls.push(`start:${cfg.serverName}:${cfg.args[0]}`) + inner.effect(() => async () => { + if (cfg.args[0] === 'slow-close') { const gate = deferred(); closures.set(cfg.serverName, gate); await gate.promise } + await delay(2); active.delete(cfg.serverName); calls.push(`stop:${cfg.serverName}`) + }) + if (cfg.args[0] === 'pending') { + const gate = deferred(); entered.set(cfg.serverName, gate) + inner.on('internal/plugin', fiber => { if (fiber === inner.fiber && fiber.uid === null) gate.resolve() }, { global: true }) + await gate.promise + } + if (cfg.args[0] === 'failure') throw new Error('synthetic-sensitive-error') + } } + ctx.provide('loader', { import: async () => plugin }) + return { ctx, plugin, active, calls, entered, closures } +} + +test('full TOML: quoted names, literal Windows paths, multiline/comma args and disabled comments', () => { + const parsed = parseCodexMcpServers(`[mcp_servers."quoted.name"]\ncommand='C:\\tools\\mcp.exe'\nargs=[\n 'one,two', # comment\n 'three',\n]\nenv={ TOKEN='synthetic' }\n[mcp_servers.off]\ncommand='x'\nenabled=false # disabled\n`) + assert.deepEqual(parsed.get('quoted.name').args, ['one,two', 'three']) + assert.equal(parsed.get('quoted.name').command, 'C:\\tools\\mcp.exe') + assert.equal(parsed.get('quoted.name').env.TOKEN, 'synthetic') + assert.equal(toMcpClientConfig('off', parsed.get('off')), null) + assert.throws(() => toMcpClientConfig('quoted.name', parsed.get('quoted.name')), /invalid-server-name/) +}) +test('TOML failures do not include source excerpts', () => { + try { parseCodexMcpServers('sensitive="synthetic-secret"\n[broken') } catch (error) { + assert.equal(error.message, 'invalid-toml') + assert.ok(!safeMcpError(error).includes('synthetic-secret')) + } +}) +test('stdio mapping preserves literal env and only forwards named present variables', () => { + const mapped = toMcpClientConfig('stdio', { command: 'fixture', env: { X: '${LITERAL}' }, env_vars: ['TOKEN', 'ABSENT'] }, { TOKEN: 'synthetic', AMBIENT_SECRET: 'not-forwarded' }) + assert.deepEqual(mapped.env, { X: '${LITERAL}', TOKEN: 'synthetic' }) + assert.throws(() => toMcpClientConfig('bad', { command: 'x', args: 'not-an-array' }), /invalid-field/) + assert.throws(() => toMcpClientConfig('bad', { command: 'x', enabled: 'false' }), /invalid-field/) + assert.throws(() => toMcpClientConfig('bad', { command: 'x', cwd: 'relative' }), /relative-cwd/) +}) +test('HTTP mapping includes static/env headers and fail-closes missing bearer variables', () => { + const mapped = toMcpClientConfig('http', { url: 'https://example.invalid/mcp', http_headers: { 'X-Static': 'static', authorization: 'old' }, env_http_headers: { 'X-Env': 'VALUE' }, bearer_token_env_var: 'TOKEN' }, { VALUE: 'value', TOKEN: 'synthetic' }) + assert.deepEqual(mapped.headers, { 'X-Static': 'static', 'X-Env': 'value', Authorization: 'Bearer synthetic' }) + assert.throws(() => toMcpClientConfig('http', { url: 'https://example.invalid', bearer_token_env_var: 'ABSENT' }, {}), /missing-env/) +}) +test('environment HTTP headers replace static spellings case-insensitively', () => { + const cfg = toMcpClientConfig('headers', { url: 'https://example.invalid', http_headers: { Authorization: 'old' }, env_http_headers: { authorization: 'TOKEN' } }, { TOKEN: 'synthetic-correct-token' }) + assert.equal(new Headers(cfg.headers).get('authorization'), 'synthetic-correct-token') +}) +test('reverse detection checks launch entrypoints, not unrelated data paths', () => { + assert.equal(isReverseBridge('files', { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', join('synthetic', 'upstream-dsh-codex-sync')] }), false) + assert.equal(isReverseBridge('alias', { command: 'node', args: [join('synthetic', 'dsh-codex-sync.js'), 'serve'] }), true) +}) +test('tool restrictions are never silently broadened; timeouts are bounded', () => { + for (const policy of [{ enabled_tools: [] }, { disabled_tools: ['delete'] }, { tool_approval: {} }]) assert.throws(() => toMcpClientConfig('x', { command: 'x', ...policy }), /unsupported-tool-policy/) + assert.throws(() => startupTimeout({ startup_timeout_sec: 86400 }), /invalid-timeout/) + assert.equal(startupTimeout({ startup_timeout_sec: 0.5 }), 500) +}) +test('silent stdio has correct token boundaries and Windows does not assume /bin/sh', () => { + const cfg = { transport: 'stdio', command: 'fixture command', args: ["a'b", 'two'] } + const silent = silenceStdio(cfg, 'linux') + assert.equal(silent.command, '/bin/sh') + assert.match(silent.args[1], /^exec 'fixture command' /) + assert.match(silent.args[1], /'two' 2>\/dev\/null$/) + assert.equal(silenceStdio(cfg, 'win32'), cfg) +}) + +test('real Cordis Fiber mount/change/off/on/remove retains no namespaces', async t => { + const fixture = await temporary(t); environment(t, { DSH_HOME: fixture.root }) + const r = runtime(); const configPath = join(fixture.root, 'config.toml') + await writeFile(configPath, server('alpha')) + const mirror = startMcpMirror(r.ctx, fixture.root, {}); fixture.own(() => mirror.dispose()) + await mirror.refresh(); assert.ok(r.active.has('alpha')) + const starts = r.calls.length + await mirror.refresh(); assert.equal(r.calls.length, starts) + await writeFile(configPath, server('alpha', 'changed')); await mirror.refresh() + assert.deepEqual(r.calls.slice(-2), ['stop:alpha', 'start:alpha:changed']) + await writeFile(configPath, server('alpha') + 'enabled=false # off\n'); await mirror.refresh() + assert.equal(r.active.size, 0) + await writeFile(configPath, server('alpha')); await mirror.refresh(); assert.equal(r.active.size, 1) + await writeFile(configPath, ''); await mirror.refresh(); assert.equal(r.active.size, 0) + await mirror.dispose(); await mirror.dispose() +}) +test('invalid configuration retains last-good clients and redacts errors', async t => { + const fixture = await temporary(t); environment(t, { DSH_HOME: fixture.root }) + const r = runtime(); const file = join(fixture.root, 'config.toml') + await writeFile(file, server('alpha')) + const mirror = startMcpMirror(r.ctx, fixture.root); fixture.own(() => mirror.dispose()) + await mirror.refresh() + await writeFile(file, 'token="synthetic-secret"\n[broken'); await mirror.refresh() + assert.ok(r.active.has('alpha')); assert.equal(mirror.getStatus().issue, 'invalid-toml') + assert.ok(!JSON.stringify(mirror.getStatus()).includes('synthetic-secret')) +}) +test('a pending beta cannot postpone disabling ready alpha', async t => { + const fixture = await temporary(t); environment(t, { DSH_HOME: fixture.root }) + const r = runtime(); const file = join(fixture.root, 'config.toml') + await writeFile(file, server('alpha')) + const mirror = startMcpMirror(r.ctx, fixture.root); fixture.own(() => mirror.dispose()) + await mirror.refresh() + await writeFile(file, server('alpha') + server('beta', 'pending')) + const pending = mirror.refresh() + await eventually(() => r.entered.has('beta')) + await writeFile(file, server('beta', 'pending')) + const revoked = mirror.refresh() + await eventually(() => !r.active.has('alpha')) + assert.ok(r.active.has('beta')) + await mirror.dispose(); await Promise.all([pending, revoked]) + assert.equal(r.active.size, 0) +}) +test('a slow beta teardown cannot postpone a later alpha revocation', async t => { + const fixture = await temporary(t); environment(t, { DSH_HOME: fixture.root }) + const r = runtime(); const file = join(fixture.root, 'config.toml') + await writeFile(file, server('alpha') + server('beta', 'slow-close')) + const mirror = startMcpMirror(r.ctx, fixture.root) + fixture.own(() => mirror.dispose()) + await mirror.refresh() + let first, second + try { + await writeFile(file, server('alpha')); first = mirror.refresh() + await eventually(() => r.closures.has('beta')) + await writeFile(file, ''); second = mirror.refresh() + await eventually(() => !r.active.has('alpha')) + assert.ok(r.active.has('beta')) + } finally { + r.closures.get('beta')?.resolve() + await Promise.all([first, second]) + } +}) +test('unload while dependency lookup is pending creates no late Fiber', async () => { + const r = runtime(); const gate = deferred(); const controller = new AbortController() + const task = launchMcp(r.ctx, { serverName: 'late', transport: 'stdio', args: ['ok'] }, { signal: controller.signal, timeoutMs: 1000, load: async () => { await gate.promise; return r.plugin } }) + controller.abort(); await assert.rejects(task, /cancelled/) + gate.resolve(); await delay(15) + assert.equal(r.active.size, 0); assert.equal(r.calls.length, 0) +}) +test('startup deadline includes executable resolution, not only plugin startup', async () => { + const r = runtime(); const gate = deferred(); r.ctx.provide('subprocess', { resolveExecutable: async () => { await gate.promise; return 'unused' } }) + const keepAlive = setTimeout(() => {}, 1000) + try { + await assert.rejects(launchMcp(r.ctx, { serverName: 'late', transport: 'stdio', command: 'x', args: ['ok'] }, { timeoutMs: 20 }), /startup-timeout/) + gate.resolve(); await delay(10); assert.equal(r.calls.length, 0) + } finally { clearTimeout(keepAlive) } +}) +test('external saves recover missing roots and repeated atomic replacements', async t => { + const fixture = await temporary(t); environment(t, { DSH_HOME: fixture.root }) + const home = join(fixture.root, 'later'); const file = join(home, 'config.toml'); const r = runtime() + const mirror = startMcpMirror(r.ctx, home, { mcpMirrorPollIntervalMs: 50 }); fixture.own(() => mirror.dispose()) + await mkdir(home); await writeFile(file, server('alpha')) + await eventually(() => r.active.has('alpha')) + for (const argument of ['atomic-one', 'atomic-two']) { + const from = join(home, 'config.new'); await writeFile(from, server('alpha', argument)) + assert.equal(resolve(from), join(home, 'config.new')); assert.equal(resolve(file), join(home, 'config.toml')) + await rename(from, file) + await eventually(() => r.calls.includes(`start:alpha:${argument}`)) + } +}) diff --git a/test/mcp-native.test.mjs b/test/mcp-native.test.mjs new file mode 100644 index 0000000..d94b1e5 --- /dev/null +++ b/test/mcp-native.test.mjs @@ -0,0 +1,76 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { runtimeRequire } from '../scripts/run-contract-tests.mjs' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { launchMcp } from '../lib/mcp-lifecycle.js' +import { mountMcpServers } from '../lib/mcp.js' +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { temporary, eventually } from './live-helpers.mjs' +const require = runtimeRequire('native') +const { Context, Service } = await import(pathToFileURL(require.resolve('@deepseek-ai/cordis')).href) +const { default: Tools } = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-tools')).href) +const native = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-mcp-client')).href) + +test('native current MCP client discovers/calls/unregisters/re-adds a hermetic stdio server', async () => { + const ctx = new Context() + class Prompt extends Service { + constructor(c) { super(c, 'systemPrompt', true) } + tools() { return () => {} } + section() { return () => {} } + getSectionOrder() { return 0 } + } + const prompt = await ctx.plugin(Prompt) + const tools = await ctx.plugin(Tools) + const cfg = { serverName: 'contract', transport: 'stdio', command: process.execPath, args: [fileURLToPath(new URL('./stdio-mcp-fixture.mjs', import.meta.url))], failOnStartupError: true } + let handle + try { + for (let generation = 0; generation < 2; generation++) { + handle = await launchMcp(ctx, cfg, { timeoutMs: 10000, load: async () => native }) + assert.ok(ctx.tools.get('mcp__contract__ping')) + const result = await ctx.tools.execute({ name: 'mcp__contract__ping', arguments: {}, callId: `synthetic-${generation}`, signal: new AbortController().signal }) + assert.equal(result.isError, false) + assert.match(JSON.stringify(result.value), /synthetic-pong/) + await handle.dispose() + assert.equal(ctx.tools.get('mcp__contract__ping'), undefined) + } + } finally { await handle?.dispose(); await tools.dispose(); await prompt.dispose() } +}) + +test('explicit clients keep native reconnection after a transient initial failure', async t => { + const fixture = await temporary(t) + const ctx = new Context() + class Prompt extends Service { + constructor(c) { super(c, 'systemPrompt', true) } + tools() { return () => {} } + section() { return () => {} } + getSectionOrder() { return 0 } + } + const prompt = await ctx.plugin(Prompt) + const tools = await ctx.plugin(Tools) + ctx.provide('loader', { import: async () => native }) + const counter = join(fixture.root, 'counter.txt') + const handle = await mountMcpServers(ctx, [['retry', { transport: 'stdio', command: process.execPath, args: [fileURLToPath(new URL('./retry-mcp-fixture.mjs', import.meta.url)), counter], reconnect: { enabled: true, initialDelayMs: 25, maxDelayMs: 25, maxAttempts: 3 } }]]) + try { + await eventually(() => Boolean(ctx.tools.get('mcp__retry__ping'))) + assert.ok(Number(await readFile(counter, 'utf8')) > 2) + } finally { await handle.dispose(); await tools.dispose(); await prompt.dispose() } +}) + +test('explicit native clients survive tools arriving after their registration', async () => { + const ctx = new Context() + class Prompt extends Service { + constructor(c) { super(c, 'systemPrompt', true) } + tools() { return () => {} } + section() { return () => {} } + getSectionOrder() { return 0 } + } + const prompt = await ctx.plugin(Prompt) + ctx.provide('loader', { import: async () => native }) + const handle = await mountMcpServers(ctx, [['late', { transport: 'stdio', command: process.execPath, args: [fileURLToPath(new URL('./stdio-mcp-fixture.mjs', import.meta.url))] }]]) + let tools + try { + tools = await ctx.plugin(Tools) + await eventually(() => Boolean(ctx.tools.get('mcp__late__ping'))) + } finally { await handle.dispose(); await tools?.dispose(); await prompt.dispose() } +}) diff --git a/test/mcp-schema-fixture.mjs b/test/mcp-schema-fixture.mjs new file mode 100644 index 0000000..921f1ef --- /dev/null +++ b/test/mcp-schema-fixture.mjs @@ -0,0 +1,15 @@ +/** Synthetic native schema; fixtures must exercise the same safety guard as production. */ +import z from '@deepseek-ai/schemastery' + +export function mcpSchema(extra = {}) { + const common = { + serverName: z.string(), toolCallTimeoutMs: z.number(), failOnStartupError: z.boolean(), + reconnect: z.object({ enabled: z.boolean(), initialDelayMs: z.number(), maxDelayMs: z.number(), maxAttempts: z.number() }), + ...extra, + } + return z.union([ + z.object({ ...common, transport: z.const('stdio'), command: z.string(), args: z.array(String).default([]), env: z.dict(String).default({}), cwd: z.string() }), + z.object({ ...common, transport: z.const('streamable-http'), url: z.string(), headers: z.dict(String).default({}) }), + ]) +} +export const Config = mcpSchema() diff --git a/test/native-runtime-020-rc2/package-lock.json b/test/native-runtime-020-rc2/package-lock.json new file mode 100644 index 0000000..137da46 --- /dev/null +++ b/test/native-runtime-020-rc2/package-lock.json @@ -0,0 +1,538 @@ +{ + "name": "codex-sync-native-mcp-020-rc2-contract", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-sync-native-mcp-020-rc2-contract", + "dependencies": { + "@deepseek-ai/cordis": "4.0.4", + "@deepseek-ai/dsh-mcp-client": "0.2.0-rc.2" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@deepseek-ai/cordis": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.4.tgz", + "integrity": "sha512-obgyxqWAmFn3Re8kvsuUnyW+ihrz6eJCnJO4fh1cQzDtmPYz/zzVeUkH9R94I0OwSVOocK67Kgakm04j/oQXzg==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.5", + "@standard-schema/spec": "^1.1.0" + }, + "bin": { + "cordis": "bin.js" + }, + "peerDependencies": { + "@deepseek-ai/cordis-plugin-include": "~1.0.9", + "@deepseek-ai/cordis-plugin-loader": "~1.0.5" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis-plugin-include": { + "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/cosmokit": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", + "license": "MIT" + }, + "node_modules/@deepseek-ai/dsh-agent": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.2.0-rc.2.tgz", + "integrity": "sha512-CUkbU+c1G0ETXkpoLkpAFo5midz66FQGtlgQOP9pzvU9H3zJQVl4H5LrhhGVbEXKLFgdbtQiOynEW8hpWn3y0Q==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2", + "@deepseek-ai/dsh-session": "0.2.0-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2", + "@deepseek-ai/dsh-workspace": "0.2.0-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-workspace": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-attachment": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-attachment/-/dsh-attachment-0.2.0-rc.2.tgz", + "integrity": "sha512-asUDLv+mfb30vjjlQtMI9aBnC+kmPoUxS1ooadhwAd8wssIlLetq97nzC5W1qd0GQGwZtPG/gpljVAMcSwPr1g==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-brand": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.0-rc.2.tgz", + "integrity": "sha512-A5XlN4tIgP0qObkYFhcZ7Oz/tM2oESEZqLwS0Qq+sM1ivGx6o4AMPgJdfKQlwLzqk0cMLNtAaVBHfiYoElt4lw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-http-proxy": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-http-proxy/-/dsh-http-proxy-0.2.0-rc.2.tgz", + "integrity": "sha512-zIGscCHeW6MUIKrksxhW03McWtKKpaDVVMf877bt51ZPP8p4UG8KmBUqJmX2l3eVoHeuuEyqM5zJSCj5NtSBGg==", + "license": "MIT", + "peer": true, + "dependencies": { + "undici": "^8.10.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-invariants": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-invariants/-/dsh-invariants-0.2.0-rc.2.tgz", + "integrity": "sha512-QOVc0HpRsS8ekvprb45FlxieDvgR/cAMaxW289HASjMoV/U/B54FpbkHuPBw4EnTw07/sPkjx2B/23+YqE0cbg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.0-rc.2.tgz", + "integrity": "sha512-6QFrQn/h0iNqCfPpgQidnHtLSpA99A7ZND/uYKaGSd/4BGP8KBhuRd0w63e9s4u+hfW8jc3j29WKcNLIOeUfcA==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.0-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.0-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2", + "@deepseek-ai/dsh-util-crypto": "0.2.0-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2", + "@deepseek-ai/schemastery": "~3.18.4", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-mcp-client": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-mcp-client/-/dsh-mcp-client-0.2.0-rc.2.tgz", + "integrity": "sha512-UqP2sY1r6qAhBPFeuclqrXiMBBxPaCNrXlXRqKxAON7uI1wmZZ0B3/1GmBviQ3/WjjTQlOOkj0su2v4e5DMkug==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2", + "@deepseek-ai/schemastery": "~3.18.4", + "@modelcontextprotocol/client": "2.0.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-attachment": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-mcp-resources": "0.2.0-rc.2", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2", + "@deepseek-ai/dsh-subprocess": "0.2.0-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.0-rc.2", + "@deepseek-ai/dsh-tools": "0.2.0-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-mcp-resources": { + "optional": true + }, + "@deepseek-ai/dsh-system-prompt": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-ptc-runtime": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-ptc-runtime/-/dsh-ptc-runtime-0.2.0-rc.2.tgz", + "integrity": "sha512-HR/3h1VFRcNlAAjCtCAxZ4V3F5pViYicXcLBuYLGjzXWpOhr4zKzeFKh9+UMLjsc9XWIarJMoSvxl662nDV/xQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-sandbox": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox/-/dsh-sandbox-0.2.0-rc.2.tgz", + "integrity": "sha512-luKF7ey6HRZkGhImqLCB5Npt4f4omDRk1r+x5qQNqqdNOuN9LXciKDMNPfnSbHfKCcqSZbH3sK+APOmKzRAhVA==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-session": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox-policy": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox-policy/-/dsh-sandbox-policy-0.2.0-rc.2.tgz", + "integrity": "sha512-0xXVqWw908/V6scohMyyU9SZSiQJYji+S1hMPulcUNLb3iew89d+WPWMIkWQBJRvcJzdQ2ghHwCESRkONXTJnQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-agent": "0.2.0-rc.2", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2", + "@deepseek-ai/dsh-sandbox": "0.2.0-rc.2", + "@deepseek-ai/dsh-session": "0.2.0-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.2.0-rc.2.tgz", + "integrity": "sha512-066p7Wv74GNWt4xA5Cyvl+7c/i9KrNEDALYh2/hu0VsJPLb4T9He+TY7y1bld9OgungmqyTy1n/cB2ZrVskvxA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.2.0-rc.2.tgz", + "integrity": "sha512-wj+6MeqCYbDcbEvKH3puHyEGdjyu51JwBoN6Ua2tz6griLufDgLM5HpSU40L5xgpbOfrYVhXZs4vRgOrMlFY2g==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session-projection": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-projection/-/dsh-session-projection-0.2.0-rc.2.tgz", + "integrity": "sha512-caJ+XGjmR8ouws0LrvuXrabrzi21akB2l8CniUHdx4IpT6GkLapFYlWLbjZlDYqEWB3ktR+q32nxW2s+f27GSA==", + "license": "MIT", + "peer": true, + "dependencies": { + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-session": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-subprocess": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-subprocess/-/dsh-subprocess-0.2.0-rc.2.tgz", + "integrity": "sha512-81ULZG0xg2ZKgrs+R+JY8okUwLp8jjsboR+QsMUMf5WFaJ2PueJ+krbhODB2enLx3MUyMX/wR6msnzi14ZNSAA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-http-proxy": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-system-prompt": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-system-prompt/-/dsh-system-prompt-0.2.0-rc.2.tgz", + "integrity": "sha512-ZZNk2gkXFV8CIT0IOZXS+pFaxNVJaRknYyH2vc4ZgZAiHKT+RqUYNr8e1F5Kp0AaN0DNlcTkjOGP5MCxeXfDjg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.0-rc.2.tgz", + "integrity": "sha512-NDob8b8DJDB/sDPz3P7xhrkxOh1O9FbN1EZRKsxP4fuTfp4hrQU7aekYS5qZENFKoR8dBJMTh/zcEBw4m31glQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-tools": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-tools/-/dsh-tools-0.2.0-rc.2.tgz", + "integrity": "sha512-vquUz8PjHWE4zaS3wH70IpYjL441p2UlUcG8TN2yJZN1RhDkuiHum4bWCsjEPyWLS/aB1QJvzdXC2EK/PRkbsQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.0-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.0-rc.2", + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-agent": "0.2.0-rc.2", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-ptc-runtime": "0.2.0-rc.2", + "@deepseek-ai/dsh-sandbox": "0.2.0-rc.2", + "@deepseek-ai/dsh-sandbox-policy": "0.2.0-rc.2", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2", + "@deepseek-ai/dsh-session": "0.2.0-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2", + "@deepseek-ai/dsh-user-approval": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.0-rc.2.tgz", + "integrity": "sha512-95RvIDcVac2BWdv1IxN6yKlRV+8eEvkofqSxV+d0r8x1kx2EIWEsbdxz6C+coYIm+8e03MiN+rwOt8J7sLfe7Q==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.0-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-user-approval": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-user-approval/-/dsh-user-approval-0.2.0-rc.2.tgz", + "integrity": "sha512-fZMfDp4IeWZMwAKEQkuAYCiGRrwoVWNObvAbpdmQNUavjfYCtwwduWqYQz+5lMQq8vENdczBj7cxnO/pOQ1oZQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4", + "@deepseek-ai/dsh-agent": "0.2.0-rc.2", + "@deepseek-ai/dsh-brand": "0.2.0-rc.2", + "@deepseek-ai/dsh-invariants": "0.2.0-rc.2", + "@deepseek-ai/dsh-llm": "0.2.0-rc.2", + "@deepseek-ai/dsh-scope": "0.2.0-rc.2", + "@deepseek-ai/dsh-session": "0.2.0-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.0-rc.2.tgz", + "integrity": "sha512-5OvvmepY69uXTagUMlnoHqg7euI4ZMifLgfdV8xZO20OslWGGiRCkJbZRyDtcJG9GsXWz9UimfWmUu52zKXJ5w==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.0-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.0-rc.2.tgz", + "integrity": "sha512-qgpsbgiZABuE9UvgNaVo9b2HiWwLeU93CTl9PFXqE0jN8ap1ALxzQsLGvr/q2MJuWDYqnFBg60XnqnY8ZxPWEg==", + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.4" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + } + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz", + "integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/undici": { + "version": "8.12.3", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", + "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/zod": { + "version": "4.6.7", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz", + "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/test/native-runtime-020-rc2/package.json b/test/native-runtime-020-rc2/package.json new file mode 100644 index 0000000..befc585 --- /dev/null +++ b/test/native-runtime-020-rc2/package.json @@ -0,0 +1,11 @@ +{ + "name": "codex-sync-native-mcp-020-rc2-contract", + "private": true, + "type": "module", + "description": "Isolated DSH 0.2.0-rc.2 native SDK contract fixture; never distributed with the plugin.", + "engines": { "node": ">=24" }, + "dependencies": { + "@deepseek-ai/cordis": "4.0.4", + "@deepseek-ai/dsh-mcp-client": "0.2.0-rc.2" + } +} diff --git a/test/native-runtime-rc3/package-lock.json b/test/native-runtime-rc3/package-lock.json new file mode 100644 index 0000000..99d6db4 --- /dev/null +++ b/test/native-runtime-rc3/package-lock.json @@ -0,0 +1,554 @@ +{ + "name": "codex-sync-native-mcp-rc3-contract", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-sync-native-mcp-rc3-contract", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-mcp-client": "0.2.1-rc.3" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@deepseek-ai/cordis": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.5.tgz", + "integrity": "sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + }, + "bin": { + "cordis": "bin.js" + }, + "peerDependencies": { + "@deepseek-ai/cordis-plugin-include": "~1.0.10", + "@deepseek-ai/cordis-plugin-loader": "~1.0.6" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis-plugin-include": { + "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/cosmokit": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", + "license": "MIT" + }, + "node_modules/@deepseek-ai/dsh-agent": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.2.1-rc.3.tgz", + "integrity": "sha512-S6x/deneAsd+pOgecRLM1PC1No9O472kHjS9pS57nuTXi2Vtdo9l7qF+q7PfiHRezL5dxv5gUBQMORPmIYDNvQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/dsh-workspace": "0.2.1-rc.3" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-workspace": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-attachment": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-attachment/-/dsh-attachment-0.2.1-rc.3.tgz", + "integrity": "sha512-JH7sWHhRdyPJri4H0rFcrv1Bv+XYfpTfYV9VwcokTZ7zxieiR7hHwFr4T2EBcuF6Jpg4vaJ2s2Raw+7/d26acg==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-brand": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.1-rc.3.tgz", + "integrity": "sha512-bPpKuu05gZj7gdW15z6PL2dz4+A4MDEafgWOrhexFO7f08g1NeI4fhE4YNOxd8N2ua+tZJjsKCMAIobFMAaGOw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-fs": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-fs/-/dsh-fs-0.2.1-rc.3.tgz", + "integrity": "sha512-tENLWe471WlAXMc13J4cns8xU6lFyu1smwpkSKR85vhGr6FyWZhTlpVohZYm66LbwKTmSWiDhd9Urk7VxN9B9w==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-http-proxy": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-http-proxy/-/dsh-http-proxy-0.2.1-rc.3.tgz", + "integrity": "sha512-q2cci63pnxt+UMlOhqzqaCLTyMxmJ+hGU6GIQ3Dnue4BucWje4FCjO8v9T5CS542afgCDoYRihPCbn7AGiDYRA==", + "license": "MIT", + "peer": true, + "dependencies": { + "undici": "8.11.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.1-rc.3.tgz", + "integrity": "sha512-7Fq7zS3yQb1J1PsaNmahQ1gHDdsb338UhTkmZCexlNecmc5I44c/PbkHcT5pJ5SO4hnLplJOdDhiIMFpvvyAaw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.3", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-crypto": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-mcp-client": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-mcp-client/-/dsh-mcp-client-0.2.1-rc.3.tgz", + "integrity": "sha512-2FM/5OfeLf7/ZP9CsBrkBNnKmSrYY32bYexNnAZ0DroxBiVlC9e1eA6fk5ecrtwt1A4H2AW2nZw6d+IaxHP02Q==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/schemastery": "~3.18.5", + "@modelcontextprotocol/client": "2.2.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-attachment": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-mcp-resources": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3", + "@deepseek-ai/dsh-subprocess": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.3", + "@deepseek-ai/dsh-tools": "0.2.1-rc.3" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-mcp-resources": { + "optional": true + }, + "@deepseek-ai/dsh-system-prompt": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-ptc-runtime": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-ptc-runtime/-/dsh-ptc-runtime-0.2.1-rc.3.tgz", + "integrity": "sha512-nFUzb1abLvCQfUsrp/fMKQMCYU+O+ttiwqUFMa+uO4rFE6Nd+xNjus3V5aaqyy78jdciyBzzNysblZeryJAcXQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox/-/dsh-sandbox-0.2.1-rc.3.tgz", + "integrity": "sha512-7JXzEw2FBNAD3hNhiMzpxCjm8Zedc6DpFfsJfvh1Uh4HuIzX2BFEtzjvEUSwXGSWA+pCZOEvaYD9v0sZoMx3fQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox-policy": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox-policy/-/dsh-sandbox-policy-0.2.1-rc.3.tgz", + "integrity": "sha512-/PlQEx/F6pwjjC/eOEBCHWG9InCu+aSEIC1k9V32noS43B/KS/FRSgP+SZ0YkbjMfk6iyS27sgglJDIY7RG1zQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.3", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.2.1-rc.3.tgz", + "integrity": "sha512-3oCu1zZhbJTzV9TtYXjVUyxc9yOaQOYzxSGQvMuZ/q/O7/1Y1ofIS2j2GETfc79mCoiQIoQAjr2gu/ncXSgALw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-session": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.2.1-rc.3.tgz", + "integrity": "sha512-z1Dfn6yB2YMm9iNThPHaIYCx0Y/mKjm+fMrWFtnPZmX0fJXVmTIr4RAfLF7ZFJk6qd52SUl8d2uX+uNbrPJESg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-session-projection": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-projection/-/dsh-session-projection-0.2.1-rc.3.tgz", + "integrity": "sha512-kyDxXb0avo0m4ZmAb8P+X6T/963NOZCvH/MgrWl3AUs5fHkXA6NfeVnalj488o5RpkRtZdqI7KtCEFNkyKAEsA==", + "license": "MIT", + "peer": true, + "dependencies": { + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-session": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-subprocess": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-subprocess/-/dsh-subprocess-0.2.1-rc.3.tgz", + "integrity": "sha512-gEttULKXWYmJ7+VwV1XX5zchkRuLaDrkxQuMSVIIsRpPZQvciO+uIUBi1bJU1BDyWkKASBqSo0i26tvUTZL45Q==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-http-proxy": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-system-prompt": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-system-prompt/-/dsh-system-prompt-0.2.1-rc.3.tgz", + "integrity": "sha512-2CXnigUF0N2Ps0AG/lOvvY9qeEhvo5uUCGCqvoGrH9IWbhoh/tfvzo9KTa5svyZIBW6mLMAyLyHOdi7f1T9tfg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.1-rc.3.tgz", + "integrity": "sha512-DOuGjmY5dMlXqXqhuXlHNgEVajTLTYuj/EabS5b8IIBC5VN36YDOtyPgaT8aq1+LI7XoReDMUYQRUHCI3SOXqw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-tools": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-tools/-/dsh-tools-0.2.1-rc.3.tgz", + "integrity": "sha512-fHmhIFaztPt9+uvOlk3p4wXMU62F+TRe0ozVPasV3seIsFcxpca74QGSK5dFHICDhKIY1T9MUh0F3itMTdMi3A==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.3", + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-ptc-runtime": "0.2.1-rc.3", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.3", + "@deepseek-ai/dsh-sandbox-policy": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3", + "@deepseek-ai/dsh-user-approval": "0.2.1-rc.3", + "@deepseek-ai/dsh-working-directory": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.1-rc.3.tgz", + "integrity": "sha512-ycKq2jF0h/iE/gwQFXn7Fx/pdKsVnPe6rkaA8F0SIZ8QfbAK8KcYmpG1Kn9zjwZAWPyb6pLMhD2GI/gXlM7f0Q==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-user-approval": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-user-approval/-/dsh-user-approval-0.2.1-rc.3.tgz", + "integrity": "sha512-n2AG2Oh3/32UNStxdkoTOYwheOjSjrJWPj9pPvgISw6vBURPUYrquoVD0AmvmV8TeWpxaCKIGsFNO08yrP9ODw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.3", + "@deepseek-ai/dsh-brand": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-scope": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.1-rc.3.tgz", + "integrity": "sha512-AKznKjQmc2JHDQO+DV2Z68zwGrr3+0qAkxNqZE3SnuBTpO7TeTaS7v2cOzQi81EhZUlYFArmKEbmjcsCrsQvvw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.1-rc.3.tgz", + "integrity": "sha512-YyHu30xQBdp7sIr4ZNUliNxm2S9yRNOwdUPiBvfQZ+KaRtekI2j+T8+TFy7qgyBiGM7YYiG0xzJVibS894WIrg==", + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-working-directory": { + "version": "0.2.1-rc.3", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-working-directory/-/dsh-working-directory-0.2.1-rc.3.tgz", + "integrity": "sha512-Ec/MG+j4jWu/4+ym9UieB2zHt22mwSFfS2s2xZfnoCQIrxkIH5ayVcY1SNttrmHFYDwsyZEG4YY2dzYRtcuIfw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.3", + "@deepseek-ai/dsh-fs": "0.2.1-rc.3", + "@deepseek-ai/dsh-llm": "0.2.1-rc.3", + "@deepseek-ai/dsh-session": "0.2.1-rc.3", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.3", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.3" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + } + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.2.0.tgz", + "integrity": "sha512-LxCou/CSYQ6dwEnjhLZY0KnEuc8V4UJ3IEQCl/uR2yHobSQIEdJKUlKLRYRF5i5FqRGHy1eK7une3aAWDHLtig==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.2.0", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.2.0.tgz", + "integrity": "sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/undici": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz", + "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/test/native-runtime-rc3/package.json b/test/native-runtime-rc3/package.json new file mode 100644 index 0000000..3ee15e3 --- /dev/null +++ b/test/native-runtime-rc3/package.json @@ -0,0 +1,11 @@ +{ + "name": "codex-sync-native-mcp-rc3-contract", + "private": true, + "type": "module", + "description": "Isolated DSH 0.2.1-rc.3 native SDK contract fixture; never distributed with the plugin.", + "engines": { "node": ">=24" }, + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-mcp-client": "0.2.1-rc.3" + } +} diff --git a/test/native-runtime/package-lock.json b/test/native-runtime/package-lock.json new file mode 100644 index 0000000..1a7572c --- /dev/null +++ b/test/native-runtime/package-lock.json @@ -0,0 +1,554 @@ +{ + "name": "codex-sync-native-mcp-contract", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "codex-sync-native-mcp-contract", + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-mcp-client": "0.2.1-rc.2" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@deepseek-ai/cordis": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cordis/-/cordis-4.0.5.tgz", + "integrity": "sha512-Sktq5axy0owk9PdnivBRNOJjHEVEibCt0+TDDZcv0+UH2KS1M910fX4kn5y45YFsrpZIi1mJf/1s5VzywMUnyg==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + }, + "bin": { + "cordis": "bin.js" + }, + "peerDependencies": { + "@deepseek-ai/cordis-plugin-include": "~1.0.10", + "@deepseek-ai/cordis-plugin-loader": "~1.0.6" + }, + "peerDependenciesMeta": { + "@deepseek-ai/cordis-plugin-include": { + "optional": true + }, + "@deepseek-ai/cordis-plugin-loader": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/cosmokit": { + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/@deepseek-ai/cosmokit/-/cosmokit-1.8.6.tgz", + "integrity": "sha512-ZSD/fN52L498LBIOYwjIOlaLv5veY6ZEwI2yzvZUKQtctn0QAPqu8tKdJ+OF5+Tv6NBq1U+wJWH+QI6OGy5EvQ==", + "license": "MIT" + }, + "node_modules/@deepseek-ai/dsh-agent": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-agent/-/dsh-agent-0.2.1-rc.2.tgz", + "integrity": "sha512-e96Tnq8g/RNCDDUW7kAypY/4cho5QxjLHMhk86BGGIEu9b31XEkSFqwqQIwtYXQez3cDR5z7LZpAM8Uqx9Y8KA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/dsh-workspace": "0.2.1-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-workspace": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-attachment": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-attachment/-/dsh-attachment-0.2.1-rc.2.tgz", + "integrity": "sha512-VtSSPYq6cOTZ3kLUAHkjIRq6SOjecfZ4p3lzn1dBU1EcUFJ5fOcN1pM2CLVec4ZYrvMxiB5XwtMeFDQPQ7jgpw==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-brand": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-brand": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-brand/-/dsh-brand-0.2.1-rc.2.tgz", + "integrity": "sha512-T2kcygikRS8rv8cKjgho2x381EgGprv5yQmvHl4/iYbuHE19OW+SLGtHWbV27PGdSHz5U8CJxasYzFosKW4e2A==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-fs": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-fs/-/dsh-fs-0.2.1-rc.2.tgz", + "integrity": "sha512-Z6d2ZKsAiJc0FaiES8wC66vuUQMGohl9tCc2p3bAsPFYkJ0+L2zTViQ9Y5BArtRe9Br8qhNjNgLlN0jb/uwv1g==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-http-proxy": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-http-proxy/-/dsh-http-proxy-0.2.1-rc.2.tgz", + "integrity": "sha512-040QkP/W3F0gcg5aAPPo17evn6+IGb4h9CxYwLVZjgPDQvcc/H86JuquMJ6WfXWtIhcPbfXS1Tb05A8eXspTlg==", + "license": "MIT", + "peer": true, + "dependencies": { + "undici": "8.11.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-llm": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-llm/-/dsh-llm-0.2.1-rc.2.tgz", + "integrity": "sha512-3xfoMDHEpUJGcH2Lu+lNXUJYRBclYfBkdCG9Au02VzIjYAm9BrFmc/MNuaVTg0vwgvPpTsd6Fx1IeGtfmQFvlg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.2", + "@deepseek-ai/dsh-typert-protocol": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-crypto": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-mcp-client": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-mcp-client/-/dsh-mcp-client-0.2.1-rc.2.tgz", + "integrity": "sha512-H5nwrx+krm9nBYKC176bB08Z0Z/+vAuQg0yv9cMpaTUEDvsnM2bBTY5paVaD6Z4YPym4XMNmgoQIpn8CUlNFLw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/schemastery": "~3.18.5", + "@modelcontextprotocol/client": "2.2.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-attachment": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-mcp-resources": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2", + "@deepseek-ai/dsh-subprocess": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2", + "@deepseek-ai/dsh-timeout": "0.2.1-rc.2", + "@deepseek-ai/dsh-tools": "0.2.1-rc.2" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-mcp-resources": { + "optional": true + }, + "@deepseek-ai/dsh-system-prompt": { + "optional": true + } + } + }, + "node_modules/@deepseek-ai/dsh-ptc-runtime": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-ptc-runtime/-/dsh-ptc-runtime-0.2.1-rc.2.tgz", + "integrity": "sha512-e81rbNwp3YNIpzIbkFI4NsWQzTD3uAP8zXU16diL9wLmITUWjMS+kvrWEXtrkWAWp5cnK2Pgn4xCbqVZ6n4I8w==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox/-/dsh-sandbox-0.2.1-rc.2.tgz", + "integrity": "sha512-nnxNIkgi4A4tkPrTV8sbVMse3c32OT0U+mwYhLqDz/+cIm5tUGufQD+Ax0zqVeClyzXsxZo0/pVtcqDJrsp+7w==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-sandbox-policy": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-sandbox-policy/-/dsh-sandbox-policy-0.2.1-rc.2.tgz", + "integrity": "sha512-fBb8zQ13CLKM60ynl3EHvFmO8F0GARofQYf7CXUkqJEuBcjxXUG14rzDKRS/PhE8oJ023lEvd5HJjE6qUjslhw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.2", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-scope": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-scope/-/dsh-scope-0.2.1-rc.2.tgz", + "integrity": "sha512-CVGPI4lzmUy7O3zg8X1LavUSmD3JKFkUdykfHN7VkyWXG5oAXSvig9s5PLnIb+sxRItmSpiqPXGnT/48X1T1qg==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-session": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session/-/dsh-session-0.2.1-rc.2.tgz", + "integrity": "sha512-WDA4lIrXtG5nf1dn2wrA4UzEr7D6e8T3AdPpVSZ7eY4N4ICMDZ0RYuD4GkM+iSb7WkLojdO8ljr0etiIMEbqJg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-session-projection": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-session-projection/-/dsh-session-projection-0.2.1-rc.2.tgz", + "integrity": "sha512-GBGgIAaC+Cw1rV7tpyGy9aaENUOkQCosP+LJHcmzqPWg64Ufts36mDEU3f0lC/nyGb0z66Ov+RbyaLLsCnZMwA==", + "license": "MIT", + "peer": true, + "dependencies": { + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-session": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-subprocess": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-subprocess/-/dsh-subprocess-0.2.1-rc.2.tgz", + "integrity": "sha512-56zNxFUPDFSIHmOaRzcuadXyrGZaFGECqQsLc78d+QIPhFkAN2bXeGIYCo++Ly5SK14FeEtgrYtKpDhRPmBR9g==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-http-proxy": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-system-prompt": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-system-prompt/-/dsh-system-prompt-0.2.1-rc.2.tgz", + "integrity": "sha512-X1WG2FMyfZapAkcCYyTl0UO5vVqDcCsA9wECJY7eeDTLHJDsqrilQJg2DRgHQzM+2/7T01QyzFZhKd7hfALJxg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-timeout": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-timeout/-/dsh-timeout-0.2.1-rc.2.tgz", + "integrity": "sha512-R75r+GkYP+ZhtIsIfn8MMuRXPkugJr0OyQ1Y+rauoTae2sdVfnE8v5zvQORRCHdh7MiOcmh10dQN70KjHh7qhQ==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-tools": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-tools/-/dsh-tools-0.2.1-rc.2.tgz", + "integrity": "sha512-K3gET3VPbtxM66pkeRsEGrZ+bQKiBqrTbNXiIreBKu0hP+qPvlSwhiSI5MTnFp2tMFK5rpuYMZosRIdbfrbJ/g==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-util-values": "0.2.1-rc.2", + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-ptc-runtime": "0.2.1-rc.2", + "@deepseek-ai/dsh-sandbox": "0.2.1-rc.2", + "@deepseek-ai/dsh-sandbox-policy": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2", + "@deepseek-ai/dsh-user-approval": "0.2.1-rc.2", + "@deepseek-ai/dsh-working-directory": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-typert-protocol": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-typert-protocol/-/dsh-typert-protocol-0.2.1-rc.2.tgz", + "integrity": "sha512-rtsHJHGE9SWX+zOgtDbPUqz3h7r+qFm3h1WASzRJxDnULqo7JaBdIiGshNTFPmetsX+r1T69CKFdTZAJmHwMug==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-user-approval": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-user-approval/-/dsh-user-approval-0.2.1-rc.2.tgz", + "integrity": "sha512-pwhw1U1IZZm5tKyPayj2APZBq5I7/I0C0ad+ohd4vKuNb6twDIltt1GEHdCNt7I19IGHLRiUY+/Q9S/8+q5K0A==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.2", + "@deepseek-ai/dsh-brand": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-scope": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/dsh-util-crypto": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-crypto/-/dsh-util-crypto-0.2.1-rc.2.tgz", + "integrity": "sha512-V4SxvXL4ZbY5RYJckVtmo3qz4YsA52pYKvDF13+8hsDCEmQIv9YfmLRMA61pjK/i05pGMe3p1pPhAB6L+NOIEA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-util-values": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-util-values/-/dsh-util-values-0.2.1-rc.2.tgz", + "integrity": "sha512-mgnByPadOgZtoBxbwMI184li494O6sNn66/NvdqN0RIrzAJmFGpFxpjFkQtQN/yetwWhlx7Ic17+6p7eKl8DNg==", + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5" + } + }, + "node_modules/@deepseek-ai/dsh-working-directory": { + "version": "0.2.1-rc.2", + "resolved": "https://registry.npmjs.org/@deepseek-ai/dsh-working-directory/-/dsh-working-directory-0.2.1-rc.2.tgz", + "integrity": "sha512-zhPtvAaCxa9U0WUN9OEG37zVBq7GOXXXwnDx2Jds4DFksGY5Lmpl3ZK1QMGz+F/Aye4VHt9zoISI7m4wDA8DEg==", + "license": "MIT", + "peer": true, + "dependencies": { + "@deepseek-ai/schemastery": "~3.18.5", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "~4.0.5", + "@deepseek-ai/dsh-agent": "0.2.1-rc.2", + "@deepseek-ai/dsh-fs": "0.2.1-rc.2", + "@deepseek-ai/dsh-llm": "0.2.1-rc.2", + "@deepseek-ai/dsh-session": "0.2.1-rc.2", + "@deepseek-ai/dsh-session-projection": "0.2.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2" + } + }, + "node_modules/@deepseek-ai/schemastery": { + "version": "3.18.5", + "resolved": "https://registry.npmjs.org/@deepseek-ai/schemastery/-/schemastery-3.18.5.tgz", + "integrity": "sha512-Mnobvqf9rHsZYv4g5edj5ddxS1oF1kIdSlz0DunUgnY3LWG5F26MqvH3YOOsSaodCgyzJ16OMN9O99/s5Crtdw==", + "license": "MIT", + "dependencies": { + "@deepseek-ai/cosmokit": "~1.8.6", + "@standard-schema/spec": "^1.1.0" + } + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.2.0.tgz", + "integrity": "sha512-LxCou/CSYQ6dwEnjhLZY0KnEuc8V4UJ3IEQCl/uR2yHobSQIEdJKUlKLRYRF5i5FqRGHy1eK7une3aAWDHLtig==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.2.0", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.2.0.tgz", + "integrity": "sha512-iLhmprRmWI8EcosOA3wVvww22z02NkgqhV4fBH6f/odQBsi7xnJc0HGmi21yWO+/iKw2yzqVE127Zhna5/+JXw==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/undici": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.11.2.tgz", + "integrity": "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + } + } +} diff --git a/test/native-runtime/package.json b/test/native-runtime/package.json new file mode 100644 index 0000000..39714df --- /dev/null +++ b/test/native-runtime/package.json @@ -0,0 +1,11 @@ +{ + "name": "codex-sync-native-mcp-contract", + "private": true, + "type": "module", + "description": "Isolated native SDK contract fixture, never distributed with the plugin.", + "engines": { "node": ">=24" }, + "dependencies": { + "@deepseek-ai/cordis": "4.0.5", + "@deepseek-ai/dsh-mcp-client": "0.2.1-rc.2" + } +} diff --git a/test/package-contents.test.mjs b/test/package-contents.test.mjs new file mode 100644 index 0000000..f98e398 --- /dev/null +++ b/test/package-contents.test.mjs @@ -0,0 +1,50 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { gunzipSync } from 'node:zlib' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { temporary } from './live-helpers.mjs' +const ROOT = fileURLToPath(new URL('../', import.meta.url)) +function archiveFiles(bytes) { + const tar = gunzipSync(bytes, { maxOutputLength: 64 * 1024 * 1024 }) + const files = new Map() + for (let offset = 0; offset + 512 <= tar.length;) { + const header = tar.subarray(offset, offset + 512) + if (header.every(byte => byte === 0)) break + const field = (start, length) => header.subarray(start, start + length).toString('utf8').replace(/\0.*$/su, '') + const name = [field(345, 155), field(0, 100)].filter(Boolean).join('/') + const size = parseInt(field(124, 12).trim() || '0', 8) + assert.ok(Number.isSafeInteger(size) && size >= 0 && offset + 512 + size <= tar.length) + if (header[156] === 0 || header[156] === 48) files.set(name.replace(/^package\//u, ''), tar.subarray(offset + 512, offset + 512 + size)) + offset += 512 + Math.ceil(size / 512) * 512 + } + return files +} +test('actual npm tarball contains runtime resources, not local data or credential literals', async t => { + const f = await temporary(t) + const npmCli = process.env.npm_execpath + const npm = npmCli ? process.execPath : process.platform === 'win32' ? 'npm.cmd' : 'npm' + const args = [...(npmCli ? [npmCli] : []), 'pack', '--ignore-scripts', '--json', '--pack-destination', f.root] + const packed = JSON.parse(execFileSync(npm, args, { cwd: ROOT, encoding: 'utf8', ...(!npmCli && process.platform === 'win32' ? { shell: true } : {}) }))[0] + assert.ok(packed.filename && !packed.filename.includes('/') && !packed.filename.includes('\\')) + const files = archiveFiles(await readFile(join(f.root, packed.filename))) + for (const name of ['package.json', 'cordis.patch.yml', 'lib/index.js', 'lib/client.js', 'lib/mcp.js', 'lib/mcp-config.js', 'lib/mcp-lifecycle.js', 'lib/runtime-compat.js', 'lib/skill-provider.js', 'locale/en.json', 'locale/zh.json', 'icon.svg', 'LICENSE', 'NOTICE']) assert.ok(files.has(name), `missing required resource: ${name}`) + assert.match(files.get('icon.svg').toString(), /]*xmlns=/u) + for (const locale of ['en', 'zh']) { + const meta = JSON.parse(files.get(`locale/${locale}.json`)).meta + assert.ok(meta.title && meta.description) + } + for (const [name, bytes] of files) { + assert.doesNotMatch(name, /(?:^|\/)(?:node_modules|test|\.git)(?:\/|$)|runtime-status|\.local\.md$|(?:^|\/)(?:auth\.json|config\.toml|\.npmrc|\.env(?:\..*)?)$|\.tgz$/u) + if (!/\.(?:js|mjs|json|md|ya?ml|svg)$/u.test(name)) continue + const text = bytes.toString('utf8') + assert.ok(!text.includes(homedir()), `home directory leaked in ${name}`) + assert.doesNotMatch(text, /\/Users\/[^\s/'"<>]+|[A-Za-z]:\\Users\\[^\s\\'"<>]+/u, `private user path in ${name}`) + assert.doesNotMatch(text, /gh[pousr]_[A-Za-z0-9]{20,}|AKIA[A-Z0-9]{16}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/u, `credential-shaped literal in ${name}`) + assert.doesNotMatch(text, /session-[0-9a-f]{8}-[0-9a-f-]{27,}/u, `runtime session identity in ${name}`) + } + assert.equal(JSON.parse(files.get('package.json')).name, 'dsh-codex-sync') +}) diff --git a/test/retry-mcp-fixture.mjs b/test/retry-mcp-fixture.mjs new file mode 100644 index 0000000..ba21d45 --- /dev/null +++ b/test/retry-mcp-fixture.mjs @@ -0,0 +1,9 @@ +// Simulate a transient first-probe/first-session failure using one synthetic +// counter owned by the test's verified temporary directory. No network access. +import { readFile, writeFile } from 'node:fs/promises' +const file = process.argv[2] +if (!file) throw new Error('synthetic counter path required') +const previous = await readFile(file, 'utf8').then(Number, () => 0) +await writeFile(file, String(previous + 1)) +if (previous < 2) process.exit(1) +await import('./stdio-mcp-fixture.mjs') diff --git a/test/runtime-compat.test.mjs b/test/runtime-compat.test.mjs new file mode 100644 index 0000000..e48e2a3 --- /dev/null +++ b/test/runtime-compat.test.mjs @@ -0,0 +1,139 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFile, writeFile, mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import semver from 'semver' +import * as bundle from '../lib/index.js' +import { prepareNativeMcp, assertSkillControl, RuntimeCompatibilityError } from '../lib/runtime-compat.js' +import { launchMcp } from '../lib/mcp-lifecycle.js' +import { safeMcpError } from '../lib/mcp-config.js' +import { mcpSchema, Config } from './mcp-schema-fixture.mjs' +import { temporary, environment, eventually } from './live-helpers.mjs' + +const http = { serverName: 'fixture', transport: 'streamable-http', url: 'https://example.invalid/mcp', headers: { Authorization: 'synthetic-secret' }, reconnect: { enabled: true, initialDelayMs: 1000, maxDelayMs: 30000, maxAttempts: 20 } } +const stdio = { serverName: 'fixture', transport: 'stdio', command: 'synthetic-command', args: ['synthetic'], env: { TEST_VALUE: 'synthetic' }, cwd: 'synthetic-cwd' } +const moduleFor = Config => ({ Config, async apply() {} }) + +test('Host compatibility admits a bounded patch/prerelease family without RC pins', async () => { + const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) + for (const version of ['0.0.1-rc.1', '0.2.0-rc.2', '0.2.1-rc.2', '0.2.1-rc.3', '0.2.1-rc.999', '0.2.1', '0.2.2-alpha.1', '0.2.2-rc.1', '0.2.8']) { + assert.equal(semver.satisfies(version, pkg.engines.dsh, { includePrerelease: true }), true, version) + } + for (const version of ['0.2.0-rc.1', '0.3.0-0', '0.3.0-alpha.1', '0.3.0-rc.1', '0.3.0', '1.0.0']) { + assert.equal(semver.satisfies(version, pkg.engines.dsh, { includePrerelease: true }), false, version) + } + // npm's peer matcher does not use the Host's includePrerelease option. + for (const version of ['0.2.0-rc.2', '0.2.1-rc.2', '0.2.1-rc.3', '0.2.1-rc.999']) assert.equal(semver.satisfies(version, pkg.peerDependencies['@deepseek-ai/dsh-mcp-client']), true, version) +}) +test('native namespace/default exports and declared settings remain compatible', () => { + const plugin = async () => {} + const input = structuredClone(http) + const result = prepareNativeMcp({ default: plugin, Config }, input) + assert.equal(result.plugin, plugin) + assert.deepEqual(result.config.headers, input.headers) + assert.deepEqual(input, http) + assert.throws(() => prepareNativeMcp({ apply() {} }, http), /mcp-client-api-unsupported/) +}) +test('passthrough of a removed cwd field cannot masquerade as native support', () => { + const schema = mcpSchema(); delete schema.list[0].dict.cwd + assert.equal(schema(structuredClone(stdio)).cwd, stdio.cwd) + assert.throws(() => prepareNativeMcp(moduleFor(schema), stdio), /mcp-config-contract-changed/) +}) +test('removed nested reconnect fields and unknown transports fail closed', () => { + const schema = mcpSchema({ reconnect: z.object({ initialDelayMs: z.number(), maxDelayMs: z.number(), maxAttempts: z.number() }) }) + assert.equal(schema(structuredClone(http)).reconnect.enabled, true) + assert.throws(() => prepareNativeMcp(moduleFor(schema), http), /mcp-config-contract-changed/) + assert.throws(() => prepareNativeMcp(moduleFor(Config), { ...http, transport: 'unknown' }), /mcp-config-contract-changed/) +}) +test('added native defaults are allowed but explicit env/header maps cannot broaden', () => { + const schema = mcpSchema({ addedDefault: z.boolean().default(true) }) + assert.equal(prepareNativeMcp(moduleFor(schema), http).config.addedDefault, true) + const modified = input => { const output = Config(input); output.headers.EXTRA_CREDENTIAL = 'synthetic'; return output } + Object.assign(modified, { type: Config.type, list: Config.list }) + assert.throws(() => prepareNativeMcp(moduleFor(modified), http), /mcp-config-contract-changed/) +}) +test('native schema errors and unfamiliar schema forms never expose configuration values', () => { + const schema = Object.assign(() => { throw new Error('synthetic-secret') }, { type: Config.type, list: Config.list }) + try { prepareNativeMcp(moduleFor(schema), http); assert.fail('expected rejection') } + catch (error) { assert.equal(safeMcpError(error), 'mcp-config-rejected'); assert.ok(!error.message.includes('synthetic-secret')) } + assert.throws(() => prepareNativeMcp(moduleFor(Object.assign(input => input, { type: 'lazy' })), http), /mcp-config-contract-changed/) +}) +test('unsupported native config is rejected before creating a child or resolving an executable', async () => { + let calls = 0 + const ctx = { get: () => ({ resolveExecutable() { calls++ } }), plugin() { calls++ } } + const schema = mcpSchema(); delete schema.list[0].dict.env + await assert.rejects(launchMcp(ctx, stdio, { load: async () => moduleFor(schema) }), /mcp-config-contract-changed/) + assert.equal(calls, 0) +}) +test('a changed optional stdio resolver does not disable HTTP clients', async () => { + const ctx = new Context(); let starts = 0 + ctx.provide('subprocess', { resolveExecutable: true }) + const native = { Config, async apply() { starts++ } } + await assert.rejects(launchMcp(ctx, stdio, { load: async () => native }), /subprocess-api-unsupported/) + assert.equal(starts, 0) + const handle = await launchMcp(ctx, http, { load: async () => native }) + try { assert.equal(starts, 1) } finally { await handle.dispose() } +}) +test('Skill provider control requires owned cancellation and invalidation', () => { + assert.doesNotThrow(() => assertSkillControl({ signal: new AbortController().signal, invalidate() {} })) + for (const control of [undefined, {}, { signal: new AbortController().signal }, { signal: { aborted: false }, invalidate() {} }]) { + assert.throws(() => assertSkillControl(control), /skills-provider-control-unsupported/) + } +}) + +async function host(t, { skills, native } = {}) { + const f = await temporary(t); environment(t, { DSH_HOME: f.root, CODEX_HOME: f.root }) + await mkdir(join(f.root, 'skills')) + await writeFile(join(f.root, 'skills', 'synthetic.md'), '---\nname: synthetic\ndescription: Synthetic test skill\n---\nfixture body\n') + await writeFile(join(f.root, 'config.toml'), "[mcp_servers.synthetic]\nurl='https://example.invalid/mcp'\n") + const ctx = new Context(); const commands = new Map(); const providers = new Set(); let starts = 0 + ctx.provide('systemPrompt', { section: () => () => {} }) + ctx.provide('commands', { register(row) { commands.set(row.name, row); return () => commands.delete(row.name) } }) + ctx.provide('skills', skills ?? { registerProvider(create) { + const controller = new AbortController() + const provider = create({ signal: controller.signal, invalidate() {} }) + providers.add(provider) + return () => { controller.abort(); providers.delete(provider) } + } }) + ctx.provide('loader', { import: async () => { + if (native === false) throw new Error('synthetic-sensitive-import-error') + return { Config, async apply() { starts++ } } + } }) + const fiber = ctx.plugin(bundle, { codexHome: f.root, autoImport: false, enableInstructions: false, enableConfig: false }) + f.own(() => fiber.dispose()) + await fiber.await() + return { ctx, fiber, commands, providers, starts: () => starts } +} +test('unsupported Skills registry leaves commands and MCP active', async t => { + const h = await host(t, { skills: { registerProvider: true } }) + await eventually(() => h.starts() === 1) + assert.equal(h.fiber.state, 2); assert.ok(h.commands.has('mcp-status')) +}) +test('unsupported provider control leaves no Skills registration or watcher behind', async t => { + const h = await host(t, { skills: { registerProvider(create) { create({ signal: new AbortController().signal }); throw new Error('must not create a watcher') } } }) + await eventually(() => h.starts() === 1) + assert.equal(h.fiber.state, 2); assert.equal(h.providers.size, 0) +}) +test('a second Skills registration failure rolls back the first and closes its watcher', async t => { + const rows = new Set(), created = []; let attempts = 0, released = 0 + const h = await host(t, { skills: { registerProvider(create) { + const controller = new AbortController() + const provider = create({ signal: controller.signal, invalidate() {} }); created.push(provider) + if (++attempts === 2) throw new Error('synthetic-sensitive-registration-error') + rows.add(provider) + return () => { released++; controller.abort(); rows.delete(provider) } + } } }) + await eventually(() => created.length === 2 && released === 1 && rows.size === 0) + await eventually(async () => (await created.find(p => p.name === 'codex').list()).length === 0) + assert.equal(h.fiber.state, 2) + await eventually(() => h.starts() === 1) +}) +test('native MCP import failure preserves both watched Skill providers and status', async t => { + const h = await host(t, { native: false }) + await eventually(() => h.providers.size === 2) + const result = await h.commands.get('mcp-status').handler({ rawInput: '' }) + assert.equal(h.fiber.state, 2); assert.equal(h.starts(), 0) + assert.ok(!JSON.stringify(result).includes('synthetic-sensitive')) +}) diff --git a/test/skills-current.test.mjs b/test/skills-current.test.mjs new file mode 100644 index 0000000..5c4aa9f --- /dev/null +++ b/test/skills-current.test.mjs @@ -0,0 +1,109 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { runtimeRequire } from '../scripts/run-contract-tests.mjs' +import { pathToFileURL } from 'node:url' +import { mkdir, writeFile, rename, unlink } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { Readable } from 'node:stream' +import { temporary, environment, eventually } from './live-helpers.mjs' +import * as plugin from '../lib/index.js' +import { registerCodexSkillProvider } from '../lib/skill-provider.js' + +// Isolate each supported DSH peer graph from the historical session-format +// fixtures. The runner installs locked fixtures and selects each via the allowlist. +const require = runtimeRequire('skills') +const { Context, Service } = await import(pathToFileURL(require.resolve('@deepseek-ai/cordis')).href) +const { default: Skills } = await import(pathToFileURL(require.resolve('@deepseek-ai/dsh-skill')).href) +const skill = (name, body = 'body', extra = '') => `---\nname: ${name}\ndescription: Description for ${name}\n${extra}---\n${body}\n` +async function host(t, root, config = {}) { + const ctx = new Context() + class Prompt extends Service { constructor(c) { super(c, 'systemPrompt', true) } section() { return () => {} } } + class Commands extends Service { constructor(c) { super(c, 'commands', true); this.rows = new Map() } register(row) { this.rows.set(row.name, row); return () => this.rows.delete(row.name) } } + class Web extends Service { constructor(c) { super(c, 'webServer', true) } register(row) { this.row = row; return () => { this.row = undefined } } } + const fibers = [] + for (const p of [Prompt, Commands, Web, Skills]) fibers.push(await ctx.plugin(p)) + const fiber = ctx.plugin(plugin, { codexHome: root, mcpMirror: false, autoImport: false, enableInstructions: false, enableConfig: false, ...config }) + await fiber.await() + await eventually(async () => (await ctx.skills.list({ cwd: root })).some(s => s.provider === 'dsh-codex-sync')) + const dispose = async () => { await fiber.dispose(); for (const f of fibers.reverse()) await f.dispose() } + return { + ctx, fiber, dispose, + names: async () => (await ctx.skills.list({ cwd: root })).filter(s => s.provider === 'codex').map(s => s.name), + command: async (name, rawInput) => ctx.commands.rows.get(name).handler({ rawInput }), + http: async (key, value) => { + const req = Readable.from([Buffer.from(JSON.stringify({ key, value }))]); req.method = 'POST'; req.url = '/dsh-codex-sync/setting' + let text = '' + const res = { setHeader() {}, end(chunk) { text += chunk ?? '' } } + await ctx.webServer.row.handler(req, res) + return JSON.parse(text) + }, + } +} + +test('current registry cache observes command and HTTP master/item/default/all changes', async t => { + const f = await temporary(t); environment(t, { DSH_HOME: f.root }) + await mkdir(join(f.root, 'skills', 'alpha'), { recursive: true }) + await mkdir(join(f.root, 'skills', 'beta-folder'), { recursive: true }) + await writeFile(join(f.root, 'skills', 'alpha', 'SKILL.md'), skill('alpha')) + await writeFile(join(f.root, 'skills', 'beta-folder', 'SKILL.md'), skill('beta')) + const h = await host(t, f.root); f.own(h.dispose) + assert.deepEqual(await h.names(), ['alpha', 'beta']) + await h.names() // populate the real completed-catalog cache + await h.command('codex-setting', 'enableSkills off'); assert.deepEqual(await h.names(), []) + await h.http('enableSkills', true); assert.deepEqual(await h.names(), ['alpha', 'beta']) + await h.command('codex-skill', 'beta-folder off'); assert.deepEqual(await h.names(), ['alpha']) + await h.command('codex-setting', 'skillSyncDefault off'); assert.deepEqual(await h.names(), []) + await h.command('codex-skill', 'all on'); assert.deepEqual(await h.names(), ['alpha', 'beta']) + await h.command('codex-skill', 'all off'); assert.deepEqual(await h.names(), []) + await h.http('skillSyncDefault', true); assert.deepEqual(await h.names(), []) // explicit per-item overrides survive defaults +}) +test('current cached catalog observes external add/edit/rename/delete and full-body reload', async t => { + const f = await temporary(t); environment(t, { DSH_HOME: f.root }) + await mkdir(join(f.root, 'skills')) + const h = await host(t, f.root); f.own(h.dispose) + assert.deepEqual(await h.names(), []) + const first = join(f.root, 'skills', 'alpha.md'); const next = join(f.root, 'skills', 'renamed.md') + await writeFile(first, skill('alpha', 'body-v1')) + await eventually(async () => (await h.names()).includes('alpha')) + assert.equal((await h.ctx.skills.get('alpha', { cwd: f.root })).resourceBase.path, join(f.root, 'skills')) + await writeFile(first, skill('alpha', 'body-v2', 'disable-model-invocation: true\n')) + await eventually(async () => (await h.ctx.skills.list({ cwd: f.root })).find(s => s.name === 'alpha')?.invocation.modelInvocable === false) + assert.match((await h.ctx.skills.get('alpha', { cwd: f.root })).content, /body-v2/) + assert.equal(resolve(first), join(f.root, 'skills', 'alpha.md')); assert.equal(resolve(next), join(f.root, 'skills', 'renamed.md')) + await rename(first, next) + await writeFile(next, skill('renamed')) + await eventually(async () => (await h.names()).join(',') === 'renamed') + assert.equal(resolve(next), join(f.root, 'skills', 'renamed.md')); await unlink(next) + await eventually(async () => (await h.names()).length === 0) +}) +test('missing skill roots created after the first cached empty observation are discovered', async t => { + const f = await temporary(t); environment(t, { DSH_HOME: f.root }) + const home = join(f.root, 'later-home'); const h = await host(t, home); f.own(h.dispose) + assert.deepEqual(await h.names(), []) + await mkdir(join(home, 'skills', 'alpha'), { recursive: true }) + await writeFile(join(home, 'skills', 'alpha', 'SKILL.md'), skill('alpha')) + await eventually(async () => (await h.names()).includes('alpha')) +}) +test('YAML policies, invalid policy exclusion, maxSkills and flat resource bases remain safe', async t => { + const f = await temporary(t); environment(t, { DSH_HOME: f.root }) + const root = join(f.root, 'skills'); await mkdir(root) + await writeFile(join(root, 'alpha.md'), '---\nname: alpha\ndescription: |\n multiline description\ndisable-model-invocation: yes\nuser-invocable: off\n---\nalpha body\n') + await writeFile(join(root, 'beta.md'), skill('beta', 'body', 'disable-model-invocation: maybe\n')) + const controller = new AbortController() + const provider = registerCodexSkillProvider(f.root, { maxSkills: 1 }, { signal: controller.signal, invalidate() {} }); f.own(() => provider.dispose()) + const rows = await provider.list(); assert.equal(rows.length, 1) + assert.equal(rows[0].description, 'multiline description\n') + assert.deepEqual(rows[0].invocation, { modelInvocable: false, userInvocable: false }) + assert.equal((await provider.get(rows[0])).resourceBase.path, root) + assert.equal(rows[0].rank, 800) + controller.abort(); assert.deepEqual(await provider.list(), []) +}) +test('plugin teardown unregisters current providers and closes watchers', async t => { + const f = await temporary(t); environment(t, { DSH_HOME: f.root }) + await mkdir(join(f.root, 'skills')); await writeFile(join(f.root, 'skills', 'alpha.md'), skill('alpha')) + const h = await host(t, f.root) + assert.deepEqual(await h.names(), ['alpha']) + await h.fiber.dispose() + assert.deepEqual(await h.names(), []) + await h.dispose() +}) diff --git a/test/stdio-mcp-fixture.mjs b/test/stdio-mcp-fixture.mjs new file mode 100644 index 0000000..ebc7d78 --- /dev/null +++ b/test/stdio-mcp-fixture.mjs @@ -0,0 +1,15 @@ +// Hermetic legacy MCP fixture: synthetic protocol values, no filesystem/network APIs. +import { createInterface } from 'node:readline' +const input = createInterface({ input: process.stdin }) +for await (const line of input) { + let request + try { request = JSON.parse(line) } catch { continue } + if (request.id === undefined) continue + let result + if (request.method === 'initialize') result = { protocolVersion: '2025-03-26', capabilities: { tools: {} }, serverInfo: { name: 'codex-sync-contract-fixture', version: '1.0.0' } } + else if (request.method === 'tools/list') result = { tools: [{ name: 'ping', description: 'Return a synthetic protocol marker.', inputSchema: { type: 'object', properties: {}, additionalProperties: false } }] } + else if (request.method === 'tools/call') result = { content: [{ type: 'text', text: 'synthetic-pong' }] } + else if (request.method === 'ping') result = {} + else { process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: request.id, error: { code: -32601, message: 'Not implemented by synthetic fixture' } })}\n`); continue } + process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id: request.id, result })}\n`) +}