🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
fix(windows): friendlier PowerShell failure reasons; no signature/lock races
Marlad5e982ae6d5d
diff --git a/src/agent/host.ts b/src/agent/host.tsindex 1d90c93..5484712 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -688,11 +688,13 @@ exec "$REAL" "$@"private settings(): BotSettings {return this.o.settings?.() ?? DEFAULT_SETTINGS;}- /** 影响子进程启动参数的设置签名 */- private settingsSig(): string {+ /**+ * 影响子进程启动参数的设置签名。带上 PowerShell 路径:装好 PowerShell 7、内置的装好或坏了退回时,空闲的代理进程换用新的。+ * 启动时记的是补丁里实际写的路径(pwsh),不是记签名那一刻的选择:中间隔着几次 await,选择可能刚好变了。+ */+ private settingsSig(pwsh = pwshProbe.cachedDshPath): string {const st = this.settings();- // 带上 PowerShell 路径:用户装好 PowerShell 7 点"重新检测"后,空闲的代理进程在下一条消息时换用它- return `${st.permission}|${st.memory.enabled}|${st.computerUse.enabled}|${st.computerUse.backend}|${st.computerUse.approval}|${pwshProbe.cachedDshPath ?? ""}`;+ return `${st.permission}|${st.memory.enabled}|${st.computerUse.enabled}|${st.computerUse.backend}|${st.computerUse.approval}|${pwsh ?? ""}`;}private sig = "";@@ -819,7 +821,7 @@ exec "$REAL" "$@"this.fallback = fb;const patch = this.writePatch(model, apps, pwshPath, modelLimits(model, known), api, info?.reasoning);this.pwshPath = pwshPath;- this.sig = this.settingsSig();+ this.sig = this.settingsSig(pwshPath);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)" } : {}) });h = new sdk.DeepSeekHarness({diff --git a/src/agent/pwsh-private.ts b/src/agent/pwsh-private.tsindex 08bc3fe..0576b4b 100644--- a/src/agent/pwsh-private.ts+++ b/src/agent/pwsh-private.ts@@ -81,6 +81,8 @@ const MARKER = ".amb-pwsh.json";const RETEST_MS = 7 * 24 * 3600_000;/** 锁文件超过这么久没有心跳就当作残留 */const LOCK_STALE_MS = 3 * 60_000;+/** 等另一个进程装完,最多等这么久 */+const LOCK_WAIT_MS = 30 * 60_000;/** 自动安装失败后的等待:第 1 次失败后 1 小时,第 2 次后 1 天,3 次后不再自动装(手动点安装会清零) */const AUTO_BACKOFF = [0, 3600_000, 24 * 3600_000];@@ -170,13 +172,16 @@ export async function launchTest(exe: string, run: Runner, o: { timeoutMs: numbereturn { ok: true, at: Date.now(), ms, version: m[1] };}-/** 用 Windows PowerShell 5.1 核对 Authenticode:每个文件都要有效(Valid),签名者和颁发者都是 Microsoft */+/**+ * 用 Windows PowerShell 5.1 核对 Authenticode:每个文件都要有效(Valid),签名者和颁发者都是 Microsoft。+ * 刚解压的文件杀毒软件要先扫一遍,加上证书吊销检查,冷机器上要几十秒(CI 上约 30 秒),给足时间。+ */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,+ timeoutMs: 180_000,env: { ...shellEnv(env), AMB_SIG_FILES: files.join("|") },});- if (r.timedOut) return { ok: false, error: "Windows PowerShell 90 秒内没有给出签名结果" };+ if (r.timedOut) return { ok: false, error: "Windows PowerShell 3 分钟内没有给出签名结果" };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 {@@ -410,8 +415,9 @@ export interface PrivateDeps {fetch?: () => typeof fetch | undefined;run?: Runner;pidAlive?: (pid: number) => boolean;- /** 下载重试的间隔基数(测试里调小) */+ /** 下载重试的间隔基数、等别的进程装完时看锁的间隔(测试里调小) */retryDelayMs?: number;+ lockPollMs?: number;/** 测试用:换掉固定的版本与哈希 */pin?: PwshPin;}@@ -601,6 +607,12 @@ export class PrivatePwsh {if (!this.support.ok || !this.arch) return this.set({ installed: false, ready: false });if (this.installing) return;await this.cleanup();+ await this.evaluate(refresh);+ }++ /** 看已装的副本能不能用(标记文件、指纹、签名、试运行),结果记进 state.json */+ private async evaluate(refresh: boolean): Promise<void> {+ if (!this.arch) return;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 });@@ -700,15 +712,28 @@ export class PrivatePwsh {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;+ // 另一个 AnyModelBot 正在装:等它(锁没了再看一眼,它装好了就直接用),最多等 LOCK_WAIT_MS+ const waitUntil = Date.now() + LOCK_WAIT_MS;+ for (;;) {+ let locked = false;+ try {+ locked = this.takeLock();+ } catch (e) {+ return fail(`建不了安装目录 ${this.root}:${(e as Error).message}`);+ }+ if (locked) break;+ if (Date.now() > waitUntil) {+ this.setProgress({ state: "failed", error: "另一个 AnyModelBot 一直在安装 PowerShell 7,稍后再试", finishedAt: Date.now() }, true);+ return false;+ }+ this.setProgress({ state: "waiting", error: "另一个 AnyModelBot 正在安装 PowerShell 7,等它装完" }, true);+ await sleep(this.d.lockPollMs ?? 5000);+ if (this.lockHeld()) continue;+ await this.evaluate(false);+ if (this.cur.ready && !o.reinstall) {+ this.setProgress({ state: "done", finishedAt: Date.now(), error: undefined }, true);+ return true;+ }}const heartbeat = setInterval(() => fs.promises.utimes(this.lockFile, new Date(), new Date()).catch(() => undefined), 30_000);heartbeat.unref?.();diff --git a/src/agent/pwsh.ts b/src/agent/pwsh.tsindex 1188998..f10ef2f 100644--- a/src/agent/pwsh.ts+++ b/src/agent/pwsh.ts@@ -13,7 +13,8 @@* - 运行中代理拉不起所用的 pwsh(宿主把 pwsh 工具的结果转过来,observeToolResult)就把它标记为坏,退回下一个,空闲时重启 DSH,并告诉用户。* - 选择变了(装好了、坏了、改回系统默认)就通知订阅者:宿主的设置签名里带着路径,空闲的代理进程换用新的。* - 版本号:先读 pwsh.deps.json,读不到(Store 别名)再 `pwsh -Version`(20 秒超时);试运行也会报版本。- * - AMB_PWSH_FORCE=missing 在任何平台上模拟"未安装"(截图、测试),不影响 DSH;AMB_PWSH_IGNORE_SYSTEM=1 不用系统里的 PowerShell+ * - AMB_PWSH_FORCE=missing 在任何平台上模拟"未安装"(截图、测试;installing / installed / broken / failed 模拟内置副本的几种状态),+ * 不影响 DSH;AMB_PWSH_IGNORE_SYSTEM=1 不用系统里的 PowerShell* (CI 用它验证内置副本);AMB_PWSH_AUTO_INSTALL=0 不自动安装。*/import { execFile } from "node:child_process";@@ -193,6 +194,28 @@ export function shellStartFailure(text: string, exe: string): string | undefinedreturn undefined;}+/** 拉不起来的原因,说给用户听:Win32 错误码 / Node 的 spawn 错误码 → 一句话 */+export function startFailureReason(line: string): string {+ const code = /\(win32\s+(\d+)\)/i.exec(line)?.[1] ?? /\b(ENOENT|EACCES|EPERM|UNKNOWN|EINVAL)\b/i.exec(line)?.[1]?.toUpperCase();+ const missing = "找不到 pwsh.exe(可能被杀毒软件删除或隔离)";+ const denied = "没有权限运行它(可能被安全软件拦截)";+ const why: Record<string, string> = {+ "2": missing,+ "3": missing,+ ENOENT: missing,+ "5": denied,+ EACCES: denied,+ EPERM: denied,+ "225": "被杀毒软件拦截",+ "1260": "被系统策略禁止运行(AppLocker / 软件限制策略)",+ "4551": "被 Windows Defender 应用程序控制拦截",+ "193": "文件损坏,或不是这台电脑能运行的程序",+ "216": "文件损坏,或不是这台电脑能运行的程序",+ "1392": "文件已损坏",+ };+ return `${(code && why[code]) || "拉不起来"}(${code ? (/^\d+$/.test(code) ? `Win32 ${code}` : code) : line.slice(0, 120)})`;+}+/** 弱信号:.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;@@ -232,7 +255,7 @@ export class PwshProbe {return this.d.platform ?? process.platform;}private get forced(): boolean {- return this.env.AMB_PWSH_FORCE === "missing";+ return FORCE_DEMO.includes(this.env.AMB_PWSH_FORCE ?? "");}private get ignoreSystem(): boolean {return this.env.AMB_PWSH_IGNORE_SYSTEM === "1";@@ -344,7 +367,7 @@ export class PwshProbe {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() };+ if (this.forced) return forcedStatus(this.env.AMB_PWSH_FORCE!, this.priv.pin.version);const extra = {mode: this.cfg.mode,autoInstall: this.cfg.agent && this.cfg.mode === "auto" && this.env.AMB_PWSH_AUTO_INSTALL !== "0",@@ -472,7 +495,10 @@ export class PwshProbe {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 (hit) {+ log.warn("the agent's pwsh tool could not start PowerShell", { exe, line: hit });+ return this.markBroken(exe, startFailureReason(hit));+ }if (SUSPECT.test(text)) void this.suspect(exe);}@@ -508,12 +534,34 @@ export class PwshProbe {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)},空闲时生效。可在 设置 → 故障排查 里重新安装或重新检测。`,+ text: `代理用的 PowerShell 起不来(${exe}:${reason.slice(0, 160)}),已自动改用${describe(to, this.priv.exe)},代理空闲时生效。可在 设置 → 故障排查 里重新安装或重新检测。`,});this.maybeAutoInstall("broken");}}+const FORCE_DEMO = ["missing", "installing", "installed", "broken", "failed"];++/** AMB_PWSH_FORCE 模拟的状态(截图、界面测试;任何平台) */+function forcedStatus(kind: string, version: string): PwshStatus {+ const now = Date.now();+ const dir = "C:\\Users\\you\\AppData\\Local\\AnyModelBot\\pwsh\\" + `${version}-x64`;+ const exe = `${dir}\\pwsh.exe`;+ const priv = (o: Partial<PrivatePwshStatus>): PrivatePwshStatus => ({ version, arch: "x64", supported: true, dir, installed: false, ready: false, install: { state: "idle" }, ...o });+ const base = { applicable: true, forced: true, checkedAt: now, mode: "auto" as const, autoInstall: true };+ if (kind === "installing") return { ...base, found: false, missing: true, private: priv({ install: { state: "downloading", received: 47 * 1048576, total: 104 * 1048576, startedAt: now - 20_000 } }) };+ if (kind === "installed") {+ const test = { ok: true, at: now, ms: 1180, version };+ return { ...base, found: true, missing: false, path: exe, source: "private", version, using: exe, private: priv({ installed: true, ready: true, test, install: { state: "done", startedAt: now - 60_000, finishedAt: now } }) };+ }+ if (kind === "broken") {+ const reason = "代理拉不起它:找不到 pwsh.exe(可能被杀毒软件删除或隔离)(Win32 2)";+ return { ...base, found: false, missing: true, private: priv({ installed: true, bad: { reason, at: now } }), fallback: { from: exe, reason, at: now } };+ }+ if (kind === "failed") return { ...base, found: false, missing: true, private: priv({ install: { state: "failed", error: "下载失败(https://github.com/…):90 秒没有收到数据", finishedAt: now } }) };+ return { applicable: true, found: false, missing: true, forced: true, checkedAt: now };+}+/** 给用户看的名字 */function describe(p: string | undefined, privateExe: string | undefined): string {if (!p || /\\WindowsPowerShell\\v1\.0\\powershell\.exe$/i.test(p)) return "系统自带的 Windows PowerShell 5.1";diff --git a/test/pwsh-private.unit.test.ts b/test/pwsh-private.unit.test.tsindex 331d9d8..dc3c0e7 100644--- a/test/pwsh-private.unit.test.ts+++ b/test/pwsh-private.unit.test.ts@@ -87,7 +87,7 @@ function fake(o: FakeOpts = {}) {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 });+ 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, lockPollMs: 5 });return { root, env, run, calls, fetches, priv, fetchFn, dir: path.join(root, `${PIN.version}-x64`) };}@@ -194,19 +194,31 @@ describe("内置 PowerShell 7:安装", () => {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);+ const waiting = g.priv.install({ manual: true });+ await new Promise((r) => setTimeout(r, 30));expect(g.priv.status().install).toMatchObject({ state: "waiting", error: expect.stringContaining("正在安装") });+ const other = fake();+ expect(await other.priv.install({ manual: true })).toBe(true);+ fs.cpSync(other.dir, f.dir, { recursive: true, preserveTimestamps: true });+ fs.copyFileSync(path.join(other.root, "state.json"), path.join(f.root, "state.json"));+ fs.rmSync(path.join(f.root, ".dl-other.zip"));+ fs.rmSync(path.join(f.root, ".lock"));+ expect(await waiting).toBe(true);+ expect(g.priv.status()).toMatchObject({ ready: true, install: { state: "done" } });expect(g.fetches).toEqual([]);- // 心跳停了 3 分钟以上:当作残留+ // 心跳停了 3 分钟以上:当作残留,自己装+ const h = fake({ pidAlive: () => true });+ fs.writeFileSync(path.join(h.root, ".lock"), JSON.stringify({ pid: 999_999, at: Date.now() }));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);+ fs.utimesSync(path.join(h.root, ".lock"), old, old);+ expect(await h.priv.install({ manual: true })).toBe(true);+ expect(h.fetches).toHaveLength(1);});it("每次启动只看文件指纹:没变就直接用(不拉起任何进程);变了重新核对签名、试运行", async () => {@@ -422,7 +434,7 @@ describe("探测器:优先级、自动安装、自动退回", () => {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(st).toMatchObject({ missing: true, using: PS5, private: { ready: false, bad: { reason: "代理拉不起它:找不到 pwsh.exe(可能被杀毒软件删除或隔离)(Win32 2)" } }, 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" } });@@ -452,7 +464,7 @@ describe("探测器:优先级、自动安装、自动退回", () => {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(probe.snapshot()).toMatchObject({ systemIssue: "代理拉不起它:找不到 pwsh.exe(可能被杀毒软件删除或隔离)(ENOENT)", missing: true });// 系统的坏了、内置的没装:自动装上expect(f.priv.busy).toBe(true);await settle(f.priv);diff --git a/test/pwsh.unit.test.ts b/test/pwsh.unit.test.tsindex 17eb943..1a3450f 100644--- a/test/pwsh.unit.test.ts+++ b/test/pwsh.unit.test.ts@@ -276,4 +276,16 @@ describe("界面接口与诊断(AMB_PWSH_FORCE=missing)", () => {expect((await api("/pwsh")).json.dismissed).toBe(true);expect((await api("/pwsh", { method: "DELETE" })).status).toBe(405);});++ it("改回系统默认 / 重新用内置的写进 config.json(agent.pwsh);不是 Windows 时不能安装", async () => {+ expect(app.config.agent.pwsh).toBe("auto");+ expect((await api("/pwsh/mode", { method: "PUT", body: { mode: "system" } })).status).toBe(200);+ expect(JSON.parse(fs.readFileSync(path.join(app.config.dataDir, "config.json"), "utf8")).agent.pwsh).toBe("system");+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).agent.pwsh).toBe("system");+ await api("/pwsh/mode", { method: "PUT", body: { mode: "auto" } });+ expect(loadConfig({ dataDir: app.config.dataDir, env: {} }).agent.pwsh).toBe("auto");+ const r = await api("/pwsh/install", { method: "POST", body: {} });+ expect(r.status).toBe(400);+ expect(r.json.error).toContain("只在 Windows 上");+ });});