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.

feat(windows): the app installs a private PowerShell 7 for the agent and heals itself

Marla915743b1f3e1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6cbe549..2ea70d5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -86,7 +86,7 @@ jobs:
needs: changes
if: needs.changes.outputs.agent == 'true'
runs-on: windows-2025
- timeout-minutes: 20
+ timeout-minutes: 30
defaults:
run:
shell: bash
@@ -132,6 +132,13 @@ jobs:
- name: Chat through the app; no console windows
run: node scripts/e2e-agent.mjs --out "$RUNNER_TEMP/e2e" --launch shell --cwd "$GITHUB_WORKSPACE" --timeout-ms 150000 --procmon --managed --stream --tool --status-probes --observe-ms 20000 --max-console-windows 0 --expect-diagnostics --expect-pwsh7 -- "$ELECTRON_EXE" .
+ # The app-managed PowerShell 7 on a real Windows: the app must ignore the runner's own PowerShell 7, download the
+ # pinned release, check its SHA256 and Authenticode signature, launch-test it, hand it to DSH and run the tool call
+ # in it (psver=7). Then, with its pwsh.exe "quarantined" like antivirus would, the agent must fall back to Windows
+ # PowerShell 5.1 (psver=5), and a one-click reinstall must bring PowerShell 7 back.
+ - name: Chat with the app-managed PowerShell 7 (download, verify, use, self-heal)
+ run: node scripts/e2e-agent.mjs --out "$RUNNER_TEMP/e2e-private-pwsh" --timeout-ms 240000 --stream --tool --private-pwsh --pwsh-heal -- "$ELECTRON_EXE" .
+
# The installers' DSH layout: Electron in Node mode loads the natives through dsh.asar and runs one
# DSH turn, then the same app chats with its agent host started from the archive.
- name: Bundled DSH (dsh.asar) under Electron
@@ -148,5 +155,7 @@ jobs:
name: windows-agent-e2e
path: |
${{ runner.temp }}/e2e
+ ${{ runner.temp }}/e2e-private-pwsh
+ !${{ runner.temp }}/e2e-private-pwsh/pwsh-home/*/**
${{ runner.temp }}/e2e-bundled
retention-days: 7
diff --git a/electron/main.ts b/electron/main.ts
index b4f3c44..cccad42 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -7,7 +7,7 @@
* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)
* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。
*/
-import { app, BrowserWindow, Menu, Tray, nativeImage, shell, dialog, safeStorage } from "electron";
+import { app, BrowserWindow, Menu, Tray, nativeImage, net, shell, dialog, safeStorage } from "electron";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -145,6 +145,8 @@ async function boot(): Promise<void> {
secretBox: safeStorage.isEncryptionAvailable()
? { encrypt: (plain) => safeStorage.encryptString(plain), decrypt: (data) => safeStorage.decryptString(data) }
: undefined,
+ // 下载内置 PowerShell 走 Chromium 的网络栈:和浏览器一样用系统代理设置与系统证书
+ fetch: ((input: string | URL | Request, init?: RequestInit) => net.fetch(input instanceof URL ? input.href : input, init)) as typeof fetch,
};
await core.start();
if (!core.web) throw new Error("管理界面未启动");
diff --git a/scripts/e2e-agent.mjs b/scripts/e2e-agent.mjs
index 6955346..840b2d4 100644
--- a/scripts/e2e-agent.mjs
+++ b/scripts/e2e-agent.mjs
@@ -14,7 +14,13 @@
// --expect-pwsh7 (Windows): require that the app detected PowerShell 7 (/amb/api/pwsh and the diagnostics
// status), passed it to DSH (the "patch written" log line) and that the --tool command ran in it
// (the pwsh tool prints $PSVersionTable.PSVersion.Major). GitHub's windows-2025 image has PowerShell 7.
-// --tool: the mock model asks for one shell tool call before answering (exercises tool spawning).
+// --private-pwsh (Windows): the app must ignore the runner's own PowerShell 7 (AMB_PWSH_IGNORE_SYSTEM=1), download,
+// verify, launch-test and use its app-managed copy (AMB_PWSH_HOME=<out>/pwsh-home, fresh). The chat waits until the
+// install is done; then the --tool command must run in PowerShell 7 from that copy.
+// --pwsh-heal (with --private-pwsh): then "quarantine" the copy's pwsh.exe like antivirus would; the next tool call cannot
+// start it, so the app must mark it broken and fall back to Windows PowerShell 5.1 (psver=5), and a one-click
+// reinstall (POST /amb/api/pwsh/install) must bring PowerShell 7 back (psver=7).
+// --tool: the mock model asks for one shell tool call before answering each message (exercises tool spawning).
// --managed: use the bundled magpie gateway (as users do) with "Modelflare" pointed at the mock
// (AMB_MODELFLARE_BASE_URL) and connected through the API; otherwise the app calls the mock directly.
// --stream: send the message through the UI's SSE endpoint (/chat/stream) instead of /chat.
@@ -72,6 +78,9 @@ const MODEL = "mock-agent";
const ANSWER = "pong-from-mock";
const wantTool = flag("tool");
const expectPwsh7 = flag("expect-pwsh7");
+const privatePwsh = flag("private-pwsh");
+const pwshHeal = flag("pwsh-heal");
+const pwshHome = path.join(out, "pwsh-home");
const managed = flag("managed");
const reasoning = flag("reasoning");
const observeMs = Number(opt("observe-ms", 0));
@@ -112,13 +121,14 @@ const llm = http.createServer(async (req, res) => {
return;
}
if (!req.url?.endsWith("/chat/completions")) return void res.writeHead(404).end();
- // One shell call first when asked (and the runtime offers a shell tool), then the answer.
+ // One shell call per user message when asked (and the runtime offers a shell tool), then the answer.
const shell = tools.find((n) => n === "bash" || n === "pwsh" || n === "powershell");
- const toolResults = msgs.filter((m) => m.role === "tool");
+ const lastUser = msgs.findLastIndex((m) => m.role === "user");
+ const toolResults = msgs.slice(lastUser + 1).filter((m) => m.role === "tool");
// PowerShell also prints its major version, so the e2e can tell PowerShell 7 from Windows PowerShell 5.1
const command = shell === "bash" ? "echo tool-ran-ok" : 'echo tool-ran-ok; "psver=$($PSVersionTable.PSVersion.Major)"';
const call = wantTool && b.tools && shell && !toolResults.length ? { name: shell, args: { description: "say hi", command } } : undefined;
- const text = toolResults.length ? `${ANSWER} [${toolResults.map((m) => textOf(m.content)).join("|").slice(0, 300)}]` : ANSWER;
+ const text = toolResults.length ? `${ANSWER} [${toolResults.map((m) => textOf(m.content)).join("|").slice(0, 1500)}]` : ANSWER;
if (!b.stream) {
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: "c1", object: "chat.completion", model: b.model, choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } }));
return;
@@ -162,7 +172,10 @@ const env = {
AMB_DSH_TRACE: path.join(out, "dsh-trace.jsonl"),
AMB_WEIXIN_API_BASE: "http://127.0.0.1:9",
AMB_MEMORY_REVIEW_DELAY_MS: "600000",
+ // --private-pwsh: pretend the runner has no PowerShell 7, so the app installs and uses its own copy (a fresh one)
+ ...(privatePwsh ? { AMB_PWSH_IGNORE_SYSTEM: "1", AMB_PWSH_HOME: pwshHome } : {}),
};
+if (privatePwsh) fs.rmSync(pwshHome, { recursive: true, force: true });
const launch = opt("launch", "node");
say("launching", launch, JSON.stringify(cmd));
let app;
@@ -297,6 +310,33 @@ try {
summary.statusFirst = await chat("/status", 20_000);
say("/status (first):", JSON.stringify(summary.statusFirst).slice(0, 500));
}
+ // --private-pwsh: wait (up to 10 minutes) until the app has installed its PowerShell 7 and switched the agent to it
+ const pwshNow = async () => (await api("/amb/api/pwsh", {}, 60_000)).body;
+ const waitPwsh = async (what, ok, ms = 600_000) => {
+ const started = Date.now();
+ const until = started + ms;
+ let st;
+ let last = "";
+ while (Date.now() < until) {
+ st = await pwshNow().catch((e) => ({ error: String(e?.message ?? e) }));
+ jl("pwsh-status.jsonl", { what, st });
+ const line = `${st?.private?.install?.state ?? "-"} ${st?.private?.install?.received ?? ""}/${st?.private?.install?.total ?? ""} using=${st?.using ?? "-"} source=${st?.source ?? "-"}`;
+ if (line !== last) say(`pwsh (${what}): ${line}`);
+ last = line;
+ if (ok(st)) return st;
+ if (st?.private?.install?.state === "failed" && what !== "fallback") throw new Error(`PowerShell install failed: ${st.private.install.error}`);
+ if (what === "install" && Date.now() - started > 90_000 && (st?.private?.install?.state ?? "idle") === "idle") throw new Error(`the app never started installing PowerShell: ${JSON.stringify(st).slice(0, 600)}`);
+ await new Promise((r) => setTimeout(r, 2000));
+ }
+ throw new Error(`timed out waiting for PowerShell (${what}): ${JSON.stringify(st).slice(0, 600)}`);
+ };
+ const privateReady = (st) => st?.source === "private" && st?.private?.ready && !st?.missing && /^7\./.test(st?.version ?? "");
+ if (privatePwsh) {
+ const st = await waitPwsh("install", privateReady);
+ summary.pwshInstalled = { version: st.version, path: st.path, test: st.private?.test, install: st.private?.install };
+ say(`app-managed PowerShell ${st.version} ready at ${st.path} (launch test ${st.private?.test?.ms} ms)`);
+ }
+
summary.chatStartedAt = stamp();
const first = chat(wantTool ? "Run the tool, then answer. TOOLTEST" : "Say hi. PINGTEST");
if (flag("status-probes")) {
@@ -315,6 +355,41 @@ try {
say("chat2:", JSON.stringify(summary.chat2).slice(0, 600));
summary.ok &&= good(summary.chat2);
}
+ // --pwsh-heal: break the app-managed copy, expect the fallback to 5.1, then a one-click reinstall back to 7
+ const psverOf = (c) => /psver=(\d+)/.exec(c?.reply ?? "")?.[1];
+ if (privatePwsh && pwshHeal) {
+ const before = await pwshNow();
+ const exe = before.path;
+ const quarantined = exe + ".quarantined";
+ fs.renameSync(exe, quarantined);
+ say(`renamed ${exe} away (like antivirus quarantine)`);
+ summary.healBroken = await chat("The shell should fail now. HEAL 1");
+ say("chat (broken shell):", JSON.stringify(summary.healBroken).slice(0, 800));
+ const fell = await waitPwsh("fallback", (st) => !!st?.private?.bad && st?.fallback?.from === exe && st?.source !== "private", 120_000);
+ summary.healFallback = { bad: fell.private?.bad, fallback: fell.fallback, using: fell.using };
+ say(`fallback: ${JSON.stringify(summary.healFallback).slice(0, 600)}`);
+ summary.healOn51 = await chat("Run the tool again on the fallback shell. HEAL 2");
+ say("chat (fallback shell):", JSON.stringify(summary.healOn51).slice(0, 600));
+ const r = await api("/amb/api/pwsh/install", { method: "POST", body: JSON.stringify({ reinstall: true }) }, 60_000);
+ say(`reinstall requested: HTTP ${r.status}`);
+ const back = await waitPwsh("reinstall", (st) => privateReady(st) && st?.private?.install?.state === "done" && fs.existsSync(exe));
+ summary.healReinstalled = { version: back.version, path: back.path, test: back.private?.test };
+ summary.healBack = await chat("Run the tool once more. HEAL 3");
+ say("chat (reinstalled shell):", JSON.stringify(summary.healBack).slice(0, 600));
+ const statusLine = await chat("/status", 20_000);
+ summary.healStatusLine = statusLine.reply;
+ const checks = {
+ brokenToolFailed: !(summary.healBroken?.reply ?? "").includes("tool-ran-ok") && /windows-acl-run|CreateProcess|spawn|ENOENT/i.test(summary.healBroken?.reply ?? ""),
+ markedBroken: !!summary.healFallback.bad,
+ fellBackTo51: psverOf(summary.healOn51) === "5" && /powershell\.exe$/i.test(summary.healFallback.using ?? ""),
+ reinstalled: !!summary.healReinstalled.test?.ok,
+ backOn7: psverOf(summary.healBack) === "7" && (summary.healBack?.reply ?? "").includes("tool-ran-ok"),
+ statusSaysPrivate: /应用内置/.test(summary.healStatusLine ?? ""),
+ };
+ summary.healChecks = checks;
+ say(`self-healing checks ${JSON.stringify(checks)}`);
+ summary.ok &&= Object.values(checks).every(Boolean);
+ }
summary.agent = (await api("/amb/api/agent").catch((e) => ({ body: String(e) }))).body;
// 4) troubleshooting endpoints (present from 0.1.6)
@@ -363,6 +438,29 @@ try {
say(`PowerShell: ${ps?.version ?? "-"} at ${ps?.path ?? "-"} (${ps?.source ?? "-"}); checks ${JSON.stringify(checks)}; tool psver ${psver.join(",") || "-"}`);
summary.ok &&= Object.values(checks).every(Boolean);
}
+ if (privatePwsh) {
+ // The app-managed copy was downloaded in this run, verified, handed to DSH and the tool call ran in it
+ const ps = (await api("/amb/api/pwsh", {}, 30_000)).body;
+ fs.writeFileSync(path.join(out, "diag-pwsh-private.json"), JSON.stringify(ps, null, 2));
+ let patchLines = [];
+ try {
+ patchLines = fs.readFileSync(path.join(dataDir, "logs", "app.log"), "utf8").split(/\r?\n/).filter((l) => l.includes("dsh start: patch written"));
+ } catch {
+ /* no log */
+ }
+ const homeJson = JSON.stringify(pwshHome).slice(1, -1);
+ const checks = {
+ ignoredSystem: !!ps?.ignoreSystem,
+ installedHere: !!summary.pwshInstalled && fs.existsSync(path.join(pwshHome, "state.json")),
+ launchTested: !!summary.pwshInstalled?.test?.ok,
+ passedToDsh: patchLines.some((l) => l.includes(homeJson) && /pwsh\.exe/i.test(l)),
+ toolRanInPrivatePwsh7: psverOf(summary.chat) === "7",
+ noLeftovers: fs.readdirSync(pwshHome).filter((n) => /^\.(dl|staging|trash)-|^\.lock$/.test(n)).length === 0,
+ };
+ summary.privatePwsh = { checks, patchLines: patchLines.map((l) => l.slice(0, 400)), status: ps };
+ say(`app-managed PowerShell checks ${JSON.stringify(checks)}`);
+ summary.ok &&= Object.values(checks).every(Boolean);
+ }
} catch (e) {
summary.error = String(e?.message ?? e);
say("error:", summary.error);
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 9863eef..1d90c93 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -318,6 +318,13 @@ function yamlStr(s: string): string {
return JSON.stringify(s); // JSON 字符串是合法的 YAML 标量
}
+/** 工具结果的文字(content 是字符串或 [{type:"text",text}]) */
+function contentText(c: unknown): string {
+ if (typeof c === "string") return c;
+ if (Array.isArray(c)) return c.map((p) => (typeof p === "string" ? p : typeof p?.text === "string" ? p.text : "")).join("\n");
+ return "";
+}
+
/** 把工具调用压成一行可读进度。 */
export function summarizeCall(name: string, argsJson: string): string {
let a: any = {};
@@ -387,6 +394,10 @@ export class AgentHost {
private initFailures = 0;
private retryAfter = 0;
private listeners = new Set<(e: HostEvent) => void>();
+ /** 当前子进程补丁里写的 PowerShell(Windows);代理拉不起它时据此退回 */
+ private pwshPath: string | undefined;
+ /** 进入 runOnce 还没结束的回合(含还在等进程、等会话的):有就不在后台重启 */
+ private entering = 0;
constructor(private o: AgentHostOptions) {}
@@ -738,6 +749,19 @@ exec "$REAL" "$@"
return this.starting;
}
+ /**
+ * 设置或 PowerShell 变了(比如内置 PowerShell 7 刚装好、或者坏了退回)而且空闲:在后台重启子进程,
+ * 下一条消息不用再等启动。正在跑的回合不打断,等下一条消息时由 ensure() 换。
+ */
+ async restartIfStale(): Promise<void> {
+ if (!this.harness || this.starting || this.active > 0 || this.entering > 0 || this.stopped || this.sig === this.settingsSig()) return;
+ const model = this.model;
+ log.info("bot settings or PowerShell changed while idle, restarting dsh in the background", { bot: this.o.botId });
+ await this.closeHarness();
+ this.state = "stopped";
+ await this.ensure(model).catch(() => undefined);
+ }
+
/** 本机上一次成功启动的耗时;没有记录 = 第一次启动(冷启动:杀毒软件逐个扫描运行时文件,可能要几分钟) */
private get initRecordFile(): string {
return path.join(this.o.dataDir, "dsh", ".init.json");
@@ -794,6 +818,7 @@ exec "$REAL" "$@"
const api: AgentApi = fb ? "openai-completions" : chosen;
this.fallback = fb;
const patch = this.writePatch(model, apps, pwshPath, modelLimits(model, known), api, info?.reasoning);
+ this.pwshPath = pwshPath;
this.sig = this.settingsSig();
const timeoutMs = this.initTimeoutMs();
this.stage("patch written", t0, { api, computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs, ...(process.platform === "win32" ? { pwsh: pwshPath ?? "dsh default (Windows PowerShell 5.1)" } : {}) });
@@ -957,6 +982,17 @@ exec "$REAL" "$@"
}
private async runOnce(input: TurnInput): Promise<{ text: string; sessionId: string; files: string[]; usage: TurnUsage }> {
+ this.entering++;
+ try {
+ return await this.runEntered(input);
+ } finally {
+ this.entering--;
+ // 回合中 PowerShell 换了(比如刚发现它起不来):回合结束、空闲了就在后台换上
+ if (this.entering === 0) void this.restartIfStale();
+ }
+ }
+
+ private async runEntered(input: TurnInput): Promise<{ text: string; sessionId: string; files: string[]; usage: TurnUsage }> {
const h = await this.ensure(input.model);
const s = await this.sessionFor(h, input.conversationId);
// 在等进程 / 会话时就被中止了:消息还没交出去,不用重启子进程
@@ -995,6 +1031,12 @@ exec "$REAL" "$@"
if (data.name === "present") presented.push(...presentPaths(String(data.arguments ?? "")));
input.observer?.onProgress?.(`🔧 ${summarizeCall(String(data.name), String(data.arguments ?? "")).split(this.workspace + "/").join("")}`);
}
+ if (ev?.type === "tool/result") {
+ // Windows:PowerShell 本身拉不起来(被杀毒软件删了、被策略拦了…)时退回下一个,不让代理一直用一个起不来的 shell(其他平台上探测器不管)
+ const msg = data?.message ?? {};
+ const call = this.calls.get(String(msg.toolCallId ?? ""));
+ if (call && /^(pwsh|powershell)$/i.test(call.name)) pwshProbe.observeToolResult(this.pwshPath, contentText(msg.content));
+ }
if (ev?.type === "request/context" && Number(data?.contextWindow) > 0) usage.window = Number(data.contextWindow);
if (ev?.type === "assistant/message" && data?.usage) {
const u = data.usage;
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index 87307e2..6af68c1 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -149,6 +149,11 @@ export class AgentManager {
return h;
}
+ /** PowerShell 等启动参数变了:空闲的代理进程在后台换用新的(正在跑回合的等下一条消息) */
+ async refreshIdle(): Promise<void> {
+ await Promise.all([...this.hosts.values()].map((h) => h.restartIfStale().catch(() => undefined)));
+ }
+
/** Computer Use 的系统可用性 + 本机器人开关,供界面与 /status 显示 */
computerUse(botId: string): ComputerUseInfo {
const st = this.settings(botId).computerUse;
diff --git a/src/agent/pwsh-private.ts b/src/agent/pwsh-private.ts
new file mode 100644
index 0000000..08bc3fe
--- /dev/null
+++ b/src/agent/pwsh-private.ts
@@ -0,0 +1,806 @@
+/**
+ * 应用内置的 PowerShell 7(只在 Windows 上):系统里没有能用的 PowerShell 7 时,应用自己下载官方 zip,校验、解压、试运行后
+ * 装在用户目录里,代理用它执行命令。不要管理员权限,不写注册表、不改 PATH,不碰用户自己的 PowerShell。
+ *
+ * - 位置:%LOCALAPPDATA%\AnyModelBot\pwsh\<版本>-<架构>\(AMB_PWSH_HOME 可改)。不放数据目录:数据目录在 Roaming(%APPDATA%),
+ * 漫游配置文件会同步这两百多 MB;LOCALAPPDATA 只在本机,开发版和安装版共用一份,删数据目录也不用重新下载。
+ * - 步骤:下载到临时文件 → 核对 SHA256(版本和哈希写死在 PRIVATE_PWSH)→ 解压到临时目录(系统自带的 tar.exe,不行再用 5.1 的
+ * Expand-Archive)→ 核对 pwsh.exe 等文件的 Authenticode 签名(5.1 的 Get-AuthenticodeSignature,必须是 Microsoft 签发)→ 按 DSH 的
+ * 方式试运行(版本号、读写临时文件、拉起外部程序)→ 写标记文件 → 整个目录改名到位。任何一步失败都删掉临时文件,不留半个副本。
+ * - 同一时间只装一个(跨进程的锁文件,带心跳);装到一半退出,下次启动先清掉残留。
+ * - 每次启动只看文件指纹(大小 + 修改时间):和上次试运行通过时一样就直接用;变了或超过 7 天才重新核对签名、试运行(约 1 秒)。
+ * - 运行中发现坏了(代理拉不起它、文件被杀毒软件删了)就标记为坏(记在 state.json,带指纹),用户重新安装或重新检测之前不再用。
+ */
+import { execFile } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { logger } from "../log.js";
+
+const log = logger("pwsh.private");
+const W = path.win32;
+
+/**
+ * 固定的版本与哈希(一处改齐)。7.6 是 LTS(.NET 10),x64 与 arm64 都支持 Windows 10 1607 / Server 2016 起的系统。
+ * 哈希来源:GitHub release v7.6.9 页面的 "SHA256 Hashes of the release artifacts",与同一 release 里的 hashes.sha256、
+ * GitHub API 的 asset digest 一致(2026-10-31 核对,并下载两个 zip 复算过)。升级:node scripts/pwsh-hashes.mjs <版本>,把输出贴到这里。
+ */
+export const PRIVATE_PWSH = {
+ version: "7.6.9",
+ sha256: {
+ x64: "ce7484804c0f0ad4dda10c958e71acdaf7eebfb22505c1b480f89e0e9f1da94d",
+ arm64: "2157fb002178e606c2a5532c56647118d90d029742f04d4900a71e3b478c2363",
+ },
+ size: { x64: 109620855, arm64: 102310068 },
+ /** .NET 10 支持的最低版本:Windows 10 1607 / Windows Server 2016(build 14393) */
+ minBuild: 14393,
+};
+export type PwshPin = typeof PRIVATE_PWSH;
+export type PwshArch = "x64" | "arm64";
+
+export const PWSH_RELEASES = "https://github.com/PowerShell/PowerShell/releases/download";
+export const zipName = (pin: PwshPin, arch: PwshArch) => `PowerShell-${pin.version}-win-${arch}.zip`;
+
+/** 下载地址:GitHub release;AMB_PWSH_MIRROR 可换成镜像前缀(照样核对哈希和签名) */
+export function zipUrl(pin: PwshPin, arch: PwshArch, env: NodeJS.ProcessEnv = process.env): string {
+ const mirror = env.AMB_PWSH_MIRROR?.trim();
+ return mirror ? `${mirror.replace(/\/+$/, "")}/${zipName(pin, arch)}` : `${PWSH_RELEASES}/v${pin.version}/${zipName(pin, arch)}`;
+}
+
+/** DSH(dsh-pwsh-local)拉起每条命令的方式:同样的参数、同样的 UTF-8 前缀 */
+export const DSH_PWSH_ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"];
+export const DSH_ENCODING_PREAMBLE = "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); $OutputEncoding = [System.Text.UTF8Encoding]::new($false); ";
+
+/** 试运行:版本号、在临时目录里写一个文件再读回来、拉起一个外部程序,最后打一行结果 */
+export const TEST_SCRIPT = [
+ "$ErrorActionPreference = 'Stop'",
+ "$d = Join-Path ([System.IO.Path]::GetTempPath()) ('amb-pwsh-' + [guid]::NewGuid().ToString('N'))",
+ "New-Item -ItemType Directory -Path $d | Out-Null",
+ "try {",
+ " $f = Join-Path $d 'probe.txt'",
+ " Set-Content -LiteralPath $f -Value 'rw-ok' -Encoding utf8",
+ " $rw = (Get-Content -LiteralPath $f -Raw).Trim()",
+ ' $ext = (& "$env:SystemRoot\\System32\\cmd.exe" /d /c echo ext-ok | Out-String).Trim()',
+ ' "AMB-PWSH-TEST ver=$($PSVersionTable.PSVersion) rw=$rw ext=$ext"',
+ "} finally { Remove-Item -LiteralPath $d -Recurse -Force -ErrorAction SilentlyContinue }",
+].join("\n");
+
+/** 核对签名:每个文件一项(状态、签名者、颁发者),JSON 数组 */
+const SIG_SCRIPT =
+ "$ErrorActionPreference = 'Stop'; $r = foreach ($p in ($env:AMB_SIG_FILES -split '\\|')) { $s = Get-AuthenticodeSignature -LiteralPath $p; " +
+ "[pscustomobject]@{ status = [string]$s.Status; subject = [string]$s.SignerCertificate.Subject; issuer = [string]$s.SignerCertificate.Issuer } }; " +
+ "ConvertTo-Json -Compress -InputObject @($r)";
+
+/** 关键文件:缺一个就不能用;它们的大小和修改时间就是指纹 */
+const KEY_FILES = ["pwsh.exe", "pwsh.dll", "System.Management.Automation.dll", "hostfxr.dll", "coreclr.dll"];
+/** 要核对签名的文件 */
+const SIGNED_FILES = ["pwsh.exe", "pwsh.dll", "System.Management.Automation.dll"];
+const MARKER = ".amb-pwsh.json";
+/** 上次试运行通过超过这么久就再试一次 */
+const RETEST_MS = 7 * 24 * 3600_000;
+/** 锁文件超过这么久没有心跳就当作残留 */
+const LOCK_STALE_MS = 3 * 60_000;
+/** 自动安装失败后的等待:第 1 次失败后 1 小时,第 2 次后 1 天,3 次后不再自动装(手动点安装会清零) */
+const AUTO_BACKOFF = [0, 3600_000, 24 * 3600_000];
+
+// ---------- 子进程 ----------
+
+export interface RunResult {
+ /** 退出码;没跑起来或被超时杀掉时为 null */
+ code: number | null;
+ stdout: string;
+ stderr: string;
+ timedOut?: boolean;
+ /** 没能拉起(ENOENT、EACCES…) */
+ error?: string;
+}
+export type Runner = (exe: string, args: string[], o: { timeoutMs: number; env?: NodeJS.ProcessEnv; cwd?: string }) => Promise<RunResult>;
+
+/** 隐藏窗口、有超时;不抛错,结果里带退出码 / 超时 / 拉起失败 */
+export const runProcess: Runner = (exe, args, o) =>
+ new Promise((resolve) => {
+ try {
+ execFile(exe, args, { windowsHide: true, timeout: o.timeoutMs, maxBuffer: 4 * 1024 * 1024, encoding: "utf8", env: o.env, cwd: o.cwd }, (err, stdout, stderr) => {
+ const e = err as (Error & { code?: unknown; killed?: boolean }) | null;
+ resolve({
+ code: !e ? 0 : typeof e.code === "number" ? e.code : null,
+ stdout: String(stdout ?? ""),
+ stderr: String(stderr ?? ""),
+ ...(e?.killed ? { timedOut: true } : {}),
+ ...(e && typeof e.code === "string" ? { error: `${e.code}: ${e.message}`.slice(0, 300) } : {}),
+ });
+ });
+ } catch (e) {
+ resolve({ code: null, stdout: "", stderr: "", error: String((e as Error)?.message ?? e).slice(0, 300) });
+ }
+ });
+
+/** 给 PowerShell 的环境:和 DSH 给代理子进程的一样只带系统目录类变量(不带本进程的其他变量),加上 DSH 的去颜色、去分页 */
+const SHELL_ENV = [
+ "PATH", "SystemRoot", "SystemDrive", "windir", "ComSpec", "PATHEXT", "TEMP", "TMP", "APPDATA", "LOCALAPPDATA", "USERPROFILE", "HOMEDRIVE", "HOMEPATH",
+ "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "CommonProgramFiles", "CommonProgramFiles(x86)", "CommonProgramW6432",
+ "ALLUSERSPROFILE", "PUBLIC", "OS", "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER", "NUMBER_OF_PROCESSORS", "USERNAME", "USERDOMAIN", "COMPUTERNAME",
+];
+export function shellEnv(env: NodeJS.ProcessEnv): Record<string, string> {
+ const out: Record<string, string> = { NO_COLOR: "1", PAGER: "cat", GIT_PAGER: "cat" };
+ for (const k of SHELL_ENV) {
+ const v = env[k];
+ if (v) out[k] = v;
+ }
+ return out;
+}
+
+const sysRoot = (env: NodeJS.ProcessEnv) => env.SystemRoot || env.windir || "C:\\Windows";
+/** 系统自带的 Windows PowerShell 5.1 */
+export const windowsPowerShell = (env: NodeJS.ProcessEnv = process.env) => W.join(sysRoot(env), "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
+const clip = (s: string, n = 300) => s.replace(/\s+/g, " ").trim().slice(0, n);
+
+// ---------- 版本、试运行、签名、解压 ----------
+
+/** pwsh.deps.json 里的版本:"pwsh/7.4.6",新版是 "pwsh/7.6.9.500"(第四段不要),预览版 "pwsh/7.6.0-preview.5" */
+export function depsJsonVersion(text: string): string | undefined {
+ const m = /"pwsh\/(\d+\.\d+\.\d+)(?:\.\d+)?(-[0-9A-Za-z.]+)?"/.exec(text);
+ return m ? m[1] + (m[2] ?? "") : undefined;
+}
+
+export interface LaunchTest {
+ ok: boolean;
+ at: number;
+ ms: number;
+ version?: string;
+ error?: string;
+ timedOut?: boolean;
+}
+
+/** 按 DSH 的方式拉起 pwsh 跑 TEST_SCRIPT;expect:版本号必须是它 */
+export async function launchTest(exe: string, run: Runner, o: { timeoutMs: number; env?: NodeJS.ProcessEnv; expect?: string }): Promise<LaunchTest> {
+ const t0 = Date.now();
+ const r = await run(exe, [...DSH_PWSH_ARGS, DSH_ENCODING_PREAMBLE + TEST_SCRIPT], { timeoutMs: o.timeoutMs, env: shellEnv(o.env ?? process.env), cwd: os.tmpdir() });
+ const ms = Date.now() - t0;
+ const m = /AMB-PWSH-TEST ver=(\S+) rw=(\S*) ext=(\S*)/.exec(r.stdout);
+ const fail = (error: string): LaunchTest => ({ ok: false, at: Date.now(), ms, ...(m ? { version: m[1] } : {}), error, ...(r.timedOut ? { timedOut: true } : {}) });
+ if (r.timedOut) return fail(`${Math.round(o.timeoutMs / 1000)} 秒内没有跑完`);
+ if (r.error) return fail(`拉不起来:${r.error}`);
+ if (!m || r.code !== 0) return fail(`没有得到预期输出(退出码 ${r.code})${r.stderr || r.stdout ? `:${clip(r.stderr || r.stdout)}` : ""}`);
+ if (m[2] !== "rw-ok") return fail("读写临时文件失败");
+ if (m[3] !== "ext-ok") return fail("拉起外部程序失败");
+ if (!(Number(m[1].split(".")[0]) >= 7)) return fail(`版本是 ${m[1]},不是 PowerShell 7`);
+ if (o.expect && m[1] !== o.expect) return fail(`版本是 ${m[1]},应为 ${o.expect}`);
+ return { ok: true, at: Date.now(), ms, version: m[1] };
+}
+
+/** 用 Windows PowerShell 5.1 核对 Authenticode:每个文件都要有效(Valid),签名者和颁发者都是 Microsoft */
+export async function verifySignatures(files: string[], run: Runner, env: NodeJS.ProcessEnv): Promise<{ ok: boolean; error?: string }> {
+ const r = await run(windowsPowerShell(env), ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", SIG_SCRIPT], {
+ timeoutMs: 90_000,
+ env: { ...shellEnv(env), AMB_SIG_FILES: files.join("|") },
+ });
+ if (r.timedOut) return { ok: false, error: "Windows PowerShell 90 秒内没有给出签名结果" };
+ if (r.error || r.code !== 0) return { ok: false, error: `Windows PowerShell 核对签名失败:${clip(r.error || r.stderr || r.stdout || `退出码 ${r.code}`)}` };
+ let list: Array<{ status?: string; subject?: string; issuer?: string }>;
+ try {
+ list = JSON.parse(r.stdout.replace(/^\uFEFF/, "").trim());
+ } catch {
+ return { ok: false, error: `看不懂签名结果:${clip(r.stdout)}` };
+ }
+ if (!Array.isArray(list) || list.length !== files.length) return { ok: false, error: "签名结果数目不对" };
+ const ms = /\bO=Microsoft Corporation\b/;
+ for (const [i, s] of list.entries()) {
+ const name = path.basename(files[i]);
+ if (s?.status !== "Valid") return { ok: false, error: `${name} 的签名无效(${s?.status || "无签名"})` };
+ if (!ms.test(s.subject ?? "") || !ms.test(s.issuer ?? "")) return { ok: false, error: `${name} 不是 Microsoft 签名的(${clip(s.subject ?? "", 120)})` };
+ }
+ return { ok: true };
+}
+
+/** 解压 zip:系统自带的 tar.exe(Windows 10 1803 起有,认 zip);没有或失败时用 5.1 的 Expand-Archive。不用 PATH 里的 tar(Git 的 GNU tar 不认 zip) */
+export async function extractZip(zip: string, dest: string, run: Runner, env: NodeJS.ProcessEnv): Promise<void> {
+ const r = await run(W.join(sysRoot(env), "System32", "tar.exe"), ["-xf", zip, "-C", dest], { timeoutMs: 10 * 60_000, env: shellEnv(env) });
+ if (r.code === 0 && !r.error && !r.timedOut) return;
+ log.warn("tar.exe could not extract the PowerShell zip; trying Expand-Archive", { code: r.code, error: r.error, stderr: clip(r.stderr) });
+ await fs.promises.rm(dest, { recursive: true, force: true });
+ await fs.promises.mkdir(dest, { recursive: true });
+ const ps = "$ProgressPreference = 'SilentlyContinue'; Expand-Archive -LiteralPath $env:AMB_ZIP -DestinationPath $env:AMB_DEST -Force";
+ const r2 = await run(windowsPowerShell(env), ["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ps], {
+ timeoutMs: 20 * 60_000,
+ env: { ...shellEnv(env), AMB_ZIP: zip, AMB_DEST: dest },
+ });
+ if (r2.code !== 0 || r2.error || r2.timedOut) throw new Error(`解压失败:${clip(r2.error || r2.stderr || r2.stdout || (r2.timedOut ? "超时" : `退出码 ${r2.code}`))}`);
+}
+
+// ---------- 系统版本与架构 ----------
+
+/** os.release() 形如 10.0.22631;读不出来就不拦(试运行会把关) */
+export function osSupport(release: string, pin: PwshPin = PRIVATE_PWSH): { ok: boolean; build?: number; reason?: string } {
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(release);
+ if (!m) return { ok: true };
+ const major = Number(m[1]);
+ const build = Number(m[3]);
+ if (major > 10 || (major === 10 && build >= pin.minBuild)) return { ok: true, build };
+ return { ok: false, build, reason: `这台电脑的 Windows 版本较旧(${release}),PowerShell ${pin.version} 需要 Windows 10 1607 / Windows Server 2016 或更新的系统` };
+}
+
+/**
+ * 装哪个架构:arm64 进程装 arm64;x64 进程在 ARM64 的 Windows 上是模拟运行,也装原生 arm64(快得多)。
+ * PROCESSOR_IDENTIFIER 不随模拟改写(Intel64 / AMD64 开头就是真 x64);认不出来时问注册表里的本机架构。32 位进程不装。
+ */
+export async function resolveArch(o: { arch?: string; env?: NodeJS.ProcessEnv; run?: Runner } = {}): Promise<PwshArch | undefined> {
+ const arch = o.arch ?? process.arch;
+ if (arch === "arm64") return "arm64";
+ if (arch !== "x64") return undefined;
+ const env = o.env ?? process.env;
+ const id = env.PROCESSOR_IDENTIFIER ?? "";
+ if (/\bARM/i.test(id) || /^ARM64$/i.test(env.PROCESSOR_ARCHITEW6432 ?? "")) return "arm64";
+ if (/^(Intel64|AMD64|EM64T)\b/i.test(id)) return "x64";
+ const r = await (o.run ?? runProcess)(W.join(sysRoot(env), "System32", "reg.exe"), ["query", "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "/v", "PROCESSOR_ARCHITECTURE"], { timeoutMs: 10_000, env: shellEnv(env) });
+ return /\bARM64\b/i.test(r.stdout) ? "arm64" : "x64";
+}
+
+/** 安装根目录:AMB_PWSH_HOME,否则 %LOCALAPPDATA%\AnyModelBot\pwsh */
+export function pwshRoot(env: NodeJS.ProcessEnv = process.env): string {
+ if (env.AMB_PWSH_HOME) return path.resolve(env.AMB_PWSH_HOME);
+ return path.join(env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"), "AnyModelBot", "pwsh");
+}
+
+// ---------- 下载 ----------
+
+export class HashMismatch extends Error {}
+/** 重试也没用的下载错误:大小不对(多半是代理或网关返回了网页)、HTTP 4xx */
+export class DownloadRefused extends Error {}
+
+/** 流式下载并边下边算 SHA256;长时间没有数据或总时长超限就中止。哈希不对时抛 HashMismatch(文件留给调用方删) */
+export async function download(o: {
+ fetch: typeof fetch;
+ url: string;
+ dest: string;
+ sha256: string;
+ size?: number;
+ onProgress?: (received: number, total?: number) => void;
+ stallMs?: number;
+ totalMs?: number;
+}): Promise<void> {
+ const ac = new AbortController();
+ const stallMs = o.stallMs ?? 90_000;
+ let stall: NodeJS.Timeout | undefined;
+ const arm = () => {
+ clearTimeout(stall);
+ stall = setTimeout(() => ac.abort(new Error(`${Math.round(stallMs / 1000)} 秒没有收到数据`)), stallMs);
+ };
+ const total = setTimeout(() => ac.abort(new Error("下载超时")), o.totalMs ?? 60 * 60_000);
+ const hash = crypto.createHash("sha256");
+ const fh = await fs.promises.open(o.dest, "w");
+ let received = 0;
+ try {
+ arm();
+ const res = await o.fetch(o.url, { signal: ac.signal, redirect: "follow" });
+ if (!res.ok || !res.body) throw res.status >= 400 && res.status < 500 && res.status !== 429 ? new DownloadRefused(`HTTP ${res.status}`) : new Error(`HTTP ${res.status}`);
+ const len = Number(res.headers.get("content-length")) || undefined;
+ if (o.size && len && len !== o.size) throw new DownloadRefused(`文件大小不对(${len} 字节,应为 ${o.size})`);
+ const reader = res.body.getReader();
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ arm();
+ received += value.byteLength;
+ if (o.size && received > o.size) throw new DownloadRefused(`文件比预期大(超过 ${o.size} 字节)`);
+ hash.update(value);
+ await fh.write(value);
+ o.onProgress?.(received, o.size ?? len);
+ }
+ } catch (e) {
+ throw ac.signal.aborted && ac.signal.reason instanceof Error ? ac.signal.reason : e;
+ } finally {
+ clearTimeout(stall);
+ clearTimeout(total);
+ await fh.close();
+ }
+ const got = hash.digest("hex");
+ if (got !== o.sha256) throw new HashMismatch(`SHA256 不符(${got.slice(0, 12)}…,应为 ${o.sha256.slice(0, 12)}…)`);
+}
+
+// ---------- 文件 ----------
+
+/** 关键文件的大小 + 修改时间;missing:第一个缺的文件 */
+async function fingerprint(dir: string): Promise<{ value: string; missing?: string }> {
+ const parts: string[] = [];
+ let missing: string | undefined;
+ for (const f of KEY_FILES) {
+ try {
+ const s = await fs.promises.stat(path.join(dir, f));
+ parts.push(`${f}:${s.size}:${Math.round(s.mtimeMs)}`);
+ } catch {
+ missing ??= f;
+ parts.push(`${f}:-`);
+ }
+ }
+ return { value: parts.join("|"), missing };
+}
+
+function readJson<T>(file: string): T | undefined {
+ try {
+ return JSON.parse(fs.readFileSync(file, "utf8")) as T;
+ } catch {
+ return undefined;
+ }
+}
+
+function writeJsonAtomic(file: string, value: unknown): void {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
+ fs.renameSync(tmp, file);
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** 改名,Windows 上杀毒软件刚扫过的文件常被占用一会儿(EPERM / EBUSY / EACCES),等一等再试 */
+async function renameRetry(from: string, to: string, tries = 20): Promise<void> {
+ for (let i = 0; ; i++) {
+ try {
+ return await fs.promises.rename(from, to);
+ } catch (e) {
+ const code = (e as NodeJS.ErrnoException).code ?? "";
+ if (i >= tries - 1 || !["EPERM", "EBUSY", "EACCES", "ENOTEMPTY"].includes(code)) throw e;
+ await sleep(500);
+ }
+ }
+}
+
+function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+// ---------- 状态 ----------
+
+export type InstallState = "idle" | "waiting" | "downloading" | "extracting" | "verifying" | "testing" | "done" | "failed";
+
+export interface InstallProgress {
+ state: InstallState;
+ /** 已下载 / 总字节 */
+ received?: number;
+ total?: number;
+ error?: string;
+ startedAt?: number;
+ finishedAt?: number;
+ /** 用户点的(不是自动装的) */
+ manual?: boolean;
+}
+
+export interface PrivatePwshStatus {
+ version: string;
+ arch?: PwshArch;
+ /** 这台电脑能不能装(Windows 版本、架构) */
+ supported: boolean;
+ reason?: string;
+ dir?: string;
+ /** 目录和标记文件在 */
+ installed: boolean;
+ /** 试运行通过、没被标记为坏:代理可以用 */
+ ready: boolean;
+ test?: LaunchTest;
+ bad?: { reason: string; at: number };
+ install: InstallProgress;
+}
+
+interface InstallRecord {
+ fp: string;
+ test?: LaunchTest;
+ bad?: { reason: string; at: number };
+}
+interface StateFile {
+ installs?: Record<string, InstallRecord>;
+ /** 自动安装:连续失败次数与上次时间 */
+ auto?: { attempts: number; lastAt: number };
+}
+
+export interface PrivateDeps {
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+ /** process.arch */
+ arch?: string;
+ /** os.release() */
+ osRelease?: string;
+ /** 下载用的 fetch(桌面版换成 Electron 的 net.fetch:走系统代理);每次下载时取 */
+ fetch?: () => typeof fetch | undefined;
+ run?: Runner;
+ pidAlive?: (pid: number) => boolean;
+ /** 下载重试的间隔基数(测试里调小) */
+ retryDelayMs?: number;
+ /** 测试用:换掉固定的版本与哈希 */
+ pin?: PwshPin;
+}
+
+export class PrivatePwsh {
+ readonly pin: PwshPin;
+ arch?: PwshArch;
+ private archP?: Promise<PwshArch | undefined>;
+ private prep?: Promise<void>;
+ private installing?: Promise<boolean>;
+ private progress: InstallProgress = { state: "idle" };
+ private cur: { installed: boolean; ready: boolean; test?: LaunchTest; bad?: { reason: string; at: number }; fp?: string } = { installed: false, ready: false };
+ private listeners = new Set<() => void>();
+
+ constructor(private readonly d: PrivateDeps = {}) {
+ this.pin = d.pin ?? PRIVATE_PWSH;
+ }
+
+ private get env(): NodeJS.ProcessEnv {
+ return this.d.env ?? process.env;
+ }
+ private get run(): Runner {
+ return this.d.run ?? runProcess;
+ }
+ get root(): string {
+ return pwshRoot(this.env);
+ }
+ get support(): { ok: boolean; build?: number; reason?: string } {
+ if ((this.d.platform ?? process.platform) !== "win32") return { ok: false, reason: "只在 Windows 上需要" };
+ return osSupport(this.d.osRelease ?? os.release(), this.pin);
+ }
+ private get key(): string {
+ return `${this.pin.version}-${this.arch}`;
+ }
+ get dir(): string | undefined {
+ return this.arch ? path.join(this.root, this.key) : undefined;
+ }
+ get exe(): string | undefined {
+ return this.dir && path.join(this.dir, "pwsh.exe");
+ }
+ /** 试运行通过、没被标记为坏 */
+ get ready(): boolean {
+ return this.cur.ready;
+ }
+ get busy(): boolean {
+ return !!this.installing;
+ }
+
+ onChange(fn: () => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+ private changed(): void {
+ for (const fn of this.listeners) {
+ try {
+ fn();
+ } catch {
+ /* ignore */
+ }
+ }
+ }
+ private set(next: PrivatePwsh["cur"]): void {
+ const before = this.cur.ready;
+ this.cur = next;
+ if (before !== next.ready) this.changed();
+ }
+ private setProgress(p: Partial<InstallProgress>, notify = false): void {
+ this.progress = { ...this.progress, ...p };
+ if (notify) this.changed();
+ }
+
+ status(): PrivatePwshStatus {
+ const sup = this.support;
+ const ok = sup.ok && !!this.arch;
+ return {
+ version: this.pin.version,
+ ...(this.arch ? { arch: this.arch } : {}),
+ supported: ok,
+ ...(!sup.ok ? { reason: sup.reason } : !this.arch && this.prep ? { reason: "这台电脑的处理器架构没有对应的 PowerShell 7 安装包" } : {}),
+ ...(this.dir ? { dir: this.dir } : {}),
+ installed: this.cur.installed,
+ ready: this.cur.ready,
+ ...(this.cur.test ? { test: this.cur.test } : {}),
+ ...(this.cur.bad ? { bad: this.cur.bad } : {}),
+ install: { ...this.progress },
+ };
+ }
+
+ // ---------- state.json ----------
+ private get stateFile(): string {
+ return path.join(this.root, "state.json");
+ }
+ private readState(): StateFile {
+ return readJson<StateFile>(this.stateFile) ?? {};
+ }
+ private updateState(fn: (s: StateFile) => void): void {
+ try {
+ const s = this.readState();
+ fn(s);
+ writeJsonAtomic(this.stateFile, s);
+ } catch (e) {
+ log.warn("could not write the PowerShell state file", { err: String((e as Error)?.message ?? e) });
+ }
+ }
+ private saveRecord(rec: InstallRecord | undefined): void {
+ this.updateState((s) => {
+ s.installs ??= {};
+ if (rec) s.installs[this.key] = rec;
+ else delete s.installs[this.key];
+ });
+ }
+
+ // ---------- 锁 ----------
+ private get lockFile(): string {
+ return path.join(this.root, ".lock");
+ }
+ /** 另一个进程正在装(锁文件的进程还在、心跳是新的) */
+ private lockHeld(): boolean {
+ try {
+ const st = fs.statSync(this.lockFile);
+ const pid = Number(readJson<{ pid?: number }>(this.lockFile)?.pid);
+ // 自己的(上次没删掉,或 pid 被复用)不算;没有心跳太久、进程不在了也不算
+ if (pid === process.pid || !(pid > 0) || Date.now() - st.mtimeMs > LOCK_STALE_MS) return false;
+ return (this.d.pidAlive ?? pidAlive)(pid);
+ } catch {
+ return false;
+ }
+ }
+ private takeLock(): boolean {
+ fs.mkdirSync(this.root, { recursive: true });
+ for (let i = 0; i < 2; i++) {
+ try {
+ fs.writeFileSync(this.lockFile, JSON.stringify({ pid: process.pid, at: Date.now() }), { flag: "wx" });
+ return true;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e;
+ }
+ if (this.lockHeld()) return false;
+ fs.rmSync(this.lockFile, { force: true });
+ }
+ return false;
+ }
+
+ /** 没人在装时清掉上次留下的临时文件、半个目录和旧版本(旧版本先改名再删:正被别的进程用着就改不了名,留着) */
+ private async cleanup(): Promise<void> {
+ if (this.installing || this.lockHeld()) return;
+ fs.rmSync(this.lockFile, { force: true });
+ const names = await fs.promises.readdir(this.root).catch(() => [] as string[]);
+ for (const n of names) {
+ const p = path.join(this.root, n);
+ if (/^\.(staging|dl|trash)-/.test(n)) {
+ log.info("removing a leftover from an earlier PowerShell install", { path: p });
+ await fs.promises.rm(p, { recursive: true, force: true }).catch(() => undefined);
+ } else if (n !== this.key && /^\d+\.\d+\.\d+(-[\w.]+)?-(x64|arm64)$/.test(n) && fs.existsSync(path.join(p, MARKER))) {
+ const trash = path.join(this.root, `.trash-${crypto.randomBytes(4).toString("hex")}`);
+ try {
+ await fs.promises.rename(p, trash);
+ await fs.promises.rm(trash, { recursive: true, force: true });
+ log.info("removed an older app-managed PowerShell", { path: p });
+ } catch {
+ /* 正在用 */
+ }
+ }
+ }
+ }
+
+ // ---------- 检查已装的副本 ----------
+
+ private resolveArchOnce(): Promise<PwshArch | undefined> {
+ this.archP ??= resolveArch({ arch: this.d.arch, env: this.env, run: this.run }).catch(() => undefined);
+ return this.archP;
+ }
+
+ /**
+ * 启动时(以及"重新检测"时)看一眼已装的副本:清理残留,文件指纹和上次试运行通过时一样就直接用;
+ * 变了就重新核对签名并试运行;refresh 时清掉"坏了"的标记并重新试运行。
+ */
+ prepare(refresh = false): Promise<void> {
+ if (this.prep && !refresh) return this.prep;
+ const p = this.doPrepare(refresh).catch((e) => log.warn("checking the app-managed PowerShell failed", { err: String((e as Error)?.message ?? e) }));
+ this.prep = p;
+ return p;
+ }
+
+ private async doPrepare(refresh: boolean): Promise<void> {
+ this.arch = await this.resolveArchOnce();
+ if (!this.support.ok || !this.arch) return this.set({ installed: false, ready: false });
+ if (this.installing) return;
+ await this.cleanup();
+ const dir = this.dir!;
+ const marker = readJson<{ version?: string; arch?: string; sha256?: string }>(path.join(dir, MARKER));
+ if (!marker || marker.version !== this.pin.version || marker.sha256 !== this.pin.sha256[this.arch]) return this.set({ installed: false, ready: false });
+ const fp = await fingerprint(dir);
+ const rec = this.readState().installs?.[this.key];
+ if (fp.missing) {
+ const bad = rec?.bad && rec.fp === fp.value ? rec.bad : { reason: `文件 ${fp.missing} 不见了(可能被杀毒软件删除或隔离)`, at: Date.now() };
+ this.saveRecord({ fp: fp.value, test: rec?.test, bad });
+ log.warn("app-managed PowerShell is incomplete", { dir, missing: fp.missing });
+ return this.set({ installed: true, ready: false, bad, test: rec?.test, fp: fp.value });
+ }
+ if (!refresh && rec?.fp === fp.value) {
+ if (rec.bad) return this.set({ installed: true, ready: false, bad: rec.bad, test: rec.test, fp: fp.value });
+ if (rec.test?.ok && Date.now() - rec.test.at < RETEST_MS) return this.set({ installed: true, ready: true, test: rec.test, fp: fp.value });
+ }
+ // 文件变了(或从没测过):先核对签名;然后试运行
+ if (rec?.fp !== fp.value) {
+ const sig = await verifySignatures(SIGNED_FILES.map((f) => path.join(dir, f)), this.run, this.env);
+ if (!sig.ok) {
+ const bad = { reason: `签名核对没通过:${sig.error}`, at: Date.now() };
+ this.saveRecord({ fp: fp.value, bad });
+ log.warn("app-managed PowerShell failed the signature check", { dir, error: sig.error });
+ return this.set({ installed: true, ready: false, bad, fp: fp.value });
+ }
+ }
+ const test = await launchTest(path.join(dir, "pwsh.exe"), this.run, { timeoutMs: 60_000, env: this.env, expect: this.pin.version });
+ log.info("app-managed PowerShell launch test", { dir, ok: test.ok, ms: test.ms, version: test.version, error: test.error });
+ if (!test.ok) {
+ const bad = { reason: `试运行没通过:${test.error}`, at: Date.now() };
+ this.saveRecord({ fp: fp.value, test, bad });
+ return this.set({ installed: true, ready: false, bad, test, fp: fp.value });
+ }
+ this.saveRecord({ fp: fp.value, test });
+ this.set({ installed: true, ready: true, test, fp: fp.value });
+ }
+
+ /** 运行中发现坏了(代理拉不起它等):标记为坏,记下原因;重新安装或重新检测之前不再用 */
+ markBad(reason: string): void {
+ if (!this.cur.installed) return;
+ const bad = { reason, at: Date.now() };
+ const rec = this.readState().installs?.[this.key];
+ this.saveRecord({ fp: this.cur.fp ?? rec?.fp ?? "", test: rec?.test, bad });
+ log.warn("app-managed PowerShell marked as broken", { dir: this.dir, reason });
+ this.set({ ...this.cur, ready: false, bad });
+ }
+
+ // ---------- 自动安装的节奏 ----------
+
+ /**
+ * 现在能不能自动装;不能时返回原因。只在一份都没装时自动装:装过但坏了(试运行没过、代理拉不起、文件被删)要用户点"重新安装",
+ * 免得"装好 → 坏 → 再装"一直循环下载。
+ */
+ autoBlocked(): string | undefined {
+ if (this.env.AMB_PWSH_AUTO_INSTALL === "0") return "AMB_PWSH_AUTO_INSTALL=0";
+ if (!this.support.ok) return this.support.reason;
+ if (!this.arch) return "不支持的处理器架构";
+ if (this.installing) return "正在安装";
+ if (this.cur.installed) return this.cur.bad ? `已装的副本用不了(${this.cur.bad.reason}),需要手动重新安装` : "已经装好";
+ const a = this.readState().auto ?? { attempts: 0, lastAt: 0 };
+ if (a.attempts >= AUTO_BACKOFF.length) return `自动安装已经失败 ${a.attempts} 次`;
+ if (Date.now() - a.lastAt < AUTO_BACKOFF[a.attempts]) return "上次自动安装失败,稍后再试";
+ return undefined;
+ }
+
+ // ---------- 安装 ----------
+
+ /**
+ * 下载、校验、解压、核对签名、试运行,然后换上。reinstall:已经有能用的也重装(删掉旧的)。
+ * 同一进程里只跑一个;另一个进程正在装时返回 false(状态是 waiting)。
+ */
+ install(o: { reinstall?: boolean; manual?: boolean } = {}): Promise<boolean> {
+ this.installing ??= this.doInstall(o).finally(() => (this.installing = undefined));
+ return this.installing;
+ }
+
+ private async doInstall(o: { reinstall?: boolean; manual?: boolean }): Promise<boolean> {
+ const startedAt = Date.now();
+ this.progress = { state: "waiting", startedAt, ...(o.manual ? { manual: true } : {}) };
+ this.changed();
+ await this.prep?.catch(() => undefined);
+ this.arch = await this.resolveArchOnce();
+ const sup = this.support;
+ // 自动安装失败才记一次(装到一半退出不算,下次启动接着装);手动点安装清零
+ const fail = (error: string) => {
+ if (!o.manual)
+ this.updateState((s) => {
+ const a = s.auto ?? { attempts: 0, lastAt: 0 };
+ s.auto = { attempts: a.attempts + 1, lastAt: Date.now() };
+ });
+ this.setProgress({ state: "failed", error, finishedAt: Date.now() }, true);
+ return false;
+ };
+ if (!sup.ok) return fail(sup.reason ?? "这台电脑装不了");
+ if (!this.arch) return fail("这台电脑的处理器架构没有对应的 PowerShell 7 安装包");
+ if (o.manual) this.updateState((s) => (s.auto = { attempts: 0, lastAt: 0 }));
+ if (!o.reinstall && this.cur.ready) {
+ this.setProgress({ state: "done", finishedAt: Date.now() }, true);
+ return true;
+ }
+ let locked = false;
+ try {
+ locked = this.takeLock();
+ } catch (e) {
+ return fail(`建不了安装目录 ${this.root}:${(e as Error).message}`);
+ }
+ if (!locked) {
+ this.setProgress({ state: "waiting", error: "另一个 AnyModelBot 正在安装 PowerShell 7" }, true);
+ return false;
+ }
+ const heartbeat = setInterval(() => fs.promises.utimes(this.lockFile, new Date(), new Date()).catch(() => undefined), 30_000);
+ heartbeat.unref?.();
+ const arch = this.arch;
+ const tag = crypto.randomBytes(4).toString("hex");
+ const zip = path.join(this.root, `.dl-${tag}.zip`);
+ const stage = path.join(this.root, `.staging-${tag}`);
+ const trash = path.join(this.root, `.trash-${tag}`);
+ const dir = this.dir!;
+ const url = zipUrl(this.pin, arch, this.env);
+ log.info("installing the app-managed PowerShell 7", { version: this.pin.version, arch, url, dir, manual: !!o.manual, reinstall: !!o.reinstall });
+ try {
+ // 1. 下载(网络错误重试两次;哈希不对不重试)
+ const fetchFn = this.d.fetch?.() ?? globalThis.fetch;
+ const size = this.pin.size[arch];
+ this.setProgress({ state: "downloading", received: 0, total: size, error: undefined }, true);
+ let lastLog = 0;
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await download({
+ fetch: fetchFn,
+ url,
+ dest: zip,
+ sha256: this.pin.sha256[arch],
+ size,
+ onProgress: (received, total) => {
+ this.setProgress({ received, total });
+ if (Date.now() - lastLog > 10_000) {
+ lastLog = Date.now();
+ log.info("downloading PowerShell 7", { received, total });
+ }
+ },
+ });
+ break;
+ } catch (e) {
+ if (e instanceof HashMismatch) throw new Error(`下载的文件校验失败,已丢弃:${e.message}`);
+ if (e instanceof DownloadRefused || attempt >= 3) throw new Error(`下载失败(${url}):${(e as Error)?.message ?? e}`);
+ log.warn("PowerShell download failed; retrying", { attempt, err: String((e as Error)?.message ?? e) });
+ this.setProgress({ received: 0 });
+ await sleep(attempt * (this.d.retryDelayMs ?? 3000));
+ }
+ }
+ // 2. 解压到临时目录
+ this.setProgress({ state: "extracting" }, true);
+ await fs.promises.mkdir(stage, { recursive: true });
+ await extractZip(zip, stage, this.run, this.env);
+ await fs.promises.rm(zip, { force: true });
+ // 3. 核对:版本号、关键文件、签名
+ this.setProgress({ state: "verifying" }, true);
+ const ver = depsJsonVersion(await fs.promises.readFile(path.join(stage, "pwsh.deps.json"), "utf8").catch(() => ""));
+ if (ver !== this.pin.version) throw new Error(`解压出来的版本是 ${ver ?? "未知"},应为 ${this.pin.version}`);
+ const fp = await fingerprint(stage);
+ if (fp.missing) throw new Error(`解压后缺少 ${fp.missing}(可能被杀毒软件拦下)`);
+ const sig = await verifySignatures(SIGNED_FILES.map((f) => path.join(stage, f)), this.run, this.env);
+ if (!sig.ok) throw new Error(`签名核对没通过:${sig.error}`);
+ // 4. 按 DSH 的方式试运行(第一次启动时杀毒软件要扫一遍,给足时间)
+ this.setProgress({ state: "testing" }, true);
+ const test = await launchTest(path.join(stage, "pwsh.exe"), this.run, { timeoutMs: 120_000, env: this.env, expect: this.pin.version });
+ if (!test.ok) throw new Error(`试运行没通过:${test.error}`);
+ fs.writeFileSync(path.join(stage, MARKER), JSON.stringify({ version: this.pin.version, arch, sha256: this.pin.sha256[arch], installedAt: Date.now(), test }, null, 2));
+ // 5. 换上:旧目录先挪开(里面的 pwsh 正在跑时挪不动,过一会儿再装),新目录整个改名到位
+ let moved = false;
+ if (fs.existsSync(dir)) {
+ try {
+ await renameRetry(dir, trash);
+ moved = true;
+ } catch (e) {
+ throw new Error(`旧的副本正在使用,换不下来(${(e as NodeJS.ErrnoException).code ?? (e as Error).message}),请稍后再试`);
+ }
+ }
+ try {
+ await renameRetry(stage, dir);
+ } catch (e) {
+ if (moved) await fs.promises.rename(trash, dir).catch(() => undefined);
+ throw new Error(`放不到安装目录:${(e as Error).message}`);
+ }
+ this.saveRecord({ fp: fp.value, test });
+ this.updateState((s) => (s.auto = { attempts: 0, lastAt: 0 }));
+ this.set({ installed: true, ready: true, test, fp: fp.value });
+ this.setProgress({ state: "done", finishedAt: Date.now(), error: undefined }, true);
+ log.info("app-managed PowerShell 7 is ready", { dir, version: test.version, ms: Date.now() - startedAt, testMs: test.ms });
+ return true;
+ } catch (e) {
+ const msg = String((e as Error)?.message ?? e).slice(0, 400);
+ log.warn("installing the app-managed PowerShell 7 failed", { err: msg, ms: Date.now() - startedAt });
+ return fail(msg);
+ } finally {
+ clearInterval(heartbeat);
+ await fs.promises.rm(zip, { force: true }).catch(() => undefined);
+ await fs.promises.rm(stage, { recursive: true, force: true }).catch(() => undefined);
+ await fs.promises.rm(trash, { recursive: true, force: true }).catch(() => undefined);
+ fs.rmSync(this.lockFile, { force: true });
+ }
+ }
+}
diff --git a/src/agent/pwsh.ts b/src/agent/pwsh.ts
index 3f60c97..1188998 100644
--- a/src/agent/pwsh.ts
+++ b/src/agent/pwsh.ts
@@ -1,21 +1,37 @@
/**
- * Windows 上的 PowerShell 7(pwsh)检测。
+ * Windows 上代理用哪个 PowerShell。
*
- * 代理(DSH)在 Windows 上用 PowerShell 执行命令(@deepseek-ai/dsh-pwsh-sandbox,经 Windows ACL 沙箱)。它自己按
- * %ProgramFiles%\PowerShell\7\pwsh.exe → PATH 里的 pwsh.exe → Windows PowerShell 5.1 的顺序找
- * (dsh-pwsh-local 的 resolvePwshPath)。经沙箱时 5.1 每条命令要二三十秒,PowerShell 7 大约 1 秒,
- * 所以没装 7 时界面里建议安装。
+ * 代理(DSH)在 Windows 上用 PowerShell 执行命令(@deepseek-ai/dsh-pwsh-sandbox,经 Windows ACL 沙箱)。经沙箱时
+ * Windows PowerShell 5.1 每条命令要二三十秒,PowerShell 7 大约 1 秒。DSH 自己按 %ProgramFiles%\PowerShell\7\pwsh.exe → PATH 里的
+ * pwsh.exe → 5.1 的顺序找(dsh-pwsh-local 的 resolvePwshPath);这里选好一个写进 DSH 补丁(pwsh-sandbox 的 pwshPath):
*
- * - 只看文件,不拉起进程、不阻塞主线程:先按 DSH 的顺序,再补上 DSH 不看的位置(7-preview 等其他 7* 目录、
- * Microsoft Store / winget 的 WindowsApps 别名)。
- * - 找到的路径写进 DSH 补丁(pwsh-sandbox 的 pwshPath),DSH 用的就是这里检测到的那一个。
- * - 版本号异步读:先读 pwsh.deps.json,读不到(Store 别名)再 `pwsh -Version`(windowsHide,5 秒超时)。
- * - 结果缓存;"重新检测"时刷新。AMB_PWSH_FORCE=missing 在任何平台上模拟"未安装"(截图、测试),不影响 DSH。
+ * 1. 系统里能用的 PowerShell 7(用户自己装的,什么都不下载):先按 DSH 的顺序找文件,再补上 DSH 不看的位置(7-preview 等其他 7*
+ * 目录、Microsoft Store / winget 的 WindowsApps 别名)。找到后在后台按 DSH 的方式试运行一次,没通过就不用它。
+ * 2. 应用内置的 PowerShell 7(pwsh-private.ts):没有 1 时在后台自动下载安装,试运行通过才用。
+ * 3. 都没有:Windows PowerShell 5.1(和以前一样)。系统里有被排除的 pwsh 时明确写 5.1 的路径,免得 DSH 自己又找回它。
+ *
+ * - 运行中代理拉不起所用的 pwsh(宿主把 pwsh 工具的结果转过来,observeToolResult)就把它标记为坏,退回下一个,空闲时重启 DSH,并告诉用户。
+ * - 选择变了(装好了、坏了、改回系统默认)就通知订阅者:宿主的设置签名里带着路径,空闲的代理进程换用新的。
+ * - 版本号:先读 pwsh.deps.json,读不到(Store 别名)再 `pwsh -Version`(20 秒超时);试运行也会报版本。
+ * - AMB_PWSH_FORCE=missing 在任何平台上模拟"未安装"(截图、测试),不影响 DSH;AMB_PWSH_IGNORE_SYSTEM=1 不用系统里的 PowerShell
+ * (CI 用它验证内置副本);AMB_PWSH_AUTO_INSTALL=0 不自动安装。
*/
import { execFile } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { logger } from "../log.js";
+import {
+ PrivatePwsh,
+ depsJsonVersion,
+ launchTest,
+ runProcess,
+ windowsPowerShell,
+ type InstallProgress,
+ type InstallState,
+ type LaunchTest,
+ type PrivatePwshStatus,
+ type Runner,
+} from "./pwsh-private.js";
const log = logger("pwsh");
const W = path.win32;
@@ -23,8 +39,10 @@ const W = path.win32;
export const PWSH_INSTALL_URL = "https://aka.ms/PSWindows";
export const PWSH_WINGET = "winget install --id Microsoft.PowerShell --source winget";
-/** program-files:%ProgramFiles%\PowerShell\7(MSI、winget);preview:7-preview 等;store:WindowsApps 别名;path:PATH 里的其他位置 */
-export type PwshSource = "program-files" | "path" | "preview" | "store";
+/** program-files:%ProgramFiles%\PowerShell\7(MSI、winget);preview:7-preview 等;store:WindowsApps 别名;path:PATH 里的其他位置;private:应用内置 */
+export type PwshSource = "program-files" | "path" | "preview" | "store" | "private";
+/** auto:系统里没有能用的 7 时用应用内置的(自动安装);system:改回系统默认,不用内置的 */
+export type PwshMode = "auto" | "system";
export interface PwshCandidate {
path: string;
@@ -36,9 +54,9 @@ export interface PwshStatus {
applicable: boolean;
/** 第一次检测还没完成 */
checking?: boolean;
- /** 找到了 pwsh.exe */
+ /** 找到了 pwsh.exe(系统里的,或内置的已就绪) */
found: boolean;
- /** 没有 PowerShell 7+:代理会退回 Windows PowerShell 5.1(或更旧的 pwsh),界面建议安装 */
+ /** 没有能用的 PowerShell 7:代理会退回 Windows PowerShell 5.1 */
missing: boolean;
path?: string;
source?: PwshSource;
@@ -47,9 +65,30 @@ export interface PwshStatus {
/** AMB_PWSH_FORCE=missing 模拟的结果 */
forced?: boolean;
checkedAt: number;
+ /** 写进 DSH 补丁的路径;空 = 交给 DSH 自己找 */
+ using?: string;
+ /** 应用内置的 PowerShell 7 */
+ private?: PrivatePwshStatus;
+ mode?: PwshMode;
+ /** 是否会自动安装内置副本(AMB_PWSH_AUTO_INSTALL=0 关掉;代理模式关着时也不装) */
+ autoInstall?: boolean;
+ /** AMB_PWSH_IGNORE_SYSTEM=1 */
+ ignoreSystem?: boolean;
+ /** 系统里找到的 PowerShell 7 用不了的原因(试运行没过、代理拉不起它) */
+ systemIssue?: string;
+ /** 最近一次自动退回:哪个 pwsh 出了问题、原因、改用了什么 */
+ fallback?: { from: string; reason: string; to?: string; at: number };
+}
+
+/** 选择变了(path)、内置副本装好或没装上(install);notice 是要告诉用户的话 */
+export interface PwshEvent {
+ kind: "path" | "install";
+ from?: string;
+ to?: string;
+ notice?: { level: "info" | "warn"; text: string };
}
-/** 可替换的环境与文件系统(测试用) */
+/** 可替换的环境、文件系统与子进程(测试用) */
export interface PwshDeps {
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
@@ -58,6 +97,10 @@ export interface PwshDeps {
readFile?: (p: string) => Promise<string>;
/** `pwsh -Version` 的输出(读版本号的最后手段) */
runVersion?: (exe: string) => Promise<string>;
+ /** 试运行用 */
+ run?: Runner;
+ /** 内置副本 */
+ priv?: PrivatePwsh;
}
const dirKey = (p: string) => W.normalize(p).replace(/\\+$/, "").toLowerCase();
@@ -103,18 +146,19 @@ export function parsePwshVersion(text: string): string | undefined {
return /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)/.exec(text)?.[1];
}
+/** 冷启动的机器上 pwsh 第一次启动可能要十几秒(CI 上 5 秒超时出过错) */
function runVersion(exe: string): Promise<string> {
return new Promise((resolve, reject) =>
- execFile(exe, ["-Version"], { windowsHide: true, timeout: 5000, encoding: "utf8", maxBuffer: 64 * 1024 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout)))),
+ execFile(exe, ["-Version"], { windowsHide: true, timeout: 20_000, encoding: "utf8", maxBuffer: 64 * 1024 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout)))),
);
}
-/** 版本号:MSI / zip 安装目录里的 pwsh.deps.json 有 "pwsh/7.4.6",不用拉起进程;Store 别名旁边没有,再问 pwsh 自己 */
+/** 版本号:MSI / zip 安装目录里的 pwsh.deps.json 有 "pwsh/7.4.6"(新版 "pwsh/7.6.9.500"),不用拉起进程;Store 别名旁边没有,再问 pwsh 自己 */
export async function readPwshVersion(c: PwshCandidate, d: PwshDeps = {}): Promise<string | undefined> {
const readFile = d.readFile ?? ((p: string) => fs.promises.readFile(p, "utf8"));
try {
- const m = /"pwsh\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.]+)?)"/.exec(await readFile(W.join(W.dirname(c.path), "pwsh.deps.json")));
- if (m) return m[1];
+ const v = depsJsonVersion(await readFile(W.join(W.dirname(c.path), "pwsh.deps.json")));
+ if (v) return v;
} catch {
/* 没有这个文件 */
}
@@ -126,99 +170,432 @@ export async function readPwshVersion(c: PwshCandidate, d: PwshDeps = {}): Promi
}
}
+const norm = (s: string) => s.replace(/\\\\/g, "\\").replace(/\//g, "\\").toLowerCase();
+/** 沙箱 runner 的 CreateProcess 失败码里,说明"这个程序本身起不来"的:找不到文件 / 路径、拒绝访问、不是有效程序、不兼容、病毒、策略拦截、文件损坏、WDAC */
+const EXE_WIN32_CODES = new Set([2, 3, 5, 193, 216, 225, 1260, 1392, 4551]);
+
+/**
+ * pwsh 工具的结果说明 PowerShell 本身没拉起来(强信号,立即退回):返回出错的那一行,否则 undefined。
+ * - 沙箱(工作区可写 / 只读):windows-acl-run: CreateProcessAsUserW failed (Win32 2): command: <exe>, cwd: …
+ * - 不经沙箱(完全权限):subprocess failed before reporting an outcome: Error: spawn <exe> ENOENT
+ * 都带着 exe 的完整路径;别的命令失败(退出码非 0、命令写错)不算。
+ */
+export function shellStartFailure(text: string, exe: string): string | undefined {
+ const want = norm(exe);
+ if (!text || !norm(text).includes(want)) return undefined;
+ for (const line of text.split(/\r?\n/)) {
+ const l = norm(line);
+ if (!l.includes(want)) continue;
+ const acl = /windows-acl-run:.*createprocess\w*\s+failed\s+\(win32\s+(\d+)\)/.exec(l);
+ if (acl && EXE_WIN32_CODES.has(Number(acl[1]))) return line.trim().slice(0, 300);
+ if (/failed before reporting an outcome/.test(l) || /\bspawn\s.*\b(enoent|eacces|eperm|unknown|einval)\b/.test(l)) return line.trim().slice(0, 300);
+ }
+ return undefined;
+}
+
+/** 弱信号:.NET 宿主起不来、沙箱 runner 拉它时出了别的错。重新试运行一次,没通过才退回 */
+const SUSPECT = /hostfxr|hostpolicy|coreclr\.dll|A fatal error (was encountered|occurred)|The application to execute does not exist|Could not load file or assembly 'System\.Management\.Automation|windows-acl-run:.*CreateProcess/i;
+
+const INSTALLING: InstallState[] = ["waiting", "downloading", "extracting", "verifying", "testing"];
+export const isInstalling = (p?: InstallProgress) => !!p && INSTALLING.includes(p.state);
+
export class PwshProbe {
+ readonly priv: PrivatePwsh;
private run?: Promise<PwshStatus>;
- private locating?: Promise<PwshCandidate | undefined>;
- private located?: PwshCandidate;
- private last?: PwshStatus;
+ private locating?: Promise<unknown>;
+ /** 系统里找到的候选(找完才有;版本稍后补上) */
+ private sys?: { c?: PwshCandidate; version?: string };
+ private checkedAt = 0;
+ private legacyExists = false;
+ /** 系统 pwsh 的试运行结果(按路径) */
+ private sysTests = new Map<string, LaunchTest | "pending">();
+ /** 代理拉不起来的系统 pwsh(本次运行内) */
+ private sysBad = new Map<string, { reason: string; at: number }>();
+ private fallback?: PwshStatus["fallback"];
+ private cfg: { agent: boolean; mode: PwshMode; fetch?: () => typeof fetch | undefined } = { agent: false, mode: "auto" };
+ private listeners = new Set<(e: PwshEvent) => void>();
+ private lastPath: string | undefined | null = null;
+ private lastInstall: InstallState = "idle";
+ private suspected = new Map<string, number>();
+ /** markBroken 里标记内置副本时先不通知,标记完一次性带上提示 */
+ private quiet = false;
- constructor(private readonly d: PwshDeps = {}) {}
+ constructor(private readonly d: PwshDeps = {}) {
+ this.priv = d.priv ?? new PrivatePwsh({ env: d.env, platform: d.platform, run: d.run, fetch: () => this.cfg.fetch?.() });
+ this.priv.onChange(() => this.onPrivateChange());
+ }
+ private get env(): NodeJS.ProcessEnv {
+ return this.d.env ?? process.env;
+ }
private get platform(): NodeJS.Platform {
return this.d.platform ?? process.platform;
}
private get forced(): boolean {
- return (this.d.env ?? process.env).AMB_PWSH_FORCE === "missing";
+ return this.env.AMB_PWSH_FORCE === "missing";
+ }
+ private get ignoreSystem(): boolean {
+ return this.env.AMB_PWSH_IGNORE_SYSTEM === "1";
}
get applicable(): boolean {
return this.platform === "win32" || this.forced;
}
+ /** 真的要选 pwsh(Windows、不是模拟) */
+ private get active(): boolean {
+ return this.platform === "win32" && !this.forced;
+ }
+ get mode(): PwshMode {
+ return this.cfg.mode;
+ }
- /** 检测(结果缓存);refresh = 重新检测 */
+ /** 应用启动时:代理模式开没开(关着不自动装)、用户的选择、下载用的 fetch(桌面版走系统代理) */
+ configure(o: { agent?: boolean; mode?: PwshMode; fetch?: () => typeof fetch | undefined }): void {
+ if (o.agent !== undefined) this.cfg.agent = o.agent;
+ if (o.mode !== undefined) this.cfg.mode = o.mode;
+ if (o.fetch !== undefined) this.cfg.fetch = o.fetch;
+ this.update();
+ this.maybeAutoInstall("configure");
+ }
+
+ onChange(fn: (e: PwshEvent) => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+ private emit(e: PwshEvent): void {
+ for (const fn of this.listeners) {
+ try {
+ fn(e);
+ } catch (err) {
+ log.warn("PowerShell listener failed", { err: String(err) });
+ }
+ }
+ }
+
+ /** 检测(结果缓存);refresh = 重新检测:重新找、重新试运行,清掉"坏了"的标记 */
check(refresh = false): Promise<PwshStatus> {
if (this.run && !refresh) return this.run;
- if (!this.applicable || this.forced) {
- this.last = { applicable: this.applicable, found: false, missing: this.forced, ...(this.forced ? { forced: true } : {}), checkedAt: Date.now() };
- return (this.run = Promise.resolve(this.last));
+ if (!this.active) {
+ this.checkedAt = Date.now();
+ return (this.run = Promise.resolve(this.compose()));
+ }
+ if (refresh) {
+ this.sysTests.clear();
+ this.sysBad.clear();
+ this.suspected.clear();
+ this.fallback = undefined;
}
const t0 = Date.now();
- const locating = findPwsh(this.d).catch((e) => {
- log.warn("PowerShell detection failed", { err: String((e as Error)?.message ?? e) });
- return undefined;
- });
+ const lstat = this.d.lstat ?? ((p: string) => fs.promises.lstat(p));
+ const locating = (this.ignoreSystem ? Promise.resolve(undefined) : findPwsh(this.d))
+ .catch((e) => {
+ log.warn("PowerShell detection failed", { err: String((e as Error)?.message ?? e) });
+ return undefined;
+ })
+ .then(async (c) => {
+ this.legacyExists = await lstat(windowsPowerShell(this.env)).then((s) => s.isFile(), () => false);
+ if (this.locating === locating) this.sys = { c };
+ return c;
+ });
this.locating = locating;
const run: Promise<PwshStatus> = locating.then(async (c) => {
- if (this.locating === locating) this.located = c;
const version = c ? await readPwshVersion(c, this.d) : undefined;
- const st: PwshStatus = { applicable: true, found: !!c, missing: !c || Number(version?.split(".")[0]) < 7, path: c?.path, source: c?.source, version, checkedAt: Date.now() };
- if (this.run === run) this.last = st;
- log.info("PowerShell", { found: st.found, missing: st.missing, path: st.path, source: st.source, version: st.version, ms: Date.now() - t0 });
+ if (this.locating === locating && this.sys) this.sys.version = version;
+ await this.priv.prepare(refresh);
+ this.checkedAt = Date.now();
+ const st = this.compose();
+ log.info("PowerShell", { found: st.found, missing: st.missing, path: st.path, source: st.source, version: st.version, using: st.using, private: st.private && { ready: st.private.ready, installed: st.private.installed, supported: st.private.supported, bad: st.private.bad?.reason }, ms: Date.now() - t0 });
+ this.update();
+ this.testSystem();
+ this.maybeAutoInstall("check");
return st;
});
this.run = run;
return run;
}
- /** 同步快照(/status、诊断):没检测过就开始检测,先返回"检测中" */
+ /** 同步快照(/status、诊断、界面):没检测过就开始检测,先返回"检测中";安装进度是实时的 */
snapshot(): PwshStatus {
if (!this.run) void this.check();
- return this.last ?? { applicable: this.applicable, checking: true, found: false, missing: false, checkedAt: 0 };
+ return this.compose();
+ }
+
+ /** 现在该用哪个 */
+ private choose(): { kind: "system" | "private" | "legacy"; path?: string; source?: PwshSource; version?: string } {
+ const s = this.sys;
+ if (s?.c && !this.systemIssue()) {
+ const t = this.sysTests.get(dirKey(s.c.path));
+ const version = s.version ?? (t && t !== "pending" ? t.version : undefined);
+ if (!(Number(version?.split(".")[0]) < 7)) return { kind: "system", path: s.c.path, source: s.c.source, version };
+ }
+ if (this.cfg.mode === "auto" && this.priv.ready && this.priv.exe) return { kind: "private", path: this.priv.exe, source: "private", version: this.priv.pin.version };
+ return { kind: "legacy", path: (s?.c || this.ignoreSystem) && this.legacyExists ? windowsPowerShell(this.env) : undefined };
+ }
+
+ /** 系统里的那个为什么不能用 */
+ private systemIssue(): string | undefined {
+ const c = this.sys?.c;
+ if (!c) return undefined;
+ const bad = this.sysBad.get(dirKey(c.path));
+ if (bad) return `代理拉不起它:${bad.reason}`;
+ const t = this.sysTests.get(dirKey(c.path));
+ if (t && t !== "pending" && !t.ok && !t.timedOut) return `试运行没通过:${t.error}`;
+ return undefined;
+ }
+
+ private compose(): PwshStatus {
+ if (!this.applicable) return { applicable: false, found: false, missing: false, checkedAt: this.checkedAt || Date.now() };
+ if (this.forced) return { applicable: true, found: false, missing: true, forced: true, checkedAt: this.checkedAt || Date.now() };
+ const extra = {
+ mode: this.cfg.mode,
+ autoInstall: this.cfg.agent && this.cfg.mode === "auto" && this.env.AMB_PWSH_AUTO_INSTALL !== "0",
+ ...(this.ignoreSystem ? { ignoreSystem: true } : {}),
+ private: this.priv.status(),
+ ...(this.fallback ? { fallback: this.fallback } : {}),
+ };
+ const s = this.sys;
+ if (!s) return { applicable: true, checking: true, found: false, missing: false, checkedAt: 0, ...extra };
+ const ch = this.choose();
+ const issue = this.systemIssue();
+ const base =
+ ch.kind !== "legacy"
+ ? { found: true, missing: false, path: ch.path, source: ch.source, version: ch.version }
+ : s.c
+ ? { found: true, missing: true, path: s.c.path, source: s.c.source, version: s.version }
+ : { found: false, missing: true };
+ return { applicable: true, ...base, checkedAt: this.checkedAt, ...(ch.path ? { using: ch.path } : {}), ...(issue ? { systemIssue: issue } : {}), ...extra };
}
/**
- * DSH 启动前调用:要写进补丁的 pwshPath。只等文件检测(不等版本号),最多 waitMs;
- * 不是 Windows、模拟"未安装"或没找到时返回 undefined(DSH 自己找)。
+ * DSH 启动前调用:要写进补丁的 pwshPath。最多等 waitMs(找文件、看一眼内置副本;不等版本号和试运行);
+ * 不是 Windows、模拟"未安装"、或什么都没有时返回 undefined(DSH 自己找)。
*/
async dshPath(waitMs = 3000): Promise<string | undefined> {
- if (this.platform !== "win32" || this.forced) return undefined;
+ if (!this.active) return undefined;
if (!this.run) void this.check();
let timer: NodeJS.Timeout | undefined;
- const c = await Promise.race([this.locating!, new Promise<undefined>((r) => (timer = setTimeout(() => r(undefined), waitMs)))]);
- clearTimeout(timer);
- return c?.path;
+ const deadline = new Promise<void>((r) => (timer = setTimeout(r, waitMs)));
+ try {
+ await Promise.race([this.locating, deadline]);
+ if (this.sys && this.choose().kind === "legacy" && this.cfg.mode === "auto") await Promise.race([this.priv.prepare(), deadline]);
+ } finally {
+ clearTimeout(timer);
+ }
+ return this.choose().path;
}
- /** 最近一次检测到的 DSH 路径(同步):变了就在代理进程空闲时重启它 */
+ /** 现在写进 DSH 补丁的路径(同步):变了就在代理进程空闲时重启它 */
get cachedDshPath(): string | undefined {
- return this.platform !== "win32" || this.forced ? undefined : this.located?.path;
+ return this.active && this.sys ? this.choose().path : undefined;
}
+
+ /** 选择变了就通知(notice:同时要告诉用户的话) */
+ private update(notice?: PwshEvent["notice"]): void {
+ if (!this.active || !this.sys) return;
+ const to = this.choose().path;
+ if (this.lastPath === null) {
+ this.lastPath = to;
+ return;
+ }
+ if (to === this.lastPath && !notice) return;
+ const from = this.lastPath;
+ this.lastPath = to;
+ if (from !== to) log.info("PowerShell for the agent changed; idle agent hosts restart", { from, to });
+ this.emit({ kind: "path", from, to, notice });
+ }
+
+ private onPrivateChange(): void {
+ if (this.quiet) return;
+ const p = this.priv.status().install;
+ const was = this.lastInstall;
+ this.lastInstall = p.state;
+ if (was !== p.state && INSTALLING.includes(was)) {
+ if (p.state === "done")
+ this.emit({ kind: "install", notice: { level: "info", text: `已为代理装好 PowerShell ${this.priv.pin.version}(应用内置,不影响你自己的 PowerShell),代理执行命令会快很多。` } });
+ if (p.state === "failed")
+ this.emit({
+ kind: "install",
+ notice: { level: "warn", text: `为代理安装 PowerShell 7 没有成功:${p.error ?? "未知原因"}。代理照常用 Windows PowerShell 5.1 执行命令;可在 设置 → 故障排查 里重试。` },
+ });
+ }
+ this.update();
+ }
+
+ /** 系统里的 pwsh 在后台按 DSH 的方式试运行一次(每个路径每次运行一次);没通过就换下一个 */
+ private testSystem(): void {
+ const c = this.sys?.c;
+ if (!this.active || !c) return;
+ const k = dirKey(c.path);
+ if (this.sysTests.has(k)) return;
+ this.sysTests.set(k, "pending");
+ void launchTest(c.path, this.d.run ?? runProcess, { timeoutMs: 60_000, env: this.env }).then((t) => {
+ if (this.sysTests.get(k) !== "pending") return;
+ this.sysTests.set(k, t);
+ log.info("PowerShell launch test", { path: c.path, ok: t.ok, ms: t.ms, version: t.version, error: t.error });
+ if (!t.ok && !t.timedOut && this.sys?.c?.path === c.path) {
+ const to = this.choose().path;
+ this.fallback = { from: c.path, reason: `试运行没通过:${t.error}`, to, at: Date.now() };
+ this.update({ level: "warn", text: `系统里的 PowerShell(${c.path})试运行没通过:${t.error}。代理改用${describe(to, this.priv.exe)}执行命令。` });
+ this.maybeAutoInstall("system test failed");
+ } else this.update();
+ });
+ }
+
+ /** 系统里没有能用的 7、内置的也没装:后台自动装(Windows、代理模式开着、没被关掉、这台电脑能装) */
+ private maybeAutoInstall(why: string): void {
+ if (!this.active || !this.sys || !this.cfg.agent || this.cfg.mode !== "auto") return;
+ if (this.choose().kind !== "legacy" || this.priv.busy) return;
+ const blocked = this.priv.autoBlocked();
+ if (blocked) return void log.info("not installing PowerShell 7 automatically", { why, reason: blocked });
+ log.info("no working PowerShell 7; installing the app-managed copy in the background", { why });
+ void this.priv.install();
+ }
+
+ /** 手动安装 / 重新安装(设置 → 故障排查、提示里的按钮):同时把选择改回 auto */
+ install(o: { reinstall?: boolean } = {}): void {
+ this.cfg.mode = "auto";
+ this.fallback = undefined;
+ const st = this.priv.status();
+ void this.priv.install({ manual: true, reinstall: !!o.reinstall || !!st.bad }).then(() => this.update());
+ }
+
+ /** 改回系统默认 / 重新用内置的 */
+ setMode(mode: PwshMode): void {
+ this.cfg.mode = mode;
+ this.update();
+ this.maybeAutoInstall("mode");
+ }
+
+ /**
+ * 代理 pwsh 工具的结果(宿主转来;exe = 这个代理进程补丁里写的路径)。
+ * 强信号(PowerShell 本身没拉起来)立即退回下一个;弱信号(.NET 宿主报错之类)重新试运行一次,没通过才退回。
+ */
+ observeToolResult(exe: string | undefined, text: string): void {
+ if (!this.active || !exe || !text) return;
+ const hit = shellStartFailure(text, exe);
+ if (hit) return this.markBroken(exe, hit);
+ if (SUSPECT.test(text)) void this.suspect(exe);
+ }
+
+ private async suspect(exe: string): Promise<void> {
+ const k = dirKey(exe);
+ if (Date.now() - (this.suspected.get(k) ?? 0) < 60_000) return;
+ this.suspected.set(k, Date.now());
+ const t = await launchTest(exe, this.d.run ?? runProcess, { timeoutMs: 60_000, env: this.env });
+ log.info("PowerShell re-test after a suspicious tool result", { path: exe, ok: t.ok, error: t.error });
+ if (!t.ok && !t.timedOut) this.markBroken(exe, `试运行没通过:${t.error}`);
+ }
+
+ /** 代理拉不起 exe:标记为坏,退回下一个(空闲时重启代理进程),告诉用户;必要时自动安装内置副本 */
+ markBroken(exe: string, reason: string): void {
+ const k = dirKey(exe);
+ if (this.priv.exe && dirKey(this.priv.exe) === k) {
+ if (!this.priv.ready) return;
+ this.quiet = true;
+ try {
+ this.priv.markBad(`代理拉不起它:${reason}`);
+ } finally {
+ this.quiet = false;
+ }
+ } else if (this.sys?.c && dirKey(this.sys.c.path) === k) {
+ if (this.sysBad.has(k)) return;
+ this.sysBad.set(k, { reason, at: Date.now() });
+ } else {
+ // Windows PowerShell 5.1 也起不来:已经没有可退的了(多半是沙箱本身的问题),只记日志
+ return void log.warn("the agent could not start PowerShell, and there is nothing left to fall back to", { exe, reason });
+ }
+ const to = this.choose().path;
+ this.fallback = { from: exe, reason, to, at: Date.now() };
+ log.warn("the agent could not start its PowerShell; falling back", { from: exe, to, reason });
+ this.update({
+ level: "warn",
+ text: `代理用的 PowerShell 起不来(${exe}:${reason.slice(0, 160)}),已自动改用${describe(to, this.priv.exe)},空闲时生效。可在 设置 → 故障排查 里重新安装或重新检测。`,
+ });
+ this.maybeAutoInstall("broken");
+ }
+}
+
+/** 给用户看的名字 */
+function describe(p: string | undefined, privateExe: string | undefined): string {
+ if (!p || /\\WindowsPowerShell\\v1\.0\\powershell\.exe$/i.test(p)) return "系统自带的 Windows PowerShell 5.1";
+ if (privateExe && dirKey(p) === dirKey(privateExe)) return "应用内置的 PowerShell 7";
+ return ` ${p} `;
}
/** 进程内共用的一个:宿主、诊断、/status、界面接口都读它 */
export const pwshProbe = new PwshProbe();
-/** DSH 补丁:Windows 上的 pwsh 执行器(pwsh-sandbox;基础 profile 里它没有 config)用检测到的这一个 */
+/** DSH 补丁:Windows 上的 pwsh 执行器(pwsh-sandbox;基础 profile 里它没有 config)用选好的这一个 */
export function pwshPatchLines(pwshPath: string | undefined): string[] {
return pwshPath ? ["- id: pwsh-sandbox", " config:", ` pwshPath: ${JSON.stringify(pwshPath)}`] : [];
}
-const SOURCE: Record<PwshSource, string> = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store" };
+const SOURCE: Record<PwshSource, string> = { "program-files": "安装目录", path: "PATH", preview: "预览版", store: "Microsoft Store", private: "应用内置" };
+const mb = (n?: number) => (n === undefined ? "?" : (n / 1048576).toFixed(0));
+
+/** 安装进度的一句话 */
+export function installProgressText(p: InstallProgress): string {
+ switch (p.state) {
+ case "waiting":
+ return p.error ?? "准备中";
+ case "downloading":
+ return `下载 ${mb(p.received)} / ${mb(p.total)} MB${p.total ? `(${Math.min(100, Math.floor(((p.received ?? 0) / p.total) * 100))}%)` : ""}`;
+ case "extracting":
+ return "解压";
+ case "verifying":
+ return "核对签名";
+ case "testing":
+ return "试运行";
+ case "done":
+ return "已装好";
+ case "failed":
+ return `没装上:${p.error ?? "未知原因"}`;
+ default:
+ return "";
+ }
+}
+
+const SLOW = "代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒";
/** 聊天里 /status 的一行(只在 Windows 上有) */
export function pwshStatusLine(st: PwshStatus): string {
if (!st.applicable) return "";
if (st.checking) return "PowerShell:检测中";
- if (!st.missing) return `PowerShell:${st.version ?? "7"}(代理用它执行命令)`;
- const now = st.found && st.version ? `PowerShell ${st.version} 版本较旧` : "没有安装 PowerShell 7,代理执行命令用的是系统自带的 Windows PowerShell 5.1,每条可能要二三十秒";
- return `PowerShell:${now}。装上 PowerShell 7,命令执行快得多,也更稳定:${PWSH_WINGET}(或打开 ${PWSH_INSTALL_URL})`;
+ const fb = st.fallback ? `;之前用的 ${st.fallback.from} 起不来(${st.fallback.reason.slice(0, 120)}),已自动换掉` : "";
+ if (!st.missing) return `PowerShell:${st.version ?? "7"}(${st.source === "private" ? "应用内置," : ""}代理用它执行命令)${fb}`;
+ const p = st.private;
+ if (p && isInstalling(p.install)) return `PowerShell:正在为代理安装 PowerShell 7…(${installProgressText(p.install)})。装好之前命令照常用 Windows PowerShell 5.1`;
+ if (p?.bad && st.mode !== "system") return `PowerShell:应用内置的 PowerShell 7 用不了(${p.bad.reason.slice(0, 160)}),${SLOW}。在 设置 → 故障排查 里可以一键重新安装`;
+ if (p?.install.state === "failed" && st.mode !== "system") return `PowerShell:为代理安装 PowerShell 7 没有成功(${p.install.error ?? "未知原因"}),${SLOW}。在 设置 → 故障排查 里可以重试,或者自己安装:${PWSH_WINGET}`;
+ if (p && !p.supported && p.reason) return `PowerShell:${p.reason},${SLOW}`;
+ const now = st.systemIssue ? `系统里的 PowerShell 7 用不了(${st.systemIssue.slice(0, 120)}),${SLOW}` : st.found && st.version ? `PowerShell ${st.version} 版本较旧,${SLOW}` : `没有安装 PowerShell 7,${SLOW}`;
+ const how = st.mode === "system" || !p?.supported ? `装上 PowerShell 7,命令执行快得多,也更稳定:${PWSH_WINGET}(或打开 ${PWSH_INSTALL_URL})` : `应用可以自己装一份(不需要管理员权限):设置 → 故障排查 → 安装;或者:${PWSH_WINGET}`;
+ return `PowerShell:${now}。${how}`;
}
-/** 诊断报告里的一行(只在 Windows 上有) */
+/** 诊断报告里的 PowerShell 行(只在 Windows 上有;内置副本另起一行) */
export function pwshReportLine(st: PwshStatus): string | undefined {
if (!st.applicable) return undefined;
if (st.checking) return "[PowerShell] 检测中";
const where = st.path ? ` · ${st.path}(${SOURCE[st.source!] ?? st.source})` : "";
- if (!st.missing) return `[PowerShell] ${st.version ?? "7(版本未知)"}${where} · 代理用它执行命令`;
- if (st.found) return `[PowerShell] ${st.version ?? "?"} 版本较旧${where} · 建议安装 PowerShell 7`;
- return `[PowerShell] 未安装 PowerShell 7:代理用 Windows PowerShell 5.1 执行命令(经沙箱每条约 25 秒,7 约 1 秒)${st.forced ? " · AMB_PWSH_FORCE 模拟" : ""}`;
+ const lines: string[] = [];
+ if (!st.missing) lines.push(`[PowerShell] ${st.version ?? "7(版本未知)"}${where} · 代理用它执行命令`);
+ else if (st.systemIssue) lines.push(`[PowerShell] 系统里的 PowerShell 7 用不了${where} · ${st.systemIssue} · 代理用 ${st.using ?? "Windows PowerShell 5.1(DSH 默认)"}`);
+ else if (st.found) lines.push(`[PowerShell] ${st.version ?? "?"} 版本较旧${where} · 建议安装 PowerShell 7`);
+ else lines.push(`[PowerShell] 未安装 PowerShell 7:代理用 Windows PowerShell 5.1 执行命令(经沙箱每条约 25 秒,7 约 1 秒)${st.forced ? " · AMB_PWSH_FORCE 模拟" : ""}`);
+ if (st.fallback) lines.push(` 自动退回 ${new Date(st.fallback.at).toISOString()}:${st.fallback.from} → ${st.fallback.to ?? "DSH 默认"} · ${st.fallback.reason}`);
+ const p = st.private;
+ if (p) {
+ const state = !p.supported
+ ? `不能装:${p.reason ?? "?"}`
+ : p.ready
+ ? `已就绪 · 试运行通过${p.test ? `(${p.test.ms} ms,${new Date(p.test.at).toISOString()})` : ""}`
+ : p.bad
+ ? `用不了:${p.bad.reason}`
+ : p.installed
+ ? "已装,还没试运行"
+ : "未安装";
+ const inst = p.install.state !== "idle" ? ` · 安装:${installProgressText(p.install)}` : "";
+ lines.push(` 内置 PowerShell ${p.version}${p.arch ? ` ${p.arch}` : ""} · ${state}${inst}${p.dir ? ` · ${p.dir}` : ""} · ${st.mode === "system" ? "已改回系统默认" : st.autoInstall ? "缺 7 时自动安装" : "不自动安装"}${st.ignoreSystem ? " · AMB_PWSH_IGNORE_SYSTEM=1" : ""}`);
+ }
+ return lines.join("\n");
}
diff --git a/src/app.ts b/src/app.ts
index 429a1e4..85ffb90 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -52,6 +52,8 @@ export interface DesktopHooks {
openExternal(url: string): void;
/** 系统钥匙串加密(Electron safeStorage);不可用时缺省,账户凭据改靠文件权限保护 */
secretBox?: SecretBox;
+ /** 走 Chromium 网络栈的 fetch(Electron net.fetch:系统代理、系统证书);下载内置 PowerShell 用,缺省时用 Node 的 fetch */
+ fetch?: typeof fetch;
}
export interface ModelflareStatus {
@@ -114,6 +116,7 @@ export class App {
/** 故障排查页最近一次"测试模型 / 测试代理"的结果(复制诊断信息时带上) */
lastDiagnostics: { model?: import("./diagnostics.js").ModelTestResult; agent?: import("./diagnostics.js").AgentTestResult } = {};
private notices: Array<{ at: number; level: "info" | "warn"; text: string }> = [];
+ private offPwsh: (() => void) | undefined;
private accountTimer: NodeJS.Timeout | undefined;
private picksTimer: NodeJS.Timeout | undefined;
private modelInfoCache: { at: number; data: Record<string, ModelInfo> } | undefined;
@@ -388,8 +391,16 @@ export class App {
this.picksTimer = setInterval(() => void this.syncModelPicks(), 3600_000);
this.picksTimer.unref();
}
- // Windows:找 PowerShell 7(只看文件,异步);代理进程启动时和界面的提示都用这个结果
- if (pwshProbe.applicable) void pwshProbe.check();
+ // Windows:选代理用的 PowerShell(系统里能用的 7 → 应用内置的 → 5.1),没有 7 时在后台自动装内置的;
+ // 选择变了(装好了、坏了退回)就告诉用户,空闲的代理进程在后台换用新的
+ if (pwshProbe.applicable) {
+ pwshProbe.configure({ agent: this.agent.available, mode: this.config.agent.pwsh, fetch: () => this.desktop?.fetch });
+ this.offPwsh = pwshProbe.onChange((e) => {
+ if (e.notice) this.notice(e.notice.level, e.notice.text);
+ if (e.kind === "path") void this.agent.refreshIdle();
+ });
+ void pwshProbe.check();
+ }
void this.prewarmAgent();
if (this.magpie && !this.opts.noWeb) {
// 余额与低余额提醒:启动后读一次,之后每 5 分钟一次
@@ -403,6 +414,7 @@ export class App {
}
async stop(): Promise<void> {
+ this.offPwsh?.();
if (this.accountTimer) clearInterval(this.accountTimer);
if (this.picksTimer) clearInterval(this.picksTimer);
this.account?.cancelLogin();
diff --git a/src/config.ts b/src/config.ts
index 1597d7c..d3bdfab 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -37,8 +37,11 @@ export interface AppConfig {
feishu: { throttleMs: number };
/** cdnBaseUrl:收发图片/文件的微信 CDN(测试时指向假服务) */
weixin: { apiBaseUrl: string; cdnBaseUrl: string };
- /** 代理宿主:dsh = DeepSeek Harness(工具/沙箱/审批);off = 纯对话 */
- agent: { mode: "dsh" | "off"; turnTimeoutMs: number; idleTimeoutMs: number; approvalTtlMs: number };
+ /**
+ * 代理宿主:dsh = DeepSeek Harness(工具/沙箱/审批);off = 纯对话。
+ * pwsh(Windows):auto = 系统里没有能用的 PowerShell 7 时用应用内置的(自动安装);system = 改回系统默认,不用内置的。
+ */
+ agent: { mode: "dsh" | "off"; turnTimeoutMs: number; idleTimeoutMs: number; approvalTtlMs: number; pwsh: "auto" | "system" };
}
export function defaultDataDir(): string {
@@ -104,6 +107,7 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEn
turnTimeoutMs: num(env.AMB_AGENT_TURN_TIMEOUT_MS, file.agent?.turnTimeoutMs ?? 30 * 60_000),
idleTimeoutMs: num(env.AMB_AGENT_IDLE_TIMEOUT_MS, file.agent?.idleTimeoutMs ?? 10 * 60_000),
approvalTtlMs: num(env.AMB_APPROVAL_TTL_MS, file.agent?.approvalTtlMs ?? 10 * 60_000),
+ pwsh: file.agent?.pwsh === "system" ? "system" : "auto",
},
};
}
diff --git a/src/web/server.ts b/src/web/server.ts
index b7fe14d..b4af088 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -17,7 +17,7 @@ import { connectionFromPids } from "../agent/peer-guard.js";
import type { ApprovalRow } from "../store/db.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
-import { pwshProbe, type PwshStatus } from "../agent/pwsh.js";
+import { pwshProbe, type PwshMode } from "../agent/pwsh.js";
const log = logger("web");
const require = createRequire(import.meta.url);
@@ -364,16 +364,39 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
return send(res, 200, { ok: true });
}
if (p === "/agent" && m === "GET") return send(res, 200, app.agent.status());
- // —— Windows:没有 PowerShell 7 时建议安装(对话空状态、设置 → 常规、故障排查)——
+ // —— Windows:代理用的 PowerShell(对话空状态、设置 → 常规、故障排查)——
if (seg[0] === "pwsh") {
- const view = (st: PwshStatus) => ({ ...st, dismissed: cfg.ui.pwshHintDismissed });
- if (seg.length === 1 && m === "GET") return send(res, 200, view(await pwshProbe.check()));
+ const view = () => ({ ...pwshProbe.snapshot(), dismissed: cfg.ui.pwshHintDismissed });
+ const setMode = (mode: PwshMode) => {
+ if (cfg.agent.pwsh === mode) return;
+ cfg.agent.pwsh = mode;
+ saveConfigFile(cfg.dataDir, (f) => (f.agent = { ...(f.agent ?? {}), pwsh: mode }));
+ };
+ if (seg.length === 1 && m === "GET") {
+ await pwshProbe.check();
+ return send(res, 200, view());
+ }
+ // 重新检测:重新找、重新试运行(装好系统 PowerShell 7 后点它;空闲的代理进程随后换用)
if (seg[1] === "recheck" && m === "POST") {
- const before = pwshProbe.cachedDshPath;
- const st = await pwshProbe.check(true);
- // 代理进程空闲时下一条消息会换用新的 PowerShell(宿主的设置签名里带着它)
- if (pwshProbe.cachedDshPath !== before) log.info("PowerShell changed; idle agent hosts restart on the next message", { from: before, to: pwshProbe.cachedDshPath });
- return send(res, 200, view(st));
+ await pwshProbe.check(true);
+ return send(res, 200, view());
+ }
+ // 安装 / 重新安装应用内置的 PowerShell 7:后台进行,进度从 GET 读
+ if (seg[1] === "install" && m === "POST") {
+ if (process.platform !== "win32" || !pwshProbe.applicable) throw new HttpError(400, "只在 Windows 上需要");
+ const b = await readJson(req);
+ setMode("auto");
+ await pwshProbe.check();
+ pwshProbe.install({ reinstall: !!b.reinstall });
+ return send(res, 200, view());
+ }
+ // 改回系统默认(system)/ 重新用内置的(auto)
+ if (seg[1] === "mode" && m === "PUT") {
+ const b = await readJson(req);
+ const mode: PwshMode = b.mode === "system" ? "system" : "auto";
+ setMode(mode);
+ pwshProbe.setMode(mode);
+ return send(res, 200, view());
}
if (seg.length === 1 && m === "PUT") {
const b = await readJson(req);
@@ -381,7 +404,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
cfg.ui.pwshHintDismissed = !!b.dismissed;
saveConfigFile(cfg.dataDir, (f) => (f.ui = { ...(f.ui ?? {}), pwshHintDismissed: cfg.ui.pwshHintDismissed }));
}
- return send(res, 200, view(await pwshProbe.check()));
+ await pwshProbe.check();
+ return send(res, 200, view());
}
throw new HttpError(405, "method not allowed");
}
diff --git a/test/pwsh-private.unit.test.ts b/test/pwsh-private.unit.test.ts
new file mode 100644
index 0000000..331d9d8
--- /dev/null
+++ b/test/pwsh-private.unit.test.ts
@@ -0,0 +1,560 @@
+/**
+ * 应用内置的 PowerShell 7:下载 → 校验 → 解压 → 核对签名 → 试运行 → 换上,以及探测器的优先级、自动安装、运行中坏了自动退回。
+ * 文件系统是真的(临时目录,AMB_PWSH_HOME),下载(fetch)和子进程(tar.exe / powershell.exe / pwsh.exe)是假的,在任何平台上跑。
+ */
+import { afterAll, describe, expect, it, vi } from "vitest";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import {
+ DSH_ENCODING_PREAMBLE,
+ PRIVATE_PWSH,
+ PrivatePwsh,
+ TEST_SCRIPT,
+ osSupport,
+ resolveArch,
+ zipUrl,
+ type PwshPin,
+ type RunResult,
+ type Runner,
+} from "../src/agent/pwsh-private.js";
+import { PwshProbe, pwshStatusLine, pwshReportLine, shellStartFailure, type PwshDeps, type PwshEvent } from "../src/agent/pwsh.js";
+import { AgentHost } from "../src/agent/host.js";
+import { Store } from "../src/store/db.js";
+
+const PF = "C:\\Program Files";
+const SYS_PWSH = `${PF}\\PowerShell\\7\\pwsh.exe`;
+const PS5 = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
+const ZIP = crypto.randomBytes(64 * 1024);
+const sha = (b: Buffer) => crypto.createHash("sha256").update(b).digest("hex");
+const PIN: PwshPin = { ...PRIVATE_PWSH, sha256: { x64: sha(ZIP), arm64: sha(ZIP) }, size: { x64: ZIP.length, arm64: ZIP.length } };
+const FILES = ["pwsh.exe", "pwsh.dll", "System.Management.Automation.dll", "hostfxr.dll", "coreclr.dll"];
+const roots: string[] = [];
+afterAll(() => roots.forEach((r) => fs.rmSync(r, { recursive: true, force: true })));
+
+interface FakeOpts {
+ /** 下载给出的内容(默认就是 ZIP) */
+ body?: Buffer;
+ fetchFails?: number;
+ tarFails?: boolean;
+ /** 签名结果 */
+ sig?: { status: string; subject?: string };
+ /** 内置 pwsh 的试运行 */
+ privateTest?: Partial<RunResult>;
+ /** 系统 pwsh 的试运行 */
+ systemTest?: Partial<RunResult>;
+ osRelease?: string;
+ env?: NodeJS.ProcessEnv;
+ root?: string;
+ pidAlive?: (pid: number) => boolean;
+}
+
+const okTest = (ver: string): RunResult => ({ code: 0, stdout: `AMB-PWSH-TEST ver=${ver} rw=rw-ok ext=ext-ok\r\n`, stderr: "" });
+
+/** 假的下载与子进程;calls 记下每次调用 */
+function fake(o: FakeOpts = {}) {
+ const root = o.root ?? fs.mkdtempSync(path.join(os.tmpdir(), "amb-pwsh-priv-"));
+ roots.push(root);
+ const calls: Array<{ exe: string; args: string[]; env?: NodeJS.ProcessEnv }> = [];
+ const fetches: string[] = [];
+ let fetchFails = o.fetchFails ?? 0;
+ const env: NodeJS.ProcessEnv = { SystemRoot: "C:\\Windows", LOCALAPPDATA: "C:\\Users\\li\\AppData\\Local", ProgramFiles: PF, PATH: "C:\\Windows\\system32", PROCESSOR_IDENTIFIER: "Intel64 Family 6", AMB_PWSH_HOME: root, ...o.env };
+ const run: Runner = async (exe, args, opts) => {
+ calls.push({ exe, args, env: opts.env });
+ if (/tar\.exe$/i.test(exe) || (/powershell\.exe$/i.test(exe) && args.join(" ").includes("Expand-Archive"))) {
+ if (/tar\.exe$/i.test(exe) && o.tarFails) return { code: 1, stdout: "", stderr: "tar.exe: Error opening archive" };
+ const dest = /tar\.exe$/i.test(exe) ? args[args.indexOf("-C") + 1] : opts.env!.AMB_DEST!;
+ for (const f of FILES) fs.writeFileSync(path.join(dest, f), `fake ${f}`);
+ fs.mkdirSync(path.join(dest, "Modules", "Microsoft.PowerShell.Archive"), { recursive: true });
+ fs.writeFileSync(path.join(dest, "pwsh.deps.json"), `{"targets":{"x":{"pwsh/${PIN.version}.500":{}}}}`);
+ return { code: 0, stdout: "", stderr: "" };
+ }
+ if (/powershell\.exe$/i.test(exe)) {
+ const files = String(opts.env?.AMB_SIG_FILES ?? "").split("|");
+ const s = o.sig ?? { status: "Valid", subject: "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" };
+ return { code: 0, stdout: JSON.stringify(files.map(() => ({ status: s.status, subject: s.subject ?? "", issuer: "CN=Microsoft Code Signing PCA 2011, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" }))), stderr: "" };
+ }
+ if (/reg\.exe$/i.test(exe)) return { code: 0, stdout: " PROCESSOR_ARCHITECTURE REG_SZ AMD64\r\n", stderr: "" };
+ if (/pwsh\.exe$/i.test(exe)) {
+ const priv = exe.startsWith(root);
+ return { ...okTest(priv ? PIN.version : "7.4.6"), ...(priv ? o.privateTest : o.systemTest) };
+ }
+ return { code: null, stdout: "", stderr: "", error: `ENOENT: ${exe}` };
+ };
+ const fetchFn = (async (url: string) => {
+ fetches.push(String(url));
+ if (fetchFails-- > 0) throw new Error("ECONNRESET");
+ return new Response(new Uint8Array(o.body ?? ZIP), { headers: { "content-length": String((o.body ?? ZIP).length) } });
+ }) as unknown as typeof fetch;
+ const priv = new PrivatePwsh({ env, platform: "win32", arch: "x64", osRelease: o.osRelease ?? "10.0.22631", run, fetch: () => fetchFn, pin: PIN, pidAlive: o.pidAlive ?? (() => false), retryDelayMs: 1 });
+ return { root, env, run, calls, fetches, priv, fetchFn, dir: path.join(root, `${PIN.version}-x64`) };
+}
+
+const leftovers = (root: string) => fs.readdirSync(root).filter((n) => n.startsWith("."));
+const states = (p: PrivatePwsh) => {
+ const seen: string[] = [];
+ p.onChange(() => {
+ const s = p.status().install.state;
+ if (seen.at(-1) !== s) seen.push(s);
+ });
+ return seen;
+};
+
+describe("内置 PowerShell 7:安装", () => {
+ it("下载 → SHA256 → tar.exe 解压 → 签名 → 按 DSH 的方式试运行 → 整个目录改名到位;不留临时文件和锁", async () => {
+ const f = fake();
+ const seen = states(f.priv);
+ expect(await f.priv.install({ manual: true })).toBe(true);
+ const st = f.priv.status();
+ expect(st).toMatchObject({ version: PIN.version, arch: "x64", supported: true, installed: true, ready: true, dir: f.dir, install: { state: "done", received: ZIP.length, total: ZIP.length } });
+ expect(f.priv.exe).toBe(path.join(f.dir, "pwsh.exe"));
+ expect(seen).toEqual(["waiting", "downloading", "extracting", "verifying", "testing", "done"]);
+ expect(f.fetches).toEqual([`https://github.com/PowerShell/PowerShell/releases/download/v${PIN.version}/PowerShell-${PIN.version}-win-x64.zip`]);
+ // tar 用系统自带的(不是 PATH 里 Git 的 GNU tar),解到临时目录
+ const tar = f.calls.find((c) => /tar\.exe$/i.test(c.exe))!;
+ expect(tar.exe).toBe("C:\\Windows\\System32\\tar.exe");
+ expect(tar.args[tar.args.indexOf("-C") + 1]).toMatch(/[\\/]\.staging-[0-9a-f]+$/);
+ // 签名:Windows PowerShell 5.1 核对 pwsh.exe、pwsh.dll、System.Management.Automation.dll
+ const sig = f.calls.find((c) => /powershell\.exe$/i.test(c.exe))!;
+ expect(sig.exe).toBe(PS5);
+ expect(sig.args).toEqual(expect.arrayContaining(["-NoProfile", "-NonInteractive", "-Command"]));
+ expect(sig.args.at(-1)).toContain("Get-AuthenticodeSignature");
+ expect(String(sig.env?.AMB_SIG_FILES).split("|").map((p) => path.basename(p))).toEqual(["pwsh.exe", "pwsh.dll", "System.Management.Automation.dll"]);
+ // 试运行:和 DSH 一模一样的参数(-NoLogo -NoProfile -NonInteractive -Command + UTF-8 前缀),只带系统目录类环境变量
+ const test = f.calls.find((c) => /pwsh\.exe$/i.test(c.exe))!;
+ expect(test.args).toEqual(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", DSH_ENCODING_PREAMBLE + TEST_SCRIPT]);
+ expect(TEST_SCRIPT).toContain("$PSVersionTable.PSVersion");
+ expect(TEST_SCRIPT).toContain("Set-Content");
+ expect(TEST_SCRIPT).toContain("cmd.exe");
+ expect(test.env).toMatchObject({ NO_COLOR: "1", SystemRoot: "C:\\Windows" });
+ expect(test.env).not.toHaveProperty("AMB_PWSH_HOME");
+ // 结果
+ expect(fs.existsSync(path.join(f.dir, ".amb-pwsh.json"))).toBe(true);
+ expect(JSON.parse(fs.readFileSync(path.join(f.root, "state.json"), "utf8")).installs[`${PIN.version}-x64`].test.ok).toBe(true);
+ expect(leftovers(f.root)).toEqual([]);
+ });
+
+ it("SHA256 不符:不解压、不留文件,报原因", async () => {
+ const f = fake({ body: Buffer.concat([ZIP.subarray(0, ZIP.length - 1), Buffer.from([ZIP[ZIP.length - 1] ^ 1])]) });
+ expect(await f.priv.install({ manual: true })).toBe(false);
+ expect(f.priv.status()).toMatchObject({ installed: false, ready: false, install: { state: "failed" } });
+ expect(f.priv.status().install.error).toMatch(/SHA256 不符/);
+ expect(f.calls.some((c) => /tar\.exe$/i.test(c.exe))).toBe(false);
+ expect(f.fetches).toHaveLength(1); // 哈希不对不重试
+ expect(fs.existsSync(f.dir)).toBe(false);
+ expect(leftovers(f.root)).toEqual([]);
+ });
+
+ it("大小不对(比如代理返回了网页):直接失败", async () => {
+ const f = fake({ body: Buffer.from("<html>blocked</html>") });
+ expect(await f.priv.install({ manual: true })).toBe(false);
+ expect(f.priv.status().install.error).toMatch(/大小不对/);
+ expect(f.fetches).toHaveLength(1); // 重试也没用,不重试
+ expect(leftovers(f.root)).toEqual([]);
+ });
+
+ it("网络错误重试;签名不是 Microsoft 的:删掉解压出来的东西", async () => {
+ const f = fake({ fetchFails: 1, sig: { status: "Valid", subject: "CN=Evil Corp, O=Evil Corp" } });
+ expect(await f.priv.install({ manual: true })).toBe(false);
+ expect(f.fetches).toHaveLength(2);
+ expect(f.priv.status().install.error).toMatch(/签名核对没通过.*不是 Microsoft 签名的/);
+ expect(fs.existsSync(f.dir)).toBe(false);
+ expect(leftovers(f.root)).toEqual([]);
+ const g = fake({ sig: { status: "HashMismatch" } });
+ expect(await g.priv.install({ manual: true })).toBe(false);
+ expect(g.priv.status().install.error).toMatch(/签名无效(HashMismatch)/);
+ });
+
+ it("试运行没通过(比如被策略拦下):不用,也不留下", async () => {
+ const f = fake({ privateTest: { code: 1, stdout: "", stderr: "Program 'pwsh.exe' failed to run: This program is blocked by group policy." } });
+ expect(await f.priv.install({ manual: true })).toBe(false);
+ expect(f.priv.status()).toMatchObject({ installed: false, ready: false });
+ expect(f.priv.status().install.error).toMatch(/试运行没通过.*blocked by group policy/);
+ expect(fs.existsSync(f.dir)).toBe(false);
+ expect(leftovers(f.root)).toEqual([]);
+ // 版本不对也不行
+ const g = fake({ privateTest: okTest("7.4.0") });
+ expect(await g.priv.install({ manual: true })).toBe(false);
+ expect(g.priv.status().install.error).toMatch(/版本是 7\.4\.0/);
+ });
+
+ it("tar.exe 解不了:改用 Windows PowerShell 5.1 的 Expand-Archive", async () => {
+ const f = fake({ tarFails: true });
+ expect(await f.priv.install({ manual: true })).toBe(true);
+ expect(f.calls.some((c) => /powershell\.exe$/i.test(c.exe) && c.args.join(" ").includes("Expand-Archive"))).toBe(true);
+ expect(f.priv.ready).toBe(true);
+ });
+
+ it("装到一半退出:下次启动清掉临时文件和残留的锁;另一个进程正在装时不抢", async () => {
+ const f = fake();
+ fs.mkdirSync(path.join(f.root, ".staging-dead", "Modules"), { recursive: true });
+ fs.writeFileSync(path.join(f.root, ".dl-dead.zip"), "partial");
+ fs.writeFileSync(path.join(f.root, ".lock"), JSON.stringify({ pid: 999_999, at: Date.now() }));
+ await f.priv.prepare();
+ expect(leftovers(f.root)).toEqual([]);
+ expect(f.priv.status()).toMatchObject({ installed: false, ready: false });
+ // 锁的主人还活着、心跳是新的:等它
+ const g = fake({ root: f.root, pidAlive: () => true });
+ fs.writeFileSync(path.join(f.root, ".lock"), JSON.stringify({ pid: 999_999, at: Date.now() }));
+ fs.writeFileSync(path.join(f.root, ".dl-other.zip"), "theirs");
+ await g.priv.prepare();
+ expect(fs.existsSync(path.join(f.root, ".dl-other.zip"))).toBe(true);
+ expect(await g.priv.install({ manual: true })).toBe(false);
+ expect(g.priv.status().install).toMatchObject({ state: "waiting", error: expect.stringContaining("正在安装") });
+ expect(g.fetches).toEqual([]);
+ // 心跳停了 3 分钟以上:当作残留
+ const old = new Date(Date.now() - 10 * 60_000);
+ fs.utimesSync(path.join(f.root, ".lock"), old, old);
+ expect(await g.priv.install({ manual: true })).toBe(true);
+ });
+
+ it("每次启动只看文件指纹:没变就直接用(不拉起任何进程);变了重新核对签名、试运行", async () => {
+ const f = fake();
+ expect(await f.priv.install({ manual: true })).toBe(true);
+ const again = fake({ root: f.root });
+ await again.priv.prepare();
+ expect(again.priv.status()).toMatchObject({ installed: true, ready: true });
+ expect(again.calls).toEqual([]);
+ // pwsh.dll 被换了:重新核对签名并试运行
+ fs.appendFileSync(path.join(f.dir, "pwsh.dll"), "changed");
+ const third = fake({ root: f.root });
+ await third.priv.prepare();
+ expect(third.priv.ready).toBe(true);
+ expect(third.calls.map((c) => path.win32.basename(c.exe).toLowerCase())).toEqual(["powershell.exe", "pwsh.exe"]);
+ // 重新检测(refresh):再试运行一次
+ await third.priv.prepare(true);
+ expect(third.calls.filter((c) => /pwsh\.exe$/i.test(c.exe))).toHaveLength(2);
+ });
+
+ it("文件被杀毒软件删了:标记为坏、不自动重装(要用户点重新安装),重新安装后恢复", async () => {
+ const f = fake();
+ expect(await f.priv.install({ manual: true })).toBe(true);
+ fs.rmSync(path.join(f.dir, "coreclr.dll"));
+ const next = fake({ root: f.root });
+ await next.priv.prepare();
+ expect(next.priv.status()).toMatchObject({ installed: true, ready: false, bad: { reason: expect.stringContaining("coreclr.dll") } });
+ expect(next.priv.autoBlocked()).toMatch(/需要手动重新安装/);
+ expect(await next.priv.install({ manual: true, reinstall: true })).toBe(true);
+ expect(next.priv.status()).toMatchObject({ installed: true, ready: true });
+ expect(next.priv.status().bad).toBeUndefined();
+ expect(fs.existsSync(path.join(f.dir, "coreclr.dll"))).toBe(true);
+ expect(leftovers(f.root)).toEqual([]);
+ });
+
+ it("Windows 太旧(低于 10 1607 / Server 2016):不下载,说明原因", async () => {
+ const f = fake({ osRelease: "10.0.10586" });
+ await f.priv.prepare();
+ expect(f.priv.status()).toMatchObject({ supported: false, reason: expect.stringContaining("Windows 版本较旧") });
+ expect(f.priv.autoBlocked()).toMatch(/Windows 版本较旧/);
+ expect(await f.priv.install({ manual: true })).toBe(false);
+ expect(f.fetches).toEqual([]);
+ expect(osSupport("10.0.14393").ok).toBe(true);
+ expect(osSupport("10.0.17763").ok).toBe(true);
+ expect(osSupport("6.3.9600").ok).toBe(false);
+ expect(osSupport("10.0.26100.1").ok).toBe(true);
+ expect(osSupport("weird").ok).toBe(true);
+ });
+
+ it("自动安装失败后退避(1 小时、1 天、之后不再自动装);AMB_PWSH_AUTO_INSTALL=0 关掉;手动点安装清零", async () => {
+ const f = fake({ body: Buffer.from("x".repeat(ZIP.length)) });
+ expect(f.priv.autoBlocked()).toBe("不支持的处理器架构"); // 还没看过这台电脑(prepare 之前)
+ await f.priv.prepare();
+ expect(f.priv.autoBlocked()).toBeUndefined();
+ expect(await f.priv.install()).toBe(false);
+ expect(f.priv.autoBlocked()).toMatch(/稍后再试/);
+ const state = () => JSON.parse(fs.readFileSync(path.join(f.root, "state.json"), "utf8"));
+ expect(state().auto.attempts).toBe(1);
+ await f.priv.install({ manual: true });
+ expect(state().auto.attempts).toBe(0);
+ expect(fake({ env: { AMB_PWSH_AUTO_INSTALL: "0" } }).priv.autoBlocked()).toBe("AMB_PWSH_AUTO_INSTALL=0");
+ });
+
+ it("架构:arm64 进程装 arm64;x64 进程在 ARM64 Windows 上(模拟运行)也装 arm64;32 位不装;镜像前缀", async () => {
+ expect(await resolveArch({ arch: "arm64", env: {} })).toBe("arm64");
+ expect(await resolveArch({ arch: "x64", env: { PROCESSOR_IDENTIFIER: "ARMv8 (64-bit) Family 8 Model 1 Revision 201, Qualcomm Technologies Inc" } })).toBe("arm64");
+ expect(await resolveArch({ arch: "x64", env: { PROCESSOR_IDENTIFIER: "AMD64 Family 25 Model 33 Stepping 0, AuthenticAMD" } })).toBe("x64");
+ expect(await resolveArch({ arch: "ia32", env: {} })).toBeUndefined();
+ // 认不出来:问注册表里的本机架构
+ const reg = vi.fn(async () => ({ code: 0, stdout: " PROCESSOR_ARCHITECTURE REG_SZ ARM64\r\n", stderr: "" }));
+ expect(await resolveArch({ arch: "x64", env: { SystemRoot: "C:\\Windows" }, run: reg })).toBe("arm64");
+ expect((reg.mock.calls[0] as unknown as [string])[0]).toBe("C:\\Windows\\System32\\reg.exe");
+ expect(zipUrl(PRIVATE_PWSH, "arm64", {})).toBe(`https://github.com/PowerShell/PowerShell/releases/download/v${PRIVATE_PWSH.version}/PowerShell-${PRIVATE_PWSH.version}-win-arm64.zip`);
+ expect(zipUrl(PRIVATE_PWSH, "x64", { AMB_PWSH_MIRROR: "https://mirror.example/pwsh/" })).toBe(`https://mirror.example/pwsh/PowerShell-${PRIVATE_PWSH.version}-win-x64.zip`);
+ // 固定的哈希是 64 位十六进制
+ expect(PRIVATE_PWSH.sha256.x64).toMatch(/^[0-9a-f]{64}$/);
+ expect(PRIVATE_PWSH.sha256.arm64).toMatch(/^[0-9a-f]{64}$/);
+ });
+});
+
+/** 探测器:系统 pwsh 在不在由 exes 决定,内置副本用上面的假环境 */
+function probeWith(f: ReturnType<typeof fake>, o: { exes?: string[]; versions?: Record<string, string> } = {}) {
+ const exes = new Set([PS5, ...(o.exes ?? [])].map((p) => p.toLowerCase()));
+ const deps: PwshDeps = {
+ platform: "win32",
+ env: f.env,
+ run: f.run,
+ priv: f.priv,
+ lstat: async (p) => {
+ if (!exes.has(p.toLowerCase())) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
+ return { isFile: () => true, isSymbolicLink: () => false };
+ },
+ readdir: async () => [],
+ readFile: async (p) => {
+ const v = o.versions?.[path.win32.dirname(p).toLowerCase()];
+ if (!v) throw new Error("ENOENT");
+ return `{"libraries":{"pwsh/${v}":{}}}`;
+ },
+ runVersion: async () => "PowerShell 7.4.6",
+ };
+ const probe = new PwshProbe(deps);
+ const events: PwshEvent[] = [];
+ probe.onChange((e) => events.push(e));
+ return { probe, events };
+}
+
+/** 等后台的安装 / 试运行做完 */
+async function settle(p: PrivatePwsh, probe?: PwshProbe) {
+ for (let i = 0; i < 200 && (p.busy || (probe && (probe as any).sysTests && [...(probe as any).sysTests.values()].includes("pending"))); i++) await new Promise((r) => setTimeout(r, 5));
+ await new Promise((r) => setTimeout(r, 5));
+}
+
+describe("探测器:优先级、自动安装、自动退回", () => {
+ it("系统里有能用的 PowerShell 7:用它,什么都不下载", async () => {
+ const f = fake();
+ const { probe } = probeWith(f, { exes: [SYS_PWSH] });
+ probe.configure({ agent: true, mode: "auto" });
+ const st = await probe.check();
+ await settle(f.priv, probe);
+ expect(st).toMatchObject({ found: true, missing: false, path: SYS_PWSH, source: "program-files", using: SYS_PWSH, autoInstall: true });
+ expect(await probe.dshPath()).toBe(SYS_PWSH);
+ expect(f.fetches).toEqual([]);
+ expect(f.calls.filter((c) => c.exe === SYS_PWSH)).toHaveLength(1); // 后台试运行了一次
+ });
+
+ it("没有 PowerShell 7(代理模式开着):后台自动装内置的;装的时候照旧用 5.1,装好后切过去并通知", async () => {
+ const f = fake();
+ const { probe, events } = probeWith(f);
+ probe.configure({ agent: true, mode: "auto" });
+ const st = await probe.check();
+ expect(st).toMatchObject({ missing: true });
+ // 装的时候:DSH 照旧拿到默认(不等安装)
+ expect(f.priv.busy).toBe(true);
+ expect(await probe.dshPath(50)).toBeUndefined();
+ expect(pwshStatusLine(probe.snapshot())).toMatch(/正在为代理安装 PowerShell 7…/);
+ await settle(f.priv);
+ const done = probe.snapshot();
+ expect(done).toMatchObject({ found: true, missing: false, source: "private", version: PIN.version, path: f.priv.exe, using: f.priv.exe });
+ expect(probe.cachedDshPath).toBe(f.priv.exe);
+ expect(await probe.dshPath()).toBe(f.priv.exe);
+ expect(events).toEqual(expect.arrayContaining([expect.objectContaining({ kind: "path", to: f.priv.exe }), expect.objectContaining({ kind: "install", notice: expect.objectContaining({ level: "info" }) })]));
+ expect(pwshStatusLine(done)).toBe(`PowerShell:${PIN.version}(应用内置,代理用它执行命令)`);
+ expect(pwshReportLine(done)).toContain(`内置 PowerShell ${PIN.version} x64 · 已就绪 · 试运行通过`);
+ });
+
+ it("代理模式没开、AMB_PWSH_AUTO_INSTALL=0、改回系统默认:都不自动装;手动安装照样可以", async () => {
+ for (const [cfg, env] of [
+ [{ agent: false, mode: "auto" as const }, {}],
+ [{ agent: true, mode: "auto" as const }, { AMB_PWSH_AUTO_INSTALL: "0" }],
+ [{ agent: true, mode: "system" as const }, {}],
+ ] as const) {
+ const f = fake({ env });
+ const { probe } = probeWith(f);
+ probe.configure(cfg);
+ const st = await probe.check();
+ await settle(f.priv);
+ expect(f.fetches).toEqual([]);
+ expect(st.missing).toBe(true);
+ expect(pwshStatusLine(st)).toContain("Windows PowerShell 5.1");
+ }
+ const f = fake({ env: { AMB_PWSH_AUTO_INSTALL: "0" } });
+ const { probe } = probeWith(f);
+ probe.configure({ agent: true, mode: "auto" });
+ await probe.check();
+ probe.install();
+ await settle(f.priv);
+ expect(probe.snapshot()).toMatchObject({ missing: false, source: "private" });
+ // 改回系统默认:不再用内置的,空闲时换回 5.1
+ probe.setMode("system");
+ expect(probe.snapshot()).toMatchObject({ missing: true, mode: "system" });
+ expect(probe.cachedDshPath).toBeUndefined();
+ });
+
+ it("系统里的 PowerShell 7 试运行没通过:不用它,改用(自动装好的)内置副本", async () => {
+ const f = fake({ systemTest: { code: -532462766, stdout: "", stderr: "Failed to load the dll from [C:\\Program Files\\PowerShell\\7\\hostfxr.dll], HRESULT: 0x80070002" } });
+ const { probe, events } = probeWith(f, { exes: [SYS_PWSH] });
+ probe.configure({ agent: true, mode: "auto" });
+ expect(await probe.check()).toMatchObject({ missing: false, source: "program-files" });
+ await settle(f.priv, probe);
+ await settle(f.priv, probe);
+ const st = probe.snapshot();
+ expect(st).toMatchObject({ missing: false, source: "private", systemIssue: expect.stringContaining("试运行没通过") });
+ expect(st.fallback).toMatchObject({ from: SYS_PWSH });
+ expect(events.some((e) => e.notice?.level === "warn" && e.notice.text.includes(SYS_PWSH))).toBe(true);
+ });
+
+ it("AMB_PWSH_IGNORE_SYSTEM=1(CI):不看系统里的;内置的装好前明确写 5.1(免得 DSH 自己找回系统的)", async () => {
+ const f = fake({ env: { AMB_PWSH_IGNORE_SYSTEM: "1" } });
+ const { probe } = probeWith(f, { exes: [SYS_PWSH] });
+ probe.configure({ agent: false });
+ const st = await probe.check();
+ expect(st).toMatchObject({ found: false, missing: true, ignoreSystem: true, using: PS5 });
+ expect(await probe.dshPath()).toBe(PS5);
+ probe.install();
+ await settle(f.priv);
+ expect(await probe.dshPath()).toBe(f.priv.exe);
+ });
+
+ it("运行中代理拉不起内置的 pwsh(被删、被拦):立即标记为坏、退回、通知;重启后还记得;重新检测通过后恢复", async () => {
+ const f = fake({ env: { AMB_PWSH_IGNORE_SYSTEM: "1" } });
+ const { probe, events } = probeWith(f);
+ probe.configure({ agent: true, mode: "auto" });
+ await probe.check();
+ await settle(f.priv);
+ const exe = f.priv.exe!;
+ expect(probe.cachedDshPath).toBe(exe);
+ // 普通的命令失败不算
+ probe.observeToolResult(exe, "Get-Foo: The term 'Get-Foo' is not recognized as a name of a cmdlet\n[exit code: 1]");
+ probe.observeToolResult(exe, `windows-acl-run: CreateProcessAsUserW failed (Win32 2): command: C:\\other\\pwsh.exe, cwd: C:\\ws`);
+ expect(probe.cachedDshPath).toBe(exe);
+ // 沙箱 runner 拉不起它
+ const text = `sandbox mode "workspace-write" is requested but no sandbox backend is usable on this host; refusing to run the command unconfined. Runner failure: windows-acl-run: CreateProcessAsUserW failed (Win32 2): command: ${exe}, cwd: C:\\data\\workspaces\\default`;
+ expect(shellStartFailure(text, exe)).toContain("CreateProcessAsUserW failed (Win32 2)");
+ probe.observeToolResult(exe, text);
+ const st = probe.snapshot();
+ expect(st).toMatchObject({ missing: true, using: PS5, private: { ready: false, bad: { reason: expect.stringContaining("代理拉不起它") } }, fallback: { from: exe, to: PS5 } });
+ expect(probe.cachedDshPath).toBe(PS5);
+ const ev = events.at(-1)!;
+ expect(ev).toMatchObject({ kind: "path", from: exe, to: PS5, notice: { level: "warn" } });
+ expect(ev.notice!.text).toContain("Windows PowerShell 5.1");
+ expect(pwshStatusLine(st)).toMatch(/应用内置的 PowerShell 7 用不了.*重新安装/);
+ // 同一个回合里再失败:不重复通知
+ const n = events.length;
+ probe.observeToolResult(exe, text);
+ expect(events).toHaveLength(n);
+ // 坏了不自动重装(免得循环下载)
+ expect(f.fetches).toHaveLength(1);
+ // 重启后还记得
+ const again = fake({ root: f.root, env: { AMB_PWSH_IGNORE_SYSTEM: "1" } });
+ await again.priv.prepare();
+ expect(again.priv.status()).toMatchObject({ installed: true, ready: false, bad: expect.anything() });
+ // 重新检测:重新试运行,通过就恢复
+ await probe.check(true);
+ expect(probe.snapshot()).toMatchObject({ missing: false, source: "private" });
+ expect(probe.snapshot().fallback).toBeUndefined();
+ });
+
+ it("不经沙箱(完全权限)时 spawn 失败也算;系统的 pwsh 坏了退回内置的", async () => {
+ const f = fake();
+ const { probe } = probeWith(f, { exes: [SYS_PWSH] });
+ probe.configure({ agent: true, mode: "auto" });
+ await probe.check();
+ await settle(f.priv, probe);
+ expect(probe.cachedDshPath).toBe(SYS_PWSH);
+ probe.observeToolResult(SYS_PWSH, `subprocess failed before reporting an outcome: Error: spawn ${SYS_PWSH} ENOENT`);
+ expect(probe.snapshot()).toMatchObject({ systemIssue: expect.stringContaining("代理拉不起它"), missing: true });
+ // 系统的坏了、内置的没装:自动装上
+ expect(f.priv.busy).toBe(true);
+ await settle(f.priv);
+ expect(probe.cachedDshPath).toBe(f.priv.exe);
+ expect(shellStartFailure(`Error: spawn ${SYS_PWSH.replaceAll("\\", "\\\\")} EACCES`, SYS_PWSH)).toBeTruthy();
+ // 沙箱里别的错误码(不是程序本身的问题)不算强信号
+ expect(shellStartFailure(`windows-acl-run: CreateProcessAsUserW failed (Win32 1314): command: ${SYS_PWSH}, cwd: C:\\ws`, SYS_PWSH)).toBeUndefined();
+ });
+
+ it(".NET 宿主报错之类的弱信号:重新试运行一次,通过就不动,没通过才退回", async () => {
+ const f = fake({ env: { AMB_PWSH_IGNORE_SYSTEM: "1" } });
+ const { probe } = probeWith(f);
+ probe.configure({ agent: true, mode: "auto" });
+ await probe.check();
+ await settle(f.priv);
+ const exe = f.priv.exe!;
+ const tests = () => f.calls.filter((c) => c.exe === exe).length;
+ const before = tests();
+ probe.observeToolResult(exe, "A fatal error was encountered. The library 'hostfxr.dll' required to execute the application was not found");
+ await new Promise((r) => setTimeout(r, 20));
+ expect(tests()).toBe(before + 1);
+ expect(probe.cachedDshPath).toBe(exe);
+ // 一分钟内不再重复试
+ probe.observeToolResult(exe, "A fatal error was encountered.");
+ await new Promise((r) => setTimeout(r, 20));
+ expect(tests()).toBe(before + 1);
+ });
+
+ it("改回系统默认再改回来;重新安装(坏了也行)", async () => {
+ const f = fake({ env: { AMB_PWSH_IGNORE_SYSTEM: "1" } });
+ const { probe } = probeWith(f);
+ probe.configure({ agent: true, mode: "auto" });
+ await probe.check();
+ await settle(f.priv);
+ probe.markBroken(f.priv.exe!, "test");
+ expect(probe.snapshot().private?.bad).toBeTruthy();
+ probe.install({ reinstall: true });
+ await settle(f.priv);
+ expect(probe.snapshot()).toMatchObject({ missing: false, source: "private" });
+ expect(probe.snapshot().private?.bad).toBeUndefined();
+ expect(f.fetches).toHaveLength(2);
+ });
+});
+
+describe("代理进程:PowerShell 换了就在空闲时重启;pwsh 工具结果交给探测器", () => {
+ const mkHost = () => {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-pwsh-host-"));
+ roots.push(dataDir);
+ return new AgentHost({ botId: "b", dataDir, runtimeDir: "/rt", bridge: { url: "http://127.0.0.1:1" } as any, store: new Store(":memory:") });
+ };
+
+ it("空闲时设置签名变了(PowerShell 换了):后台重启;有回合在跑(或正要开始)时不动", async () => {
+ const host = mkHost() as any;
+ const closed: string[] = [];
+ const fakeHarness = (id: string) => ({ id, close: async () => void closed.push(id), client: {} });
+ host.harness = fakeHarness("old");
+ host.model = "m";
+ host.sig = "stale";
+ let spawned = 0;
+ host.spawn = async () => {
+ spawned++;
+ host.sig = host.settingsSig();
+ return (host.harness = fakeHarness(`new${spawned}`));
+ };
+ host.entering = 1;
+ await host.restartIfStale();
+ expect(closed).toEqual([]);
+ host.entering = 0;
+ host.active = 1;
+ await host.restartIfStale();
+ expect(closed).toEqual([]);
+ host.active = 0;
+ await host.restartIfStale();
+ expect(closed).toEqual(["old"]);
+ expect(spawned).toBe(1);
+ // 签名没变:不重启
+ await host.restartIfStale();
+ expect(spawned).toBe(1);
+ });
+
+ it("pwsh 工具的结果(连同这个代理进程用的路径)交给探测器", async () => {
+ const { pwshProbe } = await import("../src/agent/pwsh.js");
+ const seen = vi.spyOn(pwshProbe, "observeToolResult").mockImplementation(() => undefined);
+ const host = mkHost() as any;
+ host.pwshPath = "C:\\pw\\pwsh.exe";
+ const session = {
+ id: "s1",
+ run: async (_p: unknown, o: { onNotification: (n: unknown) => void }) => {
+ const ev = (type: string, data: unknown) => o.onNotification({ method: "session.event", params: { sessionId: "s1", event: { type, data, time: Date.now() } } });
+ ev("tool/call", { callId: "c1", name: "pwsh", arguments: '{"command":"dir"}' });
+ ev("tool/result", { message: { toolCallId: "c1", isError: true, content: [{ type: "text", text: "windows-acl-run: boom" }] } });
+ ev("tool/call", { callId: "c2", name: "read_file", arguments: "{}" });
+ ev("tool/result", { message: { toolCallId: "c2", content: [{ type: "text", text: "x" }] } });
+ return { sessionId: "s1", finalResponse: "done", events: [] };
+ },
+ };
+ host.ensure = async () => ({});
+ host.sessionFor = async () => session;
+ const r = await host.runTurn({ conversationId: "c", text: "hi", model: "m" });
+ expect(r.text).toBe("done");
+ expect(seen).toHaveBeenCalledTimes(1);
+ expect(seen).toHaveBeenCalledWith("C:\\pw\\pwsh.exe", "windows-acl-run: boom");
+ seen.mockRestore();
+ });
+});
diff --git a/test/pwsh.unit.test.ts b/test/pwsh.unit.test.ts
index 059fd43..17eb943 100644
--- a/test/pwsh.unit.test.ts
+++ b/test/pwsh.unit.test.ts
@@ -20,6 +20,7 @@ vi.mock("node:child_process", async (orig) => {
});
import { PwshProbe, findPwsh, parsePwshVersion, pwshPatchLines, pwshReportLine, pwshStatusLine, readPwshVersion, PWSH_WINGET, type PwshDeps } from "../src/agent/pwsh.js";
+import { PrivatePwsh, depsJsonVersion, type Runner } from "../src/agent/pwsh-private.js";
import { App } from "../src/app.js";
import { loadConfig } from "../src/config.js";
@@ -30,17 +31,28 @@ const PS5 = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\";
const ENV = { ProgramFiles: PF, ProgramW6432: PF, LOCALAPPDATA: LOCAL, PATH: `C:\\Windows\\system32;C:\\Windows;${PS5};${APPS}` };
const DEPS_746 = '{"targets":{".NETCoreApp,Version=v8.0/win-x64":{"pwsh/7.4.6":{"dependencies":{}}}},"libraries":{"pwsh/7.4.6":{"type":"project"}}}';
-/** 假的 Windows 文件系统:exes 里是存在的 pwsh.exe(file 或 Store 别名 alias),texts 是可读的文件,dirs 是目录列表 */
-function fakeWin(o: { exes?: Record<string, "file" | "alias">; texts?: Record<string, string>; dirs?: Record<string, string[]>; env?: NodeJS.ProcessEnv; runVersion?: PwshDeps["runVersion"] } = {}) {
+/**
+ * 假的 Windows 文件系统:exes 里是存在的 pwsh.exe(file 或 Store 别名 alias),texts 是可读的文件,dirs 是目录列表。
+ * 试运行(launchTest)一律通过、报 testVersion;内置副本在一个空的临时目录里(没装),不自动安装(代理模式没开)。
+ */
+function fakeWin(o: { exes?: Record<string, "file" | "alias">; texts?: Record<string, string>; dirs?: Record<string, string[]>; env?: NodeJS.ProcessEnv; runVersion?: PwshDeps["runVersion"]; testVersion?: string } = {}) {
const k = (p: string) => p.toLowerCase();
const exes = new Map(Object.entries(o.exes ?? {}).map(([p, v]) => [k(p), v]));
const texts = new Map(Object.entries(o.texts ?? {}).map(([p, v]) => [k(p), v]));
const lstats: string[] = [];
const runs: string[] = [];
+ const tests: string[] = [];
const enoent = (p: string) => Object.assign(new Error(`ENOENT: ${p}`), { code: "ENOENT" });
+ const env = { ...(o.env ?? ENV), AMB_PWSH_HOME: fs.mkdtempSync(path.join(os.tmpdir(), "amb-pwsh-home-")), PROCESSOR_IDENTIFIER: "Intel64 Family 6 Model 154" };
+ const run: Runner = async (exe) => {
+ tests.push(exe);
+ return { code: 0, stdout: `AMB-PWSH-TEST ver=${o.testVersion ?? "7.4.6"} rw=rw-ok ext=ext-ok\r\n`, stderr: "" };
+ };
const deps: PwshDeps = {
platform: "win32",
- env: o.env ?? ENV,
+ env,
+ run,
+ priv: new PrivatePwsh({ env, platform: "win32", osRelease: "10.0.22631", arch: "x64", run }),
lstat: async (p) => {
lstats.push(p);
const v = exes.get(k(p));
@@ -63,7 +75,7 @@ function fakeWin(o: { exes?: Record<string, "file" | "alias">; texts?: Record<st
return o.runVersion(exe);
},
};
- return { deps, lstats, runs, addExe: (p: string, v: "file" | "alias" = "file") => exes.set(k(p), v) };
+ return { deps, lstats, runs, tests, addExe: (p: string, v: "file" | "alias" = "file") => exes.set(k(p), v) };
}
describe("PowerShell 7 检测", () => {
@@ -88,7 +100,18 @@ describe("PowerShell 7 检测", () => {
expect(await probe.dshPath()).toBe(exe);
expect(probe.cachedDshPath).toBe(exe);
expect(pwshStatusLine(st)).toBe("PowerShell:7.4.6(代理用它执行命令)");
- expect(pwshReportLine(st)).toBe(`[PowerShell] 7.4.6 · ${exe}(安装目录) · 代理用它执行命令`);
+ expect(pwshReportLine(st)!.split("\n")[0]).toBe(`[PowerShell] 7.4.6 · ${exe}(安装目录) · 代理用它执行命令`);
+ expect(pwshReportLine(st)).toContain("内置 PowerShell 7.6.9 x64 · 未安装");
+ });
+
+ it("新版 MSI / zip 的 pwsh.deps.json 写的是 pwsh/7.6.9.500:照样不拉起进程就读出 7.6.9", async () => {
+ const exe = `${PF}\\PowerShell\\7\\pwsh.exe`;
+ const w = fakeWin({ exes: { [exe]: "file" }, texts: { [`${PF}\\PowerShell\\7\\pwsh.deps.json`]: DEPS_746.replaceAll("7.4.6", "7.6.9.500") } });
+ expect(await new PwshProbe(w.deps).check()).toMatchObject({ found: true, missing: false, version: "7.6.9" });
+ expect(w.runs).toEqual([]);
+ expect(depsJsonVersion('"pwsh/7.6.0-preview.5"')).toBe("7.6.0-preview.5");
+ expect(depsJsonVersion('"pwsh/7.4.6"')).toBe("7.4.6");
+ expect(depsJsonVersion("{}")).toBeUndefined();
});
it("PATH 里的 pwsh.exe(带引号和空格的项);读不到 deps.json 时问 pwsh -Version", async () => {
@@ -141,9 +164,11 @@ describe("PowerShell 7 检测", () => {
expect(pwshStatusLine(st)).toContain("Windows PowerShell 5.1");
expect(pwshStatusLine(st)).toContain(PWSH_WINGET);
expect(pwshReportLine(st)).toContain("未安装 PowerShell 7");
- // 每个候选都只看了一次文件(PATH 里重复的目录去重)
- expect(new Set(w.lstats.map((p) => p.toLowerCase())).size).toBe(w.lstats.length);
- expect(w.lstats.every((p) => p.toLowerCase().endsWith("pwsh.exe"))).toBe(true);
+ // 每个候选都只看了一次文件(PATH 里重复的目录去重);另外看一眼 5.1 在不在
+ const looked = w.lstats.filter((p) => !/\\WindowsPowerShell\\v1\.0\\powershell\.exe$/i.test(p));
+ expect(new Set(looked.map((p) => p.toLowerCase())).size).toBe(looked.length);
+ expect(looked.every((p) => p.toLowerCase().endsWith("pwsh.exe"))).toBe(true);
+ expect(w.lstats.length - looked.length).toBe(1);
});
it("PATH 里只有 PowerShell 6:仍建议装 7", async () => {
@@ -197,7 +222,9 @@ describe("PowerShell 7 检测", () => {
expect(spawned).toHaveLength(1);
expect(spawned[0]).toMatchObject({ exe, args: ["-Version"], opts: { windowsHide: true } });
expect(spawned[0].opts.timeout).toBeGreaterThan(0);
- expect(spawned[0].opts.timeout).toBeLessThanOrEqual(10_000);
+ // 冷启动的机器上 pwsh 第一次启动可能要十几秒(CI 上 5 秒超时出过错)
+ expect(spawned[0].opts.timeout).toBeGreaterThanOrEqual(15_000);
+ expect(spawned[0].opts.timeout).toBeLessThanOrEqual(30_000);
expect(parsePwshVersion("PowerShell 7.6.0-preview.5\n")).toBe("7.6.0-preview.5");
expect(parsePwshVersion("garbage")).toBeUndefined();
});