Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

perf(packaging): ship DSH as one dsh.asar + native node_modules (12.5k -> ~55 files)

Marla0ac6484f3b5c
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0724e9b..9783c13 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -21,8 +21,10 @@
# anymodel-bot-<version>-linux-x86_64.AppImage ubuntu-24.04 (smoke-tested under Xvfb)
# anymodel-bot-<version>-linux-arm64.AppImage ubuntu-24.04-arm (smoke-tested under Xvfb)
# Each installer is built on a runner of its own OS *and* CPU: dsh-runtime/node_modules is full of
-# per-arch native packages (node-pty, koffi, sharp, ripgrep, libreoffice-kit, ...) and
-# scripts/prepare-dsh.mjs installs and prunes them for exactly one os-cpu.
+# per-arch native packages (node-pty, koffi, sharp, ripgrep, ...) and scripts/prepare-dsh.mjs
+# installs and prunes them for exactly one os-cpu. scripts/bundle-dsh.mjs then packs the runtime
+# into resources/dsh: one dsh.asar (all JavaScript, ~10k files) plus a node_modules/ with only the
+# native packages (~55 files), which keeps the Windows installer fast (few files to extract and scan).
#
# Code signing / notarization: optional repository secrets. Without them the build still succeeds:
# macOS is ad-hoc signed (Apple Silicon refuses to launch unsigned code) but not notarized, so
@@ -104,13 +106,14 @@ jobs:
env:
TARGETS: ${{ inputs.targets || 'all' }}
run: |
+ # app: the unpacked app electron-builder leaves next to the installer (checked before upload)
all='[
- {"name":"mac-arm64","runner":"macos-15","os":"darwin","arch":"arm64","goos":"darwin","goarch":"arm64","targets":"--mac dmg","file":"mac-arm64.dmg"},
- {"name":"mac-x64","runner":"macos-15-intel","os":"darwin","arch":"x64","goos":"darwin","goarch":"amd64","targets":"--mac dmg","file":"mac-x64.dmg"},
- {"name":"win-x64","runner":"windows-2025","os":"win32","arch":"x64","goos":"windows","goarch":"amd64","targets":"--win nsis","file":"win-x64.exe"},
- {"name":"win-arm64","runner":"windows-11-arm","os":"win32","arch":"arm64","goos":"windows","goarch":"arm64","targets":"--win nsis","file":"win-arm64.exe"},
- {"name":"linux-x64","runner":"ubuntu-24.04","os":"linux","arch":"x64","goos":"linux","goarch":"amd64","targets":"--linux AppImage","file":"linux-x86_64.AppImage"},
- {"name":"linux-arm64","runner":"ubuntu-24.04-arm","os":"linux","arch":"arm64","goos":"linux","goarch":"arm64","targets":"--linux AppImage","file":"linux-arm64.AppImage"}
+ {"name":"mac-arm64","runner":"macos-15","os":"darwin","arch":"arm64","goos":"darwin","goarch":"arm64","targets":"--mac dmg","file":"mac-arm64.dmg","app":"release/mac-arm64/anymodel bot.app/Contents/MacOS/anymodel bot"},
+ {"name":"mac-x64","runner":"macos-15-intel","os":"darwin","arch":"x64","goos":"darwin","goarch":"amd64","targets":"--mac dmg","file":"mac-x64.dmg","app":"release/mac/anymodel bot.app/Contents/MacOS/anymodel bot"},
+ {"name":"win-x64","runner":"windows-2025","os":"win32","arch":"x64","goos":"windows","goarch":"amd64","targets":"--win nsis","file":"win-x64.exe","app":"release/win-unpacked/anymodel bot.exe"},
+ {"name":"win-arm64","runner":"windows-11-arm","os":"win32","arch":"arm64","goos":"windows","goarch":"arm64","targets":"--win nsis","file":"win-arm64.exe","app":"release/win-arm64-unpacked/anymodel bot.exe"},
+ {"name":"linux-x64","runner":"ubuntu-24.04","os":"linux","arch":"x64","goos":"linux","goarch":"amd64","targets":"--linux AppImage","file":"linux-x86_64.AppImage","app":"release/linux-unpacked/anymodel-bot"},
+ {"name":"linux-arm64","runner":"ubuntu-24.04-arm","os":"linux","arch":"arm64","goos":"linux","goarch":"arm64","targets":"--linux AppImage","file":"linux-arm64.AppImage","app":"release/linux-arm64-unpacked/anymodel-bot"}
]'
if [ "$TARGETS" = all ]; then
selected=$(jq -c . <<<"$all")
@@ -212,6 +215,9 @@ jobs:
console.log(`dsh-runtime native modules OK for ${want}`);
'
+ - name: Bundle dsh-runtime into dsh.asar + native node_modules
+ run: node scripts/bundle-dsh.mjs --os "${{ matrix.os }}" --cpu "${{ matrix.arch }}"
+
- name: Build magpie
run: node scripts/build-magpie.mjs --target "${{ matrix.goos }}/${{ matrix.goarch }}"
@@ -228,11 +234,15 @@ jobs:
APPLE_TEAM_ID: ${{ matrix.os == 'darwin' && secrets.APPLE_TEAM_ID || '' }}
WIN_CSC_LINK: ${{ matrix.os == 'win32' && secrets.WIN_CSC_LINK || '' }}
WIN_CSC_KEY_PASSWORD: ${{ matrix.os == 'win32' && secrets.WIN_CSC_KEY_PASSWORD || '' }}
+ # NSIS payload (app-64.7z) at 7z level 3 instead of 9: on windows-2025 with Defender on, the
+ # installer grows 156 -> 171 MB and a fresh install drops 35 -> 22 s (extraction 21 -> 11 s).
+ # The 7z filter stays BCJ (electron-builder pins it for the NSIS decoder).
+ ELECTRON_BUILDER_COMPRESSION_LEVEL: ${{ matrix.os == 'win32' && '3' || '' }}
run: |
# Naming the target on the command line overrides the arch lists in package.json "build",
# so exactly one installer for this runner's arch is produced.
args=(${{ matrix.targets }} --${{ matrix.arch }} --publish never)
- for v in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID WIN_CSC_LINK WIN_CSC_KEY_PASSWORD; do
+ for v in CSC_LINK CSC_KEY_PASSWORD APPLE_ID APPLE_APP_SPECIFIC_PASSWORD APPLE_TEAM_ID WIN_CSC_LINK WIN_CSC_KEY_PASSWORD ELECTRON_BUILDER_COMPRESSION_LEVEL; do
[ -n "${!v}" ] || unset "$v"
done
if [ "${{ matrix.os }}" = darwin ] && [ -z "${CSC_LINK:-}" ]; then
@@ -254,6 +264,11 @@ jobs:
fi
ls -la "$INSTALLER"
+ # The packaged executable in Node mode (as the app runs DSH): SDK client and DSH from dsh.asar, native
+ # modules from resources/dsh/node_modules, and one agent turn through a mock model.
+ - name: Check the packaged DSH runtime
+ run: node scripts/verify-dsh-bundle.mjs "${{ matrix.app }}"
+
- name: Smoke-test the AppImage
if: matrix.os == 'linux'
run: |
diff --git a/README.md b/README.md
index 564035e..8d21772 100644
--- a/README.md
+++ b/README.md
@@ -50,8 +50,11 @@ npm run electron:dev # 开发运行
npm run electron:smoke # 冒烟测试(Linux 无显示器时自动用 xvfb-run)
npm run dist # 打包当前平台(magpie 随附在 resources/magpie/)
npm run dist:linux | dist:mac | dist:win
+npm run test:dsh-bundle # 用 Electron 跑真实 DSH 集成测试,加载打包后的 build/dsh(需先 prepare:dsh + bundle:dsh)
```
+- DSH 代理运行时:`scripts/prepare-dsh.mjs` 按目标平台安装 `dsh-runtime/`,`scripts/bundle-dsh.mjs` 把它打成 `resources/dsh/dsh.asar`(全部 JS,一个文件)加上 `resources/dsh/node_modules/`(只有原生包,约 55 个文件)。Electron 主进程和 `ELECTRON_RUN_AS_NODE` 子进程直接读 asar,无需首启解压;安装包因此只需解出几百个文件(Windows 上解压与杀毒逐个扫描是安装慢的主因)。开发时仍直接用 `dsh-runtime/`。
+
- 数据目录:`<userData>/data`(macOS `~/Library/Application Support/anymodel bot/data`,Windows `%APPDATA%\anymodel bot\data`,Linux `~/.config/anymodel bot/data`)
- 单实例;关闭窗口默认隐藏到托盘(设置 → 常规 可改为退出);托盘菜单:打开 / 在浏览器中打开 / 开机自启(macOS、Windows)/ 打开数据目录 / 退出
- macOS 下窗口无标题栏,红绿灯嵌在侧栏顶部;窗口最小宽度 860
diff --git a/dsh-runtime/package.json b/dsh-runtime/package.json
index 6aa10c5..f30345d 100644
--- a/dsh-runtime/package.json
+++ b/dsh-runtime/package.json
@@ -1,7 +1,7 @@
{
"name": "anymodel-bot-dsh-runtime",
"private": true,
- "description": "Pinned DeepSeek Harness (MIT) runtime used by anymodel bot as its agent host. Packaged as resources/dsh.asar (natives in dsh.asar.unpacked).",
+ "description": "Pinned DeepSeek Harness (MIT) runtime used by anymodel bot as its agent host. Packaged by scripts/bundle-dsh.mjs as resources/dsh/dsh.asar, with native packages in resources/dsh/node_modules.",
"type": "module",
"license": "MIT",
"dependencies": {
diff --git a/package-lock.json b/package-lock.json
index 1019956..4fb0fba 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,6 +16,7 @@
"qrcode-terminal": "^0.12.0"
},
"devDependencies": {
+ "@electron/asar": "^3.4.1",
"@types/node": "^22.20.5",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
diff --git a/package.json b/package.json
index faf2a3f..e449c2f 100644
--- a/package.json
+++ b/package.json
@@ -21,12 +21,14 @@
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"electron:dev": "npm run build && electron .",
- "dist": "npm run build && node scripts/prepare-dsh.mjs && node scripts/build-magpie.mjs --target current && node scripts/fetch-cua-driver.mjs --target current && electron-builder",
+ "dist": "npm run build && node scripts/prepare-dsh.mjs && node scripts/bundle-dsh.mjs && node scripts/build-magpie.mjs --target current && node scripts/fetch-cua-driver.mjs --target current && electron-builder",
"electron:smoke": "npm run build && node scripts/electron-smoke.mjs",
- "dist:linux": "npm run build && node scripts/prepare-dsh.mjs --os linux --cpu x64 && node scripts/build-magpie.mjs --target linux/amd64,linux/arm64 && node scripts/fetch-cua-driver.mjs --target linux/x64,linux/arm64 && electron-builder --linux",
- "dist:mac": "npm run build && node scripts/build-magpie.mjs --target darwin/amd64,darwin/arm64 && node scripts/fetch-cua-driver.mjs --target darwin/x64,darwin/arm64 && node scripts/prepare-dsh.mjs --os darwin --cpu arm64 && electron-builder --mac dmg zip --arm64 && node scripts/prepare-dsh.mjs --os darwin --cpu x64 && electron-builder --mac dmg zip --x64",
- "dist:win": "npm run build && node scripts/build-magpie.mjs --target windows/amd64,windows/arm64 && node scripts/fetch-cua-driver.mjs --target win32/x64,win32/arm64 && node scripts/prepare-dsh.mjs --os win32 --cpu x64 && electron-builder --win nsis --x64 && node scripts/prepare-dsh.mjs --os win32 --cpu arm64 && electron-builder --win nsis --arm64",
+ "dist:linux": "npm run build && node scripts/prepare-dsh.mjs --os linux --cpu x64 && node scripts/bundle-dsh.mjs --os linux --cpu x64 && node scripts/build-magpie.mjs --target linux/amd64,linux/arm64 && node scripts/fetch-cua-driver.mjs --target linux/x64,linux/arm64 && electron-builder --linux",
+ "dist:mac": "npm run build && node scripts/build-magpie.mjs --target darwin/amd64,darwin/arm64 && node scripts/fetch-cua-driver.mjs --target darwin/x64,darwin/arm64 && node scripts/prepare-dsh.mjs --os darwin --cpu arm64 && node scripts/bundle-dsh.mjs --os darwin --cpu arm64 && electron-builder --mac dmg zip --arm64 && node scripts/prepare-dsh.mjs --os darwin --cpu x64 && node scripts/bundle-dsh.mjs --os darwin --cpu x64 && electron-builder --mac dmg zip --x64",
+ "dist:win": "npm run build && node scripts/build-magpie.mjs --target windows/amd64,windows/arm64 && node scripts/fetch-cua-driver.mjs --target win32/x64,win32/arm64 && node scripts/prepare-dsh.mjs --os win32 --cpu x64 && node scripts/bundle-dsh.mjs --os win32 --cpu x64 && electron-builder --win nsis --x64 && node scripts/prepare-dsh.mjs --os win32 --cpu arm64 && node scripts/bundle-dsh.mjs --os win32 --cpu arm64 && electron-builder --win nsis --arm64",
"prepare:dsh": "node scripts/prepare-dsh.mjs",
+ "bundle:dsh": "node scripts/bundle-dsh.mjs",
+ "test:dsh-bundle": "node scripts/test-dsh-bundle.mjs",
"fetch:cua": "node scripts/fetch-cua-driver.mjs"
},
"dependencies": {
@@ -37,6 +39,7 @@
"qrcode-terminal": "^0.12.0"
},
"devDependencies": {
+ "@electron/asar": "^3.4.1",
"@types/node": "^22.20.5",
"@types/qrcode": "^1.5.6",
"@types/qrcode-terminal": "^0.12.2",
@@ -98,20 +101,17 @@
"to": "magpie/magpie"
},
{
- "from": "dsh-runtime",
+ "from": "build/dsh",
"to": "dsh",
"filter": [
- "package.json",
- "plugins/**"
+ "dsh.asar"
]
},
{
- "from": "dsh-runtime/node_modules",
+ "from": "build/dsh/node_modules",
"to": "dsh/node_modules",
"filter": [
- "**/*",
- "!**/*.map",
- "!**/*.d.ts"
+ "**/*"
]
},
{
@@ -155,20 +155,17 @@
"to": "magpie/magpie.exe"
},
{
- "from": "dsh-runtime",
+ "from": "build/dsh",
"to": "dsh",
"filter": [
- "package.json",
- "plugins/**"
+ "dsh.asar"
]
},
{
- "from": "dsh-runtime/node_modules",
+ "from": "build/dsh/node_modules",
"to": "dsh/node_modules",
"filter": [
- "**/*",
- "!**/*.map",
- "!**/*.d.ts"
+ "**/*"
]
},
{
@@ -210,20 +207,17 @@
"to": "magpie/magpie"
},
{
- "from": "dsh-runtime",
+ "from": "build/dsh",
"to": "dsh",
"filter": [
- "package.json",
- "plugins/**"
+ "dsh.asar"
]
},
{
- "from": "dsh-runtime/node_modules",
+ "from": "build/dsh/node_modules",
"to": "dsh/node_modules",
"filter": [
- "**/*",
- "!**/*.map",
- "!**/*.d.ts"
+ "**/*"
]
},
{
diff --git a/scripts/bundle-dsh.mjs b/scripts/bundle-dsh.mjs
new file mode 100644
index 0000000..81769ec
--- /dev/null
+++ b/scripts/bundle-dsh.mjs
@@ -0,0 +1,256 @@
+#!/usr/bin/env node
+/**
+ * Bundle the prepared DSH runtime (dsh-runtime/, see prepare-dsh.mjs) into build/dsh/ for packaging:
+ *
+ * build/dsh/dsh.asar package.json, plugins/ and every package of node_modules that is plain
+ * JavaScript/data: ~11k files in ONE archive
+ * build/dsh/node_modules/ only the packages that carry native code (.node addons, shared libraries,
+ * executables such as ripgrep, node-pty's spawn-helper, landlock-run)
+ *
+ * The packaged app points the agent host at resources/dsh/dsh.asar. Electron reads asar archives in the
+ * main process and in ELECTRON_RUN_AS_NODE children (the DSH host and every Node subprocess it starts:
+ * subprocess runner, PTC, MCP servers), including ESM imports, worker threads and fs reads. Paths inside
+ * the archive are unchanged, so DSH's own package-name resolution (manifest graph walk, interception of
+ * Node's resolver, import.meta.url anchors) works as on a plain node_modules tree.
+ *
+ * Native packages cannot live in the archive (the OS loader and child_process need real files), so they
+ * are copied next to it. Node's lookup from build/dsh/dsh.asar/node_modules/<pkg>/... continues to the
+ * parent build/dsh/node_modules, so `require("@img/sharp-win32-x64/...")`, koffi, node-pty, ripgrep and
+ * the landlock launcher resolve to real paths there, exactly as in a normal install.
+ *
+ * Why not one esbuild bundle: DSH loads ~100 plugins by package name through a graph walk over every
+ * package.json, hooks Node's internal ESM resolver, and anchors assets and workers on import.meta.url.
+ * An archive keeps all of that intact; a JS bundle would have to rewrite DSH internals.
+ *
+ * File count is what makes the Windows installer slow (NSIS extraction + Defender scanning each file):
+ * ~12.5k files in resources/dsh before, a few dozen after.
+ *
+ * node scripts/bundle-dsh.mjs # target = this machine
+ * node scripts/bundle-dsh.mjs --os win32 --cpu x64 # must match the last prepare-dsh run
+ * options: --src <prepared runtime dir> (default dsh-runtime) --out <dir> (default build/dsh)
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { builtinModules } from "node:module";
+import { fileURLToPath } from "node:url";
+import asar from "@electron/asar";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const arg = (k, d) => {
+ const i = process.argv.indexOf(`--${k}`);
+ return i > 0 ? process.argv[i + 1] : d;
+};
+const os = arg("os", process.platform);
+const cpu = arg("cpu", process.arch);
+const src = path.resolve(root, arg("src", "dsh-runtime"));
+const out = path.resolve(root, arg("out", path.join("build", "dsh")));
+const nm = path.join(src, "node_modules");
+const fail = (msg) => {
+ console.error(`bundle-dsh: ${msg}`);
+ process.exit(1);
+};
+
+/**
+ * Packages left out of the packaged runtime: big, and unreachable from what the app runs (the "sdk" profile
+ * over stdio plus the plugins in host.ts). Each entry is checked below: no shipped file may import one.
+ */
+const DROP = [
+ // Office engines (LibreOffice natives: 735 files / 182 MB on win32-x64; WASM: 145 MB on Linux). The sdk
+ // profile disables dsh-skill-office unless DSH_PRIMARY_RUNTIME / DSH_BUNDLED_OFFICE_* are set, which the
+ // app never does; office-to-pdf belongs to the web document preview.
+ /^@deepseek-ai\/libreoffice-kit-/,
+ // Speech-to-text natives, only for the optional voice-input bundle of the web UI.
+ /^sherpa-onnx-/,
+ // DSH web UI: browser bundles served by the web profile's frontend host, and the devtools inspector.
+ /^@deepseek-ai\/dsh-client-ui-/,
+ /^@deepseek-ai\/dsh-experimental-client-ui-/,
+ /^@deepseek-ai\/dsh-web-frontend$/,
+ /^@deepseek-ai\/dsh-experimental-inspector$/,
+ // Electron on Linux is glibc-only; npm installs the musl builds too because --os/--cpu ignore libc.
+ ...(os === "linux" ? [/musl/] : []),
+];
+/** References to dropped packages that exist in shipped files but are never reached in the host process. */
+const ALLOWED_REFS = [
+ // sharp probes every platform/libc build in try/catch
+ [/^node_modules\/sharp\//, /^@img\/sharp-/],
+ // browser halves of DSH packages ("./client" exports and their unbundled sources) import UI packages
+ [/^node_modules\/@deepseek-ai\/[^/]+\/lib\/(client[^/]*\.js$|types\/client\/)/, /^@deepseek-ai\/dsh-(experimental-)?client-ui-|^@deepseek-ai\/dsh-web-frontend/],
+];
+
+// Build-time leftovers inside native packages (C/C++ sources, gyp/CMake files, debug symbols, import libs).
+const NATIVE_JUNK = /\.(c|cc|cpp|cxx|h|hh|hpp|inc|S|asm|gyp|gypi|pdb|lib|exp|ilk|md|markdown)$|^CMakeLists\.txt$/i;
+
+const MAGIC = [
+ [0x7f, 0x45, 0x4c, 0x46], // ELF
+ [0xcf, 0xfa, 0xed, 0xfe], // Mach-O 64
+ [0xce, 0xfa, 0xed, 0xfe], // Mach-O 32
+ [0xfe, 0xed, 0xfa, 0xcf],
+ [0xfe, 0xed, 0xfa, 0xce],
+ [0xca, 0xfe, 0xba, 0xbe], // universal Mach-O
+ [0x4d, 0x5a], // PE (MZ)
+];
+const isNativeFile = (file, name) => {
+ if (/\.(node|dll|exe|dylib|so(\.\d+)*)$/i.test(name)) return true;
+ const buf = Buffer.alloc(4);
+ const fd = fs.openSync(file, "r");
+ const n = fs.readSync(fd, buf, 0, 4, 0);
+ fs.closeSync(fd);
+ return MAGIC.some((m) => m.length <= n && m.every((b, i) => buf[i] === b));
+};
+
+// ---------- sanity: dsh-runtime must be prepared, and for this target ----------
+if (!fs.existsSync(path.join(nm, "@deepseek-ai", "dsh-sdk-client", "package.json"))) fail(`${src} is not prepared; run scripts/prepare-dsh.mjs first`);
+const prebuilds = path.join(nm, "node-pty", "prebuilds");
+const have = fs.existsSync(prebuilds) ? fs.readdirSync(prebuilds).sort().join(",") : "";
+if (have !== `${os}-${cpu}`) fail(`dsh-runtime holds node-pty prebuilds [${have}], expected [${os}-${cpu}]; run scripts/prepare-dsh.mjs --os ${os} --cpu ${cpu} first`);
+
+// ---------- packages ----------
+/** @type {Array<{ name: string, rel: string, dir: string, deps: string[], files: string[], native: boolean }>} */
+const pkgs = [];
+function collect(modulesDir) {
+ for (const e of fs.readdirSync(modulesDir, { withFileTypes: true })) {
+ if (!e.isDirectory() || e.name.startsWith(".")) continue;
+ const names = e.name.startsWith("@") ? fs.readdirSync(path.join(modulesDir, e.name)).map((s) => `${e.name}/${s}`) : [e.name];
+ for (const name of names) {
+ const dir = path.join(modulesDir, name);
+ if (!fs.existsSync(path.join(dir, "package.json"))) continue;
+ const pj = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
+ const files = [];
+ let native = false;
+ (function walk(d) {
+ for (const f of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, f.name);
+ if (f.isDirectory()) {
+ if (d === dir && f.name === "node_modules") collect(p);
+ else walk(p);
+ } else if (f.isFile()) {
+ files.push(p);
+ if (!native && isNativeFile(p, f.name)) native = true;
+ } else if (!(d === dir && f.name === "node_modules")) fail(`unexpected non-file ${p}`);
+ }
+ })(dir);
+ pkgs.push({ name, rel: path.relative(src, dir), dir, deps: Object.keys({ ...pj.dependencies, ...pj.optionalDependencies }), files, native });
+ }
+ }
+}
+collect(nm);
+
+const dropped = new Set(pkgs.filter((p) => DROP.some((re) => re.test(p.name))).map((p) => p.rel));
+const kept = pkgs.filter((p) => !dropped.has(p.rel));
+
+// Platform packages must all be for this target (npm < 10 ignores --os/--cpu and installs the host's).
+const PLATFORM_PKG = /(?:^|[-/])(linuxmusl|linux|darwin|win32|win|freebsd|openbsd|android)-(x64|arm64|ia32|arm|riscv64|loong64|ppc64|s390x)(?:-|$)/;
+const foreign = kept.filter((p) => {
+ const m = PLATFORM_PKG.exec(p.name);
+ if (!m) return false;
+ const pkgOs = { linuxmusl: "linux", win: "win32" }[m[1]] ?? m[1];
+ return pkgOs !== os || m[2] !== cpu;
+});
+if (foreign.length) fail(`dsh-runtime holds native packages for another platform than ${os}-${cpu}: ${foreign.map((p) => p.name).join(", ")} (prepare-dsh needs npm >= 10 to honour --os/--cpu)`);
+const byRel = new Map(kept.map((p) => [p.rel, p]));
+
+/** Node's lookup of `dep` from package `p`: nearest node_modules first (inside src only). */
+function resolveDep(p, dep) {
+ let base = p.rel;
+ for (;;) {
+ const hit = byRel.get(path.join(base, "node_modules", dep));
+ if (hit) return hit;
+ const i = base.lastIndexOf(`node_modules${path.sep}`);
+ if (i < 0) return undefined;
+ base = base.slice(0, i).replace(/[\\/]$/, "");
+ }
+}
+// A package goes outside the archive if it has native code, plus (transitively) whatever it depends on:
+// from build/dsh/node_modules, Node never looks back into the archive. A nested native package takes its
+// top-level ancestor along, so that ancestor still finds it in its own node_modules.
+const outside = new Set();
+const topLevel = (rel) => {
+ const parts = rel.split(path.sep);
+ return parts.slice(0, parts[1].startsWith("@") ? 3 : 2).join(path.sep);
+};
+const queue = kept.filter((p) => p.native);
+while (queue.length) {
+ const p = queue.shift();
+ const top = topLevel(p.rel);
+ for (const q of kept.filter((k) => k.rel === top || k.rel.startsWith(top + path.sep))) {
+ if (outside.has(q.rel)) continue;
+ outside.add(q.rel);
+ for (const d of q.deps) {
+ const r = resolveDep(q, d);
+ if (r && !outside.has(r.rel)) queue.push(r);
+ }
+ }
+}
+
+// ---------- guard: no shipped file may import a dropped package ----------
+const droppedNames = new Set(pkgs.filter((p) => dropped.has(p.rel)).map((p) => p.name));
+const keptNames = new Set(kept.map((p) => p.name));
+const SPEC = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|\bimport\s+)["']([^"'./][^"']*)["']/g;
+const refs = [];
+for (const p of kept) {
+ for (const f of p.files) {
+ if (!/\.(c|m)?js$/.test(f)) continue;
+ const text = fs.readFileSync(f, "utf8");
+ for (const m of text.matchAll(SPEC)) {
+ const spec = m[1];
+ if (spec.startsWith("node:") || builtinModules.includes(spec)) continue;
+ const name = spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0];
+ const from = path.relative(src, f).replaceAll("\\", "/");
+ if (!droppedNames.has(name) || keptNames.has(name)) continue;
+ if (!ALLOWED_REFS.some(([file, target]) => file.test(from) && target.test(spec))) refs.push(`${from} -> ${spec}`);
+ }
+ }
+}
+if (refs.length) fail(`shipped files import dropped packages (shrink DROP or prove these paths unreachable):\n ${[...new Set(refs)].join("\n ")}`);
+
+// ---------- write build/dsh ----------
+fs.rmSync(out, { recursive: true, force: true });
+fs.mkdirSync(out, { recursive: true });
+const inArchive = [path.join(src, "package.json")];
+(function walk(d) {
+ for (const f of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, f.name);
+ if (f.isDirectory()) walk(p);
+ else if (f.isFile()) inArchive.push(p);
+ }
+})(path.join(src, "plugins"));
+let outsideFiles = 0;
+let outsideBytes = 0;
+for (const p of kept) {
+ if (!outside.has(p.rel)) {
+ inArchive.push(...p.files);
+ continue;
+ }
+ for (const f of p.files) {
+ if (NATIVE_JUNK.test(path.basename(f)) && !/^licen[cs]e/i.test(path.basename(f))) continue;
+ const dest = path.join(out, path.relative(src, f));
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ fs.copyFileSync(f, dest);
+ fs.chmodSync(dest, fs.statSync(f).mode & 0o777);
+ outsideFiles++;
+ outsideBytes += fs.statSync(f).size;
+ }
+}
+const archive = path.join(out, "dsh.asar");
+await asar.createPackageFromFiles(src, archive, inArchive.sort());
+if (fs.existsSync(`${archive}.unpacked`)) fail("unexpected dsh.asar.unpacked");
+
+// ---------- verify ----------
+const listed = new Set(asar.listPackage(archive, { isPack: false }).map((f) => f.replaceAll("\\", "/")));
+for (const f of ["/package.json", "/plugins/amb-bridge.mjs", "/node_modules/@deepseek-ai/dsh/package.json", "/node_modules/@deepseek-ai/dsh-sdk-client/lib/index.js"]) {
+ if (!listed.has(f)) fail(`dsh.asar is missing ${f}`);
+}
+if (!fs.existsSync(path.join(out, "node_modules", "node-pty", "prebuilds", `${os}-${cpu}`))) fail("node-pty prebuilds were not copied next to dsh.asar");
+
+const mb = (n) => (n / 1048576).toFixed(1);
+const count = (list) => list.reduce((n, p) => n + p.files.length, 0);
+const nonPackage = inArchive.length - count(kept.filter((p) => !outside.has(p.rel))); // package.json + plugins
+console.log(
+ [
+ `dsh bundled for ${os}-${cpu} → ${path.relative(root, out)}`,
+ ` dsh.asar: ${inArchive.length} files, ${mb(fs.statSync(archive).size)} MB`,
+ ` node_modules (native, real files): ${outside.size} packages, ${outsideFiles} files, ${mb(outsideBytes)} MB: ${[...outside].map((r) => r.replace(/^node_modules[\\/]/, "")).sort().join(", ")}`,
+ ` dropped: ${dropped.size} packages, ${count(pkgs.filter((p) => dropped.has(p.rel)))} files`,
+ ` resources/dsh: ${outsideFiles + 1} files (unbundled: ${count(pkgs) + nonPackage})`,
+ ].join("\n"),
+);
diff --git a/scripts/pack-dsh-asar.mjs b/scripts/pack-dsh-asar.mjs
deleted file mode 100644
index b1236f3..0000000
--- a/scripts/pack-dsh-asar.mjs
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env node
-/**
- * Deprecated (0.1.3+): DSH ships as a pruned real directory via extraResources
- * (`dsh-runtime` → `resources/dsh`), not as dsh.asar.
- * Giant asar caused Windows Defender thrashing; first-launch extract made startup slow.
- * Follow-up: esbuild-bundle DSH JS into few files + native externals (Claude/Gemini pattern).
- */
-console.log("pack-dsh-asar: no-op since 0.1.3 — use scripts/prepare-dsh.mjs; extraResources copies dsh-runtime → resources/dsh");
-process.exit(0);
diff --git a/scripts/test-dsh-bundle.mjs b/scripts/test-dsh-bundle.mjs
new file mode 100644
index 0000000..66e4130
--- /dev/null
+++ b/scripts/test-dsh-bundle.mjs
@@ -0,0 +1,39 @@
+#!/usr/bin/env node
+// Run the real-DSH integration test (test/agent.integration.test.ts) against the packaged layout from
+// scripts/bundle-dsh.mjs instead of dsh-runtime/: Electron in Node mode (as in the app) runs the test, and the
+// agent host loads the SDK client and starts DSH from dsh.asar + the native node_modules next to it.
+// node scripts/test-dsh-bundle.mjs [bundle dir, default build/dsh]
+// The bundle is copied out of the checkout first (vitest rewrites import() of files under the project root to
+// root-relative ids, which do not exist on disk), and not into /tmp: the Linux sandbox hides /tmp from tool
+// subprocesses, and the PTC runtime runs Electron on files inside dsh.asar.
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const bundle = path.resolve(root, process.argv[2] ?? path.join("build", "dsh"));
+if (!fs.existsSync(path.join(bundle, "dsh.asar"))) {
+ console.error(`test-dsh-bundle: ${bundle}/dsh.asar not found; run scripts/bundle-dsh.mjs first`);
+ process.exit(1);
+}
+const base = path.join(os.homedir(), ".cache");
+fs.mkdirSync(base, { recursive: true });
+const tmp = fs.mkdtempSync(path.join(base, "amb-dsh-bundle-"));
+const copy = path.join(tmp, "dsh");
+let status = 1;
+try {
+ fs.cpSync(bundle, copy, { recursive: true });
+ const electron = createRequire(import.meta.url)("electron");
+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1", AMB_DSH_RUNTIME: path.join(copy, "dsh.asar") };
+ const probe = spawnSync(electron, ["-e", "process.exit(require('fs').existsSync(process.env.AMB_DSH_RUNTIME + '/node_modules/@deepseek-ai/dsh-sdk-client/package.json') ? 0 : 1)"], { env });
+ if (probe.status !== 0) throw new Error(`Electron cannot read ${env.AMB_DSH_RUNTIME}`);
+ const vitest = path.join(root, "node_modules", "vitest", "vitest.mjs");
+ const r = spawnSync(electron, [vitest, "run", "test/agent.integration.test.ts", ...process.argv.slice(3)], { cwd: root, env, stdio: "inherit" });
+ status = r.status ?? 1;
+} finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+}
+process.exit(status);
diff --git a/scripts/verify-dsh-bundle.mjs b/scripts/verify-dsh-bundle.mjs
new file mode 100644
index 0000000..5a3e594
--- /dev/null
+++ b/scripts/verify-dsh-bundle.mjs
@@ -0,0 +1,155 @@
+#!/usr/bin/env node
+// Check the bundled DSH runtime (scripts/bundle-dsh.mjs) the way the app uses it: Electron in Node mode loads the
+// SDK client from dsh.asar, native modules resolve to the real node_modules next to it, and a DSH host started
+// from the archive answers one turn through a mock OpenAI-compatible model.
+// node scripts/verify-dsh-bundle.mjs <packaged executable> # e.g. release/linux-unpacked/anymodel-bot
+// node scripts/verify-dsh-bundle.mjs <electron> <path/to/dsh.asar> # e.g. node_modules/electron/dist/electron build/dsh/dsh.asar
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const self = fileURLToPath(import.meta.url);
+
+if (process.argv[2] !== "--child") {
+ const exe = path.resolve(process.argv[2] ?? "");
+ if (!process.argv[2] || !fs.existsSync(exe)) {
+ console.error("usage: node scripts/verify-dsh-bundle.mjs <packaged executable> [dsh.asar]");
+ process.exit(2);
+ }
+ // resources/ is next to the executable on Windows and Linux, Contents/Resources on macOS.
+ const resources = process.platform === "darwin" ? path.join(path.dirname(exe), "..", "Resources") : path.join(path.dirname(exe), "resources");
+ const runtime = path.resolve(process.argv[3] ?? path.join(resources, "dsh", "dsh.asar"));
+ const r = spawnSync(exe, [self, "--child", runtime], {
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
+ stdio: "inherit",
+ timeout: 180_000,
+ windowsHide: true,
+ });
+ if (r.error) console.error(r.error);
+ process.exit(r.status ?? 1);
+}
+
+// ---------- child: runs inside the (packaged) Electron in Node mode ----------
+const runtime = process.argv[3];
+const nm = path.join(runtime, "node_modules");
+const step = async (name, fn) => {
+ const t = Date.now();
+ try {
+ const detail = await fn();
+ console.log(`ok ${name} (${Date.now() - t} ms)${detail ? ` ${detail}` : ""}`);
+ } catch (e) {
+ console.error(`FAIL ${name}: ${e?.stack ?? e}`);
+ process.exit(1);
+ }
+};
+/** require() as seen from a DSH package inside the archive */
+const from = (pkg) => createRequire(path.join(nm, pkg, "package.json"));
+const withTimeout = (p, ms, what) => Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error(`${what} timed out`)), ms))]);
+
+if (!process.versions.electron) throw new Error("run me through Electron (ELECTRON_RUN_AS_NODE=1)");
+console.log(`DSH bundle check: Electron ${process.versions.electron} (Node ${process.versions.node}) ${process.platform}-${process.arch}, ${runtime}`);
+
+await step("archive readable", () => {
+ if (!fs.existsSync(path.join(nm, "@deepseek-ai", "dsh-sdk-client", "package.json"))) throw new Error(`no dsh-sdk-client in ${runtime}`);
+});
+// One real turn first, so its timing is the cold start (nothing of DSH loaded yet in this process or the OS cache
+// beyond what the previous steps touched): DSH host spawned by the SDK client from the archive, model = mock
+// OpenAI-compatible server. DSH_HOST_INIT_MS is spawn -> initialize done, as the app waits for it (90 s timeout).
+await step("DSH host answers through a mock model", async () => {
+ const llm = http.createServer(async (req, res) => {
+ if (req.url?.endsWith("/models")) return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ object: "list", data: [{ id: "mock", object: "model" }] }));
+ let raw = "";
+ for await (const c of req) raw += c;
+ const body = JSON.parse(raw || "{}");
+ if (!body.stream) return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ choices: [{ message: { role: "assistant", content: "title" }, finish_reason: "stop" }] }));
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const send = (o) => res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: body.model, ...o })}\n\n`);
+ send({ choices: [{ index: 0, delta: { role: "assistant", content: "bundle-pong" } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
+ send({ choices: [], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } });
+ res.end("data: [DONE]\n\n");
+ });
+ await new Promise((r) => llm.listen(0, "127.0.0.1", r));
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "amb-dsh-check-"));
+ const patch = path.join(home, "check.patch.yml");
+ fs.writeFileSync(
+ patch,
+ [
+ "- id: llm-pi-ai",
+ " config:",
+ " providers:",
+ " magpie:",
+ " api: openai-completions",
+ ` baseURL: 'http://127.0.0.1:${llm.address().port}/v1'`,
+ " apiKeyEnv: AMB_CHECK_KEY",
+ " models:",
+ " - id: mock",
+ " name: mock",
+ " contextWindow: 128000",
+ " maxTokens: 16000",
+ "",
+ ].join("\n"),
+ );
+ const ti = Date.now();
+ const { DeepSeekHarness } = await import(pathToFileURL(path.join(nm, "@deepseek-ai", "dsh-sdk-client", "lib", "index.js")).href);
+ const sdkMs = Date.now() - ti;
+ const env = { PATH: process.env.PATH ?? "", HOME: home, USERPROFILE: home, SystemRoot: process.env.SystemRoot ?? "", LANG: "C.UTF-8", ELECTRON_RUN_AS_NODE: "1", AMB_CHECK_KEY: "k" };
+ const h = new DeepSeekHarness({ profile: "sdk", patches: [patch], dshHome: home, env, cwd: home, processCwd: home, provider: "magpie", model: "mock", initializeTimeoutMs: 90_000, shutdownTimeoutMs: 3000 });
+ const t = Date.now();
+ try {
+ await h.start();
+ const started = Date.now() - t;
+ console.log(`DSH_HOST_INIT_MS=${started}`);
+ const r = await withTimeout(h.session().run("ping"), 60_000, "turn");
+ if (!String(r.finalResponse).includes("bundle-pong")) throw new Error(`unexpected reply ${JSON.stringify(r.finalResponse)}`);
+ return `(sdk import ${sdkMs} ms, host spawn -> initialized ${started} ms)`;
+ } finally {
+ await h.close().catch(() => {});
+ llm.close();
+ fs.rmSync(home, { recursive: true, force: true, maxRetries: 5 });
+ }
+});
+await step("koffi", () => `v${from("@deepseek-ai/dsh-subprocess-local")("koffi").version}`);
+await step("node-addon-require-builtin", () => {
+ from("@deepseek-ai/dsh-app-boot")("node-addon-require-builtin");
+});
+await step("sharp", async () => {
+ const sharp = from("@deepseek-ai/dsh-attachment-local")("sharp");
+ const png = await sharp({ create: { width: 4, height: 4, channels: 3, background: "#3366ff" } }).png().toBuffer();
+ // (not .metadata(): under Electron on Linux it crashes, unbundled too; see sharp's SharpElectronLinux warning)
+ const small = await sharp(png).resize(2, 2).jpeg().toBuffer();
+ return `png ${png.length} B -> jpeg ${small.length} B`;
+});
+await step("ripgrep", async () => {
+ const entry = from("@deepseek-ai/dsh-tool-fs-search").resolve("@vscode/ripgrep");
+ const { rgPath } = await import(pathToFileURL(entry).href);
+ if (rgPath.includes(".asar" + path.sep)) throw new Error(`rg resolved inside the archive: ${rgPath}`);
+ const r = spawnSync(rgPath, ["--version"], { encoding: "utf8", windowsHide: true });
+ if (r.status !== 0) throw new Error(`${rgPath} --version: ${r.status} ${r.error ?? r.stderr}`);
+ return r.stdout.split("\n")[0];
+});
+await step("node-pty", async () => {
+ const pty = from("@deepseek-ai/dsh-subprocess-local")("node-pty");
+ const [file, args] = process.platform === "win32" ? ["cmd.exe", ["/c", "echo pty-ok"]] : ["/bin/sh", ["-c", "echo pty-ok"]];
+ const term = pty.spawn(file, args, { cols: 80, rows: 10, cwd: os.tmpdir(), env: process.env });
+ let out = "";
+ term.onData((d) => (out += d));
+ await withTimeout(new Promise((r) => term.onExit(r)), 20_000, "pty");
+ if (!out.includes("pty-ok")) throw new Error(`unexpected pty output ${JSON.stringify(out)}`);
+});
+if (process.platform === "linux") {
+ await step("landlock-run", async () => {
+ const entry = from("@deepseek-ai/dsh-sandbox-local").resolve("@deepseek-ai/node-addon-system/landlock-run");
+ const { launcherPath } = await import(pathToFileURL(entry).href);
+ const bin = launcherPath();
+ fs.accessSync(bin, fs.constants.X_OK);
+ return bin.includes(".asar" + path.sep) ? (() => { throw new Error(`launcher inside the archive: ${bin}`); })() : "";
+ });
+}
+
+console.log("DSH bundle check passed");
+process.exit(0);
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 34af9d3..fbdced0 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -47,15 +47,16 @@ function isDshRuntime(dir: string): boolean {
/**
* 找到随应用分发的 DSH 运行时目录(含 node_modules/@deepseek-ai/dsh)。
- * 打包后优先 `resources/dsh`(extraResources 实目录);开发时用 `dsh-runtime/`。
- * 实目录可直接给 ELECTRON_RUN_AS_NODE 子进程用,无需再 extract。
+ * 打包后是 `resources/dsh/dsh.asar`(JS 打成一个归档,原生包是旁边的 resources/dsh/node_modules 实文件);开发时用 `dsh-runtime/`。
+ * Electron 主进程与 ELECTRON_RUN_AS_NODE 子进程都能直接读 asar,无需再 extract。
*/
export function locateDshRuntime(appRoot: string): string | undefined {
const res = (process as any).resourcesPath as string | undefined;
const cands = [
process.env.AMB_DSH_RUNTIME,
path.join(appRoot, "dsh-runtime"), // dev checkout
- res ? path.join(res, "dsh") : undefined, // packaged: resources/dsh (pruned tree)
+ res ? path.join(res, "dsh", "dsh.asar") : undefined, // packaged: resources/dsh/dsh.asar (scripts/bundle-dsh.mjs)
+ res ? path.join(res, "dsh") : undefined, // packaged: resources/dsh (pruned tree, ≤ 0.1.5)
path.join(appRoot, "dsh"), // packaged inside app.asar (older layout)
res ? path.join(res, "app.asar", "dsh") : undefined,
res ? path.join(res, "app.asar.unpacked", "dsh") : undefined,
@@ -65,7 +66,7 @@ export function locateDshRuntime(appRoot: string): string | undefined {
/**
* Identity for callers that historically extracted asar → dataDir.
- * DSH now ships as a real `resources/dsh` directory (no asar, no first-launch extract).
+ * DSH ships as `resources/dsh/dsh.asar`, which Electron reads in place (no first-launch extract).
* Kept so App / tests can call it without branching; returns `runtimeDir` unchanged.
*/
export function materializeDshRuntime(runtimeDir: string, _cacheRoot?: string): string {
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index 65d1ade..892d8d4 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import http from "node:http";
+import module from "node:module";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { App } from "../src/app.js";
import { loadConfig } from "../src/config.js";
@@ -14,6 +15,15 @@ import { listen } from "./helpers.js";
* 验证:插件加载、bridge 注入密钥、bash 沙箱、审批流程(API 批准/拒绝)、读围栏、回环 API 防护。
*/
const runtime = locateDshRuntime(findAppRoot());
+/** workflow 脚本先剥离 TS 类型;Electron 自带的 Node 支持,部分发行版的系统 Node 不带 amaro。 */
+const canStripTypes = (() => {
+ try {
+ (module as any).stripTypeScriptTypes("let a: number = 1");
+ return true;
+ } catch {
+ return false;
+ }
+})();
const hasBwrap = fs.existsSync("/usr/bin/bwrap");
async function body(req: http.IncomingMessage): Promise<any> {
@@ -39,7 +49,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
function plan(messages: any[]): { tool?: { name: string; args: any }; text?: string } {
let lastUser = -1;
for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
+ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
}
const user = textOf(messages[lastUser]?.content);
const tools = messages.slice(lastUser + 1).filter((m) => m.role === "tool");
@@ -50,6 +60,13 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
[/READFILE/, [{ name: "read", args: { file_path: path.join(dataDir, "config.json") } }, { name: "read", args: { file_path: "qs.py" } }]],
[/PRESENT/, [{ name: "bash", args: { description: "run", command: "printf 'hello deliverable' > report.txt" } }, { name: "present", args: { files: [{ path: "report.txt", description: "报告" }, { path: "/etc/hostname" }] } }]],
[/ASKQ/, [{ name: "ask_user_question", args: { questions: [{ id: "lang", question: "用哪种语言?", options: [{ label: "Python" }, { label: "Go" }] }] } }]],
+ // 原生依赖与子进程:ripgrep(grep/glob)、PTC 的 Node 子进程(workflow)
+ [/NATIVES/, [
+ { name: "bash", args: { description: "run", command: "printf 'needle-4711\\n' > hay.txt && printf 'x' > dot.png" } },
+ { name: "grep", args: { pattern: "needle-47" } },
+ { name: "glob", args: { pattern: "*.png" } },
+ ...(canStripTypes ? [{ name: "workflow", args: { script: "return { answer: 6 * 7 }", meta: { name: "calc", description: "multiply" } } }] : []),
+ ]],
[/LOOPBACK/, [{ name: "bash", args: { description: "run", command: `python3 -c "import urllib.request as u\ntry:\n print('API', u.urlopen('${base}/amb/api/status').status)\nexcept Exception as e:\n print('API', getattr(e,'code',e))"` } }]],
];
for (const [re, steps] of scripts) {
@@ -190,6 +207,16 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
expect(r.reply).toContain("Go");
}, 120_000);
+ it("runs tools backed by native modules and Node subprocesses", async () => {
+ const r = await chat("NATIVES check");
+ const parts = r.reply.replace(/^RESULT<<|>>$/g, "").split("|");
+ expect(parts).toHaveLength(canStripTypes ? 4 : 3);
+ expect(parts[1]).toContain("hay.txt");
+ expect(parts[1]).toContain("needle-4711");
+ expect(parts[2]).toContain("dot.png");
+ if (canStripTypes) expect(parts[3]).toContain("42");
+ }, 120_000);
+
it("blocks loopback management API calls from the agent", async () => {
const r = await chat("LOOPBACK check");
expect(r.reply).toContain("API 403");