From 870e459e4633326c79f541405b568563ba6fe2f7 Mon Sep 17 00:00:00 2001 From: NianJiuZst <3235467914@qq.com> Date: Tue, 17 Nov 2026 11:26:17 +0800 Subject: [PATCH 1/2] feat(dsh): restore lightweight DSH plugin on unified bsk CLI runtime Why: - Retiring `@wxg-prc-cpg/browser-skill-dsh-plugin` in #731 eliminated ~22k LOC of duplicated session lifecycle, cooperation plumbing, and React inspection overlays, but also dropped BrowserSkill's native distribution entry in the DeepSeek Harness (`dsh-plugin`) ecosystem and left existing npm consumers on a frozen 0.5.0 package. - DeepSeek Harness already provides shell execution and `ImplicitScopeRegistry` already isolates concurrent conversations via `DSH_SESSION_ID`, so the DSH plugin only needs to publish the canonical CLI skill, heal GUI/profile `PATH` lookup, and guide first-run `bsk` installation without reintroducing parallel `bsk_*` tool wrappers or fragile `@deepseek-ai/dsh-client-ui-*` `rc` locks. What: - Restore `packages/dsh-plugin-browserskill` (`@wxg-prc-cpg/browser-skill-dsh-plugin`) as a ~350-LOC Cordis plugin depending only on `@deepseek-ai/cordis` and `@deepseek-ai/schemastery` (zero `@deepseek-ai/dsh-*` host `rc` peer locks and zero Web UI client bundle). - Sync the canonical `crates/bsk-cli/skill` bundle, `install.sh`, `install.ps1`, `AGENT_INSTALL.md`, and `LICENSE` at build/prepack time so DSH shares the exact single-source-of-truth CLI skill and Agent Window workflow with all other harnesses. - Automatically append `~/.local/bin` (`$BSK_INSTALL_DIR`) to the DSH host `PATH` (and prepend any explicit `bskPath` directory, unwinding on dispose); when `bsk` is missing on the host, prepend an on-demand setup header pointing to the bundled cross-platform `bin/install-bsk.mjs` launcher and local `AGENT_INSTALL.md`, dropping the setup header automatically on subsequent conversations once `bsk` is installed. - Add end-to-end integration tests against real Cordis `Context` and `@deepseek-ai/dsh-skill` `SkillRegistry`, restore out-of-tree tarball verification (`scripts/check-dsh-package.mjs`), `dsh-plugin-v*` release automation (`.github/workflows/release-dsh-plugin.yml`, `scripts/release.mjs`), CI checks, and bilingual documentation/changelogs. --- .github/workflows/ci.yml | 6 + .github/workflows/release-dsh-plugin.yml | 108 +++++++ AGENT_INSTALL.md | 5 + CHANGELOG.md | 13 +- CHANGELOG.zh-CN.md | 4 +- README.md | 19 +- README.zh-CN.md | 19 +- package.json | 1 + packages/dsh-plugin-browserskill/.gitignore | 7 + packages/dsh-plugin-browserskill/README.md | 62 ++++ .../bin/install-bsk.mjs | 142 +++++++++ .../dsh-plugin-browserskill/cordis.patch.yml | 5 + packages/dsh-plugin-browserskill/package.json | 73 +++++ .../scripts/build-bundle.mjs | 39 +++ packages/dsh-plugin-browserskill/src/env.mts | 149 +++++++++ .../dsh-plugin-browserskill/src/index.mts | 64 ++++ .../dsh-plugin-browserskill/src/skill.mts | 145 +++++++++ .../tests/plugin.integration.test.ts | 283 ++++++++++++++++++ .../dsh-plugin-browserskill/tsconfig.json | 14 + .../dsh-plugin-browserskill/vitest.config.ts | 8 + pnpm-lock.yaml | 154 ++++++++++ scripts/check-dsh-package.mjs | 125 ++++++++ scripts/release.mjs | 31 +- scripts/release.test.mjs | 6 +- 24 files changed, 1460 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/release-dsh-plugin.yml create mode 100644 packages/dsh-plugin-browserskill/.gitignore create mode 100644 packages/dsh-plugin-browserskill/README.md create mode 100755 packages/dsh-plugin-browserskill/bin/install-bsk.mjs create mode 100644 packages/dsh-plugin-browserskill/cordis.patch.yml create mode 100644 packages/dsh-plugin-browserskill/package.json create mode 100644 packages/dsh-plugin-browserskill/scripts/build-bundle.mjs create mode 100644 packages/dsh-plugin-browserskill/src/env.mts create mode 100644 packages/dsh-plugin-browserskill/src/index.mts create mode 100644 packages/dsh-plugin-browserskill/src/skill.mts create mode 100644 packages/dsh-plugin-browserskill/tests/plugin.integration.test.ts create mode 100644 packages/dsh-plugin-browserskill/tsconfig.json create mode 100644 packages/dsh-plugin-browserskill/vitest.config.ts create mode 100644 scripts/check-dsh-package.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77f4ed8f0..016ef385e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -250,6 +250,12 @@ jobs: - name: Run VOM tests run: pnpm --filter @browser-skill/vom test + - name: Typecheck, test, and verify DSH plugin package + run: >- + pnpm --filter @wxg-prc-cpg/browser-skill-dsh-plugin typecheck && + pnpm --filter @wxg-prc-cpg/browser-skill-dsh-plugin test && + node scripts/check-dsh-package.mjs + - name: Run extension unit tests run: pnpm ext:test diff --git a/.github/workflows/release-dsh-plugin.yml b/.github/workflows/release-dsh-plugin.yml new file mode 100644 index 000000000..cb55c87d2 --- /dev/null +++ b/.github/workflows/release-dsh-plugin.yml @@ -0,0 +1,108 @@ +name: Release dsh plugin + +on: + push: + tags: + - dsh-plugin-v* + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-dsh-plugin-${{ github.ref }} + cancel-in-progress: false + +env: + PACKAGE_NAME: "@wxg-prc-cpg/browser-skill-dsh-plugin" + PACKAGE_DIR: packages/dsh-plugin-browserskill + +jobs: + resolve: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} + tag: ${{ steps.version.outputs.tag }} + steps: + - uses: actions/checkout@v6 + + - name: Resolve plugin version + id: version + shell: bash + run: | + set -euo pipefail + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="$(node -p "require('./${{ env.PACKAGE_DIR }}/package.json').version")" + else + VERSION="${GITHUB_REF_NAME#dsh-plugin-v}" + fi + VERSION="${VERSION#v}" + echo "version=${VERSION}" >> "$GITHUB_OUTPUT" + echo "tag=dsh-plugin-v${VERSION}" >> "$GITHUB_OUTPUT" + + guard: + needs: resolve + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Verify tag matches package.json name and version + shell: bash + run: | + set -euo pipefail + PKG_NAME="$(node -p "require('./${{ env.PACKAGE_DIR }}/package.json').name")" + PKG_VERSION="$(node -p "require('./${{ env.PACKAGE_DIR }}/package.json').version")" + RELEASE_VERSION="${{ needs.resolve.outputs.version }}" + if [ "$PKG_NAME" != "$PACKAGE_NAME" ]; then + echo "package.json name (${PKG_NAME}) does not match expected ${PACKAGE_NAME}" + exit 1 + fi + if [ "$PKG_VERSION" != "$RELEASE_VERSION" ]; then + echo "${PACKAGE_DIR}/package.json version (${PKG_VERSION}) does not match release version (${RELEASE_VERSION})" + exit 1 + fi + echo "Version guard passed: ${PKG_NAME}@${RELEASE_VERSION}" + + publish: + needs: [resolve, guard] + runs-on: ubuntu-latest + # Secret NPM_TOKEN is stored on the "npm-publish" GitHub Environment. + environment: npm-publish + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v6 + with: + node-version: 22 + cache: pnpm + registry-url: https://registry.npmjs.org + scope: "@wxg-prc-cpg" + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Typecheck plugin + run: pnpm --filter "${{ env.PACKAGE_NAME }}" typecheck + + - name: Test plugin + run: pnpm --filter "${{ env.PACKAGE_NAME }}" test + + - name: Verify packaged skill and installer resources + run: pnpm --filter "${{ env.PACKAGE_NAME }}" build && node scripts/check-dsh-package.mjs + + - name: Publish to npm + working-directory: ${{ env.PACKAGE_DIR }} + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + set -euo pipefail + if [ -z "${NODE_AUTH_TOKEN:-}" ]; then + echo "::error::Environment secret NPM_TOKEN is not configured" + exit 1 + fi + pnpm publish --access public --no-git-checks + echo "Published ${PACKAGE_NAME}@${{ needs.resolve.outputs.version }}" diff --git a/AGENT_INSTALL.md b/AGENT_INSTALL.md index 329d6e190..dca32cd87 100644 --- a/AGENT_INSTALL.md +++ b/AGENT_INSTALL.md @@ -44,6 +44,11 @@ may retain its old PATH even after a new terminal picks up the installation. ## 2. Install for the intended agent harness +- **DeepSeek Harness (`dsh`):** install the [DSH plugin](README.md#deepseek-harness-plugin) + into the user's profile (`dsh plugin --profile web add @wxg-prc-cpg/browser-skill-dsh-plugin`, + replacing `web` with their profile name), or install the skill directly via + `bsk install-skill --harness dsh --json`. The plugin already bundles `browser-skill` + and heals `~/.local/bin` on `PATH`, so skip `bsk install-skill` when the plugin is added. - **Supported harnesses:** inspect the available IDs and paths: ```sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c2f13520..ce811d17e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ determines which versions can connect. ### Changed +- **Lightweight `@wxg-prc-cpg/browser-skill-dsh-plugin` on the unified `bsk` CLI runtime**: Replaced the ~22k-LOC bespoke `bsk_*` wrapper and Web UI bundle in `packages/dsh-plugin-browserskill` with a lightweight Cordis plugin (free of `@deepseek-ai/dsh-*` host `rc` peer locks) that packages the canonical `crates/bsk-cli/skill` bundle, automatically heals host `PATH` for `~/.local/bin` (`$BSK_INSTALL_DIR`) and configured `bskPath`, and bundles an on-demand cross-platform `bsk` CLI + browser extension setup workflow (`bin/install-bsk.mjs` + `AGENT_INSTALL.md`) sharing the standard `bsk` CLI and `DSH_SESSION_ID` daemon scoping alongside restored `dsh-plugin-v*` release automation. - **Zero-tax Chrome MV3 `registration: "runtime"` dual-tier content script injection, SW-startup orphan Agent Window reaping, and shared `content/dom-primitives.ts`**: Migrated all four MV3 content-script entrypoints (`content`, `cooperation.content`, `record-frame.content`, and `long-screenshot-page.content`) out of static `manifest.json` `content_scripts` into idempotent runtime injection (`claimIdempotentContentScript`) with `noScriptStartedPostMessage: true` so ordinary browsing incurs zero content-script, `window.postMessage`, or React 19 overhead; injected Tier A (`content.js` and `long-screenshot-page.js`) per `tabId`/`documentId` via idempotent `ensureOverlayInjected` across controlled task tabs, `webNavigation.onCommitted` (including Speculation Rules prerender outermost frames, sequenced strictly after Tier B `cooperation.js` arming/repair), pre-confirmation `tab_borrow` candidate user tabs, `request_help`, `record`, and active `video` overlays while skipping uninjected tabs on `hidden` / `CAPTURE_SUPPRESS` / `INPUT_PASSTHROUGH`; dynamically registered/unregistered pure-TypeScript Tier B (`cooperation.js` and `record-frame.js`) with `persistAcrossSessions: false` when active sessions or recordings transition between `0` and `>= 1`, loading silently at `document_start` with 0 DOM listeners and 0 startup IPC until armed by Background (`COOPERATION_ARM_FRAME` / `RECORD_FRAME_START` plus 50ms per-tab subframe coalescing, `cooperation.js` co-injection in `injectRecordFrameAllFrames`, and non-destructive per-frame `injectCooperationAllFrames` repair across `tab_borrow`, `ack === undefined` frames, and dynamically inserted light-DOM or open/closed `ShadowRoot` `about:blank` / `srcdoc` subframes); tracked dedicated Agent Window `ownedTabIds` in `chrome.storage.session` (`bsk.orphan_agent_windows`) to reap orphaned pure Agent Windows on Service Worker restart without ever closing windows containing user, borrowed, or human-preserved tabs; and extracted `apps/extension/src/content/dom-primitives.ts`. - **Single daemon `tool_pipeline`, 4-module `daemon/ipc` decomposition, non-blocking persistence, and shared `cli::orchestration` kernel**: Decomposed 3,489-line `daemon/ipc.rs` into `daemon/tool_pipeline.rs` (single unified `tool.*` pipeline with RAII `AuditTicketGuard`, `SessionActivityGuard`, `ToolInflightRegistry`, `IntentWal`, and post-settlement scope/run-log reconciliation), `daemon/ipc_sessions.rs`, `daemon/ipc_transport.rs`, and a slim `daemon/ipc.rs` router; promoted exhaustive `OutcomeKind` (`bsk-protocol`) / `Outcome` (`daemon/tool_policy.rs`) routing in `daemon/queue.rs`; moved `TransferRegistry` staging/import/session-teardown I/O, `AuditStore` JSONL `sync_data()` writes (including `session.user_interrupt` markers), and monotonic-sequence `IntentWal` flushes/atomic `sync_data()` compactions out of global state `Mutex`es and Tokio worker threads via `spawn_blocking`; and extracted `cli/orchestration.rs` to share Canvas screenshot point-click validation, `open`/`sync`/action/positive timeout bounds, explicit `--session` + `--browser` conflict checks, cached VOM hydration, and 2-second `CANCEL_RESPONSE_GRACE` settlement across `bsk` CLI and `bsk mcp`. - **100% strongly typed `bsk-protocol` contracts, typed `EventFrame` payloads, out-of-band WS correlation, and native `ActionMetadata` SSOT**: Replaced all 19 remaining `serde_json::Value` RPC contracts in `Method::contract_meta` (`ToolCooperate`, `LocalAuth*`, `AuditRequest`, `LedgerRequest`, `Session*`, `BrowserList`, `ToolOperationAwait`, and `Transfer*`) with strict Rust/JSON Schema structs, replaced untyped `EventFrame.payload: Value` across Rust and TypeScript with an exhaustive 10-variant `EventFrame` discriminated union, moved `_audit_id` and `_operation_id` out of business `params` into top-level `RequestFrame` envelope fields (deleting in-place `params` mutation and `stripEnvelopeParams`), embedded `ActionMetadata` / passive `context_id` natively with `#[serde(deny_unknown_fields)]` across all 23 `Full` and 9 passive-read `*Params` structs (eliminating post-hoc `catalog.rs` JSON Schema surgery and manual 4-key copy/re-insertion in `daemon/ipc.rs`), and unified `MethodSpec.action_metadata` (`Full` / `ContextOnly` / `TabBindingContext` / `Dynamic` / `None`) as the single source of truth across `bsk-protocol` and `bsk-cli`. @@ -111,11 +112,13 @@ determines which versions can connect. - Removed dead write-only `apps/extension/src/lib/sessions-live-flag.ts` (`bh.sessions_live` / `SESSIONS_LIVE_FLAG_KEY`) and ineffective Isolated World `history.pushState` / `history.replaceState` monkey-patching in `apps/extension/src/content/record-capture.ts`. - Removed `reattachIfSoftDetached`, `reconcileSoftDetachedFrames`, and `resolveTarget` compensation hooks from `CdpRunner`, `RefStore.remapChildFrameSessions`, partial hand-written `CdpRunner` wrapper object literals (replaced with full `delegateCdpRunner` delegation), and isolated default `new ChromiumCdp()` fallback instances outside `background.ts`. - Removed deprecated `TraceV2` recording types/converters (retaining `TraceV3` only), all 9 legacy `1.x` `Feature::*` compatibility gates, extension/daemon `"1.6"`/`LEGACY_MIN_COMPATIBLE_PEER` shims, duplicate `DragParams.observation_id` / legacy drag modes, and duplicate `wire_*` runtime validators from generated TypeScript artifacts. -- Retired and removed `packages/dsh-plugin-browserskill`, its standalone release - workflow, and DSH-specific test shims; DeepSeek Harness now uses the standard - `bsk` CLI and `bsk mcp` server, with in-flight MCP cancellation, cooperation - settlement, CLI video export, and dynamic-reading browser regressions migrated - to `bsk` CLI and `bsk mcp` (#731, #732). +- Removed the legacy bespoke `bsk_*` tool wrapper, duplicated session start journal, + forked DSH-only skill markdown, and Web UI thumbnail-polling React overlay from + `packages/dsh-plugin-browserskill` (along with `@deepseek-ai/dsh-*` host `rc` peer + locks and DSH-specific test shims); DeepSeek Harness now uses the standard `bsk` CLI + and `bsk mcp` server, with in-flight MCP cancellation, cooperation settlement, CLI + video export, and dynamic-reading browser regressions migrated to `bsk` CLI and + `bsk mcp` (#731, #732). ## [0.5.0] - 2026-11-12 diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index e3d6cd302..8f6311726 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -17,6 +17,7 @@ CLI 和扩展可以分别发布,能否连接由协议兼容性决定。更新 ### 变更 +- **基于统一 `bsk` CLI 运行时的轻量 `@wxg-prc-cpg/browser-skill-dsh-plugin` 插件**:将 `packages/dsh-plugin-browserskill` 从原先约 2.2 万行的自定义 `bsk_*` 工具包装器与 Web UI 前端组件重构为极简 Cordis 插件(彻底移除 `@deepseek-ai/dsh-*` 宿主 `rc` 版本对等依赖锁),直接内嵌主仓唯一的 `crates/bsk-cli/skill` 资源包,自动为宿主补齐 `~/.local/bin`(`$BSK_INSTALL_DIR`)与自定义 `bskPath` 的 `PATH` 解析,并打包跨平台按需 `bsk` CLI 安装器与浏览器扩展连接引导流程(`bin/install-bsk.mjs` + `AGENT_INSTALL.md`),底层与其他所有 Agent 100% 共用标准 `bsk` CLI 与 `DSH_SESSION_ID` 自动作用域机制,同时恢复 `dsh-plugin-v*` 独立发版流水线。 - **Chrome MV3 `registration: "runtime"` 零税双层按需内容脚本注入、SW 启动期孤儿 Agent 窗口兜底回收与共享 `content/dom-primitives.ts`**:将全部 4 个 MV3 内容脚本入口(`content`、`cooperation.content`、`record-frame.content` 与 `long-screenshot-page.content`)以 `noScriptStartedPostMessage: true` 与 `claimIdempotentContentScript` 幂等守卫迁出静态 `manifest.json` `content_scripts`,彻底消除日常浏览普通网页时的全局 `` 内容脚本、`window.postMessage` 广播与 React 19 加载税;通过幂等 `ensureOverlayInjected` 对受控任务标签页、`webNavigation.onCommitted`(含 Speculation Rules 预渲染顶层帧,且严格排在 Tier B `cooperation.js` 激活/补注入之后)、确认前 `tab_borrow` 候选用户标签页、`request_help`、`record` 与活跃 `video` 浮层按 `tabId`/`documentId` 单点注入 Tier A(`content.js` 与 `long-screenshot-page.js`),并在 `hidden` / `CAPTURE_SUPPRESS` / `INPUT_PASSTHROUGH` 时跳过未注入标签页;在活跃会话或录制于 `0` 与 `>= 1` 间切换时以 `persistAcrossSessions: false` 动态启停纯 TS 轻量 Tier B(`cooperation.js` 与 `record-frame.js`),使其在 `document_start` 零 DOM 监听、零启动唤醒 IPC 静默加载并由后台按需点名激活(`COOPERATION_ARM_FRAME` / `RECORD_FRAME_START` 配合单标签页 50ms 子帧合并去抖、`injectRecordFrameAllFrames` 协同注入 `cooperation.js`,以及在 `tab_borrow`、`ack === undefined` 帧与动态插入的普通 DOM 或 open/closed `ShadowRoot` 内同源 `about:blank` / `srcdoc` 子帧上进行无损按帧探测补注入);通过 `chrome.storage.session`(`bsk.orphan_agent_windows`)追踪独占 Agent 窗口创建的标签页集合,在 Service Worker 重启后精准回收无活跃会话的纯孤儿 Agent 窗口(严格保留含用户、借用或人工接管标签页的窗口);并抽离共享 DOM 原语模块 `apps/extension/src/content/dom-primitives.ts`。 - **守护进程单一 `tool_pipeline` 工具管线、`daemon/ipc` 四模块拆解、无锁阻塞持久化与 `cli::orchestration` 客户端共享编排内核**:将 3,489 行的 `daemon/ipc.rs` 拆解为 `daemon/tool_pipeline.rs`(统一收口全部 `tool.*` 执行路径的 RAII `AuditTicketGuard`、`SessionActivityGuard`、`ToolInflightRegistry`、`IntentWal` 与作用域/运行日志结算)、`daemon/ipc_sessions.rs`、`daemon/ipc_transport.rs` 及精简路由层 `daemon/ipc.rs`;在 `bsk-protocol` 与 `daemon/tool_policy.rs` / `daemon/queue.rs` 中建立穷尽式 `OutcomeKind` / `Outcome` 结果与超时归因路由;通过局部状态分离与 `spawn_blocking` 将 `TransferRegistry` 大文件暂存/导入复制/会话销毁目录清理、`AuditStore` JSONL `sync_data()` 刷盘(含 `session.user_interrupt` 标记)与单调序号 `IntentWal` 刷盘及 `sync_data()` 原子压缩彻底移出全局状态 `Mutex` 与 Tokio 工作线程阻塞路径;并提取 `cli/orchestration.rs` 统一 `bsk` CLI 与 `bsk mcp` 的 Canvas 截图坐标点击校验、`open`/`sync`/动作/正数超时边界、显式 `--session` + `--browser` 冲突校验、缓存 VOM 回填以及 2 秒 `CANCEL_RESPONSE_GRACE` 优雅取消结算。 - **`bsk-protocol` 100% 强类型化、强类型 `EventFrame` 事件载荷、WS 信封相关性解耦与原生 `ActionMetadata` 单一事实源**:将 `Method::contract_meta` 中剩余全部 19 个 `serde_json::Value` RPC 契约(`ToolCooperate`、`LocalAuth*`、`AuditRequest`、`LedgerRequest`、`Session*`、`BrowserList`、`ToolOperationAwait` 与 `Transfer*`)收口为编译期强类型 Rust/JSON Schema 结构;将跨 Rust 与 TypeScript 的裸 `EventFrame.payload: Value` 升级为穷尽覆盖全部 10 类事件的强类型 `EventFrame` 判别联合;将扩展 WS 请求上的 `_audit_id` 与 `_operation_id` 迁出业务 `params` 并提升至 `RequestFrame` 顶层可选字段(彻底移除原地篡改 `params` 与扩展侧 `stripEnvelopeParams` 补偿剥离);在全部 23 个 `Full` 与 9 个被动只读 `*Params` 结构中原生内嵌 `ActionMetadata` / `context_id` 并统一启用 `#[serde(deny_unknown_fields)]`(净删 `catalog.rs` 事后 JSON Schema 拼接补丁与 `daemon/ipc.rs` 手工拷出再塞回 4 个元字段的胶水代码);并将 `MethodSpec.action_metadata`(`Full` / `ContextOnly` / `TabBindingContext` / `Dynamic` / `None`)打通为 `bsk-protocol` 与 `bsk-cli` 共享的唯一真源。 @@ -55,8 +56,7 @@ CLI 和扩展可以分别发布,能否连接由协议兼容性决定。更新 - 移除已沦为只写不读死代码的 `apps/extension/src/lib/sessions-live-flag.ts`(`bh.sessions_live` / `SESSIONS_LIVE_FLAG_KEY`)以及 `apps/extension/src/content/record-capture.ts` 中在隔离世界无效的 `history.pushState` / `history.replaceState` 重写死代码。 - 从 `CdpRunner` 及上层调用栈净删 `reattachIfSoftDetached`、`reconcileSoftDetachedFrames` 与 `resolveTarget` 三大外泄补偿钩子,移除 `RefStore.remapChildFrameSessions`、手写残缺局部 `CdpRunner` 对象字面量(统一收口为 `delegateCdpRunner` 全量委托代理)以及 `background.ts` 以外所有孤立默认的 `new ChromiumCdp()` 野实例。 - 移除已废弃的 `TraceV2` 录制协议类型与转换器(仅保留 `TraceV3`)、全部 9 套 `1.x` `Feature::*` 历史版本协商门禁、扩展/守护进程 `"1.6"`/`LEGACY_MIN_COMPATIBLE_PEER` 兼容兜底、重复字段 `DragParams.observation_id` / 旧拖拽模式以及生成 TS 产物中重复导出的 `wire_*` 运行时校验器。 -- 下线并整体移除 `packages/dsh-plugin-browserskill`、独立发版流水线及专属测试桩;DeepSeek Harness - 与其他 Agent 统一通过标准 `bsk` CLI 与 `bsk mcp` 调用,在途请求取消、协作结算、CLI 录屏导出与动态读取等真浏览器回归用例已完整迁移至 `bsk` CLI 与 `bsk mcp`(#731、#732)。 +- 移除 `packages/dsh-plugin-browserskill` 中旧版自定义 `bsk_*` 工具包装器、重复会话启动日志、独立分叉的 DSH 专属 skill 文档以及 Web UI 缩略图轮询 React 浮层(连同 `@deepseek-ai/dsh-*` 宿主 `rc` 对等依赖锁与专属测试桩一并清理);DeepSeek Harness 与其他 Agent 统一通过标准 `bsk` CLI 与 `bsk mcp` 调用,在途请求取消、协作结算、CLI 录屏导出与动态读取等真浏览器回归用例已完整迁移至 `bsk` CLI 与 `bsk mcp`(#731、#732)。 ## [0.5.0] - 2026-11-12 diff --git a/README.md b/README.md index b8d015b38..b8b75c7b7 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ https://github.com/user-attachments/assets/6111d978-baa6-4a76-92c4-4f51d47ae617 -Qoder, Qoder CN, and DeepSeek Harness are also supported as skill targets (`bsk install-skill --harness qoder`, `--harness qoder-cn`, and `--harness dsh`). +Qoder, Qoder CN, and DeepSeek Harness are also supported as skill targets (`bsk install-skill --harness qoder`, `--harness qoder-cn`, and `--harness dsh`), and **[DeepSeek Harness](#deepseek-harness-plugin)** also provides a lightweight plugin (`@wxg-prc-cpg/browser-skill-dsh-plugin`) with bundled skill registration and on-demand `bsk` CLI setup. These and other agents that can run shell commands use the same **`bsk` CLI**, and MCP clients can also connect through **`bsk mcp`** ([MCP setup](docs/mcp.md)). You choose the agent and model; BrowserSkill connects it to your browser. @@ -198,6 +198,19 @@ Use `bsk --help` or `bsk --help` for command options. Always stop your In WorkBuddy/CodeBuddy, or hosts that reap command children, the agent should reuse an existing daemon or run `bsk daemon start --foreground` in a managed background task, then verify it from a separate tool call. Follow the [host setup guide](docs/sandboxed-agents.md) for shared `BSK_HOME`, `BSK_AUTO_START=0`, and the independent-terminal fallback when the host cannot keep a task alive. +## DeepSeek Harness plugin + +The lightweight [DSH plugin](packages/dsh-plugin-browserskill/README.md) (`@wxg-prc-cpg/browser-skill-dsh-plugin`) packages the canonical `browser-skill` CLI skill for DeepSeek Harness profiles, automatically adds `~/.local/bin` (or a configured `bskPath`) to the host `PATH`, and bundles an on-demand `bsk` CLI + extension setup flow when `bsk` is not yet installed. Under the hood, it shares the exact same `bsk` CLI, daemon (`DSH_SESSION_ID` implicit scoping), and Agent Window runtime as every other agent. + +```sh +dsh plugin --profile web add @wxg-prc-cpg/browser-skill-dsh-plugin +dsh --profile web +``` + +Replace `web` with your profile name. Invoke `/browser-skill` in a conversation — if `bsk` is missing, the agent runs the bundled installer and guides browser extension connection automatically. No separate `bsk install-skill` step is needed. + +[Plugin usage and configuration](packages/dsh-plugin-browserskill/README.md) · [npm package](https://www.npmjs.com/package/@wxg-prc-cpg/browser-skill-dsh-plugin) + ## Website debugging **Give your agent the browser evidence behind a bug.** Start capture before reproducing an issue on a website you are authorized to debug, then inspect the result in the extension or through the agent. @@ -301,7 +314,7 @@ A daemon that `bsk` started in the background also checks for a new release ever `bsk doctor` shows the last update attempt; `update-state.json` in the bsk home keeps its stage, result and error. Updates of one executable run one at a time, even from different bsk homes, through `.bsk.update.lock` (`.bsk.exe.update.lock` on Windows), which stays next to it. Until an update is confirmed, the previous executable stays next to the new one as `.bsk.old-*` (`.bsk.exe.old-*` on Windows); one that is still running remains until its process exits, and a later daemon start removes it. On Windows, self-update renames the running executable, which NTFS supports; where the file system refuses, the update fails and leaves the installation unchanged. bsk supports Windows 10 and Windows Server 2016 or later. -Update the extension through its browser store. Check `bsk --version`, `bsk status`, and `bsk doctor`. Keep the CLI, running daemon, and extension on matching releases for new features. This README describes the current repository; store builds can lag during review. Check the [changelog](CHANGELOG.md) and [releases](https://github.com/Tencent/BrowserSkill/releases) for availability. +Update the extension through its browser store. If you use the DeepSeek Harness plugin, update it in your profile (`dsh plugin --profile web update @wxg-prc-cpg/browser-skill-dsh-plugin --latest`) and restart that profile. Check `bsk --version`, `bsk status`, and `bsk doctor`. Keep the CLI, running daemon, extension, and optional DSH plugin on matching releases for new features. This README describes the current repository; store builds can lag during review. Check the [changelog](CHANGELOG.md) and [releases](https://github.com/Tencent/BrowserSkill/releases) for availability. Managed CLI skills update on daemon startup, `session start`, or `doctor` while their files remain unchanged. Local edits and custom skills are preserved. Start a new agent session to load updated instructions; doctor reports any paused skill updates. @@ -328,6 +341,7 @@ Stop the daemon in its owning host or supervisor, update with `bsk update --yes | Connect a server-side agent | [Remote browser connections](docs/remote-extension-connection.md) | | Run in a sandbox | [Sandboxed agents](docs/sandboxed-agents.md) | | Review recorded task metadata | [Operation audit](docs/operation-audit.md) | +| Integrate with DeepSeek Harness | [DSH plugin](packages/dsh-plugin-browserskill/README.md) | | Connect over MCP | [MCP server](docs/mcp.md) | | Understand the implementation | [Architecture](docs/architecture.md) · [Protocol](crates/bsk-protocol/README.md) | @@ -348,6 +362,7 @@ The CLI is built under `target/release/`; load `apps/extension/dist/chrome-mv3/` | `crates/bsk-cli` | CLI, daemon, and bundled agent skill | | `crates/bsk-protocol` | Wire types and JSON schemas | | `apps/extension` | Browser automation, debugging workspace, and extension UI | +| `packages/dsh-plugin-browserskill` | Lightweight DeepSeek Harness skill and on-demand setup plugin | | `packages/ui`, `packages/i18n`, `packages/vom` | Shared UI, localization, and page observation | | `evals/browser` | Local test pages and browser capability evaluations | diff --git a/README.zh-CN.md b/README.zh-CN.md index 078e8cbe5..930e6e1fc 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -61,7 +61,7 @@ https://github.com/user-attachments/assets/959cb520-80ba-4b9e-b6d8-d94523b03693 -Qoder、Qoder CN 与 DeepSeek Harness 同样作为 skill 安装目标支持(`bsk install-skill --harness qoder`、`--harness qoder-cn` 和 `--harness dsh`)。 +Qoder、Qoder CN 与 DeepSeek Harness 同样作为 skill 安装目标支持(`bsk install-skill --harness qoder`、`--harness qoder-cn` 和 `--harness dsh`);**[DeepSeek Harness](#deepseek-harness-插件)** 同时提供轻量插件(`@wxg-prc-cpg/browser-skill-dsh-plugin`),自带 skill 注册与按需 `bsk` 安装引导。 这些 Agent,以及其他能调用 Shell 的 Agent,都可以通过同一套 **`bsk` CLI** 使用;支持 MCP 的客户端也可通过 **`bsk mcp`** 接入([MCP 配置](docs/mcp.md))。Agent 和模型由你选择,BrowserSkill 负责连接浏览器。 @@ -196,6 +196,19 @@ bsk session stop 在 WorkBuddy/CodeBuddy 或会回收命令子进程的宿主中,Agent 应先复用已有 daemon;需要启动时,在宿主管理的后台任务中运行 `bsk daemon start --foreground`,并在另一条工具调用中验证连接。[宿主配置指南](docs/sandboxed-agents.md)说明了如何共用 `BSK_HOME`、设置 `BSK_AUTO_START=0`,以及宿主无法维持任务时的独立终端兜底方式。 +## DeepSeek Harness 插件 + +轻量版 [DSH 插件](packages/dsh-plugin-browserskill/README.md)(`@wxg-prc-cpg/browser-skill-dsh-plugin`)为 DeepSeek Harness profile 内置主仓统一的 `browser-skill` CLI skill,自动将 `~/.local/bin`(或配置的 `bskPath`)补入宿主 `PATH`,并在本机尚未安装 `bsk` 时提供按需自动安装与浏览器扩展连接引导;底层与其他所有 Agent 共享同一套 `bsk` CLI、daemon(自动识别 `DSH_SESSION_ID` 隔离会话)与独立 Agent Window 运行时。 + +```sh +dsh plugin --profile web add @wxg-prc-cpg/browser-skill-dsh-plugin +dsh --profile web +``` + +将 `web` 替换为自己的 profile 名称。在对话中调用 `/browser-skill` 并描述任务即可——若本机未安装 `bsk`,Agent 会自动调用包内安装脚本并引导开启浏览器扩展,无需额外执行 `bsk install-skill`。 + +[插件使用与配置](packages/dsh-plugin-browserskill/README.md) · [npm 包](https://www.npmjs.com/package/@wxg-prc-cpg/browser-skill-dsh-plugin) + ## 网站调试 **让 Agent 看到问题发生时的浏览器证据。** 在你有权调试的网站上,先开启采集,再复现问题,随后在扩展中查看,或交给 Agent 分析。 @@ -294,7 +307,7 @@ bsk update --yes `bsk doctor` 会显示最近一次更新的结果;bsk home 下的 `update-state.json` 记录了它的阶段、结果和错误原因。同一个可执行文件的更新会依次进行,即使来自不同的 bsk home 也是如此,靠的是它旁边的 `.bsk.update.lock`(Windows 上为 `.bsk.exe.update.lock`),这个文件会一直保留。更新确认成功前,旧版本会以 `.bsk.old-*`(Windows 上为 `.bsk.exe.old-*`)的名字留在新版本旁边;仍在运行的旧版本会保留到对应进程退出,之后再启动 daemon 时会清理。Windows 上的自更新依赖重命名正在运行的可执行文件,NTFS 支持这一操作;文件系统不支持时,更新会失败,已安装的版本保持不变。bsk 支持 Windows 10 和 Windows Server 2016 及以上版本。 -扩展通过浏览器商店更新。通过 `bsk --version`、`bsk status` 和 `bsk doctor` 检查版本与连接。使用新功能时,保持 CLI、正在运行的 daemon 和扩展版本匹配。本 README 介绍当前仓库的能力,商店版本可能因审核而滞后;已发布内容以[更新日志](CHANGELOG.md)和 [Releases](https://github.com/Tencent/BrowserSkill/releases) 为准。 +扩展通过浏览器商店更新。如使用 DeepSeek Harness 插件,可在对应 profile 中单独更新(`dsh plugin --profile web update @wxg-prc-cpg/browser-skill-dsh-plugin --latest`)并重启该 profile。通过 `bsk --version`、`bsk status` 和 `bsk doctor` 检查版本与连接。使用新功能时,保持 CLI、正在运行的 daemon、扩展和可选 DSH 插件版本匹配。本 README 介绍当前仓库的能力,商店版本可能因审核而滞后;已发布内容以[更新日志](CHANGELOG.md)和 [Releases](https://github.com/Tencent/BrowserSkill/releases) 为准。 受管理的 CLI skill 在文件未被修改时,会随 daemon 启动、`session start` 或 `doctor` 自动同步;本地修改和自定义 skill 会保留。开启新的 Agent 会话以加载更新后的指令,doctor 会提示暂停同步的安装。 @@ -321,6 +334,7 @@ bsk update --yes | 连接服务器上的 Agent | [远程浏览器连接](docs/remote-extension-connection.md) | | 在沙盒中使用 | [沙盒环境配置](docs/sandboxed-agents.md) | | 回看任务操作元数据 | [操作审计](docs/operation-audit.md) | +| 接入 DeepSeek Harness | [DSH 插件](packages/dsh-plugin-browserskill/README.md) | | 通过 MCP 接入 | [MCP 服务](docs/mcp.md) | | 了解项目实现 | [架构](docs/architecture.md) · [协议](crates/bsk-protocol/README.md) | @@ -341,6 +355,7 @@ CLI 产物位于 `target/release/`;将 `apps/extension/dist/chrome-mv3/` 作 | `crates/bsk-cli` | CLI、daemon 和内置 Agent skill | | `crates/bsk-protocol` | 通信类型与 JSON Schema | | `apps/extension` | 浏览器自动化、调试工作区和扩展界面 | +| `packages/dsh-plugin-browserskill` | 轻量 DeepSeek Harness skill 与按需安装引导插件 | | `packages/ui`、`packages/i18n`、`packages/vom` | 共享 UI、多语言和页面观察 | | `evals/browser` | 本地测试页面与浏览器能力评测 | diff --git a/package.json b/package.json index dc3323751..a27dbe53c 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "ext:dev": "pnpm --filter @browser-skill/extension dev", "ext:test": "pnpm --filter @browser-skill/extension test", "ext:test:browser": "node scripts/run-browser-tests.mjs", + "dsh:test": "pnpm --filter @wxg-prc-cpg/browser-skill-dsh-plugin test", "vom:test": "pnpm --filter @browser-skill/vom test", "lint": "biome check . && stylelint \"**/*.css\"", "format": "biome format --write .", diff --git a/packages/dsh-plugin-browserskill/.gitignore b/packages/dsh-plugin-browserskill/.gitignore new file mode 100644 index 000000000..2d1c1e53c --- /dev/null +++ b/packages/dsh-plugin-browserskill/.gitignore @@ -0,0 +1,7 @@ +/lib/ +/skill/ +/install.sh +/install.ps1 +/AGENT_INSTALL.md +/LICENSE +/src/skill-content.generated.mts diff --git a/packages/dsh-plugin-browserskill/README.md b/packages/dsh-plugin-browserskill/README.md new file mode 100644 index 000000000..920261e13 --- /dev/null +++ b/packages/dsh-plugin-browserskill/README.md @@ -0,0 +1,62 @@ +# BrowserSkill for DeepSeek Harness + +[![npm version](https://img.shields.io/npm/v/@wxg-prc-cpg/browser-skill-dsh-plugin)](https://www.npmjs.com/package/@wxg-prc-cpg/browser-skill-dsh-plugin) + +Lightweight [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (`dsh`) plugin for [BrowserSkill](https://github.com/Tencent/BrowserSkill). + +It packages the canonical `browser-skill` agent skill, automatically heals `PATH` for `~/.local/bin` (and any configured `bskPath`), and bundles an on-demand `bsk` CLI + browser extension setup flow — running on the exact same `bsk` CLI, daemon (`DSH_SESSION_ID` session isolation), and Agent Window runtime as Claude Code, Codex, Cursor, and OpenClaw. + +## Installation + +Add the plugin to your DeepSeek Harness profile (or install it from the DSH Web UI plugin panel), then start DSH: + +```sh +dsh plugin --profile web add @wxg-prc-cpg/browser-skill-dsh-plugin +dsh --profile web +``` + +Replace `web` with your profile name if you use another profile. No separate `bsk install-skill` step is needed. + +### On-demand setup (first run) + +If `bsk` and the browser extension are already installed, start using `/browser-skill` right away: + +```text +/browser-skill open https://example.com, summarize the page, and close the browser session. +``` + +If `bsk` is **not** installed on your computer yet, simply invoke `/browser-skill` (or ask DSH to open a webpage): + +1. The plugin detects that `bsk` is missing and instructs the DSH agent to run the bundled cross-platform installer (`bin/install-bsk.mjs`, which installs `bsk` into `~/.local/bin` without `sudo`). +2. Because the plugin automatically adds `~/.local/bin` to the DSH host `PATH`, `bsk` becomes available immediately in the same session without restarting DSH. +3. The agent runs `bsk doctor` and gives you the [Chrome Web Store](https://chromewebstore.google.com/detail/hhcmgoofomhgciiibhipgmgkgnoenaoi) or [Edge Add-ons](https://microsoftedge.microsoft.com/addons/detail/browserskill/emacgiaaaiojkkpkddmmdfhmokgmnikg) link if the browser extension still needs to be installed and connected. + +You can also run the bundled CLI installer manually at any time: + +```sh +npx --package @wxg-prc-cpg/browser-skill-dsh-plugin bsk-dsh-install +``` + +## Configuration + +The plugin exposes one optional setting in `cordis.patch.yml` and the DSH Web UI settings form: + +| Option | Default | Description | +| --- | --- | --- | +| `bskPath` | `"bsk"` | Path to the `bsk` executable or its directory. Defaults to resolving `bsk` from `PATH` or `~/.local/bin` (`$BSK_INSTALL_DIR`). | + +## How it works + +- **Unified CLI runtime:** Uses DSH's shell execution tool to run `bsk` commands (`bsk open`, `bsk click`, `bsk fill`, `bsk sync`, `bsk close`) with full support for shared control, full-page screenshots, structured extraction, file upload/download, task video recording, recipes, and website debugging. +- **Automatic session scoping:** The `bsk` daemon recognizes `DSH_SESSION_ID` automatically so concurrent conversations and subagents keep isolated browser scopes without manual `--session` flags. +- **MCP alternative:** For restricted profiles without shell execution, connect `bsk mcp` through `@deepseek-ai/dsh-mcp-client` instead (see [MCP setup](https://github.com/Tencent/BrowserSkill/blob/main/docs/mcp.md)). + +## Updating + +Update the plugin in your DSH profile, then restart that profile: + +```sh +dsh plugin --profile web update @wxg-prc-cpg/browser-skill-dsh-plugin --latest +``` + +Update the `bsk` CLI (`bsk update --yes`) and browser extension separately when a release requires a newer protocol version. diff --git a/packages/dsh-plugin-browserskill/bin/install-bsk.mjs b/packages/dsh-plugin-browserskill/bin/install-bsk.mjs new file mode 100755 index 000000000..289c1d71b --- /dev/null +++ b/packages/dsh-plugin-browserskill/bin/install-bsk.mjs @@ -0,0 +1,142 @@ +#!/usr/bin/env node +/** + * Cross-platform on-demand installer for the `bsk` CLI bundled inside + * `@wxg-prc-cpg/browser-skill-dsh-plugin`. + * + * Usage: + * node bin/install-bsk.mjs # install if missing, reuse if already present + * node bin/install-bsk.mjs --check # exit 0 if `bsk --version` succeeds, 1 otherwise + * node bin/install-bsk.mjs --force # run bundled platform installer unconditionally + */ + +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { delimiter, dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const args = new Set(process.argv.slice(2)); +const checkOnly = args.has("--check"); +const forceInstall = args.has("--force"); +const isWin = process.platform === "win32"; +const exeName = isWin ? "bsk.exe" : "bsk"; + +function expandHome(rawPath, home) { + if (rawPath === "~") return home; + if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) { + return join(home, rawPath.slice(2)); + } + return rawPath; +} + +function resolveInstallDir() { + const home = process.env.HOME || process.env.USERPROFILE || homedir(); + const custom = process.env.BSK_INSTALL_DIR?.trim(); + return custom ? resolve(expandHome(custom, home)) : join(home, ".local", "bin"); +} + +function probeBinary(candidate) { + const res = spawnSync(candidate, ["--version"], { + encoding: "utf8", + timeout: 10_000, + windowsHide: true, + }); + if (res.error || res.status !== 0) return null; + return (res.stdout || res.stderr || "").trim() || "ok"; +} + +function findInstalledBsk() { + const installCandidate = join(resolveInstallDir(), exeName); + const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === "path") ?? "PATH"; + const entries = (process.env[pathKey] ?? "") + .split(delimiter) + .map((entry) => entry.trim()) + .filter(Boolean); + + const candidates = [...entries.map((dir) => join(dir, exeName)), installCandidate]; + const seen = new Set(); + for (const candidate of candidates) { + const key = isWin ? candidate.toLowerCase() : candidate; + if (seen.has(key)) continue; + seen.add(key); + if (!existsSync(candidate)) continue; + const version = probeBinary(candidate); + if (version !== null) { + return { path: candidate, version }; + } + } + return null; +} + +function runPlatformInstaller() { + if (isWin) { + const script = join(pkgRoot, "install.ps1"); + if (!existsSync(script)) { + console.error(`error: bundled installer missing at ${script}`); + process.exit(1); + } + for (const shell of ["powershell.exe", "pwsh"]) { + const res = spawnSync(shell, ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script], { + stdio: "inherit", + }); + if (res.error && "code" in res.error && res.error.code === "ENOENT") { + continue; + } + if (res.status !== 0) { + process.exit(res.status ?? 1); + } + return; + } + console.error("error: neither powershell.exe nor pwsh was found on PATH"); + process.exit(1); + } + + const script = join(pkgRoot, "install.sh"); + if (!existsSync(script)) { + console.error(`error: bundled installer missing at ${script}`); + process.exit(1); + } + const res = spawnSync("sh", [script], { stdio: "inherit" }); + if (res.error) { + console.error(`error: failed to launch sh: ${res.error.message}`); + process.exit(1); + } + if (res.status !== 0) { + process.exit(res.status ?? 1); + } +} + +const existing = findInstalledBsk(); + +if (checkOnly) { + if (existing) { + console.log(`${existing.path} (${existing.version})`); + process.exit(0); + } + console.error("bsk CLI is not installed"); + process.exit(1); +} + +const agentGuidePath = join(pkgRoot, "AGENT_INSTALL.md"); + +if (existing && !forceInstall) { + console.log(`==> bsk is already installed at ${existing.path} (${existing.version})`); + console.log( + `==> Next: run 'bsk doctor' and follow ${agentGuidePath} (Steps 3-5) to verify browser connection.`, + ); + process.exit(0); +} + +runPlatformInstaller(); + +const installed = findInstalledBsk(); +if (!installed) { + console.error("error: installer finished, but bsk executable could not be verified"); + process.exit(1); +} + +console.log(`==> Verified ${installed.path} (${installed.version})`); +console.log( + `==> Next: run 'bsk doctor' and follow ${agentGuidePath} (Steps 3-5) to verify browser connection.`, +); diff --git a/packages/dsh-plugin-browserskill/cordis.patch.yml b/packages/dsh-plugin-browserskill/cordis.patch.yml new file mode 100644 index 000000000..882eb62b9 --- /dev/null +++ b/packages/dsh-plugin-browserskill/cordis.patch.yml @@ -0,0 +1,5 @@ +- insert: + - id: browserskill + # Must be the published package name — the loader imports this specifier. + # Quoted because YAML reserves a leading '@' in plain scalars. + name: "@wxg-prc-cpg/browser-skill-dsh-plugin" diff --git a/packages/dsh-plugin-browserskill/package.json b/packages/dsh-plugin-browserskill/package.json new file mode 100644 index 000000000..66eff1573 --- /dev/null +++ b/packages/dsh-plugin-browserskill/package.json @@ -0,0 +1,73 @@ +{ + "name": "@wxg-prc-cpg/browser-skill-dsh-plugin", + "description": "DeepSeek Harness plugin that bundles the BrowserSkill skill and on-demand bsk CLI setup", + "version": "0.5.0", + "license": "MIT", + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Tencent/BrowserSkill.git", + "directory": "packages/dsh-plugin-browserskill" + }, + "homepage": "https://github.com/Tencent/BrowserSkill/tree/main/packages/dsh-plugin-browserskill#readme", + "bugs": { + "url": "https://github.com/Tencent/BrowserSkill/issues" + }, + "keywords": [ + "dsh-plugin", + "deepseek-harness", + "browserskill", + "browser-automation" + ], + "type": "module", + "main": "./lib/index.mjs", + "types": "./lib/index.d.mts", + "bin": { + "bsk-dsh-install": "./bin/install-bsk.mjs" + }, + "exports": { + ".": { + "types": "./lib/index.d.mts", + "default": "./lib/index.mjs" + }, + "./package.json": "./package.json" + }, + "files": [ + "lib", + "bin", + "skill", + "install.sh", + "install.ps1", + "AGENT_INSTALL.md", + "cordis.patch.yml", + "LICENSE" + ], + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "scripts": { + "build": "node scripts/build-bundle.mjs && tsc", + "typecheck": "node scripts/build-bundle.mjs && tsc --noEmit", + "test": "pnpm run build && vitest run", + "prepack": "pnpm run build" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "^4.0.2", + "@deepseek-ai/schemastery": "^3.18.2" + }, + "devDependencies": { + "@deepseek-ai/cordis": "4.0.2", + "@deepseek-ai/dsh-llm": "0.1.5-rc.3", + "@deepseek-ai/dsh-scope": "0.1.5-rc.3", + "@deepseek-ai/dsh-skill": "0.1.5-rc.3", + "@deepseek-ai/schemastery": "3.18.2", + "@types/node": "^22.10.0", + "typescript": "^5.8.0", + "vitest": "^4.1.6" + } +} diff --git a/packages/dsh-plugin-browserskill/scripts/build-bundle.mjs b/packages/dsh-plugin-browserskill/scripts/build-bundle.mjs new file mode 100644 index 000000000..21b353688 --- /dev/null +++ b/packages/dsh-plugin-browserskill/scripts/build-bundle.mjs @@ -0,0 +1,39 @@ +import { chmodSync, copyFileSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { validateSkillDirectory } from "../../../scripts/lib/validate-skill.mjs"; + +const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); +const repoRoot = join(pkgRoot, "..", ".."); +const canonicalSkillDir = join(repoRoot, "crates", "bsk-cli", "skill"); + +const { name, description, content, files } = validateSkillDirectory(canonicalSkillDir, { + maxEntryBytes: 2_000, +}); + +const destSkillDir = join(pkgRoot, "skill"); +rmSync(destSkillDir, { recursive: true, force: true }); +cpSync(canonicalSkillDir, destSkillDir, { recursive: true }); + +for (const asset of ["install.sh", "install.ps1", "AGENT_INSTALL.md", "LICENSE"]) { + copyFileSync(join(repoRoot, asset), join(pkgRoot, asset)); +} +if (process.platform !== "win32") { + chmodSync(join(pkgRoot, "install.sh"), 0o755); + chmodSync(join(pkgRoot, "bin", "install-bsk.mjs"), 0o755); +} + +mkdirSync(join(pkgRoot, "src"), { recursive: true }); +const banner = + "// GENERATED by scripts/build-bundle.mjs — do not edit.\n" + + "// Source: crates/bsk-cli/skill/SKILL.md; references load on demand from resourceBase.\n"; +writeFileSync( + join(pkgRoot, "src", "skill-content.generated.mts"), + `${banner}export const BSK_SKILL_NAME = ${JSON.stringify(name)};\n` + + `export const BSK_SKILL_DESCRIPTION = ${JSON.stringify(description)};\n` + + `export const BSK_SKILL_MARKDOWN = ${JSON.stringify(content)};\n`, +); + +console.log( + `dsh-plugin bundle synced (${files.size} skill files, ${Buffer.byteLength(content)} body bytes)`, +); diff --git a/packages/dsh-plugin-browserskill/src/env.mts b/packages/dsh-plugin-browserskill/src/env.mts new file mode 100644 index 000000000..8fd72d519 --- /dev/null +++ b/packages/dsh-plugin-browserskill/src/env.mts @@ -0,0 +1,149 @@ +import { accessSync, constants, statSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; + +export function expandHome(rawPath: string, homeDir: string): string { + if (rawPath === "~") return homeDir; + if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) { + return join(homeDir, rawPath.slice(2)); + } + return rawPath; +} + +function resolveHomeDir(env: NodeJS.ProcessEnv): string { + return env.HOME || env.USERPROFILE || homedir(); +} + +export function defaultInstallDir(env: NodeJS.ProcessEnv = process.env): string { + const home = resolveHomeDir(env); + const override = env.BSK_INSTALL_DIR?.trim(); + return override ? resolve(expandHome(override, home)) : join(home, ".local", "bin"); +} + +function findPathKey(env: NodeJS.ProcessEnv): string { + return Object.keys(env).find((key) => key.toLowerCase() === "path") ?? "PATH"; +} + +function normalizeDir(dir: string): string { + const trimmed = dir.replace(/[\\/]+$/, ""); + return process.platform === "win32" ? trimmed.toLowerCase() : trimmed; +} + +function isExecutableFile(filePath: string): boolean { + try { + if (!statSync(filePath).isFile()) return false; + if (process.platform !== "win32") { + accessSync(filePath, constants.X_OK); + } + return true; + } catch { + return false; + } +} + +function isDefaultBskCommand(bskPath: string | undefined): boolean { + const trimmed = bskPath?.trim(); + return !trimmed || trimmed === "bsk" || trimmed.toLowerCase() === "bsk.exe"; +} + +/** + * Synchronously locate the `bsk` binary without spawning a child process or daemon. + * Returns the resolved executable path when present, or `null` when missing. + */ +export function resolveBskExecutable(bskPath?: string): string | null { + const env = process.env; + const isWin = process.platform === "win32"; + const home = resolveHomeDir(env); + const exeName = isWin ? "bsk.exe" : "bsk"; + + if (!isDefaultBskCommand(bskPath)) { + const target = resolve(expandHome(bskPath!.trim(), home)); + try { + const stat = statSync(target); + if (stat.isDirectory()) { + const inDir = join(target, exeName); + return isExecutableFile(inDir) ? inDir : null; + } + if (stat.isFile()) { + return isExecutableFile(target) ? target : null; + } + } catch { + if (isWin && !target.toLowerCase().endsWith(".exe")) { + const withExe = `${target}.exe`; + if (isExecutableFile(withExe)) return withExe; + } + return null; + } + return null; + } + + const sep = isWin ? ";" : ":"; + const pathKey = findPathKey(env); + const pathEntries = (env[pathKey] ?? "") + .split(sep) + .map((entry) => entry.trim()) + .filter(Boolean); + + for (const dir of [...pathEntries, defaultInstallDir(env)]) { + const candidate = join(dir, exeName); + if (isExecutableFile(candidate)) { + return candidate; + } + } + return null; +} + +/** + * Ensure the DSH host process `PATH` includes the default `bsk` install directory + * (`$BSK_INSTALL_DIR` or `~/.local/bin`) and, when an explicit `bskPath` is configured, + * prepends its directory so shell invocations of `bsk` resolve consistently. + */ +export function ensureBskInPath(bskPath?: string): () => void { + const env = process.env; + const isWin = process.platform === "win32"; + const sep = isWin ? ";" : ":"; + const home = resolveHomeDir(env); + const pathKey = findPathKey(env); + + const splitEntries = () => + (env[pathKey] ?? "") + .split(sep) + .map((entry) => entry.trim()) + .filter(Boolean); + + const installDir = defaultInstallDir(env); + const installNorm = normalizeDir(installDir); + const initialEntries = splitEntries(); + if (!initialEntries.some((entry) => normalizeDir(entry) === installNorm)) { + env[pathKey] = [...initialEntries, installDir].join(sep); + } + + if (isDefaultBskCommand(bskPath)) { + return () => {}; + } + + const rawTarget = resolve(expandHome(bskPath!.trim(), home)); + let customDir = dirname(rawTarget); + try { + if (statSync(rawTarget).isDirectory()) { + customDir = rawTarget; + } + } catch { + // Keep dirname(rawTarget) when rawTarget points to a not-yet-installed binary path. + } + + const customNorm = normalizeDir(customDir); + const currentEntries = splitEntries(); + if (currentEntries[0] && normalizeDir(currentEntries[0]) === customNorm) { + return () => {}; + } + + const filtered = currentEntries.filter((entry) => normalizeDir(entry) !== customNorm); + env[pathKey] = [customDir, ...filtered].join(sep); + + return () => { + const latest = splitEntries(); + const restored = latest.filter((entry) => normalizeDir(entry) !== customNorm); + env[pathKey] = restored.join(sep); + }; +} diff --git a/packages/dsh-plugin-browserskill/src/index.mts b/packages/dsh-plugin-browserskill/src/index.mts new file mode 100644 index 000000000..903c3cf3d --- /dev/null +++ b/packages/dsh-plugin-browserskill/src/index.mts @@ -0,0 +1,64 @@ +/** + * Lightweight DeepSeek Harness plugin for BrowserSkill (`@wxg-prc-cpg/browser-skill-dsh-plugin`). + * + * Registers the canonical BrowserSkill CLI skill (`crates/bsk-cli/skill`), + * heals `PATH` for default/configured `bsk` installations, and guides on-demand + * `bsk` CLI + browser extension setup when `bsk` is not yet installed. + * Browser execution uses the exact same `bsk` CLI + daemon (`DSH_SESSION_ID` + * implicit scoping) + browser extension architecture as every other agent. + */ + +import type { Context } from "@deepseek-ai/cordis"; +import Schema from "@deepseek-ai/schemastery"; +import { ensureBskInPath, resolveBskExecutable } from "./env.mjs"; +import { armAgentScopedBskSkill, buildDshSkillContent, registerBskSkill } from "./skill.mjs"; + +export const name = "@wxg-prc-cpg/browser-skill-dsh-plugin"; + +export interface PluginConfig { + bskPath?: string; +} + +/** Runtime configuration schema exposed to Cordis and DSH settings UI. */ +export const Config = Schema.object({ + bskPath: Schema.string() + .default("bsk") + .description( + "Path to the bsk CLI executable or directory (defaults to resolving `bsk` from PATH or ~/.local/bin).", + ), +}); + +export type Config = PluginConfig; + +export function apply(ctx: Context, config: Partial = {}): void { + const bskPath = config.bskPath ?? "bsk"; + const restorePath = ensureBskInPath(bskPath); + const disposers: (() => void)[] = [restorePath]; + + if (typeof (ctx as { effect?: unknown }).effect === "function") { + ctx.effect(() => () => { + for (const dispose of [...disposers].reverse()) { + dispose(); + } + disposers.length = 0; + }); + } + + if (typeof (ctx as { inject?: unknown }).inject === "function") { + ctx.inject(["skills"], (injected) => { + injected.effect(() => registerBskSkill(injected, bskPath)); + }); + } else { + disposers.push(registerBskSkill(ctx, bskPath)); + } + + disposers.push(armAgentScopedBskSkill(ctx, bskPath)); +} + +export { + armAgentScopedBskSkill, + buildDshSkillContent, + ensureBskInPath, + registerBskSkill, + resolveBskExecutable, +}; diff --git a/packages/dsh-plugin-browserskill/src/skill.mts b/packages/dsh-plugin-browserskill/src/skill.mts new file mode 100644 index 000000000..9692dfe76 --- /dev/null +++ b/packages/dsh-plugin-browserskill/src/skill.mts @@ -0,0 +1,145 @@ +/** + * Progressive disclosure of the unified BrowserSkill CLI skill through DeepSeek + * Harness's official skill registry (`ctx.skills`), paired with on-demand + * `bsk` CLI setup guidance when `bsk` is not yet installed on the host. + */ + +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Context } from "@deepseek-ai/cordis"; +import { resolveBskExecutable } from "./env.mjs"; +import { + BSK_SKILL_DESCRIPTION, + BSK_SKILL_MARKDOWN, + BSK_SKILL_NAME, +} from "./skill-content.generated.mjs"; + +const PACKAGE_ROOT = fileURLToPath(new URL("../", import.meta.url)); +const SKILL_DIRECTORY = join(PACKAGE_ROOT, "skill"); +const INSTALLER_SCRIPT = join(PACKAGE_ROOT, "bin", "install-bsk.mjs"); +const AGENT_INSTALL_GUIDE = join(PACKAGE_ROOT, "AGENT_INSTALL.md"); + +/** Structural view of the DSH skill registry seam (`@deepseek-ai/dsh-skill`). */ +interface SkillsLike { + register(skill: { + name: string; + description: string; + content: string; + source?: string; + resourceBase?: { kind: "directory"; path: string }; + }): () => void; +} + +/** Structural view of a live DSH agent and the agent registry seam. */ +interface AgentLike { + ctx: Context; +} + +interface AgentsLike { + list(): AgentLike[]; +} + +/** + * Render the skill markdown for DSH. When `bsk` is already installed, returns + * the canonical `SKILL.md` body unchanged (zero extra token overhead). When + * `bsk` is missing, prepends concise on-demand setup instructions pointing to + * the bundled local installer and `AGENT_INSTALL.md`. + */ +export function buildDshSkillContent(bskPath?: string): string { + if (resolveBskExecutable(bskPath) !== null) { + return BSK_SKILL_MARKDOWN; + } + return ( + "## First-time setup (`bsk` CLI not detected)\n\n" + + "`bsk` was not found on this machine. Complete on-demand setup before running browser commands:\n\n" + + `1. Install the \`bsk\` CLI (never use \`sudo\`): \`node ${JSON.stringify(INSTALLER_SCRIPT)}\`\n` + + `2. Follow \`${AGENT_INSTALL_GUIDE}\` (Steps 3-5): run \`bsk doctor\`, ask the user to install and enable the Chrome or Edge extension if \`extension connected\` fails, re-run \`bsk doctor\`, then proceed with the task.\n\n` + + BSK_SKILL_MARKDOWN + ); +} + +/** + * Register `browser-skill` into the given Cordis context's `skills` service. + * Degrades silently when the composition omits the `skills` service. + */ +export function registerBskSkill(ctx: Context, bskPath?: string): () => void { + const skills = (ctx as { get?: (name: string) => unknown }).get?.("skills") as + | SkillsLike + | undefined + | null; + if (skills == null || typeof skills.register !== "function") { + return () => {}; + } + return skills.register({ + name: BSK_SKILL_NAME, + description: BSK_SKILL_DESCRIPTION, + content: buildDshSkillContent(bskPath), + source: "bundled", + resourceBase: { + kind: "directory", + path: SKILL_DIRECTORY, + }, + }); +} + +/** + * Register `browser-skill` into every exact agent scope so stale filesystem + * copies in `~/.agents/skills/browser-skill` do not shadow the plugin, and so + * new conversations automatically drop the first-time setup banner once `bsk` + * has been installed on demand. + */ +export function armAgentScopedBskSkill(ctx: Context, bskPath?: string): () => void { + const registrations = new Map void>(); + let active = true; + + const registerForAgent = (agent: AgentLike): void => { + if (!active || registrations.has(agent)) return; + registrations.set(agent, registerBskSkill(agent.ctx, bskPath)); + }; + + const syncExistingAgents = (targetCtx: Context): void => { + const agents = (targetCtx as { get?: (name: string) => unknown }).get?.("agents") as + | AgentsLike + | undefined + | null; + if (agents != null && typeof agents.list === "function") { + for (const agent of agents.list()) { + registerForAgent(agent); + } + } + }; + + let stopCreated = () => {}; + let stopDisposed = () => {}; + const eventCtx = ctx as unknown as { + on?: (event: string, listener: (payload: { agent: AgentLike }) => undefined) => () => void; + }; + if (typeof eventCtx.on === "function") { + stopCreated = eventCtx.on("agent/created", ({ agent }) => { + registerForAgent(agent); + return undefined; + }); + stopDisposed = eventCtx.on("agent/disposed", ({ agent }) => { + registrations.delete(agent); + return undefined; + }); + } + + syncExistingAgents(ctx); + if (typeof (ctx as { inject?: unknown }).inject === "function") { + ctx.inject(["agents"], (injected) => { + syncExistingAgents(injected); + }); + } + + return () => { + if (!active) return; + active = false; + stopDisposed(); + stopCreated(); + for (const unregister of [...registrations.values()].reverse()) { + unregister(); + } + registrations.clear(); + }; +} diff --git a/packages/dsh-plugin-browserskill/tests/plugin.integration.test.ts b/packages/dsh-plugin-browserskill/tests/plugin.integration.test.ts new file mode 100644 index 000000000..19d15556d --- /dev/null +++ b/packages/dsh-plugin-browserskill/tests/plugin.integration.test.ts @@ -0,0 +1,283 @@ +import { spawnSync } from "node:child_process"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Context } from "@deepseek-ai/cordis"; +import { createScope, scopeTarget } from "@deepseek-ai/dsh-scope"; +import { renderSkillContent, SkillRegistry } from "@deepseek-ai/dsh-skill"; +import { afterEach, describe, expect, it } from "vitest"; +import { validateSkillDirectory } from "../../../scripts/lib/validate-skill.mjs"; +import * as BrowserSkillPlugin from "../src/index.mjs"; + +const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), ".."); +const repoRoot = join(pkgRoot, "..", ".."); +const isWin = process.platform === "win32"; +const exeName = isWin ? "bsk.exe" : "bsk"; + +function findPathKey(env: NodeJS.ProcessEnv): string { + return Object.keys(env).find((k) => k.toLowerCase() === "path") ?? "PATH"; +} + +function writeExecutableBsk(dir: string, versionOutput = "bsk 0.5.0"): string { + mkdirSync(dir, { recursive: true }); + const target = join(dir, exeName); + if (isWin) { + // Copy node.exe or cmd.exe? On Windows, a tiny .cmd wrapper wouldn't match `bsk.exe`, + // so compile-free tests on Windows can copy process.execPath only if needed; here on + // POSIX a shell script with +x is a real executable, and on Windows a minimal PE or cmd check. + // Wait: on Windows `spawnSync("bsk.exe", ["--version"])` needs a valid PE executable! + // Copying `where.exe` / `hostname.exe` exits 0 or we can copy `process.execPath`? + // `node.exe --version` prints `v22.x.x` and exits 0! + writeFileSync(target, readFileSync(process.execPath)); + } else { + writeFileSync(target, `#!/bin/sh\necho "${versionOutput}"\n`, { mode: 0o755 }); + chmodSync(target, 0o755); + } + return target; +} + +function pathWithoutBsk(basePath: string): string { + return basePath + .split(delimiter) + .filter((dir) => { + if (!dir.trim()) return false; + try { + readFileSync(join(dir, exeName)); + return false; + } catch { + return true; + } + }) + .join(delimiter); +} + +describe("@wxg-prc-cpg/browser-skill-dsh-plugin end-to-end integration", () => { + const pathKey = findPathKey(process.env); + const savedEnv = { + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + BSK_INSTALL_DIR: process.env.BSK_INSTALL_DIR, + PATH: process.env[pathKey], + }; + const tempDirs: string[] = []; + + function makeTempHome(): string { + const dir = mkdtempSync(join(tmpdir(), "bsk-dsh-e2e-")); + tempDirs.push(dir); + return dir; + } + + afterEach(() => { + if (savedEnv.HOME === undefined) delete process.env.HOME; + else process.env.HOME = savedEnv.HOME; + if (savedEnv.USERPROFILE === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = savedEnv.USERPROFILE; + if (savedEnv.BSK_INSTALL_DIR === undefined) delete process.env.BSK_INSTALL_DIR; + else process.env.BSK_INSTALL_DIR = savedEnv.BSK_INSTALL_DIR; + process.env[pathKey] = savedEnv.PATH ?? ""; + + while (tempDirs.length > 0) { + const dir = tempDirs.pop()!; + rmSync(dir, { recursive: true, force: true }); + } + }); + + it("preserves package identity and keeps peerDependencies free of DSH host rc locks", () => { + const manifest = JSON.parse(readFileSync(join(pkgRoot, "package.json"), "utf8")) as { + name: string; + peerDependencies: Record; + dsh: { bundle: { patch: string } }; + }; + const patch = readFileSync(join(pkgRoot, manifest.dsh.bundle.patch), "utf8"); + + expect(BrowserSkillPlugin.name).toBe("@wxg-prc-cpg/browser-skill-dsh-plugin"); + expect(manifest.name).toBe(BrowserSkillPlugin.name); + expect(patch).toContain(`name: "${BrowserSkillPlugin.name}"`); + + const hostLockedPeers = Object.keys(manifest.peerDependencies).filter( + (dep) => dep === "@deepseek-ai/dsh" || dep.startsWith("@deepseek-ai/dsh-"), + ); + expect(hostLockedPeers).toEqual([]); + }); + + it("guides on-demand bsk installation when missing, heals PATH, and switches to lean canonical skill once installed", async () => { + const home = makeTempHome(); + const installDir = join(home, ".local", "bin"); + process.env.HOME = home; + process.env.USERPROFILE = home; + process.env.BSK_INSTALL_DIR = installDir; + process.env[pathKey] = pathWithoutBsk(savedEnv.PATH ?? ""); + + const canonical = validateSkillDirectory(join(repoRoot, "crates", "bsk-cli", "skill"), { + maxEntryBytes: 2_000, + }); + + // Mount our plugin BEFORE SkillRegistry to verify Cordis `ctx.inject(["skills"])` + // works regardless of plugin load order in cordis.patch.yml. + const root = new Context(); + const pluginFiber = root.plugin(BrowserSkillPlugin); + const skillFiber = root.plugin(SkillRegistry); + await pluginFiber; + await skillFiber; + + // 1. Default ~/.local/bin was appended to host PATH automatically. + expect((process.env[pathKey] ?? "").split(delimiter)).toContain(installDir); + + // 2. Bundled installer --check reports missing bsk before installation. + const installerScript = join(pkgRoot, "bin", "install-bsk.mjs"); + const checkBefore = spawnSync(process.execPath, [installerScript, "--check"], { + encoding: "utf8", + env: process.env, + }); + expect(checkBefore.status).toBe(1); + + // 3. Stale ~/.agents/skills/browser-skill in preset layer must NOT shadow the plugin, + // and Conversation 1 receives the on-demand setup guidance because bsk is missing. + const presetKey = { preset: "standard" }; + const presetScope = createScope(skillFiber.ctx, presetKey); + presetScope.ctx.skills.register({ + name: "browser-skill", + description: "Stale external skill", + content: "Outdated instructions", + source: "user-agents", + }); + + const agent1Key = { agent: "conv-1" }; + const agent1Scope = createScope(skillFiber.ctx, agent1Key, { parent: presetKey }); + const agent1 = { id: "conv-1", ctx: agent1Scope.ctx }; + await root.serial(scopeTarget(agent1, agent1Key), "agent/created", { + agent: agent1, + source: "startup", + }); + + const conv1Skill = await skillFiber.ctx.skills.get("browser-skill", { scope: agent1Key }); + expect(conv1Skill).toBeDefined(); + expect(conv1Skill?.source).toBe("bundled"); + expect(conv1Skill?.description).toBe(canonical.description); + expect(conv1Skill?.content).toContain("## First-time setup (`bsk` CLI not detected)"); + expect(conv1Skill?.content).toContain(JSON.stringify(installerScript)); + expect(conv1Skill?.content).toContain(join(pkgRoot, "AGENT_INSTALL.md")); + expect(conv1Skill?.content.endsWith(canonical.content)).toBe(true); + + const rendered1 = renderSkillContent(conv1Skill!); + expect(rendered1).toContain("Base directory for this skill:"); + expect(realpathSync(conv1Skill!.resourceBase!.path)).toBe(realpathSync(join(pkgRoot, "skill"))); + + // 4. After on-demand installation places `bsk` into ~/.local/bin: + // - `install-bsk.mjs` is idempotent and verifies the binary; + // - `bsk --version` resolves directly through the healed DSH host PATH; + // - Conversation 2 automatically receives the lean canonical SKILL.md without setup overhead. + writeExecutableBsk(installDir, "bsk 0.5.0"); + + const runIdempotentInstall = spawnSync(process.execPath, [installerScript], { + encoding: "utf8", + env: process.env, + }); + expect(runIdempotentInstall.status).toBe(0); + expect(runIdempotentInstall.stdout).toContain("already installed"); + expect(runIdempotentInstall.stdout).toContain("bsk doctor"); + + const directBsk = spawnSync(exeName, ["--version"], { + encoding: "utf8", + env: process.env, + }); + expect(directBsk.status).toBe(0); + + const agent2Key = { agent: "conv-2" }; + const agent2Scope = createScope(skillFiber.ctx, agent2Key, { parent: presetKey }); + const agent2 = { id: "conv-2", ctx: agent2Scope.ctx }; + await root.serial(scopeTarget(agent2, agent2Key), "agent/created", { + agent: agent2, + source: "startup", + }); + + const conv2Skill = await skillFiber.ctx.skills.get("browser-skill", { scope: agent2Key }); + expect(conv2Skill?.content).toBe(canonical.content); + expect(conv2Skill?.content).not.toContain("First-time setup"); + + await agent2Scope.dispose(); + await agent1Scope.dispose(); + await presetScope.dispose(); + await pluginFiber.dispose(); + await skillFiber.dispose(); + }); + + it("prepends configured bskPath directory to PATH and unwinds it on plugin dispose", async () => { + const home = makeTempHome(); + const customDir = join(home, "custom-bsk"); + const customBin = writeExecutableBsk(customDir, "bsk 0.5.0-custom"); + + process.env.HOME = home; + process.env.USERPROFILE = home; + process.env.BSK_INSTALL_DIR = join(home, ".local", "bin"); + process.env[pathKey] = pathWithoutBsk(savedEnv.PATH ?? ""); + + const root = new Context(); + const skillFiber = root.plugin(SkillRegistry); + const pluginFiber = root.plugin(BrowserSkillPlugin, { + bskPath: `~/custom-bsk/${exeName}`, + }); + await skillFiber; + await pluginFiber; + + expect((process.env[pathKey] ?? "").split(delimiter)[0]).toBe(customDir); + expect(BrowserSkillPlugin.resolveBskExecutable(`~/custom-bsk/${exeName}`)).toBe(customBin); + + const globalSkill = await skillFiber.ctx.skills.get("browser-skill"); + expect(globalSkill?.source).toBe("bundled"); + expect(globalSkill?.content).not.toContain("First-time setup"); + + await pluginFiber.dispose(); + expect((process.env[pathKey] ?? "").split(delimiter)).not.toContain(customDir); + await skillFiber.dispose(); + }); + + it("executes bundled platform installer via bin/install-bsk.mjs when bsk is absent and verifies installed binary", () => { + const home = makeTempHome(); + const installDir = join(home, ".local", "bin"); + const isolatedPkg = makeTempHome(); + mkdirSync(join(isolatedPkg, "bin"), { recursive: true }); + writeFileSync( + join(isolatedPkg, "bin", "install-bsk.mjs"), + readFileSync(join(pkgRoot, "bin", "install-bsk.mjs")), + ); + writeFileSync(join(isolatedPkg, "AGENT_INSTALL.md"), "# Guide\n"); + + if (isWin) { + writeFileSync( + join(isolatedPkg, "install.ps1"), + `$dir = $env:BSK_INSTALL_DIR\nNew-Item -ItemType Directory -Force -Path $dir | Out-Null\nCopy-Item -LiteralPath "${process.execPath.replace(/"/g, '""')}" -Destination (Join-Path $dir "bsk.exe")\n`, + ); + } else { + writeFileSync( + join(isolatedPkg, "install.sh"), + '#!/bin/sh\nset -eu\nmkdir -p "$BSK_INSTALL_DIR"\nprintf \'#!/bin/sh\\necho "bsk 0.5.0-installed"\\n\' > "$BSK_INSTALL_DIR/bsk"\nchmod 0755 "$BSK_INSTALL_DIR/bsk"\n', + { mode: 0o755 }, + ); + } + + process.env.HOME = home; + process.env.USERPROFILE = home; + process.env.BSK_INSTALL_DIR = installDir; + process.env[pathKey] = pathWithoutBsk(savedEnv.PATH ?? ""); + + const runInstall = spawnSync(process.execPath, [join(isolatedPkg, "bin", "install-bsk.mjs")], { + cwd: home, + encoding: "utf8", + env: process.env, + }); + expect(runInstall.status).toBe(0); + expect(runInstall.stdout).toContain("Verified"); + expect(runInstall.stdout).toContain(join(installDir, exeName)); + expect(runInstall.stdout).toContain("AGENT_INSTALL.md"); + }); +}); diff --git a/packages/dsh-plugin-browserskill/tsconfig.json b/packages/dsh-plugin-browserskill/tsconfig.json new file mode 100644 index 000000000..f9aed6577 --- /dev/null +++ b/packages/dsh-plugin-browserskill/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "rootDir": "src", + "outDir": "lib", + "declaration": true, + "strict": true, + "skipLibCheck": true, + "verbatimModuleSyntax": true + }, + "include": ["src/**/*.mts"] +} diff --git a/packages/dsh-plugin-browserskill/vitest.config.ts b/packages/dsh-plugin-browserskill/vitest.config.ts new file mode 100644 index 000000000..faa6d98e1 --- /dev/null +++ b/packages/dsh-plugin-browserskill/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + include: ["tests/**/*.test.ts"], + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 50b638114..5cb5a86a9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -121,6 +121,33 @@ importers: specifier: ^0.20.0 version: 0.20.26(@types/node@22.20.1)(jiti@2.7.0)(rolldown@1.2.4)(rollup@4.60.4) + packages/dsh-plugin-browserskill: + devDependencies: + '@deepseek-ai/cordis': + specifier: 4.0.2 + version: 4.0.2 + '@deepseek-ai/dsh-llm': + specifier: 0.1.5-rc.3 + version: 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-scope': + specifier: 0.1.5-rc.3 + version: 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)) + '@deepseek-ai/dsh-skill': + specifier: 0.1.5-rc.3 + version: 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-llm@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2))(@deepseek-ai/dsh-scope@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2))) + '@deepseek-ai/schemastery': + specifier: 3.18.2 + version: 3.18.2 + '@types/node': + specifier: ^22.10.0 + version: 22.20.1 + typescript: + specifier: ^5.8.0 + version: 5.9.3 + vitest: + specifier: ^4.1.6 + version: 4.1.6(@types/node@22.20.1)(happy-dom@15.11.7)(vite@8.0.13(@types/node@22.20.1)(esbuild@0.27.7)(jiti@2.7.0)) + packages/i18n: dependencies: i18next: @@ -311,6 +338,72 @@ packages: peerDependencies: postcss-selector-parser: ^7.0.0 + '@deepseek-ai/cordis@4.0.2': + resolution: {integrity: sha512-asOnXP1TzFSFQlHb1iegDZp0z/8WD1c7YNrwJR/Tx2bzNuMXfcekE/I67Iv6SQXeLB4csxqCngzQKANP7gdw0g==} + hasBin: true + peerDependencies: + '@deepseek-ai/cordis-plugin-include': ^1.0.7 + '@deepseek-ai/cordis-plugin-loader': ^1.0.3 + peerDependenciesMeta: + '@deepseek-ai/cordis-plugin-include': + optional: true + '@deepseek-ai/cordis-plugin-loader': + optional: true + + '@deepseek-ai/cosmokit@1.9.0': + resolution: {integrity: sha512-5O1S53mZiJyZYcvxxD0Qv1EY7qFPSxbGyD8CbVK6gw7W9FvcXZj2YIX1ZkOqyQQ3Xt2rFkZDHJv0+V3Zmmp8CA==} + + '@deepseek-ai/dsh-brand@0.1.5-rc.3': + resolution: {integrity: sha512-pzbPtyEwnFMCrUYLwFio8GmUxtTqqAkhW5IheWH1tSgUnVIAu4OwVbxwTNiDGMRbgTRAzT9xZ7bukUejpyob4w==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-invariants@0.1.5-rc.3': + resolution: {integrity: sha512-1iPfLsu8zFAsfIRYE958uMhB3oTO/LmN3ArTifxWFlRvCmBRd9Ca6l7DZh/daLnJsDSdtLQtVzPqbgTV9tzNlQ==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-llm@0.1.5-rc.3': + resolution: {integrity: sha512-c6Z7S1SlRAgLKQ/MZKp0mCMrBz06X9XEddLFxhK5Flq0PM18dsJgIbRgNpobILy2AJyYx0vnHbepjmITW6BXWA==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-scope@0.1.5-rc.3': + resolution: {integrity: sha512-2B45GShJQwPs+Ad4MdI2kkbxkogagZopAY2lbYowAz6Oris3jGxZJ4v3/ZyJw7c9bhTJUagHXCpXQYFSIXumLA==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/dsh-invariants': ^0.1.5-rc.3 + + '@deepseek-ai/dsh-skill@0.1.5-rc.3': + resolution: {integrity: sha512-fNrzzdeLoPc0zsg07CgaCnT/MrZEzjs8SocpK6Upc/odOwQJOAARjJBCCka+7i7dQABwY3/cSd/BQTPkvzC1vA==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/dsh-llm': ^0.1.5-rc.3 + '@deepseek-ai/dsh-scope': ^0.1.5-rc.3 + + '@deepseek-ai/dsh-timeout@0.1.5-rc.3': + resolution: {integrity: sha512-Z7HyqvGaO/k4XLp/EykvIuA0i67CvWb/R0c7Lt/3/8dwmDvqKWgWvh/EiNip7UMXMpQBJzI+Xe4OuzXV/A90Nw==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-typert-protocol@0.1.5-rc.3': + resolution: {integrity: sha512-lcQGIQK4Z5dBguLQFzoDiHQBT387egSnFYJOakEjqIMM9jkAfMI/HqlsVSRSzHW7SQL9f6SxJMHCD7pIkJzsWA==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-util-crypto@0.1.5-rc.3': + resolution: {integrity: sha512-gQAFF2TLLAV5ejHAklCplePVdL2TV4CH1Xt3A0bqaLxZ2zoOxXoVUieUzPrHo+X1NKfsmdcWvOx9zdlDkXY+sQ==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-util-values@0.1.5-rc.3': + resolution: {integrity: sha512-K0qEm9XmgcxCMuJBK7skNE3v35JTOurN24IwrZ4t0xoaSlZSF4wR0L/R7ipj9IQSlB7sGdQLdegTNsZmSlmw4Q==} + peerDependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/schemastery@3.18.2': + resolution: {integrity: sha512-njDtZsznjYxok7KLLlHOPyuv2efdWVbSflAHgztSfbMsg+CVraEoRe2DjOCgClYv3ZCSm7WXoaUkbB/+RY7tWQ==} + '@devicefarmer/adbkit-logcat@2.1.3': resolution: {integrity: sha512-yeaGFjNBc/6+svbDeul1tNHtNChw6h8pSHAt5D+JsedUrMTN7tla7B15WLDyekxsuS2XlZHRxpuC6m92wiwCNw==} engines: {node: '>= 4'} @@ -3059,6 +3152,67 @@ snapshots: dependencies: postcss-selector-parser: 7.1.1 + '@deepseek-ai/cordis@4.0.2': + dependencies: + '@deepseek-ai/cosmokit': 1.9.0 + '@standard-schema/spec': 1.1.0 + + '@deepseek-ai/cosmokit@1.9.0': {} + + '@deepseek-ai/dsh-brand@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/schemastery': 3.18.2 + + '@deepseek-ai/dsh-llm@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/dsh-brand': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-timeout': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-typert-protocol': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-util-crypto': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-util-values': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/schemastery': 3.18.2 + zod: 4.4.3 + + '@deepseek-ai/dsh-scope@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2))': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/dsh-invariants': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + + '@deepseek-ai/dsh-skill@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-llm@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2))(@deepseek-ai/dsh-scope@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)))': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + '@deepseek-ai/dsh-llm': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/dsh-scope': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)(@deepseek-ai/dsh-invariants@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)) + '@deepseek-ai/dsh-util-values': 0.1.5-rc.3(@deepseek-ai/cordis@4.0.2) + '@deepseek-ai/schemastery': 3.18.2 + + '@deepseek-ai/dsh-timeout@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-typert-protocol@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-util-crypto@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/dsh-util-values@0.1.5-rc.3(@deepseek-ai/cordis@4.0.2)': + dependencies: + '@deepseek-ai/cordis': 4.0.2 + + '@deepseek-ai/schemastery@3.18.2': + dependencies: + '@deepseek-ai/cosmokit': 1.9.0 + '@standard-schema/spec': 1.1.0 + '@devicefarmer/adbkit-logcat@2.1.3': {} '@devicefarmer/adbkit-monkey@1.2.1': {} diff --git a/scripts/check-dsh-package.mjs b/scripts/check-dsh-package.mjs new file mode 100644 index 000000000..839f78b69 --- /dev/null +++ b/scripts/check-dsh-package.mjs @@ -0,0 +1,125 @@ +// Run after building `@wxg-prc-cpg/browser-skill-dsh-plugin`. +// Packs the actual npm tarball, unpacks it outside the repository, verifies +// every bundled skill/installer asset byte-for-byte against the canonical repo +// sources, and exercises the packed plugin inside a real Cordis + SkillRegistry runtime. +import assert from "node:assert/strict"; +import { execFileSync, execSync, spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { validateSkillDirectory } from "./lib/validate-skill.mjs"; + +const repoRoot = fileURLToPath(new URL("../", import.meta.url)); +const pkgDir = join(repoRoot, "packages", "dsh-plugin-browserskill"); +const pkgRequire = createRequire(join(pkgDir, "package.json")); +const canonicalSkillDir = join(repoRoot, "crates", "bsk-cli", "skill"); +const temp = mkdtempSync(join(tmpdir(), "bsk-dsh-package-")); +const originalCwd = process.cwd(); + +let skillFiber; +let pluginFiber; + +try { + const packResult = JSON.parse( + execSync("npm pack --ignore-scripts --json", { + cwd: pkgDir, + encoding: "utf8", + env: { + ...Object.fromEntries( + Object.entries(process.env).filter( + ([name]) => !/^npm_config_(?:cache|pack_destination)$/i.test(name), + ), + ), + npm_config_cache: join(temp, "npm-cache"), + npm_config_pack_destination: temp, + }, + }), + ); + const [archive] = Array.isArray(packResult) ? packResult : Object.values(packResult); + assert(typeof archive?.filename === "string", "npm pack did not return an archive"); + + execFileSync("tar", ["-xzf", join(temp, archive.filename), "-C", temp]); + const unpacked = join(temp, "package"); + + const options = { maxEntryBytes: 2_000 }; + const canonical = validateSkillDirectory(canonicalSkillDir, options); + const packed = validateSkillDirectory(join(unpacked, "skill"), options); + assert.deepEqual( + packed.files, + canonical.files, + "npm tarball must ship every canonical crates/bsk-cli/skill resource unchanged", + ); + + for (const rootAsset of ["install.sh", "install.ps1", "AGENT_INSTALL.md", "LICENSE"]) { + assert.deepEqual( + readFileSync(join(unpacked, rootAsset)), + readFileSync(join(repoRoot, rootAsset)), + `npm tarball must ship ${rootAsset} unchanged`, + ); + } + assert.deepEqual( + readFileSync(join(unpacked, "cordis.patch.yml")), + readFileSync(join(pkgDir, "cordis.patch.yml")), + "npm tarball must ship cordis.patch.yml unchanged", + ); + + symlinkSync(join(pkgDir, "node_modules"), join(unpacked, "node_modules"), "junction"); + process.chdir(temp); + + const { Context } = await import(pathToFileURL(pkgRequire.resolve("@deepseek-ai/cordis")).href); + const { SkillRegistry } = await import( + pathToFileURL(pkgRequire.resolve("@deepseek-ai/dsh-skill")).href + ); + const packedPlugin = await import(pathToFileURL(join(unpacked, "lib/index.mjs")).href); + + const root = new Context(); + skillFiber = root.plugin(SkillRegistry); + pluginFiber = root.plugin(packedPlugin); + await skillFiber; + await pluginFiber; + + const skill = await skillFiber.ctx.skills.get("browser-skill"); + assert(skill, "packed plugin must register browser-skill in SkillRegistry"); + assert.equal(skill.name, packed.name); + assert.equal(skill.description, packed.description); + assert( + skill.content.endsWith(packed.content), + "registered body must end with canonical SKILL.md body", + ); + assert.equal(skill.resourceBase.kind, "directory"); + assert.equal( + realpathSync(skill.resourceBase.path), + realpathSync(join(unpacked, "skill")), + "resourceBase must resolve inside unpacked npm package, never repository source", + ); + + for (const [relPath, content] of packed.files) { + assert.equal(readFileSync(join(skill.resourceBase.path, relPath), "utf8"), content); + if (relPath.startsWith("references/")) { + assert(!skill.content.includes(content.trim()), "references must stay deferred"); + } + } + + const probe = spawnSync(process.execPath, [join(unpacked, "bin/install-bsk.mjs"), "--check"], { + cwd: temp, + encoding: "utf8", + }); + assert( + probe.status === 0 || probe.status === 1, + `bundled install-bsk.mjs --check failed unexpectedly: ${probe.stderr}`, + ); + + console.log( + `npm bundle verified: ${packed.files.size} canonical skill files + installer assets resolved outside repository`, + ); +} finally { + try { + if (pluginFiber) await pluginFiber.dispose(); + if (skillFiber) await skillFiber.dispose(); + } finally { + process.chdir(originalCwd); + rmSync(temp, { recursive: true, force: true }); + } +} diff --git a/scripts/release.mjs b/scripts/release.mjs index b3c4ddab5..1cebb3538 100755 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -2,7 +2,7 @@ /** * Unified release script for BrowserSkill. * - * Bumps CLI and Extension to the same version, updates + * Bumps CLI, Extension, and DSH Plugin to the same version, updates * CHANGELOG.md, commits, tags, and optionally pushes. * * Usage: @@ -10,14 +10,14 @@ * node scripts/release.mjs --dry-run # preview changes only * node scripts/release.mjs --push # also push to origin * node scripts/release.mjs --push --only ext # push only ext tag - * node scripts/release.mjs --push --only cli # push only cli tag + * node scripts/release.mjs --push --only cli,dsh # push only cli + dsh tags * node scripts/release.mjs --push-tags --only ext # push tag(s) for an already-committed release * * Options: * --dry-run Show what would change without writing anything * --push After commit+tag, push the branch and all release tags * --push-tags Push release tags only (skip version bump; useful for staged rollout) - * --only Comma-separated subset of: cli, ext (default: both) + * --only Comma-separated subset of: cli, ext, dsh (default: all three) * --no-commit Write files but skip git commit and tagging */ @@ -25,12 +25,13 @@ import { execSync } from "node:child_process"; import { readFileSync, writeFileSync } from "node:fs"; import { parseArgs } from "node:util"; -const TAG_PREFIX = { cli: "cli-v", ext: "ext-v" }; -const ALL_COMPONENTS = ["cli", "ext"]; +const TAG_PREFIX = { cli: "cli-v", ext: "ext-v", dsh: "dsh-plugin-v" }; +const ALL_COMPONENTS = ["cli", "ext", "dsh"]; const VERSION_FILES = { cargo: "Cargo.toml", extension: "apps/extension/package.json", + dshPlugin: "packages/dsh-plugin-browserskill/package.json", }; // --------------------------------------------------------------------------- @@ -94,7 +95,9 @@ if (pushTagsOnly) { const newVersion = positionals[0]; if (!newVersion) { - console.error("Usage: node scripts/release.mjs [--dry-run] [--push] [--only cli,ext]"); + console.error( + "Usage: node scripts/release.mjs [--dry-run] [--push] [--only cli,ext,dsh]", + ); process.exit(1); } @@ -114,8 +117,9 @@ function readCurrentVersions() { cargo.match(/^version\s*=\s*"([^"]+)"/m)?.[1]; const extPkg = JSON.parse(readFileSync(VERSION_FILES.extension, "utf8")); + const dshPkg = JSON.parse(readFileSync(VERSION_FILES.dshPlugin, "utf8")); - return { cargo: cargoVer, extension: extPkg.version }; + return { cargo: cargoVer, extension: extPkg.version, dshPlugin: dshPkg.version }; } const current = readCurrentVersions(); @@ -123,6 +127,7 @@ const current = readCurrentVersions(); console.log("Current versions:"); console.log(` CLI/Daemon (Cargo.toml): ${current.cargo}`); console.log(` Extension (package.json): ${current.extension}`); +console.log(` DSH Plugin (package.json): ${current.dshPlugin}`); console.log(`\nBumping all → ${newVersion}`); if (dryRun) console.log(" (dry-run mode — no files will be written)\n"); @@ -206,6 +211,11 @@ const writes = [ content: bumpPackageJson(VERSION_FILES.extension, newVersion), label: "Extension package.json", }, + { + path: VERSION_FILES.dshPlugin, + content: bumpPackageJson(VERSION_FILES.dshPlugin, newVersion), + label: "DSH Plugin package.json", + }, ]; const changelogUpdate = updateChangelog(newVersion); @@ -250,7 +260,9 @@ if (noCommit || dryRun) { } console.log("\nCommitting..."); -run("git add Cargo.toml Cargo.lock apps/extension/package.json CHANGELOG.md 2>/dev/null || true"); +run( + "git add Cargo.toml Cargo.lock apps/extension/package.json packages/dsh-plugin-browserskill/package.json CHANGELOG.md 2>/dev/null || true", +); run(`git commit -m "chore(release): ${newVersion}"`); console.log("Tagging..."); @@ -283,8 +295,9 @@ if (!pushAfter) { console.log(" # Push extension tag first (store review takes time)"); console.log(` git push origin ext-v${newVersion}`); console.log(""); - console.log(" # Then push CLI tag"); + console.log(" # Then push CLI and DSH plugin tags"); console.log(` git push origin cli-v${newVersion}`); + console.log(` git push origin dsh-plugin-v${newVersion}`); } // --------------------------------------------------------------------------- diff --git a/scripts/release.test.mjs b/scripts/release.test.mjs index fddd4aea3..07a12b3f4 100644 --- a/scripts/release.test.mjs +++ b/scripts/release.test.mjs @@ -11,11 +11,13 @@ const scriptPath = fileURLToPath(new URL("./release.mjs", import.meta.url)); function prepareRelease(t, changelog, extraArgs = []) { const cwd = mkdtempSync(join(tmpdir(), "bsk-release-test-")); t.after(() => rmSync(cwd, { recursive: true, force: true })); - for (const dir of ["apps/extension", "bin"]) { + for (const dir of ["apps/extension", "packages/dsh-plugin-browserskill", "bin"]) { mkdirSync(join(cwd, dir), { recursive: true }); } writeFileSync(join(cwd, "Cargo.toml"), '[workspace.package]\nversion = "0.2.1"\n'); - writeFileSync(join(cwd, "apps/extension", "package.json"), '{"version":"0.2.1"}\n'); + for (const dir of ["apps/extension", "packages/dsh-plugin-browserskill"]) { + writeFileSync(join(cwd, dir, "package.json"), '{"version":"0.2.1"}\n'); + } writeFileSync(join(cwd, "CHANGELOG.md"), changelog); // Exercise the real file-writing path without compiling Rust or creating Git tags. const windows = process.platform === "win32"; From da97d558f55f533d4155226186da958ba7a890a9 Mon Sep 17 00:00:00 2001 From: NianJiuZst <3235467914@qq.com> Date: Tue, 17 Nov 2026 14:59:40 +0800 Subject: [PATCH 2/2] fix(cooperation,screenshot): avoid spurious FrameUnresponsiveError on cold 2x full-page captures Why: - After Wave 5A (#754) moved `content.js` to lazy runtime injection, cold 2x DPR SwiftShader full-page captures (`agent.browser.test.ts` `scale = 2` on 2-vCPU Linux CI runners) can overlap initial Tier-A ShadowRoot CSS/React mount and `CAPTURE_SUPPRESS` two-frame compositing with `runBrowserMutation` frame collection, intermittently exceeding the 1200ms per-frame IPC deadline with `FrameUnresponsiveError` (`effect_state: "none"`). - `guardedRunner.runBrowserMutation` also invoked `beginDomMutation()` followed immediately by `prepare()`, issuing two redundant back-to-back full-tab `collectCooperationFrames` sweeps per call, while `handleFullPageScreenshot` wrapped passive read-only `inspect` probes in `runBrowserMutation`. What: - Call `prepare(undefined, "Browser.mutate")` directly in `runBrowserMutation` (`action-guard.ts`), preserving full decision/expectation and pending-gesture verification in a single frame sweep before `dispatch(true, "Browser.mutate")`. - Skip `runBrowserMutation` on passive `inspect` probes in `handleFullPageScreenshot` (`screenshot-full-page.ts`). - Raise `FRAME_REPLY_TIMEOUT_MS` (`browser-bridge.ts`) and `OWNER_REPLY_MS` (`hidden-frames.ts`) from `1200ms` to `3000ms`. --- CHANGELOG.md | 1 + CHANGELOG.zh-CN.md | 1 + apps/extension/src/cooperation/action-guard.ts | 3 +-- apps/extension/src/cooperation/browser-bridge.test.ts | 9 +++++---- apps/extension/src/cooperation/browser-bridge.ts | 6 +++++- apps/extension/src/cooperation/hidden-frames.ts | 2 +- apps/extension/src/tools/screenshot-full-page.ts | 4 +++- 7 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce811d17e..86d3a9545 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ determines which versions can connect. ### Fixed +- Eliminated redundant back-to-back frame collection sweeps in `guardedRunner.runBrowserMutation` (`action-guard.ts`), skipped mutation fencing on passive `inspect` probes in `handleFullPageScreenshot`, and raised the per-frame cooperation IPC reply deadline (`FRAME_REPLY_TIMEOUT_MS` / `OWNER_REPLY_MS`) from `1200ms` to `3000ms` so cold high-DPR / software-rasterized full-page captures and Tier-A overlay mounts do not spuriously fail with `FrameUnresponsiveError` (#761). - Added `--max-tokens` (`max_tokens` in MCP) to `bsk step`, `bsk plan`, `bsk_interact` (with `sync_after` or `until_visible`), and `bsk_plan`, forwarding it to the post-action `tool.cooperate` sync instead of hardcoding `None` so `--max-tokens` baselines stay reusable across `delta` and `unchanged` syncs without forcing an unbounded page re-capture (#755). - Ignored internal `data-bsk-*` attributes and `` (`[data-bsk-overlay]`) ShadowHost mutations in `cooperation-capture.ts` so active recording and sensitive-field markers no longer advance `FrameState.structure`, excluded extension ShadowRoot UI controls (`HelpRequestOverlay`, `RecordOverlay`, `BorrowConfirmationOverlay`) across `record-capture.ts`, `record-hover-surface.ts`, and `cooperation-capture.ts` so overlay interactions and hover surfaces are never mis-recorded as webpage steps, and re-evaluated tab control ownership after awaiting `ensureOverlayInjected` so mid-injection tab detachments never flash stale `control` state. - VOM token estimation now handles unpaired UTF-16 surrogates without combining them with the following symbol or throwing a `RangeError`; valid emoji pairs retain their existing estimates. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 8f6311726..ec6bb91bf 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -30,6 +30,7 @@ CLI 和扩展可以分别发布,能否连接由协议兼容性决定。更新 ### 修复 +- 消除 `guardedRunner.runBrowserMutation`(`action-guard.ts`)中重复的连续整标签页帧状态采集、跳过 `handleFullPageScreenshot` 中只读 `inspect` 探测步骤的变更门禁,并将协作帧 IPC 响应超时阈值(`FRAME_REPLY_TIMEOUT_MS` / `OWNER_REPLY_MS`)从 `1200ms` 放宽至 `3000ms`,防止高分屏(2x DPR)/ 软光栅冷启动与按需浮层挂载期间误报 `FrameUnresponsiveError`(#761)。 - 为 `bsk step`、`bsk plan`、MCP `bsk_interact`(搭配 `sync_after` 或 `until_visible`)及 `bsk_plan` 补齐 `--max-tokens`(MCP 为 `max_tokens`)参数并透传至后置 `tool.cooperate` 同步请求,解决此前硬编码 `None` 导致带预算会话在后续动作触发 `token_budget_changed` 并回退为整页无上限重采的问题(#755)。 - 在 `cooperation-capture.ts` 中忽略扩展内部私有 `data-bsk-*` 属性与 ``(`[data-bsk-overlay]`)ShadowHost 变更以消除录制/敏感字段标记对 `FrameState.structure` 的自污染,在 `record-capture.ts`、`record-hover-surface.ts` 与 `cooperation-capture.ts` 中统一过滤扩展自身 ShadowRoot 浮层控件(`HelpRequestOverlay`、`RecordOverlay`、`BorrowConfirmationOverlay`)防止浮层内点击/输入或悬停面被误录为网页操作,并在 `ensureOverlayInjected` 异步注入完成后二次校验标签页受控归属以杜绝注入途中断开控制导致的陈旧浮层闪现。 - VOM Token 估算现在能处理未配对的 UTF-16 代理字符,不会再误合并后续符号或抛出 `RangeError`;有效 emoji 代理对的估算保持不变。 diff --git a/apps/extension/src/cooperation/action-guard.ts b/apps/extension/src/cooperation/action-guard.ts index b9e53764a..1fc4a4d06 100644 --- a/apps/extension/src/cooperation/action-guard.ts +++ b/apps/extension/src/cooperation/action-guard.ts @@ -231,8 +231,7 @@ export function guardedRunner(cdp: T, options: ActionGuard if (key === "runBrowserMutation") return async (operation: () => Promise): Promise => { if (!prepare) throw new Error("Shared-tab observation cannot mutate the browser"); - await beginDomMutation?.(); - await prepare(); + await prepare(undefined, "Browser.mutate"); dispatch?.(true, "Browser.mutate"); return operation(); }; diff --git a/apps/extension/src/cooperation/browser-bridge.test.ts b/apps/extension/src/cooperation/browser-bridge.test.ts index c3a298764..ba5548f51 100644 --- a/apps/extension/src/cooperation/browser-bridge.test.ts +++ b/apps/extension/src/cooperation/browser-bridge.test.ts @@ -4,6 +4,7 @@ import { attachCooperation, COOPERATION_SUBFRAME_DEBOUNCE_MS, collectCooperationFrames, + FRAME_REPLY_TIMEOUT_MS, } from "./browser-bridge"; import { FrameCollectionError, FrameUnresponsiveError } from "./frame-error"; import type { FrameOwner } from "./hidden-frames"; @@ -99,7 +100,7 @@ it("keeps the collection deadline when a retry never responds", async () => { const result = expect(collectCooperationFrames(7, COOPERATION_READ, "lease")).rejects.toThrow( "A page frame is not responding", ); - await vi.advanceTimersByTimeAsync(1200); + await vi.advanceTimersByTimeAsync(FRAME_REPLY_TIMEOUT_MS); await result; expect(send).toHaveBeenCalledTimes(2); }); @@ -125,7 +126,7 @@ it("cannot arm a late retry after the collection deadline", async () => { const result = expect(collectCooperationFrames(7, COOPERATION_ARM, "lease")).rejects.toThrow( "A page frame is not responding", ); - await vi.advanceTimersByTimeAsync(1200); + await vi.advanceTimersByTimeAsync(FRAME_REPLY_TIMEOUT_MS); await result; reply(undefined); await vi.advanceTimersByTimeAsync(25); @@ -335,7 +336,7 @@ it("cannot arm a repaired collector after the deadline", async () => { const result = expect(collectCooperationFrames(7, COOPERATION_ARM, "lease")).rejects.toThrow( "not responding", ); - await vi.advanceTimersByTimeAsync(1200); + await vi.advanceTimersByTimeAsync(FRAME_REPLY_TIMEOUT_MS); await result; finish(); await vi.advanceTimersByTimeAsync(25); @@ -453,7 +454,7 @@ const settle = async (work: Promise) => { (value) => ({ value }), (error: unknown) => ({ error }), ); - await vi.advanceTimersByTimeAsync(1200); + await vi.advanceTimersByTimeAsync(FRAME_REPLY_TIMEOUT_MS); return outcome as Promise<{ value?: T; error?: unknown }>; }; diff --git a/apps/extension/src/cooperation/browser-bridge.ts b/apps/extension/src/cooperation/browser-bridge.ts index 3d70d7daa..6b8bced89 100644 --- a/apps/extension/src/cooperation/browser-bridge.ts +++ b/apps/extension/src/cooperation/browser-bridge.ts @@ -22,6 +22,7 @@ import { } from "./types"; export const COOPERATION_SUBFRAME_DEBOUNCE_MS = 50; +export const FRAME_REPLY_TIMEOUT_MS = 3_000; function validFrame(value: unknown): value is FrameState { if (!value || typeof value !== "object") return false; @@ -114,7 +115,10 @@ async function readFrame( return active ? request() : undefined; })(), new Promise((_, reject) => { - timer = setTimeout(() => reject(new FrameUnresponsiveError([frameIdentity(frame)])), 1200); + timer = setTimeout( + () => reject(new FrameUnresponsiveError([frameIdentity(frame)])), + FRAME_REPLY_TIMEOUT_MS, + ); }), ]); if (!validFrame(value)) diff --git a/apps/extension/src/cooperation/hidden-frames.ts b/apps/extension/src/cooperation/hidden-frames.ts index ed44038c3..2ce5429f5 100644 --- a/apps/extension/src/cooperation/hidden-frames.ts +++ b/apps/extension/src/cooperation/hidden-frames.ts @@ -11,7 +11,7 @@ export interface FrameOwner { } const OWNER_ELEMENTS = new Set(["iframe", "frame", "object", "embed", "fencedframe"]); -const OWNER_REPLY_MS = 1200; +const OWNER_REPLY_MS = 3_000; const MAX_OWNERS = 4096; /** diff --git a/apps/extension/src/tools/screenshot-full-page.ts b/apps/extension/src/tools/screenshot-full-page.ts index fa0aae80d..55e146008 100644 --- a/apps/extension/src/tools/screenshot-full-page.ts +++ b/apps/extension/src/tools/screenshot-full-page.ts @@ -216,7 +216,9 @@ export async function handleFullPageScreenshot( page: (command) => { if (command.action !== "finish") phase = `page ${command.action}`; const run = () => client.page(command); - return command.action !== "finish" && deps.cdp.runBrowserMutation + return command.action !== "finish" && + command.action !== "inspect" && + deps.cdp.runBrowserMutation ? deps.cdp.runBrowserMutation(run) : run(); },