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): 服务端剩余文案(一):处理过程的步骤、/stop 与 /tasks 的回复、状态与失败原因、后台任务阶段

dyk98549a40e60c1e
diff --git a/src/agent/activity.ts b/src/agent/activity.ts
index 3ec957b..39dc4ce 100644
--- a/src/agent/activity.ts
+++ b/src/agent/activity.ts
@@ -3,6 +3,7 @@
* 网页对话里折叠在"用时"下面,微信/飞书会话在信息面板里看;/status 和看门狗用它说明卡在哪一步。
*/
import { summarizeCall } from "./host.js";
+import { t as tr } from "../i18n/index.js";
export interface ActivityStep {
/** 同一步的更新沿用同一个 id(工具调用 id、m<回合>.<步>…) */
@@ -33,7 +34,7 @@ const oneLine = (s: string, n = 140) => clip(s.replace(/\s+/g, " ").trim(), n);
function textOf(content: unknown): string {
if (!Array.isArray(content)) return typeof content === "string" ? content : "";
return content
- .map((b: any) => (b?.type === "text" ? String(b.text ?? "") : b?.type === "image" ? "[图片]" : ""))
+ .map((b: any) => (b?.type === "text" ? String(b.text ?? "") : b?.type === "image" ? tr("activity.image") : ""))
.filter(Boolean)
.join("\n");
}
@@ -88,7 +89,7 @@ export class ActivityLog {
return true;
}
case "step/start":
- this.put({ id: `m${data.turn}.${data.step}`, kind: "model", title: this.model || "模型", status: "running", at: time });
+ this.put({ id: `m${data.turn}.${data.step}`, kind: "model", title: this.model || tr("activity.model"), status: "running", at: time });
return true;
case "assistant/message": {
const msg = data.message ?? {};
@@ -105,9 +106,9 @@ export class ActivityLog {
this.put({
id,
kind: "model",
- title: model || "模型",
- summary: text ? oneLine(text) : calls.length ? `调用 ${calls.join("、")}` : thinking ? "(只有思考,没有文字)" : "(空回复)",
- output: clip([thinking && `[思考]\n${thinking}`, text].filter(Boolean).join("\n\n"), MAX_OUTPUT) || undefined,
+ title: model || tr("activity.model"),
+ summary: text ? oneLine(text) : calls.length ? tr("activity.calls", { list: calls.join(tr("activity.listSep")) }) : thinking ? tr("activity.thinkingOnly") : tr("activity.emptyReply"),
+ output: clip([thinking && `${tr("activity.thinkingTag")}\n${thinking}`, text].filter(Boolean).join("\n\n"), MAX_OUTPUT) || undefined,
status: "ok",
at,
ms: Math.max(0, time - at),
@@ -137,7 +138,7 @@ export class ActivityLog {
this.put({ ...prev, status: msg.isError ? "error" : "ok", ms: Math.max(0, time - prev.at), output: clip(textOf(msg.content), MAX_OUTPUT) || undefined });
// 命令跑得太久,转到了后台:单独记一步,结束时(job/settled 或结束通知)更新
const job = promotedJob(data);
- if (job) this.put({ id: `j:${job}`, kind: "job", title: "后台命令", summary: prev.summary, input: prev.input, status: "running", at: time });
+ if (job) this.put({ id: `j:${job}`, kind: "job", title: tr("activity.job"), summary: prev.summary, input: prev.input, status: "running", at: time });
return true;
}
case "job/settled": {
@@ -153,22 +154,22 @@ export class ActivityLog {
if (!n) return true;
const prev = this.find(`j:${n.id}`);
if (prev?.status === "running") this.put({ ...prev, status: "ok", ms: Math.max(0, time - prev.at) });
- else if (!prev) this.put({ id: `j:${n.id}`, kind: "job", title: "后台命令结束", summary: oneLine(n.summary) || undefined, status: "ok", at: time });
+ else if (!prev) this.put({ id: `j:${n.id}`, kind: "job", title: tr("activity.jobDone"), summary: oneLine(n.summary) || undefined, status: "ok", at: time });
return true;
}
case "steer":
// 宿主发的:用户在回合进行中又发了一条,并进了这一轮
- this.put({ id: `u${time}`, kind: "steer", title: "追加消息", summary: oneLine(String(data.text ?? "")), status: "ok", at: time });
+ this.put({ id: `u${time}`, kind: "steer", title: tr("activity.steer"), summary: oneLine(String(data.text ?? "")), status: "ok", at: time });
return true;
case "llm/retry": {
const f = data.failure ?? {};
- const why = String(f.message ?? f.code ?? "请求失败");
+ const why = String(f.message ?? f.code ?? tr("activity.requestFailed"));
const of = data.maxRetries ? `${data.retry}/${data.maxRetries}` : String(data.retry ?? "");
this.put({
id: `r${data.retryId ?? data.turn}.${data.retry}`,
kind: "retry",
- title: "模型请求失败,重试",
- summary: oneLine(`第 ${of} 次,${Math.round((Number(data.delayMs) || 0) / 1000)} 秒后:${why}`),
+ title: tr("activity.retryTitle"),
+ summary: oneLine(tr("activity.retrySummary", { n: of, s: Math.round((Number(data.delayMs) || 0) / 1000), why })),
status: "error",
at: time,
});
@@ -178,10 +179,10 @@ export class ActivityLog {
return false;
case "api/fallback":
// 宿主发的:上游不接受这个接口上的请求,换 Chat Completions 重做这一轮
- this.put({ id: `f${time}`, kind: "retry", title: "改用 Chat Completions 重试", summary: oneLine(`${data.from ?? ""} 被拒:${data.reason ?? ""}`), status: "ok", at: time });
+ this.put({ id: `f${time}`, kind: "retry", title: tr("activity.fallbackTitle"), summary: oneLine(tr("activity.fallbackSummary", { from: String(data.from ?? ""), reason: String(data.reason ?? "") })), status: "ok", at: time });
return true;
case "compaction/start":
- this.put({ id: `c${time}`, kind: "compact", title: "压缩上下文", status: "running", at: time });
+ this.put({ id: `c${time}`, kind: "compact", title: tr("activity.compact"), status: "running", at: time });
return true;
case "compaction/end": {
const prev = this.steps.findLast((s) => s.kind === "compact" && s.status === "running");
@@ -191,11 +192,11 @@ export class ActivityLog {
// bridge 在后台让上游压缩了这个会话的历史(不是 DSH 事件,见 server-compaction.ts);不算代理有进展
case "server-compaction": {
const k = (n: unknown) => `${Math.round((Number(n) || 0) / 1000)}k`;
- this.put({ id: `sc${time}`, kind: "compact", title: "服务端压缩上下文", summary: `约 ${k(data.before)} → ${k(data.after)} tokens`, status: "ok", at: time, ms: Number(data.ms) || undefined });
+ this.put({ id: `sc${time}`, kind: "compact", title: tr("activity.serverCompact"), summary: tr("activity.compactSummary", { before: k(data.before), after: k(data.after) }), status: "ok", at: time, ms: Number(data.ms) || undefined });
return false;
}
case "subagent/started":
- this.put({ id: `s${data.childSessionId}`, kind: "subagent", title: "子代理", status: "running", at: time });
+ this.put({ id: `s${data.childSessionId}`, kind: "subagent", title: tr("activity.subagent"), status: "running", at: time });
return true;
case "subagent/finished": {
const prev = this.find(`s${data.childSessionId}`);
@@ -203,7 +204,7 @@ export class ActivityLog {
this.put({
id: `s${data.childSessionId}`,
kind: "subagent",
- title: "子代理",
+ title: tr("activity.subagent"),
summary: last ? oneLine(last) : String(data.stopReason ?? "") || undefined,
output: last ? clip(last, MAX_OUTPUT) : undefined,
status: data.status === "ok" ? "ok" : "error",
@@ -217,7 +218,7 @@ export class ActivityLog {
if (r.kind === "error") {
// 还挂着的步骤(模型请求、工具)跟着这个错误结束
for (const s of this.steps) if (s.status === "running") this.put({ ...s, status: "error", cut: true, ms: Math.max(0, time - s.at) });
- this.put({ id: `e${data.turn}`, kind: "error", title: "回合出错", summary: oneLine(String(r.error?.message ?? "unknown error"), 300), status: "error", at: time });
+ this.put({ id: `e${data.turn}`, kind: "error", title: tr("activity.turnError"), summary: oneLine(String(r.error?.message ?? "unknown error"), 300), status: "error", at: time });
}
return true;
}
@@ -228,13 +229,13 @@ export class ActivityLog {
/** 回合正常结束:还在后台跑的命令不算失败,注明回复时它仍在运行(结束后代理会被唤醒,另发一条回复) */
finish(time = Date.now()): void {
- for (const s of this.steps) if (s.kind === "job" && s.status === "running") this.put({ ...s, status: "ok", summary: [s.summary, "(回复时仍在后台运行)"].filter(Boolean).join(" "), ms: Math.max(0, time - s.at) });
+ for (const s of this.steps) if (s.kind === "job" && s.status === "running") this.put({ ...s, status: "ok", summary: [s.summary, tr("activity.stillRunning")].filter(Boolean).join(" "), ms: Math.max(0, time - s.at) });
}
/** 外部原因结束(/stop、看门狗、超时):还在进行的步骤标成失败,再记一条说明 */
end(why: string, time = Date.now()): void {
for (const s of this.steps) if (s.status === "running") this.put({ ...s, status: "error", cut: true, ms: Math.max(0, time - s.at) });
- this.put({ id: `x${time}`, kind: "error", title: "已中止", summary: why, status: "error", at: time });
+ this.put({ id: `x${time}`, kind: "error", title: tr("activity.stopped"), summary: why, status: "error", at: time });
}
private find(id: string): ActivityStep | undefined {
@@ -259,19 +260,19 @@ export function describeStep(s: ActivityStep): string {
const doing = s.status === "running" || !!s.cut;
switch (s.kind) {
case "model":
- return doing ? `等待 ${s.title} 回复` : `${s.title} 回复了${s.summary ? `:${s.summary}` : ""}`;
+ return doing ? tr("activity.descWaiting", { model: s.title }) : tr("activity.descReplied", { model: s.title, summary: s.summary ? tr("activity.withSummary", { text: s.summary }) : "" });
case "tool":
- return doing ? `正在运行 ${what}` : `${what}(${s.status === "error" ? "失败" : "完成"})`;
+ return doing ? tr("activity.descRunning", { what }) : tr(s.status === "error" ? "activity.descFailed" : "activity.descDone", { what });
case "retry":
- return `模型请求失败,正在重试(${s.summary ?? ""})`;
+ return tr("activity.descRetry", { summary: s.summary ?? "" });
case "subagent":
- return doing ? "子代理在工作" : `子代理结束${s.summary ? `:${s.summary}` : ""}`;
+ return doing ? tr("activity.descSubagent") : tr("activity.descSubagentDone", { summary: s.summary ? tr("activity.withSummary", { text: s.summary }) : "" });
case "compact":
- return doing ? "正在压缩上下文" : "压缩了上下文";
+ return tr(doing ? "activity.descCompacting" : "activity.descCompacted");
case "job":
- return doing ? `后台命令在运行${s.summary ? `:${s.summary}` : ""}` : `${s.title}${s.summary ? `:${s.summary}` : ""}`;
+ return doing ? tr("activity.descJob", { summary: s.summary ? tr("activity.withSummary", { text: s.summary }) : "" }) : `${s.title}${s.summary ? tr("activity.withSummary", { text: s.summary }) : ""}`;
case "steer":
- return `收到追加消息${s.summary ? `:${s.summary}` : ""}`;
+ return tr("activity.descSteer", { summary: s.summary ? tr("activity.withSummary", { text: s.summary }) : "" });
case "error":
return what;
}
@@ -280,5 +281,5 @@ export function describeStep(s: ActivityStep): string {
/** "12 秒" / "3 分 5 秒" */
export function fmtSecs(ms: number): string {
const s = Math.max(0, Math.round(ms / 1000));
- return s < 60 ? `${s} 秒` : `${Math.floor(s / 60)} 分${s % 60 ? ` ${s % 60} 秒` : "钟"}`;
+ return s < 60 ? tr("activity.secs", { s }) : s % 60 ? tr("activity.minSecs", { m: Math.floor(s / 60), s: s % 60 }) : tr("activity.mins", { m: Math.floor(s / 60) });
}
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 4c15e6e..24b5375 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -82,7 +82,7 @@ export function storeInbound(workspace: string, ev: InboundEvent, now = new Date
p.path = `inbox/${name}`;
} catch (e) {
log.warn("save inbound media failed", { type: p.type, message: (e as Error).message.slice(0, 200) });
- p.error = "保存到工作区失败";
+ p.error = t("runtime.saveFailed");
}
}
}
@@ -127,10 +127,11 @@ interface Inflight {
}
/** 回合还没交给代理(或纯对话还没出字)就被停止时的回复 */
-export const stoppedText = (ms: number) => `已中止(处理了 ${fmtSecs(ms)})。`;
+export const stoppedText = (ms: number) => t("runtime.stopped", { d: fmtSecs(ms) });
/** 新消息并进了正在进行的代理回合:先回这一句,回复在那一轮结束时一起给 */
-export const STEER_ACK = "收到,这条会并入正在进行的处理,稍后一起回复。";
+/** 处理中又发来一句、并进正在进行的回合时回的那句(按当前语言) */
+export const steerAck = () => t("runtime.steerAck");
/**
* 不是回复某条消息、而是主动发到会话里(代理自己醒来的一轮:后台命令结束):渠道给出这个会话的出站会话。
@@ -394,7 +395,7 @@ export class BotRuntime {
const err = e as Error & { status?: number };
if (signal.aborted) {
// 停止:已生成的部分保留,末尾注明;还没出字就只说已中止
- const msg = acc ? `${acc}\n\n(已中止)` : stoppedText(Date.now() - run.since);
+ const msg = acc ? `${acc}\n\n${t("runtime.stoppedMark")}` : stoppedText(Date.now() - run.since);
store.addMessage(conv.id, "assistant", msg);
await out.apply({ type: "stream.finish", text: msg });
return;
@@ -429,19 +430,19 @@ export class BotRuntime {
const agent = this.opts.agent;
const tasks = agent?.tasks;
// 后台任务:/tasks 列出,/stop 编号 停止一个(只读本地状态、不碰聊天回合,不进会话队列)
- if (cmd === "/tasks") return { handled: true, ack: tasks ? tasks.listText(convId) : "后台任务只在代理模式下可用。" };
+ if (cmd === "/tasks") return { handled: true, ack: tasks ? tasks.listText(convId) : t("runtime.tasksAgentOnly") };
const stopTask = /^\/stop\s+(\d{1,2})$/.exec(cmd);
- if (stopTask) return { handled: true, ack: tasks ? tasks.stopByIndex(convId, Number(stopTask[1]), `${ev.channel}:${ev.sender.id}`) : "后台任务只在代理模式下可用。" };
+ if (stopTask) return { handled: true, ack: tasks ? tasks.stopByIndex(convId, Number(stopTask[1]), `${ev.channel}:${ev.sender.id}`) : t("runtime.tasksAgentOnly") };
// /stop 必须插队:它要停的正是排在前面、卡住的那个回合(纯对话、代理还在启动时也算)
if (cmd === "/stop") {
const since = this.busySince(convId) ?? agent?.turnsInProgress.get(convId)?.since;
if (since === undefined || !this.stop(convId)) {
// 没有在处理的消息,但有后台任务在跑:说一声怎么停它(/stop 不停后台任务)
const working = tasks?.working(convId) ?? [];
- const hint = working.length ? `\n后台任务在进行:${working.map((t, i) => `${i + 1}. ${t.title}`).join(";")}。发 /stop 编号 可停止。` : "";
- return { handled: true, ack: `当前没有正在处理的消息。${hint}` };
+ const hint = working.length ? t("runtime.stopHint", { list: working.map((x, i) => `${i + 1}. ${x.title}`).join(t("runtime.listSepStrong")) }) : "";
+ return { handled: true, ack: t("runtime.nothingToStop", { hint }) };
}
- return { handled: true, ack: `正在中止上一条消息(已处理 ${fmtSecs(Date.now() - since)})…` };
+ return { handled: true, ack: t("runtime.stoppingPrev", { d: fmtSecs(Date.now() - since) }) };
}
if (!agent) return { handled: false };
// 审批、提问的回复;后台任务的只认引用、编号开头,或它是机器人最后一条消息时的选项编号(见 ApprovalCenter.handleReply)
@@ -449,11 +450,11 @@ export class BotRuntime {
const r = agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`, { ...tasks?.replyContext(convId), ...(quote ? { quote, plain } : {}) });
if (r.handled) return r;
// 前一条还在处理:能并入进行中的代理回合时由 handle 并入并回一句;不能时说一声这条排在后面、怎么中止(每个回合只说一次),消息照常入队
- const t = agent.turnsInProgress.get(convId);
- if (t && !t.queuedNotice && !agent.canSteer(convId)) {
- t.queuedNotice = true;
- const last = t.activity.last;
- return { handled: false, ack: `上一条消息还在处理(已 ${fmtSecs(Date.now() - t.since)}${last ? `,现在:${clipLine(describeStep(last))}` : ""}),这条会排在它后面。发送 /stop 可以中止。` };
+ const cur = agent.turnsInProgress.get(convId);
+ if (cur && !cur.queuedNotice && !agent.canSteer(convId)) {
+ cur.queuedNotice = true;
+ const last = cur.activity.last;
+ return { handled: false, ack: t("runtime.queuedBehind", { d: fmtSecs(Date.now() - cur.since), now: last ? t("runtime.nowDoing", { step: clipLine(describeStep(last)) }) : "" }) };
}
return r;
}
@@ -690,7 +691,7 @@ export class BotRuntime {
t.userStored = true;
t.steered = true;
t.release?.();
- await out.apply({ type: "text", text: STEER_ACK, ack: true });
+ await out.apply({ type: "text", text: steerAck(), ack: true });
return true;
}
@@ -715,15 +716,15 @@ export class BotRuntime {
const r = (this.repliers.get(`${botId}:${conv.channel}`) ?? this.repliers.get(`*:${conv.channel}`))?.(conv, handle, `wake:${wakeId}`);
if (!r) log.warn("no way to reply in this conversation; the wake-up reply is only kept in its history", { bot: botId, conversationId: convId, channel: conv.channel });
const out: ReplySession = r?.out ?? { apply: async () => undefined };
- const t: Inflight = { botId, since: Date.now(), abort: new AbortController(), userStored: true };
- const done = this.enter(convId, t);
+ const fl: Inflight = { botId, since: Date.now(), abort: new AbortController(), userStored: true };
+ const done = this.enter(convId, fl);
// 重启标记:这一轮没做完应用就退出或崩溃了,下次启动告诉用户(说的是让命令跑起来的那条消息)
const asked = store.listMessages(convId, 20).filter((m) => m.role === "user").at(-1)?.content;
- markInflight(store, convId, asked || "后台命令的结果");
+ markInflight(store, convId, asked || t("runtime.jobResult"));
const steps = new Map<string, ActivityStep>();
const unbind = agent.approvals.bindSink(convId, async (row) => void (await out.apply(interactiveOp(row))));
const halt = () => agent.stopTurn(convId);
- t.abort.signal.addEventListener("abort", halt, { once: true });
+ fl.abort.signal.addEventListener("abort", halt, { once: true });
try {
const model = conv.model || bot.defaultModel || this.opts.defaultModel();
const routed = model && this.opts.route ? this.opts.route(botId, model) : model;
@@ -742,16 +743,16 @@ export class BotRuntime {
} catch (e) {
// 应用正在退出时代理进程被关掉:不回复,重启标记留着
if (this.closing) {
- t.interrupted = true;
+ fl.interrupted = true;
return;
}
const msg = turnFailedText(e as Error, [...steps.values()]);
store.addMessage(convId, "assistant", msg, [...steps.values()]);
await out.apply({ type: "stream.finish", text: msg });
- this.answered(convId, t);
+ this.answered(convId, fl);
return;
}
- const finalText = res.text.trim() || "(后台任务已结束,没有文字回复)";
+ const finalText = res.text.trim() || t("runtime.jobDoneNoText");
store.addMessage(convId, "assistant", finalText, [...steps.values()]);
await out.apply({ type: "stream.finish", text: finalText });
for (const f of res.files ?? []) {
@@ -761,13 +762,13 @@ export class BotRuntime {
log.warn("deliver file failed", { name: path.basename(f), message: (e as Error).message.slice(0, 200) });
}
}
- this.answered(convId, t);
+ this.answered(convId, fl);
} finally {
- t.abort.signal.removeEventListener("abort", halt);
+ fl.abort.signal.removeEventListener("abort", halt);
unbind();
await out.apply({ type: "typing", on: false }).catch(() => undefined);
done.leave();
- if (!this.inflight.get(convId)?.size && !t.interrupted) {
+ if (!this.inflight.get(convId)?.size && !fl.interrupted) {
try {
clearInflight(store, convId);
} catch {
@@ -866,25 +867,25 @@ const clipLine = (s: string, n = 80) => (s.length > n ? s.slice(0, n - 1) + "…
export function busyLine(since: number, lastProgress: number, steps: ActivityStep[], steer = false): string {
const now = Date.now();
const last = steps.at(-1);
- const parts = [`已 ${fmtSecs(now - since)}`];
- if (steps.length) parts.push(`${steps.length} 步`);
- if (!lastProgress) parts.push("还在等代理进程接手");
- else if (last) parts.push(`现在:${clipLine(describeStep(last))}`);
- if (lastProgress && now - lastProgress >= 60_000) parts.push(`${fmtSecs(now - lastProgress)}没有新进展`);
- return `本会话上一条消息还在处理(${parts.join(",")}),${steer ? "新消息会并入正在进行的处理" : "新消息会排在它后面"}。发送 /stop 可以中止`;
+ const parts = [t("runtime.busyFor", { d: fmtSecs(now - since) })];
+ if (steps.length) parts.push(t("runtime.busySteps", { count: steps.length }));
+ if (!lastProgress) parts.push(t("runtime.busyWaitingAgent"));
+ else if (last) parts.push(t("runtime.busyNow", { step: clipLine(describeStep(last)) }));
+ if (lastProgress && now - lastProgress >= 60_000) parts.push(t("runtime.busyIdle", { d: fmtSecs(now - lastProgress) }));
+ return t(steer ? "runtime.busySteer" : "runtime.busyQueue", { parts: parts.join(t("runtime.listSep")) });
}
/** 代理回合失败时给用户的话:中止(/stop、没进展、超时)各说清原因和下一步,进程被重启的另说 */
export function turnFailedText(err: Error, steps: ActivityStep[]): string {
const last = steps.filter((s) => s.kind !== "error").at(-1);
- const where = last ? `${last.cut || last.status === "running" ? "卡在" : "最后一步"}:${clipLine(describeStep(last))}。` : "";
+ const where = last ? t(last.cut || last.status === "running" ? "runtime.stuckAt" : "runtime.lastStep", { step: clipLine(describeStep(last)) }) : "";
if (err instanceof TurnStopped) {
// 只中止了这个会话;宽限期内没停下才重启了代理进程(同一机器人的其它会话也被打断)
- const restart = err.restarted ? "并重启代理进程" : "";
- if (err.reason === "user") return `已中止(处理了 ${fmtSecs(err.ms)})。${err.restarted ? "代理进程已重启," : ""}可以继续发消息。`;
- if (err.reason === "idle") return `⚠️ 代理 ${fmtSecs(err.ms)}没有任何进展,已自动中止${restart}。${where}可以重新发送,或用 /model 换个模型试试。`;
- return `⚠️ 这条消息处理超过了 ${fmtSecs(err.ms)}的上限,已中止${restart}。${where}可以把任务拆小一点再发。`;
+ const restart = err.restarted ? t("runtime.andRestarted") : "";
+ if (err.reason === "user") return t("runtime.stoppedByUser", { d: fmtSecs(err.ms), restarted: err.restarted ? t("runtime.restartedNote") : "" });
+ if (err.reason === "idle") return t("runtime.stoppedIdle", { d: fmtSecs(err.ms), restart, where });
+ return t("runtime.stoppedLimit", { d: fmtSecs(err.ms), restart, where });
}
- if (/runtime (closed|exited)/i.test(err.message)) return "⚠️ 代理进程重启了(可能是同一机器人的另一个会话中止了卡住的消息),这条消息没有处理完,请重新发送。";
- return `⚠️ 代理执行失败:${err.message.slice(0, 300)}`;
+ if (/runtime (closed|exited)/i.test(err.message)) return t("runtime.runtimeRestarted");
+ return t("runtime.agentFailed", { error: err.message.slice(0, 300) });
}
diff --git a/src/i18n/messages/activity.ts b/src/i18n/messages/activity.ts
new file mode 100644
index 0000000..a0bc3c3
--- /dev/null
+++ b/src/i18n/messages/activity.ts
@@ -0,0 +1,84 @@
+// activity:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
+import type { Catalog } from "../types.js";
+
+export const zh = {
+ image: "[图片]",
+ model: "模型",
+ calls: "调用 {list}",
+ listSep: "、",
+ thinkingOnly: "(只有思考,没有文字)",
+ emptyReply: "(空回复)",
+ thinkingTag: "[思考]",
+ job: "后台命令",
+ jobDone: "后台命令结束",
+ steer: "追加消息",
+ requestFailed: "请求失败",
+ retryTitle: "模型请求失败,重试",
+ retrySummary: "第 {n} 次,{s} 秒后:{why}",
+ fallbackTitle: "改用 Chat Completions 重试",
+ fallbackSummary: "{from} 被拒:{reason}",
+ compact: "压缩上下文",
+ serverCompact: "服务端压缩上下文",
+ compactSummary: "约 {before} → {after} tokens",
+ subagent: "子代理",
+ turnError: "回合出错",
+ stillRunning: "(回复时仍在后台运行)",
+ stopped: "已中止",
+ withSummary: ":{text}",
+ descWaiting: "等待 {model} 回复",
+ descReplied: "{model} 回复了{summary}",
+ descRunning: "正在运行 {what}",
+ descFailed: "{what}(失败)",
+ descDone: "{what}(完成)",
+ descRetry: "模型请求失败,正在重试({summary})",
+ descSubagent: "子代理在工作",
+ descSubagentDone: "子代理结束{summary}",
+ descCompacting: "正在压缩上下文",
+ descCompacted: "压缩了上下文",
+ descJob: "后台命令在运行{summary}",
+ descSteer: "收到追加消息{summary}",
+ secs: "{s} 秒",
+ minSecs: "{m} 分 {s} 秒",
+ mins: "{m} 分钟",
+} satisfies Catalog;
+
+export const en: Catalog<typeof zh> = {
+ image: "[image]",
+ model: "model",
+ calls: "calls {list}",
+ listSep: ", ",
+ thinkingOnly: "(thinking only, no text)",
+ emptyReply: "(empty reply)",
+ thinkingTag: "[thinking]",
+ job: "Background command",
+ jobDone: "Background command finished",
+ steer: "Follow-up message",
+ requestFailed: "request failed",
+ retryTitle: "Model request failed, retrying",
+ retrySummary: "attempt {n}, in {s}s: {why}",
+ fallbackTitle: "Retrying with Chat Completions",
+ fallbackSummary: "{from} was rejected: {reason}",
+ compact: "Compacting context",
+ serverCompact: "Server-side context compaction",
+ compactSummary: "about {before} → {after} tokens",
+ subagent: "Sub-agent",
+ turnError: "Turn failed",
+ stillRunning: "(still running in the background when the reply was sent)",
+ stopped: "Stopped",
+ withSummary: ": {text}",
+ descWaiting: "waiting for {model}",
+ descReplied: "{model} replied{summary}",
+ descRunning: "running {what}",
+ descFailed: "{what} (failed)",
+ descDone: "{what} (done)",
+ descRetry: "model request failed, retrying ({summary})",
+ descSubagent: "a sub-agent is working",
+ descSubagentDone: "sub-agent finished{summary}",
+ descCompacting: "compacting the context",
+ descCompacted: "compacted the context",
+ descJob: "background command running{summary}",
+ descSteer: "got a follow-up message{summary}",
+ secs: "{s}s",
+ minSecs: "{m} min {s}s",
+ mins: "{m} min",
+};
diff --git a/src/i18n/messages/index.ts b/src/i18n/messages/index.ts
index f9c3936..50d3625 100644
--- a/src/i18n/messages/index.ts
+++ b/src/i18n/messages/index.ts
@@ -13,5 +13,7 @@ import * as approvals from "./approvals.js";
import * as media from "./media.js";
import * as cu from "./cu.js";
import * as pwsh from "./pwsh.js";
+import * as activity from "./activity.js";
+import * as tasks from "./tasks.js";
-export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh };
+export const catalogs = { web, desktop, app, diag, modelflare, account, magpie, channel, runtime, agent, approvals, media, cu, pwsh, activity, tasks };
diff --git a/src/i18n/messages/runtime.ts b/src/i18n/messages/runtime.ts
index e32e26f..736dd3e 100644
--- a/src/i18n/messages/runtime.ts
+++ b/src/i18n/messages/runtime.ts
@@ -72,6 +72,34 @@ export const zh = {
modelReset: "✅ 已恢复为机器人默认模型",
modelNotFound: "⚠️ 找不到模型「{name}」,发送 /model 查看列表",
modelSwitched: "✅ 本会话已切换到 {model}",
+ saveFailed: "保存到工作区失败",
+ stopped: "已中止(处理了 {d})。",
+ steerAck: "收到,这条会并入正在进行的处理,稍后一起回复。",
+ stoppedMark: "(已中止)",
+ tasksAgentOnly: "后台任务只在代理模式下可用。",
+ stopHint: "\n后台任务在进行:{list}。发 /stop 编号 可停止。",
+ listSepStrong: ";",
+ nothingToStop: "当前没有正在处理的消息。{hint}",
+ stoppingPrev: "正在中止上一条消息(已处理 {d})…",
+ queuedBehind: "上一条消息还在处理(已 {d}{now}),这条会排在它后面。发送 /stop 可以中止。",
+ nowDoing: ",现在:{step}",
+ jobResult: "后台命令的结果",
+ jobDoneNoText: "(后台任务已结束,没有文字回复)",
+ busyFor: "已 {d}",
+ busySteps: { other: "{count} 步" },
+ busyWaitingAgent: "还在等代理进程接手",
+ busyNow: "现在:{step}",
+ busyIdle: "{d}没有新进展",
+ busySteer: "本会话上一条消息还在处理({parts}),新消息会并入正在进行的处理。发送 /stop 可以中止",
+ busyQueue: "本会话上一条消息还在处理({parts}),新消息会排在它后面。发送 /stop 可以中止",
+ stuckAt: "卡在:{step}。",
+ lastStep: "最后一步:{step}。",
+ andRestarted: "并重启代理进程",
+ restartedNote: "代理进程已重启,",
+ stoppedByUser: "已中止(处理了 {d})。{restarted}可以继续发消息。",
+ stoppedIdle: "⚠️ 代理 {d}没有任何进展,已自动中止{restart}。{where}可以重新发送,或用 /model 换个模型试试。",
+ stoppedLimit: "⚠️ 这条消息处理超过了 {d}的上限,已中止{restart}。{where}可以把任务拆小一点再发。",
+ runtimeRestarted: "⚠️ 代理进程重启了(可能是同一机器人的另一个会话中止了卡住的消息),这条消息没有处理完,请重新发送。",
} satisfies Catalog;
export const en: Catalog<typeof zh> = {
@@ -141,4 +169,32 @@ export const en: Catalog<typeof zh> = {
modelReset: "✅ Back to the bot's default model",
modelNotFound: "⚠️ No model \"{name}\"; send /model to see the list",
modelSwitched: "✅ This conversation now uses {model}",
+ saveFailed: "Couldn't save to the workspace",
+ stopped: "Stopped (ran for {d}).",
+ steerAck: "Got it. This joins the reply in progress; you'll get one answer for both.",
+ stoppedMark: "(stopped)",
+ tasksAgentOnly: "Background tasks are only available in agent mode.",
+ stopHint: "\nBackground tasks running: {list}. Send /stop <number> to stop one.",
+ listSepStrong: "; ",
+ nothingToStop: "Nothing is being processed right now.{hint}",
+ stoppingPrev: "Stopping the previous message (ran for {d})…",
+ queuedBehind: "The previous message is still being processed ({d} so far{now}); this one will wait behind it. Send /stop to stop it.",
+ nowDoing: ", now: {step}",
+ jobResult: "result of a background command",
+ jobDoneNoText: "(The background task finished without a text reply)",
+ busyFor: "{d} so far",
+ busySteps: { one: "{count} step", other: "{count} steps" },
+ busyWaitingAgent: "still waiting for the agent process",
+ busyNow: "now: {step}",
+ busyIdle: "no progress for {d}",
+ busySteer: "The previous message in this conversation is still being processed ({parts}); new messages join it. Send /stop to stop it",
+ busyQueue: "The previous message in this conversation is still being processed ({parts}); new messages wait behind it. Send /stop to stop it",
+ stuckAt: "Stuck at: {step}. ",
+ lastStep: "Last step: {step}. ",
+ andRestarted: " and restarted the agent process",
+ restartedNote: "The agent process was restarted. ",
+ stoppedByUser: "Stopped (ran for {d}). {restarted}You can keep sending messages.",
+ stoppedIdle: "⚠️ The agent made no progress for {d}, so it was stopped automatically{restart}. {where}Send it again, or try another model with /model.",
+ stoppedLimit: "⚠️ This message took longer than the {d} limit and was stopped{restart}. {where}Try splitting the task into smaller pieces.",
+ runtimeRestarted: "⚠️ The agent process restarted (another conversation with the same bot may have stopped a stuck message), so this message wasn't finished. Please send it again.",
};
diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.ts
new file mode 100644
index 0000000..95c6dd6
--- /dev/null
+++ b/src/i18n/messages/tasks.ts
@@ -0,0 +1,26 @@
+// tasks:zh 与 en 的键必须一一对应(en 的类型由 zh 推出,少一个多一个都过不了类型检查)。
+import type { Catalog } from "../types.js";
+
+export const zh = {
+ stageStopped: "已停止",
+ stageDelivery: "未送达",
+ stageAnswer: "等你回答",
+ stageApproval: "等你批准",
+ stageBudget: "预算用完",
+ stageFailed: "失败",
+ stageReady: "已完成",
+ stageQueued: "排队中",
+ stageWorking: "进行中",
+} satisfies Catalog;
+
+export const en: Catalog<typeof zh> = {
+ stageStopped: "Stopped",
+ stageDelivery: "Not delivered",
+ stageAnswer: "Waiting for your answer",
+ stageApproval: "Waiting for your approval",
+ stageBudget: "Budget used up",
+ stageFailed: "Failed",
+ stageReady: "Done",
+ stageQueued: "Queued",
+ stageWorking: "In progress",
+};
diff --git a/src/tasks/stage.ts b/src/tasks/stage.ts
index ec573e4..35f9dc2 100644
--- a/src/tasks/stage.ts
+++ b/src/tasks/stage.ts
@@ -3,6 +3,7 @@
* 用户看到的只有这几种:进行中、等你、已完成、失败、已停止。改编自 dsh-superagent 的 core/stage.ts(MIT)。
*/
import type { RunOutcome, RunState } from "../store/db.js";
+import { t as tr, type MessageKey } from "../i18n/index.js";
export type StageKey =
| "stopped"
@@ -36,15 +37,15 @@ export interface StageInput {
}
const STAGES: Record<StageKey, Stage> = {
- stopped: { key: "stopped", label: "已停止", group: "ended" },
- "needs-you/delivery": { key: "needs-you/delivery", label: "未送达", group: "needs" },
- "needs-you/answer": { key: "needs-you/answer", label: "等你回答", group: "needs" },
- "needs-you/approval": { key: "needs-you/approval", label: "等你批准", group: "needs" },
- "needs-you/budget": { key: "needs-you/budget", label: "预算用完", group: "needs" },
- failed: { key: "failed", label: "失败", group: "needs" },
- ready: { key: "ready", label: "已完成", group: "ended" },
- "working/queued": { key: "working/queued", label: "排队中", group: "working" },
- working: { key: "working", label: "进行中", group: "working" },
+ stopped: { key: "stopped", get label() { return tr("tasks.stageStopped" as MessageKey); }, group: "ended" },
+ "needs-you/delivery": { key: "needs-you/delivery", get label() { return tr("tasks.stageDelivery" as MessageKey); }, group: "needs" },
+ "needs-you/answer": { key: "needs-you/answer", get label() { return tr("tasks.stageAnswer" as MessageKey); }, group: "needs" },
+ "needs-you/approval": { key: "needs-you/approval", get label() { return tr("tasks.stageApproval" as MessageKey); }, group: "needs" },
+ "needs-you/budget": { key: "needs-you/budget", get label() { return tr("tasks.stageBudget" as MessageKey); }, group: "needs" },
+ failed: { key: "failed", get label() { return tr("tasks.stageFailed" as MessageKey); }, group: "needs" },
+ ready: { key: "ready", get label() { return tr("tasks.stageReady" as MessageKey); }, group: "ended" },
+ "working/queued": { key: "working/queued", get label() { return tr("tasks.stageQueued" as MessageKey); }, group: "working" },
+ working: { key: "working", get label() { return tr("tasks.stageWorking" as MessageKey); }, group: "working" },
};
export function stageOf(key: StageKey): Stage {
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index c4b37c7..3d1c391 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -8,7 +8,7 @@ import { App } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { RETRY_NOTE, SHELL_LIMITS, locateDshRuntime } from "../src/agent/host.js";
import { CHAT_RULES, MEMORY_GUIDE, botIdentity } from "../src/agent/prompts/index.js";
-import { STEER_ACK } from "../src/core/runtime.js";
+import { steerAck } from "../src/core/runtime.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
import { listen, mockIlink } from "./helpers.js";
@@ -1215,7 +1215,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
["STEERTEXT extra-xyz", true],
]);
expect((await first).reply).toBe("SAW<<STEERTEXT extra-xyz>>");
- expect((await second).reply).toBe(STEER_ACK);
+ expect((await second).reply).toBe(steerAck());
// 第二条没有单独开一轮:之后的模型请求都带着第一条(同一轮里的下一步)
expect(calls.slice(before).every((c) => JSON.stringify(c.body).includes("STEERME please"))).toBe(true);
const after = await console_();
@@ -1241,7 +1241,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
await waitFor(() => b.ops.some((o) => o.type === "text" && o.ack));
go();
expect(await a.done).toMatch(/^SAWIMG<<data:image\/(png|jpeg|webp);base64\|path>>$/);
- expect(await b.done).toBe(STEER_ACK);
+ expect(await b.done).toBe(steerAck());
const hist = app.store.listMessages(a.conv).map((m) => [m.role, m.content.replace(/inbox\/\S+\.png/, "inbox/X.png")]);
expect(hist.slice(-3)).toEqual([
["user", "STEERME with a picture"],
@@ -1473,9 +1473,9 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
await waitFor(() => sentTo(OWNER, "SAW<<STEERTEXT from wechat>>").length === 1, 60_000);
await app.outbox.idle();
const mine = ilink.state.sent.slice(before).filter((s) => s.to === OWNER).map((s) => s.text);
- expect(mine).toEqual([STEER_ACK, "SAW<<STEERTEXT from wechat>>"]);
+ expect(mine).toEqual([steerAck(), "SAW<<STEERTEXT from wechat>>"]);
// ack 的出站记录:短有效期、只发一次
- const ack = outboxRows(OWNER).filter((r) => r.body.text === STEER_ACK);
+ const ack = outboxRows(OWNER).filter((r) => r.body.text === steerAck());
expect(ack).toHaveLength(1);
expect(ack[0].status).toBe("sent");
expect(ack[0].expiresAt - ack[0].createdAt).toBeLessThanOrEqual(10 * 60_000);
@@ -1505,7 +1505,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
await waitFor(() => sentTo(FRIEND, "NOSTEER").length === 1, 60_000);
await app.outbox.idle();
expect(sentTo(FRIEND, "SAW<<")).toHaveLength(0);
- expect(sentTo(FRIEND, STEER_ACK)).toHaveLength(0);
+ expect(sentTo(FRIEND, steerAck())).toHaveLength(0);
expect(app.store.listMessages(conv).map((m) => m.content)).not.toContain("STEERTEXT should not get in");
// 模型从没见过这条
expect(calls.some((c) => JSON.stringify(c.body).includes("STEERTEXT should not get in"))).toBe(false);
diff --git a/test/live-control.unit.test.ts b/test/live-control.unit.test.ts
index b09dc0c..a7e10ca 100644
--- a/test/live-control.unit.test.ts
+++ b/test/live-control.unit.test.ts
@@ -6,7 +6,7 @@ import { AgentBridge } from "../src/agent/bridge.js";
import { ControlChannel } from "../src/agent/control.js";
import { ActivityLog, describeStep, promotedJob } from "../src/agent/activity.js";
import { answerText } from "../src/agent/host.js";
-import { BotRuntime, STEER_ACK } from "../src/core/runtime.js";
+import { BotRuntime, steerAck } from "../src/core/runtime.js";
import { Store } from "../src/store/db.js";
import { DEFAULT_SETTINGS } from "../src/agent/settings.js";
import type { AgentManager } from "../src/agent/manager.js";
@@ -209,7 +209,7 @@ describe("runtime: a message sent while an agent turn runs", () => {
await until(() => s.finishers.length === 1);
const b = s.send("补充一句");
await until(() => b.texts().length > 0);
- expect(b.texts()).toEqual([STEER_ACK]);
+ expect(b.texts()).toEqual([steerAck()]);
expect(s.steered).toEqual(["补充一句"]);
// 第二条等第一条的回合结束才算处理完(网页 live 登记里它一直在)
let bDone = false;