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(i18n): 服务端剩余文案(三):内置 PowerShell 的安装与故障原因、微信/飞书渠道的暂缓与失败说明、接口报错、代理进程、诊断输出、命令行设置向导

dyk986b66a92c884d
diff --git a/scripts/e2e-agent.mjs b/scripts/e2e-agent.mjs
index e68be54..f63a234 100644
--- a/scripts/e2e-agent.mjs
+++ b/scripts/e2e-agent.mjs
@@ -383,7 +383,7 @@ try {
brokenToolFailed: !(summary.healBroken?.reply ?? "").includes("tool-ran-ok") && /windows-acl-run|CreateProcess|spawn|ENOENT/i.test(summary.healBroken?.reply ?? ""),
markedBroken: !!summary.healFallback.bad,
// the reason is put in words (Win32 2 from the sandbox runner = pwsh.exe is gone)
- reasonExplained: /找不到 pwsh\.exe/.test(summary.healFallback.bad?.reason ?? ""),
+ reasonExplained: /找不到 pwsh\.exe|pwsh\.exe not found/.test(summary.healFallback.bad?.reason ?? ""),
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"),
diff --git a/src/agent/control.ts b/src/agent/control.ts
index 04ffbc7..0e17d27 100644
--- a/src/agent/control.ts
+++ b/src/agent/control.ts
@@ -1,4 +1,5 @@
import crypto from "node:crypto";
+import { t as tr } from "../i18n/index.js";
/** 发给代理进程里 amb-control 插件的一条指令 */
export interface ControlCommand {
@@ -29,13 +30,13 @@ export class ControlChannel {
/** 新子进程:换通道 id,旧的指令作废 */
reset(): string {
- this.close("代理进程已重启");
+ this.close(tr("agent.processRestarted"));
this.id = crypto.randomBytes(12).toString("hex");
return this.id;
}
/** 子进程没了:等着的指令全部失败 */
- close(reason = "代理进程已退出"): void {
+ close(reason = tr("agent.processExited")): void {
this.id = "";
this.lastSeen = 0;
this.queue = [];
@@ -117,14 +118,14 @@ export class ControlChannel {
/** 发一条指令,等插件回报;超时或子进程退出时失败 */
send<T = Record<string, unknown>>(op: string, args: Record<string, unknown>, timeoutMs: number): Promise<T> {
- if (!this.id) return Promise.reject(new Error("代理进程没有运行"));
+ if (!this.id) return Promise.reject(new Error(tr("agent.processNotRunning")));
const id = `c${++this.seq}`;
const cmd: ControlCommand = { ...args, id, op };
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
this.queue = this.queue.filter((c) => c !== cmd);
- reject(new Error(`代理进程没有响应(${op})`));
+ reject(new Error(tr("agent.processNoResponse", { op })));
}, timeoutMs);
this.pending.set(id, { resolve, reject, timer });
const w = this.waiter;
diff --git a/src/agent/host.ts b/src/agent/host.ts
index cd8ffdb..e3d3ba2 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -15,7 +15,7 @@ import { pwshPatchLines, pwshProbe } from "./pwsh.js";
import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";
import { acceptsImages } from "../llm/client.js";
import { CUA_SKILL, MEDIA_SKILL, TASK_RULES, agentPersona, botPrompt } from "./prompts/index.js";
-import { t } from "../i18n/index.js";
+import { t, t as tr } from "../i18n/index.js";
const log = logger("agent.host");
@@ -1192,7 +1192,7 @@ exec "$REAL" "$@"
return h;
} catch (e) {
clearInterval(watchdog);
- this.control.close("代理进程启动失败");
+ this.control.close(tr("agent.closeStartFailed"));
this.emit({ type: "failed", message: (e as Error).message });
this.initFailures++;
this.onFailure(e as Error);
@@ -1229,7 +1229,7 @@ exec "$REAL" "$@"
/** 子进程没了:醒着的那几轮随之失败 */
private endWakes(): void {
- for (const w of this.wakes.values()) w.end(new Error("代理进程已退出"));
+ for (const w of this.wakes.values()) w.end(new Error(tr("agent.processExited")));
this.wakes.clear();
}
@@ -1239,7 +1239,7 @@ exec "$REAL" "$@"
this.opened.clear();
this.taskSessions.clear();
this.taskBusy.clear();
- this.control.close("代理进程已重启");
+ this.control.close(tr("agent.processRestarted"));
this.endWakes();
if (!h) return;
try {
@@ -1367,13 +1367,13 @@ exec "$REAL" "$@"
if (input.signal?.aborted) throw stopReason(input.signal);
if (!(await this.useRoute(s.id, route))) {
// 指令通道不通、或补不进这个模型:没有别的回合在跑时,带上这个模型重启子进程;忙的时候不能让这个会话悄悄用错模型
- if (this.active > 0 || this.taskBusy.size > 0) throw new Error(`暂时无法切换到模型 ${input.model}(代理进程正忙,没能在运行中加上这个模型),请稍后再试`);
+ if (this.active > 0 || this.taskBusy.size > 0) throw new Error(tr("agent.cantSwitchBusy", { model: input.model }));
log.warn("restarting dsh to use a model it could not add at runtime", { bot: this.o.botId, model: input.model });
this.known.add(input.model);
await this.closeHarness();
this.state = "stopped";
s = await this.sessionFor(await this.ensure(input.model), input.conversationId);
- if (!(await this.useRoute(s.id, route))) throw new Error(`代理进程无法使用模型 ${input.model}`);
+ if (!(await this.useRoute(s.id, route))) throw new Error(tr("agent.cantUseModel", { model: input.model }));
}
// 代理自己醒着的一轮(后台命令结束)还没完:等它完了再发这条(它的回复由跟踪它的那一轮发出)
const woke = this.wakes.get(s.id);
@@ -1391,7 +1391,7 @@ exec "$REAL" "$@"
const images = this.imageInput ? (input.images ?? []) : [];
// 这一轮:用的接口、上游拒绝过本机器人的哪些模型请求
const api = route.api;
- const tr = this.tracker(s.id, route, input.observer, accept);
+ const trk = this.tracker(s.id, route, input.observer, accept);
const rejections: Rejection[] = [];
const offRejection =
this.o.bridge.onRejection?.((r) => {
@@ -1400,10 +1400,10 @@ exec "$REAL" "$@"
try {
const prompt = images.length ? [{ type: "text", text: input.text }, ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType }))] : input.text;
input.observer?.onStart?.();
- const run = s.run(prompt, { onNotification: tr.onNotification });
+ const run = s.run(prompt, { onNotification: trk.onNotification });
const r = await this.awaitTurn(turn, run, input.signal);
this.failures = 0;
- const { turnError, toolCalls, presented, answers, usage } = tr.st;
+ const { turnError, toolCalls, presented, answers, usage } = trk.st;
const rejected = turnError !== undefined && api !== "openai-completions" ? shapeRejection(rejections, turnError) : undefined;
if (rejected) this.rememberFallback(input.model, api, rejected);
if (!r.finalResponse && turnError) {
@@ -1592,7 +1592,7 @@ exec "$REAL" "$@"
* 在新的子进程里先 resume(失败抛 ResumeFailed)。任务用它自己的模型(按会话选,和聊天一样不用重启)。
*/
async promptTask(o: { sessionId: string; folder: string; model: string; text: string; resume: boolean }): Promise<string> {
- if (!o.model) throw new Error("没有可用的模型");
+ if (!o.model) throw new Error(tr("agent.noModelAvailable"));
const route = await this.routeFor(o.model);
const h = await this.ensure(o.model);
this.taskSessions.add(o.sessionId);
@@ -1609,7 +1609,7 @@ exec "$REAL" "$@"
}
this.opened.add(o.sessionId);
}
- if (!(await this.useRoute(o.sessionId, route))) throw new Error(`代理进程无法使用模型 ${o.model}`);
+ if (!(await this.useRoute(o.sessionId, route))) throw new Error(tr("agent.cantUseModel", { model: o.model }));
this.known.add(o.model);
return await h.client.prompt(o.sessionId, [{ type: "text", text: o.text }]);
}
@@ -1664,12 +1664,12 @@ exec "$REAL" "$@"
this.active++;
const turn: HostTurn = { sessionId: w.sessionId, model: input.model, accepted: Promise.resolve(), finishing: false, stopping: false, wake: true };
this.turns.set(input.conversationId, turn);
- const tr = this.tracker(w.sessionId, route, input.observer);
+ const trk = this.tracker(w.sessionId, route, input.observer);
try {
input.observer?.onStart?.();
- w.attach(tr.onNotification);
+ w.attach(trk.onNotification);
await this.awaitTurn(turn, w.done, input.signal);
- const { turnError, answers, presented, usage } = tr.st;
+ const { turnError, answers, presented, usage } = trk.st;
if (!answers.length && turnError) throw new Error(turnError);
return { text: answers.join("\n\n"), sessionId: w.sessionId, files: deliverables(this.workspace, presented), usage };
} catch (e) {
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index e2455a5..6e7aca5 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -13,7 +13,7 @@ import { APPROVAL_TTL_MS, ApprovalCenter, TASK_APPROVAL_TTL_MS, type QuestionIte
import { MemoryError, MemoryStore, type Scope } from "./memory.js";
import type { TaskHost, TaskService } from "../tasks/service.js";
import { DEFAULT_SETTINGS, type BotSettings, type MediaConfirm } from "./settings.js";
-import { t, tl } from "../i18n/index.js";
+import { t, tl, t as tr } from "../i18n/index.js";
import {
HANDOFF_SYSTEM,
REVIEW_SYSTEM,
@@ -350,7 +350,7 @@ export class AgentManager {
return r;
} catch (e) {
if (e instanceof TurnStopped && e.reason === "timeout") {
- t.activity.end("超过单回合上限");
+ t.activity.end(tr("agent.endTurnLimit"));
for (const r of this.approvals.pendingChat(conv)) this.approvals.cancel(r.id, "stopped");
}
throw e;
@@ -390,7 +390,7 @@ export class AgentManager {
}
private halt(conv: string, t: TurnProgress, why: TurnStopped): void {
- t.activity.end(why.reason === "user" ? "用户中止" : why.reason === "idle" ? "长时间没有进展,自动中止" : "超过单回合上限");
+ t.activity.end(tr(why.reason === "user" ? "agent.endUser" : why.reason === "idle" ? "agent.endIdle" : "agent.endTurnLimit"));
t.abort.abort(why);
// 这一轮还在等的批准 / 回答随之作废(回合被中止,没人再等它们)
for (const r of this.approvals.pendingChat(conv)) this.approvals.cancel(r.id, "stopped");
@@ -678,7 +678,7 @@ export class AgentManager {
const files = text.match(/media\/[\w.-]+/g) ?? ["media/"];
log.warn("media finished after its turn ended", { bot: botId, files });
const name = this.o.store.getBot(botId)?.name ?? botId;
- this.o.onNotice?.(`机器人「${name}」生成的${kind === "image" ? "图片" : "视频"}已保存在它的工作区(${files.join("、")}),但请求它的那条消息已经中止,没有发到聊天里。需要的话在对话里让机器人把它发出来。`);
+ this.o.onNotice?.(tr("agent.mediaSavedNotDelivered", { name, kind: tr(kind === "image" ? "agent.kindImage" : "agent.kindVideo"), files: files.join(tr("agent.mediaListSep")) }));
}
/** 生成前的确认:问用户这次用哪个模型(本次的、默认的和几个推荐的,或回复别的模型名),等到回答、取消或过期 */
@@ -903,7 +903,7 @@ export class AgentManager {
settings: (botId) => this.settings(botId),
memoryPrefix: (botId, conv) => this.memoryPrefix(botId, conv),
prompt: (botId, o) => {
- if (!this.available) return Promise.reject(new Error("代理模式不可用"));
+ if (!this.available) return Promise.reject(new Error(tr("agent.agentModeUnavailable")));
return this.host(botId).promptTask(o);
},
steer: (botId, sessionId, id, text) => this.hosts.get(botId)?.steerTask(sessionId, id, text) ?? Promise.resolve(false),
diff --git a/src/agent/pwsh-private.ts b/src/agent/pwsh-private.ts
index 0576b4b..494f23a 100644
--- a/src/agent/pwsh-private.ts
+++ b/src/agent/pwsh-private.ts
@@ -17,6 +17,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { logger } from "../log.js";
+import { t as tr } from "../i18n/index.js";
const log = logger("pwsh.private");
const W = path.win32;
@@ -162,13 +163,13 @@ export async function launchTest(exe: string, run: Runner, o: { timeoutMs: numbe
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}`);
+ if (r.timedOut) return fail(tr("pwsh.privTimeout", { s: Math.round(o.timeoutMs / 1000) }));
+ if (r.error) return fail(tr("pwsh.privCantStart", { error: r.error }));
+ if (!m || r.code !== 0) return fail(tr("pwsh.privUnexpected", { code: r.code, out: r.stderr || r.stdout ? tr("pwsh.privColon", { text: clip(r.stderr || r.stdout) }) : "" }));
+ if (m[2] !== "rw-ok") return fail(tr("pwsh.privRwFailed"));
+ if (m[3] !== "ext-ok") return fail(tr("pwsh.privExtFailed"));
+ if (!(Number(m[1].split(".")[0]) >= 7)) return fail(tr("pwsh.privNot7", { v: m[1] }));
+ if (o.expect && m[1] !== o.expect) return fail(tr("pwsh.privWrongVersion", { v: m[1], want: o.expect }));
return { ok: true, at: Date.now(), ms, version: m[1] };
}
@@ -181,20 +182,20 @@ export async function verifySignatures(files: string[], run: Runner, env: NodeJS
timeoutMs: 180_000,
env: { ...shellEnv(env), AMB_SIG_FILES: files.join("|") },
});
- 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}`)}` };
+ if (r.timedOut) return { ok: false, error: tr("pwsh.privSigTimeout") };
+ if (r.error || r.code !== 0) return { ok: false, error: tr("pwsh.privSigFailed", { error: clip(r.error || r.stderr || r.stdout || tr("pwsh.privExitCode", { code: 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)}` };
+ return { ok: false, error: tr("pwsh.privSigUnreadable", { out: clip(r.stdout) }) };
}
- if (!Array.isArray(list) || list.length !== files.length) return { ok: false, error: "签名结果数目不对" };
+ if (!Array.isArray(list) || list.length !== files.length) return { ok: false, error: tr("pwsh.privSigCount") };
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)})` };
+ if (s?.status !== "Valid") return { ok: false, error: tr("pwsh.privSigInvalid", { name, status: s?.status || tr("pwsh.privNoSig") }) };
+ if (!ms.test(s.subject ?? "") || !ms.test(s.issuer ?? "")) return { ok: false, error: tr("pwsh.privNotMs", { name, subject: clip(s.subject ?? "", 120) }) };
}
return { ok: true };
}
@@ -211,7 +212,7 @@ export async function extractZip(zip: string, dest: string, run: Runner, env: No
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}`))}`);
+ if (r2.code !== 0 || r2.error || r2.timedOut) throw new Error(tr("pwsh.privUnzipFailed", { error: clip(r2.error || r2.stderr || r2.stdout || (r2.timedOut ? tr("pwsh.privTimedOut") : tr("pwsh.privExitCode", { code: r2.code }))) }));
}
// ---------- 系统版本与架构 ----------
@@ -223,7 +224,7 @@ export function osSupport(release: string, pin: PwshPin = PRIVATE_PWSH): { ok: b
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 或更新的系统` };
+ return { ok: false, build, reason: tr("pwsh.privOldWindows", { release, version: pin.version }) };
}
/**
@@ -270,9 +271,9 @@ export async function download(o: {
let stall: NodeJS.Timeout | undefined;
const arm = () => {
clearTimeout(stall);
- stall = setTimeout(() => ac.abort(new Error(`${Math.round(stallMs / 1000)} 秒没有收到数据`)), stallMs);
+ stall = setTimeout(() => ac.abort(new Error(tr("pwsh.privStall", { s: Math.round(stallMs / 1000) }))), stallMs);
};
- const total = setTimeout(() => ac.abort(new Error("下载超时")), o.totalMs ?? 60 * 60_000);
+ const total = setTimeout(() => ac.abort(new Error(tr("pwsh.privDownloadTimeout"))), o.totalMs ?? 60 * 60_000);
const hash = crypto.createHash("sha256");
const fh = await fs.promises.open(o.dest, "w");
let received = 0;
@@ -281,14 +282,14 @@ export async function download(o: {
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})`);
+ if (o.size && len && len !== o.size) throw new DownloadRefused(tr("pwsh.privSizeWrong", { len, size: 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} 字节)`);
+ if (o.size && received > o.size) throw new DownloadRefused(tr("pwsh.privTooBig", { size: o.size }));
hash.update(value);
await fh.write(value);
o.onProgress?.(received, o.size ?? len);
@@ -301,7 +302,7 @@ export async function download(o: {
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)}…)`);
+ if (got !== o.sha256) throw new HashMismatch(tr("pwsh.privHash", { got: got.slice(0, 12), want: o.sha256.slice(0, 12) }));
}
// ---------- 文件 ----------
@@ -446,7 +447,7 @@ export class PrivatePwsh {
return pwshRoot(this.env);
}
get support(): { ok: boolean; build?: number; reason?: string } {
- if ((this.d.platform ?? process.platform) !== "win32") return { ok: false, reason: "只在 Windows 上需要" };
+ if ((this.d.platform ?? process.platform) !== "win32") return { ok: false, reason: tr("pwsh.privWindowsOnly") };
return osSupport(this.d.osRelease ?? os.release(), this.pin);
}
private get key(): string {
@@ -496,7 +497,7 @@ export class PrivatePwsh {
version: this.pin.version,
...(this.arch ? { arch: this.arch } : {}),
supported: ok,
- ...(!sup.ok ? { reason: sup.reason } : !this.arch && this.prep ? { reason: "这台电脑的处理器架构没有对应的 PowerShell 7 安装包" } : {}),
+ ...(!sup.ok ? { reason: sup.reason } : !this.arch && this.prep ? { reason: tr("pwsh.privNoArch") } : {}),
...(this.dir ? { dir: this.dir } : {}),
installed: this.cur.installed,
ready: this.cur.ready,
@@ -619,7 +620,7 @@ export class PrivatePwsh {
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() };
+ const bad = rec?.bad && rec.fp === fp.value ? rec.bad : { reason: tr("pwsh.privFileMissing", { file: 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 });
@@ -632,7 +633,7 @@ export class PrivatePwsh {
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() };
+ const bad = { reason: tr("pwsh.privSigNotPassed", { error: 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 });
@@ -641,7 +642,7 @@ export class PrivatePwsh {
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() };
+ const bad = { reason: tr("pwsh.testFailed", { error: test.error }), at: Date.now() };
this.saveRecord({ fp: fp.value, test, bad });
return this.set({ installed: true, ready: false, bad, test, fp: fp.value });
}
@@ -668,12 +669,12 @@ export class PrivatePwsh {
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}),需要手动重新安装` : "已经装好";
+ if (!this.arch) return tr("pwsh.privArchUnsupported");
+ if (this.installing) return tr("pwsh.privInstalling");
+ if (this.cur.installed) return this.cur.bad ? tr("pwsh.privBadCopy", { reason: this.cur.bad.reason }) : tr("pwsh.privAlreadyInstalled");
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 "上次自动安装失败,稍后再试";
+ if (a.attempts >= AUTO_BACKOFF.length) return tr("pwsh.privAutoFailedN", { n: a.attempts });
+ if (Date.now() - a.lastAt < AUTO_BACKOFF[a.attempts]) return tr("pwsh.privAutoBackoff");
return undefined;
}
@@ -705,8 +706,8 @@ export class PrivatePwsh {
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 (!sup.ok) return fail(sup.reason ?? tr("pwsh.privCantInstall"));
+ if (!this.arch) return fail(tr("pwsh.privNoArch"));
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);
@@ -719,14 +720,14 @@ export class PrivatePwsh {
try {
locked = this.takeLock();
} catch (e) {
- return fail(`建不了安装目录 ${this.root}:${(e as Error).message}`);
+ return fail(tr("pwsh.privMkdir", { dir: this.root, error: (e as Error).message }));
}
if (locked) break;
if (Date.now() > waitUntil) {
- this.setProgress({ state: "failed", error: "另一个 AnyModelBot 一直在安装 PowerShell 7,稍后再试", finishedAt: Date.now() }, true);
+ this.setProgress({ state: "failed", error: tr("pwsh.privOtherInstalling"), finishedAt: Date.now() }, true);
return false;
}
- this.setProgress({ state: "waiting", error: "另一个 AnyModelBot 正在安装 PowerShell 7,等它装完" }, true);
+ this.setProgress({ state: "waiting", error: tr("pwsh.privOtherWaiting") }, true);
await sleep(this.d.lockPollMs ?? 5000);
if (this.lockHeld()) continue;
await this.evaluate(false);
@@ -769,8 +770,8 @@ export class PrivatePwsh {
});
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}`);
+ if (e instanceof HashMismatch) throw new Error(tr("pwsh.privDiscarded", { error: e.message }));
+ if (e instanceof DownloadRefused || attempt >= 3) throw new Error(tr("pwsh.privDownloadFailed", { url, error: String((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));
@@ -784,15 +785,15 @@ export class PrivatePwsh {
// 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}`);
+ if (ver !== this.pin.version) throw new Error(tr("pwsh.privExtractedVersion", { v: ver ?? tr("pwsh.privUnknown"), want: this.pin.version }));
const fp = await fingerprint(stage);
- if (fp.missing) throw new Error(`解压后缺少 ${fp.missing}(可能被杀毒软件拦下)`);
+ if (fp.missing) throw new Error(tr("pwsh.privMissingAfterExtract", { file: 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}`);
+ if (!sig.ok) throw new Error(tr("pwsh.privSigNotPassed", { 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}`);
+ if (!test.ok) throw new Error(tr("pwsh.testFailed", { 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;
@@ -801,14 +802,14 @@ export class PrivatePwsh {
await renameRetry(dir, trash);
moved = true;
} catch (e) {
- throw new Error(`旧的副本正在使用,换不下来(${(e as NodeJS.ErrnoException).code ?? (e as Error).message}),请稍后再试`);
+ throw new Error(tr("pwsh.privInUse", { 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}`);
+ throw new Error(tr("pwsh.privCantPlace", { error: (e as Error).message }));
}
this.saveRecord({ fp: fp.value, test });
this.updateState((s) => (s.auto = { attempts: 0, lastAt: 0 }));
diff --git a/src/agent/pwsh.ts b/src/agent/pwsh.ts
index 01bff4b..c0f5e08 100644
--- a/src/agent/pwsh.ts
+++ b/src/agent/pwsh.ts
@@ -33,7 +33,7 @@ import {
type PrivatePwshStatus,
type Runner,
} from "./pwsh-private.js";
-import { t, type MessageKey } from "../i18n/index.js";
+import { t, type MessageKey, t as tr } from "../i18n/index.js";
const log = logger("pwsh");
const W = path.win32;
@@ -201,8 +201,8 @@ export function shellStartFailure(text: string, exe: string): string | 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 missing = tr("pwsh.whyMissing");
+ const denied = tr("pwsh.whyDenied");
const why: Record<string, string> = {
"2": missing,
"3": missing,
@@ -210,14 +210,14 @@ export function startFailureReason(line: string): string {
"5": denied,
EACCES: denied,
EPERM: denied,
- "225": "被杀毒软件拦截",
- "1260": "被系统策略禁止运行(AppLocker / 软件限制策略)",
- "4551": "被 Windows Defender 应用程序控制拦截",
- "193": "文件损坏,或不是这台电脑能运行的程序",
- "216": "文件损坏,或不是这台电脑能运行的程序",
- "1392": "文件已损坏",
+ "225": tr("pwsh.whyAntivirus"),
+ "1260": tr("pwsh.whyPolicy"),
+ "4551": tr("pwsh.whyWdac"),
+ "193": tr("pwsh.whyBadExe"),
+ "216": tr("pwsh.whyBadExe"),
+ "1392": tr("pwsh.whyCorrupt"),
};
- return `${(code && why[code]) || "拉不起来"}(${code ? (/^\d+$/.test(code) ? `Win32 ${code}` : code) : line.slice(0, 120)})`;
+ return tr("pwsh.whyLine", { why: (code && why[code]) || tr("pwsh.whyCantStart"), detail: code ? (/^\d+$/.test(code) ? `Win32 ${code}` : code) : line.slice(0, 120) });
}
/** 弱信号:.NET 宿主起不来、沙箱 runner 拉它时出了别的错。重新试运行一次,没通过才退回 */
@@ -363,9 +363,9 @@ export class PwshProbe {
const c = this.sys?.c;
if (!c) return undefined;
const bad = this.sysBad.get(dirKey(c.path));
- if (bad) return `代理拉不起它:${bad.reason}`;
+ if (bad) return tr("pwsh.agentCantStart", { reason: bad.reason });
const t = this.sysTests.get(dirKey(c.path));
- if (t && t !== "pending" && !t.ok && !t.timedOut) return `试运行没通过:${t.error}`;
+ if (t && t !== "pending" && !t.ok && !t.timedOut) return tr("pwsh.testFailed", { error: t.error });
return undefined;
}
@@ -437,11 +437,11 @@ export class PwshProbe {
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),代理执行命令会快很多。` } });
+ this.emit({ kind: "install", notice: { level: "info", text: tr("pwsh.noticeInstalled", { version: this.priv.pin.version }) } });
if (p.state === "failed")
this.emit({
kind: "install",
- notice: { level: "warn", text: `为代理安装 PowerShell 7 没有成功:${p.error ?? "未知原因"}。代理照常用 Windows PowerShell 5.1 执行命令;可在 设置 → 故障排查 里重试。` },
+ notice: { level: "warn", text: tr("pwsh.noticeInstallFailed", { error: p.error ?? tr("pwsh.unknownReason") }) },
});
}
this.update();
@@ -460,8 +460,8 @@ export class PwshProbe {
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.fallback = { from: c.path, reason: tr("pwsh.testFailed", { error: t.error }), to, at: Date.now() };
+ this.update({ level: "warn", text: tr("pwsh.noticeSystemTestFailed", { path: c.path, error: t.error, to: describe(to, this.priv.exe) }) });
this.maybeAutoInstall("system test failed");
} else this.update();
});
@@ -512,7 +512,7 @@ export class PwshProbe {
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}`);
+ if (!t.ok && !t.timedOut) this.markBroken(exe, tr("pwsh.testFailed", { error: t.error }));
}
/** 代理拉不起 exe:标记为坏,退回下一个(空闲时重启代理进程),告诉用户;必要时自动安装内置副本 */
@@ -522,7 +522,7 @@ export class PwshProbe {
if (!this.priv.ready) return;
this.quiet = true;
try {
- this.priv.markBad(`代理拉不起它:${reason}`);
+ this.priv.markBad(tr("pwsh.agentCantStart", { reason }));
} finally {
this.quiet = false;
}
@@ -538,7 +538,7 @@ 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: tr("pwsh.noticeFellBack", { exe, reason: reason.slice(0, 160), to: describe(to, this.priv.exe) }),
});
this.maybeAutoInstall("broken");
}
@@ -568,8 +568,8 @@ function forcedStatus(kind: string, version: string): PwshStatus {
/** 给用户看的名字 */
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";
+ if (!p || /\\WindowsPowerShell\\v1\.0\\powershell\.exe$/i.test(p)) return tr("pwsh.descSystem51");
+ if (privateExe && dirKey(p) === dirKey(privateExe)) return tr("pwsh.descPrivate7");
return ` ${p} `;
}
diff --git a/src/app.ts b/src/app.ts
index a6a3605..97a03b9 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -44,7 +44,7 @@ import { MediaService, pickDefault } from "./agent/media.js";
import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";
import type { BotSettings } from "./agent/settings.js";
import { TaskService } from "./tasks/service.js";
-import { detached, setLangPref, t } from "./i18n/index.js";
+import { detached, setLangPref, t, t as tr } from "./i18n/index.js";
import { Attention, approvalItems, deliveryItem, type AttentionItem } from "./tasks/attention.js";
const log = logger("app");
@@ -270,7 +270,7 @@ export class App {
for (const [botId, ch] of this.channels) {
const st = ch.weixin?.status;
if (st?.state !== "expired") continue;
- out.push({ id: `login:${botId}:weixin`, kind: "login", botId, botName: this.store.getBot(botId)?.name ?? botId, subject: "微信登录已过期", status: "", line: "", since: st.since, severity: "err", actions: ["relogin"], channel: "weixin" });
+ out.push({ id: `login:${botId}:weixin`, kind: "login", botId, botName: this.store.getBot(botId)?.name ?? botId, subject: tr("app.weixinExpiredSubject"), status: "", line: "", since: st.since, severity: "err", actions: ["relogin"], channel: "weixin" });
}
return out;
}
diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.ts
index 2e632d2..f8036e0 100644
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@ -5,7 +5,7 @@ import { Gone, ReplyIds, stableId, type Outbox } from "../../core/outbox.js";
import type { OutboxBody, OutboxKind, OutboxRow } from "../../store/db.js";
import { CARD_ELEMENT_ID, actionCardSpec, type FeishuTransport } from "./transport.js";
import { logger } from "../../log.js";
-import { t } from "../../i18n/index.js";
+import { t, t as tr } from "../../i18n/index.js";
const log = logger("feishu.card");
@@ -55,12 +55,12 @@ export async function deliverFeishu(transport: FeishuTransport, row: OutboxRow,
return replyText(text);
}
case "notice": {
- if (!transport.sendText) throw new Gone("飞书传输层不支持主动发消息");
+ if (!transport.sendText) throw new Gone(tr("channel.feishuNoPush"));
await transport.sendText(row.peerId, b.text ?? "", stableId(row.id, 0));
return;
}
case "file": {
- const name = b.name ?? "文件";
+ const name = b.name ?? tr("channel.fileFallback");
if (transport.replyFile && row.progress === 0) {
try {
await transport.replyFile(row.replyTo, b.path ?? "", stableId(row.id, 0));
@@ -71,7 +71,7 @@ export async function deliverFeishu(transport: FeishuTransport, row: OutboxRow,
}
progress(1);
}
- await transport.replyText(row.replyTo, `⚠️ 文件「${name}」发送失败,可在工作区中查看。`, stableId(row.id, 1));
+ await transport.replyText(row.replyTo, tr("channel.file_failed", { name }), stableId(row.id, 1));
return;
}
case "card": {
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index e90f022..4317d5f 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -10,7 +10,7 @@ import { StreamingMarkdownFilter } from "./markdown-filter.js";
import { WeixinQuota } from "./quota.js";
import type { Delivery } from "../../core/delivery.js";
import { logger } from "../../log.js";
-import { t } from "../../i18n/index.js";
+import { t, t as tr, tl } from "../../i18n/index.js";
export const WEIXIN_CAPS: ChannelCapabilities = {
streaming: false,
@@ -76,7 +76,7 @@ function mediaItems(items: MessageItem[] | undefined): MessageItem[] {
const deliverLog = logger("weixin.send");
/** 回复太长、本轮配额不够时,最后一条末尾的说明 */
-const OVER_QUOTA_NOTE = "\n\n…(回复过长,已达到本轮可发送条数上限,请回复任意消息继续)";
+const overQuotaNote = () => "\n\n" + tr("channel.reply_truncated");
/** 文件临时发不出去(网络、CDN 5xx)时先重试这么多次,再改发一句"发送失败" */
const MEDIA_RETRIES = 2;
/** ack、审批提示:过一会儿就没意义了,发不出去不必一直等 */
@@ -100,15 +100,20 @@ function budgetOf(quota: WeixinQuota, userId: string, row: Pick<OutboxRow, "purp
/** 能不能给这个人发:要有会话凭证、24 小时窗口没过、还有配额;不能就留着(Held),等他下次发消息;返回凭证 */
function reachable(quota: WeixinQuota, userId: string, row: Pick<OutboxRow, "purpose">): string {
const peer = quota.peer(userId);
- if (!peer?.contextToken) throw new Held("对方还没有给机器人发过消息,等他发消息后再发", "no_token");
- if (!quota.open(userId)) throw new Held("对方超过 24 小时没有发消息,等他下次发消息时再发", "window_closed");
- if (quota.remaining(userId) <= 0) throw new Held("本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发", "quota");
- if (budgetOf(quota, userId, row) <= 0) throw new Held("本轮剩下的条数留给后台任务的结果了,等他下次发消息时再发", "quota");
+ if (!peer?.contextToken) throw new Held(tr("channel.heldNoToken"), "no_token");
+ if (!quota.open(userId)) throw new Held(tr("channel.heldWindowClosed"), "window_closed");
+ if (quota.remaining(userId) <= 0) throw new Held(tr("channel.heldQuota"), "quota");
+ if (budgetOf(quota, userId, row) <= 0) throw new Held(tr("channel.heldReserved"), "quota");
return peer.contextToken;
}
/** 留着的消息在对方下次发消息时送达,开头加上这句 */
-export const AWAY_PREFIX = "你不在时:";
+/** 合并发出的「你不在时」那条的开头(按当前语言);去掉它时两种语言的都认 */
+export const awayPrefix = () => tr("channel.awayPrefix");
+const stripAway = (s: string) => {
+ for (const p of [tl("zh-CN", "channel.awayPrefix"), tl("en", "channel.awayPrefix")]) if (s.startsWith(p)) return s.slice(p.length);
+ return s;
+};
/**
* 对方又发消息了,留着给他的消息怎么发(Outbox.release 的 combine):相邻的文字合成一条「你不在时:…」(一条微信放得下就合),
@@ -118,7 +123,7 @@ export function combineHeld(rows: OutboxRow[]): HeldGroup[] {
const groups: HeldGroup[] = [];
let cur: { rows: OutboxRow[]; texts: string[]; len: number } | undefined;
const flush = () => {
- if (cur) groups.push({ rows: cur.rows, body: { text: AWAY_PREFIX + (cur.texts.length > 1 ? "\n" : "") + cur.texts.join("\n\n"), raw: true, away: true } });
+ if (cur) groups.push({ rows: cur.rows, body: { text: awayPrefix() + (cur.texts.length > 1 ? "\n" : "") + cur.texts.join("\n\n"), raw: true, away: true } });
cur = undefined;
};
for (const r of rows) {
@@ -129,9 +134,9 @@ export function combineHeld(rows: OutboxRow[]): HeldGroup[] {
continue;
}
// 已经合成过的(又被留着)不再加前缀;Markdown 先按微信的规则过滤掉,合成的那条原样发
- const text = r.body.away ? raw.slice(AWAY_PREFIX.length).trim() : r.body.raw ? raw.trim() : filterMarkdown(raw);
+ const text = r.body.away ? stripAway(raw).trim() : r.body.raw ? raw.trim() : filterMarkdown(raw);
if (cur && cur.len + 2 + text.length > WEIXIN_CAPS.maxTextLength) flush();
- cur ??= { rows: [], texts: [], len: AWAY_PREFIX.length };
+ cur ??= { rows: [], texts: [], len: awayPrefix().length };
cur.rows.push(r);
cur.texts.push(text);
cur.len += 2 + text.length;
@@ -148,7 +153,7 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
const user = row.peerId;
const token = reachable(quota, user, row);
if (row.kind === "file") {
- const name = row.body.name ?? "文件";
+ const name = row.body.name ?? tr("channel.fileFallback");
if (row.progress === 0) {
try {
// 上传失败不占配额
@@ -161,7 +166,7 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
}
progress(1);
}
- await client.sendText(user, `⚠️ 文件「${name}」发送失败,可在工作区中查看。`, token, stableId(row.id, 1));
+ await client.sendText(user, tr("channel.file_failed", { name }), token, stableId(row.id, 1));
quota.tryConsume(user);
return;
}
@@ -171,7 +176,8 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
const budget = budgetOf(quota, user, row);
if (rest.length > budget) {
rest = rest.slice(0, budget);
- rest[budget - 1] = rest[budget - 1].slice(0, WEIXIN_CAPS.maxTextLength - OVER_QUOTA_NOTE.length) + OVER_QUOTA_NOTE;
+ const note = overQuotaNote();
+ rest[budget - 1] = rest[budget - 1].slice(0, WEIXIN_CAPS.maxTextLength - note.length) + note;
}
for (let i = 0; i < rest.length; i++) {
const n = row.progress + i;
@@ -347,12 +353,12 @@ export class WeixinChannel {
}
private async deliver(row: OutboxRow, progress: (n: number) => void): Promise<void> {
- if (!this.client) throw new Later("微信渠道没有运行");
- if ((this.store.getWeixinAccount(this.botId)?.pausedUntil ?? 0) > Date.now()) throw new Later("微信登录已过期,等重新扫码");
+ if (!this.client) throw new Later(tr("channel.laterNotRunning"));
+ if ((this.store.getWeixinAccount(this.botId)?.pausedUntil ?? 0) > Date.now()) throw new Later(tr("channel.laterExpired"));
try {
await deliverWeixin(this.client, this.quota, row, progress);
} catch (e) {
- if (e instanceof WeixinApiError && e.sessionExpired) throw new Later("微信登录已过期,等重新扫码");
+ if (e instanceof WeixinApiError && e.sessionExpired) throw new Later(tr("channel.laterExpired"));
throw e;
}
}
diff --git a/src/cli/init.ts b/src/cli/init.ts
index b75cb27..ac77b39 100644
--- a/src/cli/init.ts
+++ b/src/cli/init.ts
@@ -9,6 +9,7 @@ import { spawn } from "node:child_process";
import { stdin, stdout } from "node:process";
import { loadConfig } from "../config.js";
import { App } from "../app.js";
+import { t as tr } from "../i18n/index.js";
/** 行队列:兼容交互终端与管道输入(管道时所有行会一次性到达) */
function lineReader() {
@@ -37,7 +38,7 @@ function lineReader() {
muted = secret && tty;
const l = await next();
muted = false;
- if (!tty) stdout.write(secret ? "(已输入)\n" : `${l ?? ""}\n`);
+ if (!tty) stdout.write(secret ? tr("cli.entered") + "\n" : `${l ?? ""}\n`);
return (l ?? "").trim();
},
close: () => rl.close(),
@@ -55,29 +56,29 @@ async function main(): Promise<void> {
await app.magpie?.stop();
app.store.close();
}
- console.log("\n完成。运行 npm start 启动;微信请在管理界面的信息面板「渠道」里扫码,或运行 npm run weixin:login。");
+ console.log("\n" + tr("cli.done"));
}
async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: string): Promise<void> {
- console.log(`anymodel bot 首次设置(数据目录:${dataDir})\n`);
+ console.log(tr("cli.title", { dir: dataDir }) + "\n");
if (app.magpie) {
if (!app.magpie.binPath) {
- throw new Error("找不到 magpie 可执行文件,请先运行:npm run setup");
+ throw new Error(tr("cli.noMagpie"));
}
await app.magpie.start();
const status = app.modelflareStatus();
const account = app.ensureAccount();
if (status.connected) {
- console.log(`Modelflare 已连接(尾号 ${status.keyTail}${account.signedIn ? `,账户 ${account.status().name || "已登录"}` : ""}),保留现有连接。`);
+ console.log(tr("cli.alreadyConnected", { tail: status.keyTail, account: account.signedIn ? tr("cli.accountSuffix", { name: account.status().name || tr("cli.signedIn") }) : "" }));
} else {
- const how = (await rl.ask("连接 Modelflare:回车 = 登录账户(在这台电脑的浏览器里完成),输入 key = 粘贴 API Key,输入 skip = 稍后在界面里连接:")).toLowerCase();
+ const how = (await rl.ask(tr("cli.askHow"))).toLowerCase();
if (how !== "skip") {
- const line = (await rl.ask("线路:回车 = 国际(modelflare.dev),输入 cn = 中国大陆优化(origin.modelflare.dev):")).trim() === "cn" ? "cn" : "auto";
+ const line = (await rl.ask(tr("cli.askLine"))).trim() === "cn" ? "cn" : "auto";
if (how === "key") {
const key = await rl.ask("Modelflare API Key:", true);
const r = await app.connectModelflare(key, line);
- if (!r.ok) throw new Error(r.message + (r.suggestLine === "cn" ? "(可重试并选择 cn 线路)" : ""));
- console.log(`✓ 已连接 Modelflare,找到 ${r.models.length} 个模型`);
+ if (!r.ok) throw new Error(r.message + (r.suggestLine === "cn" ? tr("cli.tryCn") : ""));
+ console.log(tr("cli.connected", { count: r.models.length }));
} else {
await app.setModelflareLine(line);
await loginInBrowser(app);
@@ -85,13 +86,13 @@ async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: strin
}
}
}
- const appId = (await rl.ask("飞书 App ID(cli_xxx,留空跳过):")).trim();
+ const appId = (await rl.ask(tr("cli.askFeishuId"))).trim();
if (appId) {
- const secret = await rl.ask("飞书 App Secret:", true);
+ const secret = await rl.ask(tr("cli.askFeishuSecret"), true);
let bot = app.store.listBots()[0];
- if (!bot) bot = app.store.createBot({ id: "default", name: "我的助手", weixinEnabled: true });
+ if (!bot) bot = app.store.createBot({ id: "default", name: tr("app.default_bot_name"), weixinEnabled: true });
app.store.updateBot(bot.id, { feishuAppId: appId, feishuAppSecret: secret });
- console.log(`✓ 已保存到机器人「${bot.name}」`);
+ console.log(tr("cli.savedToBot", { name: bot.name }));
}
}
@@ -99,17 +100,17 @@ async function setup(app: App, rl: ReturnType<typeof lineReader>, dataDir: strin
async function loginInBrowser(app: App): Promise<void> {
const account = app.ensureAccount();
const url = await account.startLogin();
- console.log(`\n在这台电脑的浏览器里打开下面的链接,登录(或注册)Modelflare 并点「继续」授权:\n${url}\n`);
+ console.log(`\n${tr("cli.openLink")}\n${url}\n`);
openInBrowser(url);
for (;;) {
await new Promise((r) => setTimeout(r, 500));
const s = account.status();
if (s.state === "signed_in") {
const models = await app.runtime.listModels(true).catch(() => []);
- console.log(`✓ 已登录 ${s.name || "Modelflare"},本机 Key 已连接,找到 ${models.length} 个模型`);
+ console.log(tr("cli.signedInConnected", { name: s.name || "Modelflare", count: models.length }));
return;
}
- if (s.state !== "signing_in") throw new Error(s.error || "登录没有完成");
+ if (s.state !== "signing_in") throw new Error(s.error || tr("cli.loginIncomplete"));
}
}
@@ -127,6 +128,6 @@ function openInBrowser(url: string): void {
}
main().catch((e) => {
- console.error("设置失败:", (e as Error).message);
+ console.error(tr("cli.setupFailed"), (e as Error).message);
process.exit(1);
});
diff --git a/src/cli/weixin-login.ts b/src/cli/weixin-login.ts
index 8be1d37..f3e2149 100644
--- a/src/cli/weixin-login.ts
+++ b/src/cli/weixin-login.ts
@@ -3,12 +3,13 @@ import path from "node:path";
import { loadConfig } from "../config.js";
import { Store } from "../store/db.js";
import { WeixinLogin } from "../channels/weixin/login.js";
+import { t as tr } from "../i18n/index.js";
async function main(): Promise<void> {
const config = loadConfig();
const store = new Store(path.join(config.dataDir, "anymodel.db"));
const botId = process.argv[2] || store.listBots()[0]?.id || "default";
- if (!store.getBot(botId)) store.createBot({ id: botId, name: "我的助手", weixinEnabled: true });
+ if (!store.getBot(botId)) store.createBot({ id: botId, name: tr("app.default_bot_name"), weixinEnabled: true });
const login = new WeixinLogin({
apiBaseUrl: config.weixin.apiBaseUrl,
pngPath: path.join(config.dataDir, "weixin", `${botId}-login-qr.png`),
@@ -20,7 +21,7 @@ async function main(): Promise<void> {
store.saveWeixinAccount({ botId, botToken: res.botToken, ilinkBotId: res.ilinkBotId, baseUrl: res.baseUrl, ownerUserId: res.userId });
store.updateBot(botId, { weixinEnabled: true });
store.close();
- console.log("✓ 微信已连接,运行 npm start 开始收发消息(若已在运行,请重启或在界面中重新启用微信渠道)。");
+ console.log(tr("cli.weixinConnected"));
}
main().catch((e) => {
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
index 3e94b90..17cf4cc 100644
--- a/src/diagnostics.ts
+++ b/src/diagnostics.ts
@@ -11,7 +11,7 @@ import { shapeRejection } from "./agent/api-fallback.js";
import { logFilePath, logger, readLogTail, redactText, redactValue } from "./log.js";
import { bareModel } from "./modelflare.js";
import { pwshProbe, pwshReportLine } from "./agent/pwsh.js";
-import { t, type MessageKey } from "./i18n/index.js";
+import { t, type MessageKey, t as tr } from "./i18n/index.js";
const log = logger("diagnostics");
@@ -424,7 +424,17 @@ export function diagnosticsReport(app: App, lines = 200): string {
const ps = pwshReportLine(s.pwsh);
if (ps) out.push(ps);
const ob = s.outbox;
- if (ob) out.push(`[出站队列] 等待发送 ${ob.pending} 条(重试中 ${ob.retrying})${ob.lastError ? ` · 最近错误:${ob.lastError}` : ""}${ob.held ? ` · 等对方发消息后再发 ${ob.held} 条` : ""} · 最近 7 天没发出去 ${ob.gone7d} 条${ob.lastGone ? ` · 最近一次:${ob.lastGone}` : ""}`);
+ if (ob)
+ out.push(
+ tr("diag.outboxLine", {
+ pending: ob.pending,
+ retrying: ob.retrying,
+ lastError: ob.lastError ? tr("diag.outboxLastError", { error: ob.lastError }) : "",
+ held: ob.held ? tr("diag.outboxHeld", { n: ob.held }) : "",
+ gone: ob.gone7d,
+ lastGone: ob.lastGone ? tr("diag.outboxLastGone", { text: ob.lastGone }) : "",
+ }),
+ );
const m = app.lastDiagnostics.model;
if (m) {
out.push("");
diff --git a/src/i18n/messages/agent.ts b/src/i18n/messages/agent.ts
index c2f1b09..4584dc2 100644
--- a/src/i18n/messages/agent.ts
+++ b/src/i18n/messages/agent.ts
@@ -40,6 +40,22 @@ export const zh = {
memForgetMany: "有 {count} 条匹配,请写得更具体,或传 all: true 全部删除:\n{list}",
memInTopic: "({topic})",
memForgotten: "已删除 {count} 条({scope})",
+ endTurnLimit: "超过单回合上限",
+ endUser: "用户中止",
+ endIdle: "长时间没有进展,自动中止",
+ mediaSavedNotDelivered: "机器人「{name}」生成的{kind}已保存在它的工作区({files}),但请求它的那条消息已经中止,没有发到聊天里。需要的话在对话里让机器人把它发出来。",
+ kindImage: "图片",
+ kindVideo: "视频",
+ mediaListSep: "、",
+ agentModeUnavailable: "代理模式不可用",
+ closeStartFailed: "代理进程启动失败",
+ processExited: "代理进程已退出",
+ processRestarted: "代理进程已重启",
+ cantSwitchBusy: "暂时无法切换到模型 {model}(代理进程正忙,没能在运行中加上这个模型),请稍后再试",
+ cantUseModel: "代理进程无法使用模型 {model}",
+ noModelAvailable: "没有可用的模型",
+ processNotRunning: "代理进程没有运行",
+ processNoResponse: "代理进程没有响应({op})",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -77,4 +93,20 @@ export const en: Catalog<typeof zh> = {
memForgetMany: "{count} entries match; be more specific, or pass all: true to delete them all:\n{list}",
memInTopic: " ({topic})",
memForgotten: { one: "Deleted 1 entry ({scope})", other: "Deleted {count} entries ({scope})" },
+ endTurnLimit: "exceeded the per-turn limit",
+ endUser: "stopped by the user",
+ endIdle: "no progress for a long time, stopped automatically",
+ mediaSavedNotDelivered: "The {kind} that bot \"{name}\" generated was saved in its workspace ({files}), but the message that asked for it was stopped, so it wasn't sent to the chat. Ask the bot in the chat to send it if you need it.",
+ kindImage: "image",
+ kindVideo: "video",
+ mediaListSep: ", ",
+ agentModeUnavailable: "Agent mode isn't available",
+ closeStartFailed: "The agent process failed to start",
+ processExited: "The agent process exited",
+ processRestarted: "The agent process restarted",
+ cantSwitchBusy: "Can't switch to the model {model} right now (the agent process is busy and couldn't add it while running); try again later",
+ cantUseModel: "The agent process can't use the model {model}",
+ noModelAvailable: "No model available",
+ processNotRunning: "The agent process isn't running",
+ processNoResponse: "The agent process didn't respond ({op})",
};
diff --git a/src/i18n/messages/app.ts b/src/i18n/messages/app.ts
index f4b7adf..de76876 100644
--- a/src/i18n/messages/app.ts
+++ b/src/i18n/messages/app.ts
@@ -20,6 +20,7 @@ export const zh = {
media_quoted_video: "引用的视频",
media_voice: "[语音]",
media_not_downloaded: "{label}(未能下载:{error})",
+ weixinExpiredSubject: "微信登录已过期",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -39,4 +40,5 @@ export const en: Catalog<typeof zh> = {
media_quoted_video: "Quoted video",
media_voice: "[Voice]",
media_not_downloaded: "{label} (couldn't download: {error})",
+ weixinExpiredSubject: "WeChat sign-in expired",
};
diff --git a/src/i18n/messages/channel.ts b/src/i18n/messages/channel.ts
index af3c927..2a52b2d 100644
--- a/src/i18n/messages/channel.ts
+++ b/src/i18n/messages/channel.ts
@@ -42,6 +42,15 @@ export const zh = {
cdn_failed: "CDN 下载失败",
too_large: "文件过大({size} MB,上限 {max} MB)",
decrypt_failed: "解密失败(密钥不对?)",
+ awayPrefix: "你不在时:",
+ heldNoToken: "对方还没有给机器人发过消息,等他发消息后再发",
+ heldWindowClosed: "对方超过 24 小时没有发消息,等他下次发消息时再发",
+ heldQuota: "本轮可发送条数已用完(对方每发一条消息,24 小时内最多回复 10 条),等他下次发消息时再发",
+ heldReserved: "本轮剩下的条数留给后台任务的结果了,等他下次发消息时再发",
+ fileFallback: "文件",
+ laterNotRunning: "微信渠道没有运行",
+ laterExpired: "微信登录已过期,等重新扫码",
+ feishuNoPush: "飞书传输层不支持主动发消息",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -81,4 +90,13 @@ export const en: Catalog<typeof zh> = {
cdn_failed: "CDN download failed",
too_large: "File too large ({size} MB, limit {max} MB)",
decrypt_failed: "Decryption failed (wrong key?)",
+ awayPrefix: "While you were away: ",
+ heldNoToken: "They haven't messaged the bot yet; it'll be sent after they do",
+ heldWindowClosed: "They haven't messaged in over 24 hours; it'll be sent next time they do",
+ heldQuota: "This turn's message allowance is used up (up to 10 replies within 24 hours of each message they send); it'll be sent next time they message",
+ heldReserved: "The rest of this turn's allowance is reserved for background task results; it'll be sent next time they message",
+ fileFallback: "file",
+ laterNotRunning: "The WeChat channel isn't running",
+ laterExpired: "WeChat sign-in expired; waiting for a new QR scan",
+ feishuNoPush: "The Feishu transport can't send messages on its own",
};
diff --git a/src/i18n/messages/cli.ts b/src/i18n/messages/cli.ts
new file mode 100644
index 0000000..9753cfd
--- /dev/null
+++ b/src/i18n/messages/cli.ts
@@ -0,0 +1,46 @@
+// cli:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
+import type { Catalog } from "../types.js";
+
+export const zh = {
+ entered: "(已输入)",
+ done: "完成。运行 npm start 启动;微信请在管理界面的信息面板「渠道」里扫码,或运行 npm run weixin:login。",
+ title: "anymodel bot 首次设置(数据目录:{dir})",
+ noMagpie: "找不到 magpie 可执行文件,请先运行:npm run setup",
+ alreadyConnected: "Modelflare 已连接(尾号 {tail}{account}),保留现有连接。",
+ accountSuffix: ",账户 {name}",
+ signedIn: "已登录",
+ askHow: "连接 Modelflare:回车 = 登录账户(在这台电脑的浏览器里完成),输入 key = 粘贴 API Key,输入 skip = 稍后在界面里连接:",
+ askLine: "线路:回车 = 国际(modelflare.dev),输入 cn = 中国大陆优化(origin.modelflare.dev):",
+ tryCn: "(可重试并选择 cn 线路)",
+ connected: "✓ 已连接 Modelflare,找到 {count} 个模型",
+ askFeishuId: "飞书 App ID(cli_xxx,留空跳过):",
+ askFeishuSecret: "飞书 App Secret:",
+ savedToBot: "✓ 已保存到机器人「{name}」",
+ openLink: "在这台电脑的浏览器里打开下面的链接,登录(或注册)Modelflare 并点「继续」授权:",
+ signedInConnected: "✓ 已登录 {name},本机 Key 已连接,找到 {count} 个模型",
+ loginIncomplete: "登录没有完成",
+ setupFailed: "设置失败:",
+ weixinConnected: "✓ 微信已连接,运行 npm start 开始收发消息(若已在运行,请重启或在界面中重新启用微信渠道)。",
+} satisfies Catalog;
+
+export const en: Catalog<typeof zh> = {
+ entered: "(entered)",
+ done: "Done. Run npm start to launch. For WeChat, scan the QR code under Channels in the console's info panel, or run npm run weixin:login.",
+ title: "anymodel bot first-run setup (data directory: {dir})",
+ noMagpie: "magpie executable not found; run npm run setup first",
+ alreadyConnected: "Modelflare is already connected (key ending {tail}{account}); keeping the existing connection.",
+ accountSuffix: ", account {name}",
+ signedIn: "signed in",
+ askHow: "Connect Modelflare: Enter = sign in (in this computer's browser), key = paste an API key, skip = connect later in the console: ",
+ askLine: "Route: Enter = international (modelflare.dev), cn = optimized for mainland China (origin.modelflare.dev): ",
+ tryCn: " (you can retry and choose the cn route)",
+ connected: "✓ Connected to Modelflare, found {count} models",
+ askFeishuId: "Feishu App ID (cli_xxx, leave empty to skip): ",
+ askFeishuSecret: "Feishu App Secret: ",
+ savedToBot: "✓ Saved to the bot \"{name}\"",
+ openLink: "Open the link below in this computer's browser, sign in to (or sign up for) Modelflare and click Continue to authorize:",
+ signedInConnected: "✓ Signed in to {name}; this computer's key is connected, found {count} models",
+ loginIncomplete: "Sign-in didn't finish",
+ setupFailed: "Setup failed:",
+ weixinConnected: "✓ WeChat connected. Run npm start to send and receive messages (if it's already running, restart it or re-enable the WeChat channel in the console).",
+};
diff --git a/src/i18n/messages/diag.ts b/src/i18n/messages/diag.ts
index 5f753f6..6e6f7cf 100644
--- a/src/i18n/messages/diag.ts
+++ b/src/i18n/messages/diag.ts
@@ -81,6 +81,10 @@ export const zh = {
report_passed: "通过",
report_not_passed: "未通过({stage})",
report_log_tail: "[最近 {count} 行日志]",
+ outboxLine: "[出站队列] 等待发送 {pending} 条(重试中 {retrying}){lastError}{held} · 最近 7 天没发出去 {gone} 条{lastGone}",
+ outboxLastError: " · 最近错误:{error}",
+ outboxHeld: " · 等对方发消息后再发 {n} 条",
+ outboxLastGone: " · 最近一次:{text}",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -162,4 +166,8 @@ export const en: Catalog<typeof zh> = {
report_passed: "passed",
report_not_passed: "failed ({stage})",
report_log_tail: { one: "[Last {count} log line]", other: "[Last {count} log lines]" },
+ outboxLine: "[Outbox] {pending} waiting to send ({retrying} retrying){lastError}{held} · {gone} not sent in the last 7 days{lastGone}",
+ outboxLastError: " · last error: {error}",
+ outboxHeld: " · {n} waiting until they message again",
+ outboxLastGone: " · most recent: {text}",
};
diff --git a/src/i18n/messages/index.ts b/src/i18n/messages/index.ts
index 9ce4a67..b33759b 100644
--- a/src/i18n/messages/index.ts
+++ b/src/i18n/messages/index.ts
@@ -17,5 +17,6 @@ import * as activity from "./activity.js";
import * as tasks from "./tasks.js";
import * as access from "./access.js";
import * as delivery from "./delivery.js";
+import * as cli from "./cli.js";
-export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, activity, tasks, access, delivery };
+export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, activity, tasks, access, delivery, cli };
diff --git a/src/i18n/messages/pwsh.ts b/src/i18n/messages/pwsh.ts
index e83da18..10b6f98 100644
--- a/src/i18n/messages/pwsh.ts
+++ b/src/i18n/messages/pwsh.ts
@@ -57,6 +57,68 @@ export const zh = {
policyAuto: "缺 7 时自动安装",
policyManual: "不自动安装",
privateLine: " 内置 PowerShell {version}{arch} · {state}{inst}{dir} · {policy}{ignore}",
+ whyMissing: "找不到 pwsh.exe(可能被杀毒软件删除或隔离)",
+ whyDenied: "没有权限运行它(可能被安全软件拦截)",
+ whyAntivirus: "被杀毒软件拦截",
+ whyPolicy: "被系统策略禁止运行(AppLocker / 软件限制策略)",
+ whyWdac: "被 Windows Defender 应用程序控制拦截",
+ whyBadExe: "文件损坏,或不是这台电脑能运行的程序",
+ whyCorrupt: "文件已损坏",
+ whyCantStart: "拉不起来",
+ whyLine: "{why}({detail})",
+ agentCantStart: "代理拉不起它:{reason}",
+ testFailed: "试运行没通过:{error}",
+ noticeInstalled: "已为代理装好 PowerShell {version}(应用内置,不影响你自己的 PowerShell),代理执行命令会快很多。",
+ noticeInstallFailed: "为代理安装 PowerShell 7 没有成功:{error}。代理照常用 Windows PowerShell 5.1 执行命令;可在 设置 → 故障排查 里重试。",
+ noticeSystemTestFailed: "系统里的 PowerShell({path})试运行没通过:{error}。代理改用{to}执行命令。",
+ noticeFellBack: "代理用的 PowerShell 起不来({exe}:{reason}),已自动改用{to},代理空闲时生效。可在 设置 → 故障排查 里重新安装或重新检测。",
+ descSystem51: "系统自带的 Windows PowerShell 5.1",
+ descPrivate7: "应用内置的 PowerShell 7",
+ privTimeout: "{s} 秒内没有跑完",
+ privCantStart: "拉不起来:{error}",
+ privUnexpected: "没有得到预期输出(退出码 {code}){out}",
+ privColon: ":{text}",
+ privRwFailed: "读写临时文件失败",
+ privExtFailed: "拉起外部程序失败",
+ privNot7: "版本是 {v},不是 PowerShell 7",
+ privWrongVersion: "版本是 {v},应为 {want}",
+ privSigTimeout: "Windows PowerShell 3 分钟内没有给出签名结果",
+ privSigFailed: "Windows PowerShell 核对签名失败:{error}",
+ privExitCode: "退出码 {code}",
+ privSigUnreadable: "看不懂签名结果:{out}",
+ privSigCount: "签名结果数目不对",
+ privSigInvalid: "{name} 的签名无效({status})",
+ privNoSig: "无签名",
+ privNotMs: "{name} 不是 Microsoft 签名的({subject})",
+ privUnzipFailed: "解压失败:{error}",
+ privTimedOut: "超时",
+ privOldWindows: "这台电脑的 Windows 版本较旧({release}),PowerShell {version} 需要 Windows 10 1607 / Windows Server 2016 或更新的系统",
+ privStall: "{s} 秒没有收到数据",
+ privDownloadTimeout: "下载超时",
+ privSizeWrong: "文件大小不对({len} 字节,应为 {size})",
+ privTooBig: "文件比预期大(超过 {size} 字节)",
+ privHash: "SHA256 不符({got}…,应为 {want}…)",
+ privWindowsOnly: "只在 Windows 上需要",
+ privNoArch: "这台电脑的处理器架构没有对应的 PowerShell 7 安装包",
+ privFileMissing: "文件 {file} 不见了(可能被杀毒软件删除或隔离)",
+ privSigNotPassed: "签名核对没通过:{error}",
+ privArchUnsupported: "不支持的处理器架构",
+ privInstalling: "正在安装",
+ privBadCopy: "已装的副本用不了({reason}),需要手动重新安装",
+ privAlreadyInstalled: "已经装好",
+ privAutoFailedN: "自动安装已经失败 {n} 次",
+ privAutoBackoff: "上次自动安装失败,稍后再试",
+ privCantInstall: "这台电脑装不了",
+ privMkdir: "建不了安装目录 {dir}:{error}",
+ privOtherInstalling: "另一个 AnyModelBot 一直在安装 PowerShell 7,稍后再试",
+ privOtherWaiting: "另一个 AnyModelBot 正在安装 PowerShell 7,等它装完",
+ privDiscarded: "下载的文件校验失败,已丢弃:{error}",
+ privDownloadFailed: "下载失败({url}):{error}",
+ privExtractedVersion: "解压出来的版本是 {v},应为 {want}",
+ privUnknown: "未知",
+ privMissingAfterExtract: "解压后缺少 {file}(可能被杀毒软件拦下)",
+ privInUse: "旧的副本正在使用,换不下来({error}),请稍后再试",
+ privCantPlace: "放不到安装目录:{error}",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -111,4 +173,66 @@ export const en: Catalog<typeof zh> = {
policyAuto: "installs automatically when 7 is missing",
policyManual: "no automatic install",
privateLine: " app-managed PowerShell {version}{arch} · {state}{inst}{dir} · {policy}{ignore}",
+ whyMissing: "pwsh.exe not found (it may have been deleted or quarantined by antivirus)",
+ whyDenied: "no permission to run it (it may have been blocked by security software)",
+ whyAntivirus: "blocked by antivirus",
+ whyPolicy: "blocked by system policy (AppLocker / software restriction policies)",
+ whyWdac: "blocked by Windows Defender Application Control",
+ whyBadExe: "the file is damaged, or isn't a program this computer can run",
+ whyCorrupt: "the file is corrupted",
+ whyCantStart: "couldn't start",
+ whyLine: "{why} ({detail})",
+ agentCantStart: "the agent couldn't start it: {reason}",
+ testFailed: "test run failed: {error}",
+ noticeInstalled: "PowerShell {version} is installed for the agent (app-managed; your own PowerShell isn't touched). Commands will run much faster.",
+ noticeInstallFailed: "Installing PowerShell 7 for the agent didn't work: {error}. The agent keeps running commands with Windows PowerShell 5.1; you can retry in Settings → Troubleshooting.",
+ noticeSystemTestFailed: "The PowerShell on this system ({path}) failed its test run: {error}. The agent now runs commands with {to}.",
+ noticeFellBack: "The agent's PowerShell wouldn't start ({exe}: {reason}), so it switched to {to} automatically; this takes effect when the agent is idle. You can reinstall or check again in Settings → Troubleshooting.",
+ descSystem51: "the built-in Windows PowerShell 5.1",
+ descPrivate7: "the app-managed PowerShell 7",
+ privTimeout: "didn't finish within {s}s",
+ privCantStart: "couldn't start: {error}",
+ privUnexpected: "unexpected output (exit code {code}){out}",
+ privColon: ": {text}",
+ privRwFailed: "couldn't read and write a temp file",
+ privExtFailed: "couldn't start an external program",
+ privNot7: "version is {v}, not PowerShell 7",
+ privWrongVersion: "version is {v}, expected {want}",
+ privSigTimeout: "Windows PowerShell didn't return a signature result within 3 minutes",
+ privSigFailed: "Windows PowerShell couldn't verify the signature: {error}",
+ privExitCode: "exit code {code}",
+ privSigUnreadable: "couldn't read the signature result: {out}",
+ privSigCount: "wrong number of signature results",
+ privSigInvalid: "{name} has an invalid signature ({status})",
+ privNoSig: "unsigned",
+ privNotMs: "{name} isn't signed by Microsoft ({subject})",
+ privUnzipFailed: "couldn't extract: {error}",
+ privTimedOut: "timed out",
+ privOldWindows: "this computer's Windows is too old ({release}); PowerShell {version} needs Windows 10 1607 / Windows Server 2016 or later",
+ privStall: "no data received for {s}s",
+ privDownloadTimeout: "download timed out",
+ privSizeWrong: "wrong file size ({len} bytes, expected {size})",
+ privTooBig: "the file is larger than expected (over {size} bytes)",
+ privHash: "SHA256 mismatch ({got}…, expected {want}…)",
+ privWindowsOnly: "only needed on Windows",
+ privNoArch: "there's no PowerShell 7 package for this computer's processor architecture",
+ privFileMissing: "the file {file} is gone (it may have been deleted or quarantined by antivirus)",
+ privSigNotPassed: "signature check failed: {error}",
+ privArchUnsupported: "unsupported processor architecture",
+ privInstalling: "installing",
+ privBadCopy: "the installed copy can't be used ({reason}); reinstall it manually",
+ privAlreadyInstalled: "already installed",
+ privAutoFailedN: "automatic install has failed {n} times",
+ privAutoBackoff: "the last automatic install failed; it will try again later",
+ privCantInstall: "it can't be installed on this computer",
+ privMkdir: "couldn't create the install folder {dir}: {error}",
+ privOtherInstalling: "another AnyModelBot has been installing PowerShell 7 for a while; try again later",
+ privOtherWaiting: "another AnyModelBot is installing PowerShell 7; waiting for it to finish",
+ privDiscarded: "the downloaded file failed verification and was discarded: {error}",
+ privDownloadFailed: "download failed ({url}): {error}",
+ privExtractedVersion: "the extracted version is {v}, expected {want}",
+ privUnknown: "unknown",
+ privMissingAfterExtract: "{file} is missing after extraction (antivirus may have blocked it)",
+ privInUse: "the old copy is in use and can't be replaced ({error}); try again later",
+ privCantPlace: "couldn't move it into the install folder: {error}",
};
diff --git a/src/i18n/messages/web.ts b/src/i18n/messages/web.ts
index 6d3c392..b4c1f27 100644
--- a/src/i18n/messages/web.ts
+++ b/src/i18n/messages/web.ts
@@ -25,6 +25,17 @@ export const zh = {
budgetRange: "预算要在 0 到 100000 美元之间",
groupNotOwned: "群不属于该机器人",
emptyText: "内容为空",
+ alreadyHandled: "已经处理过了",
+ unsupportedAction: "不支持这个操作",
+ couldntComplete: "没能完成,可能已经处理过了",
+ taskNotFound: "任务不存在",
+ runNotFound: "没有这次运行",
+ taskAlreadyStopped: "任务已经停止了",
+ windowsOnly: "只在 Windows 上需要",
+ recordNotFound: "记录不存在",
+ requestAlreadyHandled: "这个请求已经处理过了",
+ noSuchChannel: "没有这个渠道",
+ weixinOwnerRescan: "微信主人要重新扫码才能更换",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -51,4 +62,15 @@ export const en: Catalog<typeof zh> = {
budgetRange: "The budget must be between $0 and $100,000",
groupNotOwned: "This group doesn't belong to this bot",
emptyText: "Message is empty",
+ alreadyHandled: "Already handled",
+ unsupportedAction: "This action isn't supported",
+ couldntComplete: "Couldn't complete it; it may already have been handled",
+ taskNotFound: "Task not found",
+ runNotFound: "Run not found",
+ taskAlreadyStopped: "The task has already stopped",
+ windowsOnly: "Only needed on Windows",
+ recordNotFound: "Record not found",
+ requestAlreadyHandled: "This request has already been handled",
+ noSuchChannel: "No such channel",
+ weixinOwnerRescan: "To change the WeChat owner, scan the QR code again",
};
diff --git a/src/web/server.ts b/src/web/server.ts
index c8cbffb..57344b3 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -23,7 +23,7 @@ import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";
import { peerName, shortPeer, whoText } from "../core/access.js";
import type { AccessEntry } from "../store/db.js";
import { GUIDE_STEPS, deriveGuide, isGuideStep, mergeGuide, normalizeGuide, type GuideState } from "../guide.js";
-import { normalizeLang, requestLang, setLangPref, t, type LangPref } from "../i18n/index.js";
+import { normalizeLang, requestLang, setLangPref, t, type LangPref, t as tr } from "../i18n/index.js";
const log = logger("web");
const require = createRequire(import.meta.url);
@@ -458,8 +458,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
const action = seg[2] ?? "";
if (seg.length !== 3 || m !== "POST") throw new HttpError(404, "not found");
const item = app.attention.list().find((x) => x.id === id);
- if (!item) throw new HttpError(409, "已经处理过了");
- if (!(item.actions as string[]).includes(action)) throw new HttpError(400, "不支持这个操作");
+ if (!item) throw new HttpError(409, tr("web.alreadyHandled"));
+ if (!(item.actions as string[]).includes(action)) throw new HttpError(400, tr("web.unsupportedAction"));
const b = await readJson(req);
let ok = false;
if (action === "approve" || action === "deny") ok = app.agent.approvals.decide(item.approvalId!, action === "approve", "web");
@@ -470,7 +470,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
} else if (item.kind === "delivery" && (action === "retry" || action === "dismiss")) ok = app.delivery.act(item.id, action);
else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;
else if (action === "stop") ok = await app.tasks.stopTask(item.taskId!, "web");
- if (!ok) throw new HttpError(409, "没能完成,可能已经处理过了");
+ if (!ok) throw new HttpError(409, tr("web.couldntComplete"));
app.attention.kick();
return send(res, 200, { ok: true, items: app.attention.list() });
}
@@ -488,19 +488,19 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
});
}
const task = seg[1] ? app.tasks.get(decodeURIComponent(seg[1])) : undefined;
- if (!task) throw new HttpError(404, "任务不存在");
+ if (!task) throw new HttpError(404, tr("web.taskNotFound"));
if (seg.length === 2 && m === "GET") {
const runs = app.store.listRuns({ taskId: task.id }).map((r) => ({ id: r.id, cause: r.cause, state: r.state, outcome: r.outcome, error: r.error, queuedAt: r.queuedAt, startedAt: r.startedAt, endedAt: r.endedAt, steps: app.tasks.activity(r.id).length }));
return send(res, 200, { task, runs });
}
if (seg.length === 5 && seg[2] === "runs" && seg[4] === "activity" && m === "GET") {
const run = app.store.getRun(decodeURIComponent(seg[3]));
- if (!run || run.taskId !== task.id) throw new HttpError(404, "没有这次运行");
+ if (!run || run.taskId !== task.id) throw new HttpError(404, tr("web.runNotFound"));
return send(res, 200, { steps: app.tasks.activity(run.id) });
}
if (seg.length === 3 && seg[2] === "stop" && m === "POST") {
const ok = await app.tasks.stopTask(task.id, "web");
- if (!ok) throw new HttpError(409, "任务已经停止了");
+ if (!ok) throw new HttpError(409, tr("web.taskAlreadyStopped"));
return send(res, 200, { task: app.tasks.get(task.id) });
}
throw new HttpError(404, "not found");
@@ -524,7 +524,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
// 安装 / 重新安装应用内置的 PowerShell 7:后台进行,进度从 GET 读
if (seg[1] === "install" && m === "POST") {
- if (process.platform !== "win32" || !pwshProbe.applicable) throw new HttpError(400, "只在 Windows 上需要");
+ if (process.platform !== "win32" || !pwshProbe.applicable) throw new HttpError(400, tr("web.windowsOnly"));
const b = await readJson(req);
setMode("auto");
await pwshProbe.check();
@@ -769,24 +769,24 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
if (seg[2] === "access" && seg.length === 5 && m === "POST") {
const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
- if (!entry || entry.botId !== id) throw new HttpError(404, "记录不存在");
+ if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
if (seg[4] === "approve" || seg[4] === "deny") {
const r = app.access.decide(entry.id, seg[4] === "approve", "web");
- if (!r) throw new HttpError(409, "这个请求已经处理过了");
+ if (!r) throw new HttpError(409, tr("web.requestAlreadyHandled"));
return send(res, 200, { entry: publicAccess(r) });
}
}
// 更换主人:清掉"第一个发消息"的主人,下一个发单聊消息的人成为主人(扫码登录的微信要重新扫码)
if (seg[2] === "access" && seg[3] === "owner" && seg.length === 5 && m === "DELETE") {
const ch = seg[4];
- if (ch !== "weixin" && ch !== "feishu") throw new HttpError(404, "没有这个渠道");
- if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, "微信主人要重新扫码才能更换");
+ if (ch !== "weixin" && ch !== "feishu") throw new HttpError(404, tr("web.noSuchChannel"));
+ if (app.access.owner(id, ch)?.via === "login") throw new HttpError(409, tr("web.weixinOwnerRescan"));
app.access.resetOwner(id, ch);
return send(res, 200, { ok: true });
}
if (seg[2] === "access" && seg.length === 4 && m === "DELETE") {
const entry = app.store.getAccessById(decodeURIComponent(seg[3]));
- if (!entry || entry.botId !== id) throw new HttpError(404, "记录不存在");
+ if (!entry || entry.botId !== id) throw new HttpError(404, tr("web.recordNotFound"));
app.access.remove(entry.id);
return send(res, 200, { ok: true });
}
diff --git a/test/outbox.unit.test.ts b/test/outbox.unit.test.ts
index 7c93007..ec2baa1 100644
--- a/test/outbox.unit.test.ts
+++ b/test/outbox.unit.test.ts
@@ -9,7 +9,7 @@ import os from "node:os";
import path from "node:path";
import { Store, type OutboxRow } from "../src/store/db.js";
import { Gone, HOLD_TTL_MS, Held, Later, OUTBOX_TTL_MS, Outbox, REJECTIONS_BEFORE_GONE, stableId } from "../src/core/outbox.js";
-import { AWAY_PREFIX, combineHeld, deliverWeixin } from "../src/channels/weixin/channel.js";
+import { awayPrefix, combineHeld, deliverWeixin } from "../src/channels/weixin/channel.js";
import { WeixinQuota } from "../src/channels/weixin/quota.js";
import { deliverFeishu } from "../src/channels/feishu/card.js";
import { FakeFeishu, until } from "./helpers.js";
@@ -114,7 +114,7 @@ describe("Outbox", () => {
await ob.send(input("reply", "这次的回复"));
await ob.idle();
// 普通回复先按微信的规则过滤 Markdown(图片去掉),审批提示原样
- expect(sent).toEqual([`${AWAY_PREFIX}\n**结果**:A 云最便宜\n\n需批准:\`rm -rf build/\``, "[file 报告.md]", `${AWAY_PREFIX}第四条`, "这次的回复"]);
+ expect(sent).toEqual([`${awayPrefix()}\n**结果**:A 云最便宜\n\n需批准:\`rm -rf build/\``, "[file 报告.md]", `${awayPrefix()}第四条`, "这次的回复"]);
expect(["h1", "h2", "h3", "h4"].map((id) => store.getOutbox(id)!.status)).toEqual(["sent", "merged", "sent", "sent"]);
expect(store.getOutbox("other")!.status).toBe("held");
// 只发一次:再放一次、同一 id 再写一遍都不会重发
@@ -147,11 +147,11 @@ describe("Outbox", () => {
expect(ob.release("b", "weixin", "u1", combineHeld)).toBe(1);
await ob.idle();
expect(store.getOutbox("ack")).toMatchObject({ status: "gone", error: expect.stringMatching(/等待太久/) });
- expect(store.getOutbox("final")).toMatchObject({ status: "held", body: { text: `${AWAY_PREFIX}结果`, away: true } });
+ expect(store.getOutbox("final")).toMatchObject({ status: "held", body: { text: `${awayPrefix()}结果`, away: true } });
open = true;
ob.release("b", "weixin", "u1", combineHeld);
await ob.idle();
- expect(sent).toEqual([`${AWAY_PREFIX}结果`]);
+ expect(sent).toEqual([`${awayPrefix()}结果`]);
});
it("waits for the channel to register; expired messages are marked gone and the next one goes", async () => {