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.

Merge origin/master into feat/server-compaction

Marlafc99bbce1c8b
diff --cc test/agent.integration.test.ts
index 5b74cc1,c863f05..34271db
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@@ -174,7 -172,7 +176,7 @@@ describe.skipIf(!runtime || !hasBwrap |
function plan(messages: any[]): Step {
let lastUser = -1;
for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|PADDED|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|OUTWRITE|RMRF|RMWS|CHILDRM|SUBRM|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
++ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|COUNTER|OUTWRITE|RMRF|RMWS|CHILDRM|SUBRM|PADDED|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
}
const user = textOf(messages[lastUser]?.content);
const tools = messages.slice(lastUser + 1).filter((m) => m.role === "tool");
@@@ -681,114 -667,97 +698,208 @@@
expect(mine[0].body.input.filter((i: any) => i.type === "function_call_output")).toHaveLength(1);
}, 180_000);
+ // —— 完全权限:不进沙箱、不请求提权;递归删除仍经审批 ——
+ const setPermission = async (permission: string) => {
+ const r = (await api("/bots/default/settings", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ permission }) })) as any;
+ expect(r.settings.permission).toBe(permission);
+ };
+ const approvalCount = () => app.store.listApprovals({ limit: 500 }).length;
+ const pendingApproval = async () => {
+ for (let i = 0; i < 300; i++) {
+ const row = ((await api("/approvals?status=pending")) as any).approvals[0];
+ if (row) return row;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ return undefined;
+ };
+
+ it("workspace (default): writes outside the workspace stay in the sandbox, escalation asks", async () => {
+ const pending = chat("OUTWRITE workspace");
+ // 第二步显式要 danger-full-access:工作区模式下要审批(这里拒绝)
+ const row = await pendingApproval();
+ expect(row?.tool).toBe("bash");
+ await api(`/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ const r = await pending;
+ expect(r.reply).toContain("DB-HIDDEN");
+ expect(r.reply).not.toContain("escalated-42");
+ expect(fs.existsSync(path.join(outside, "marker.txt"))).toBe(false);
+ }, 120_000);
+
+ it("full: commands run unsandboxed with no approval prompt; the loopback API stays blocked", async () => {
+ await setPermission("full");
+ const before = approvalCount();
+ const r = await chat("OUTWRITE full");
+ expect(r.reply).toContain("out-42");
+ expect(r.reply).toContain("DB-READABLE");
+ expect(r.reply).toContain("escalated-42");
+ expect(fs.readFileSync(path.join(outside, "marker.txt"), "utf8").trim()).toBe("out-42");
+ expect(approvalCount()).toBe(before);
+ expect(r.prompts).toEqual([]);
+ expect((await chat("LOOPBACK full")).reply).toContain("API 403");
+ expect((await chat("/status")).reply).toMatch(/运行方式:代理模式(DeepSeek Harness,完全权限:不经沙箱)\n注意:完全权限下命令以你的用户身份直接运行/);
+ }, 180_000);
+
+ it("full: rm -rf asks first; deny keeps the directory, a plain rm does not ask", async () => {
+ fs.writeFileSync(path.join(outside, "single.txt"), "x");
+ fs.mkdirSync(path.join(outside, "victim", "sub"), { recursive: true });
+ fs.writeFileSync(path.join(outside, "victim", "sub", "f.txt"), "keep me");
+ const pending = chat("RMRF deny");
+ const row = await pendingApproval();
+ expect(row).toMatchObject({ tool: "bash", reason: "递归删除,需要你确认(rm -rf)" });
+ expect(row.detail).toContain(`rm -rf ${outside}/victim`);
+ // 第一步的普通删除已经执行了,没有问
+ expect(fs.existsSync(path.join(outside, "single.txt"))).toBe(false);
+ expect(fs.existsSync(path.join(outside, "victim"))).toBe(true);
+ const no = await fetch(`${base}/amb/api/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ expect(no.status).toBe(200);
+ const r = await pending;
+ expect(r.reply).toContain("single-gone");
+ expect(r.reply).toMatch(/rejected/);
+ expect(r.reply).not.toContain("victim-gone");
+ expect(fs.readFileSync(path.join(outside, "victim", "sub", "f.txt"), "utf8")).toBe("keep me");
+ expect(r.prompts[0]?.prompt).toMatch(new RegExp(`需批准: bash \`rm -rf ${outside}/victim && echo victim-gone\` — 回复 y ${row.code} / n ${row.code}`));
+ }, 180_000);
+
+ it("full: approving the recursive delete runs it once", async () => {
+ fs.writeFileSync(path.join(outside, "single.txt"), "x");
+ const pending = chat("RMRF allow");
+ const row = await pendingApproval();
+ expect(row?.detail).toContain("rm -rf");
+ const ok = await fetch(`${base}/amb/api/approvals/${row.id}/approve`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ expect(ok.status).toBe(200);
+ const r = await pending;
+ expect(r.reply).toContain("victim-gone");
+ expect(fs.existsSync(path.join(outside, "victim"))).toBe(false);
+ expect(app.store.getApproval(row.id)!.status).toBe("allowed");
+ }, 180_000);
+
+ it("full: a subagent's recursive delete is gated too", async () => {
+ fs.mkdirSync(path.join(outside, "victim2", "sub"), { recursive: true });
+ const pending = chat("SUBRM please");
+ const row = await pendingApproval();
+ expect(row).toMatchObject({ tool: "bash", reason: "递归删除,需要你确认(rm -rf)" });
+ await api(`/approvals/${row.id}/deny`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+ await pending;
+ expect(fs.existsSync(path.join(outside, "victim2", "sub"))).toBe(true);
+ }, 180_000);
+
+ it("back to workspace: recursive deletes inside the workspace run without asking, as before", async () => {
+ await setPermission("workspace");
+ const before = approvalCount();
+ const r = await chat("RMWS check");
+ expect(r.reply).toContain("tree-gone");
+ expect(approvalCount()).toBe(before);
+ expect((await chat("/status")).reply).toContain("运行方式:代理模式(DeepSeek Harness,工作区沙箱)");
+ }, 180_000);
++
+ // —— 服务端压缩:改写过(换上压缩历史)的请求被拒,bridge 先用原请求重发;这不算接口被拒,模型不改走 Chat ——
+ it("server compaction over Responses: a rewritten request the upstream rejects is resent unmodified; no Chat fallback", async () => {
+ const M = "gpt-6-compact-mock";
+ catalog[M] = ["openai", "openai-response", "openai-response-compact"];
+ const sc = app.agent.serverCompaction!;
+ const host = app.agent.host("default");
+ process.env.AMB_SERVER_COMPACTION_TOKENS = "2000";
+ try {
+ const from = calls.length;
+ // 过线:后台探测(直连压缩 + 经网关续接);会话往后长、历史长过系统提示后在后台压缩,下一轮带着压缩窗口发
+ let n = 0;
+ while (!callsFor(M, from).some((c) => c.sealed && c.body.stream) && n < 8) {
+ expect((await turnOn("sc-user", M, `PADDED ${++n}`)).reply).toMatch(/^PADDED-OK z+$/);
+ await sc.settled();
+ }
+ expect(sc.status()[M]).toMatchObject({ ok: true, reason: "probe passed" });
+ expect(compacts.filter((c) => c.model === M).length).toBeGreaterThanOrEqual(2);
+ const first = callsFor(M, from).find((c) => c.sealed && c.body.stream)!;
+ expect(first).toBeDefined();
+ expect(first.error).toBeUndefined();
+ expect(first.body.input[0].role).toBe("system");
+ expect(host.api).toBe("openai-responses");
+
+ // 上游开始拒收 compaction 项(Modelflare 实测的 400「无效的参数」):bridge 用原请求重发,回合照常
+ sealedRejects.add(M);
+ const next = calls.length;
+ const r = await turnOn("sc-user", M, `PADDED ${++n}`);
+ expect(r.reply).toMatch(/^PADDED-OK z+$/);
+ const mine = callsFor(M, next).filter((c) => c.body.tools && c.body.stream);
+ expect(mine.map((c) => `${c.api}:${c.sealed ? "sealed" : "plain"}:${c.error ?? "ok"}`)).toEqual(["responses:sealed:400", "responses:plain:ok"]);
+ // 不改走 Chat:没有回退记录,代理进程仍走 Responses,活动里没有"改用 Chat Completions 重试"
+ expect(app.agent.apiFallbacks.get(M)).toBeUndefined();
+ expect(host.api).toBe("openai-responses");
+ expect(r.steps.some((s) => s.kind === "retry")).toBe(false);
+ expect(sc.status()[M]).toMatchObject({ ok: false, reason: expect.stringContaining("rewritten request rejected (400): 无效的参数") });
+
+ // 之后原样发,照常走 Responses
+ const after = calls.length;
+ expect((await turnOn("sc-user", M, `PADDED ${++n}`)).reply).toMatch(/^PADDED-OK z+$/);
+ const later = callsFor(M, after).filter((c) => c.body.tools);
+ expect(later.length).toBeGreaterThan(0);
+ expect(later.map((c) => `${c.api}:${c.sealed ? "sealed" : "plain"}:${c.error ?? "ok"}`)).toEqual(later.map(() => "responses:plain:ok"));
+ expect(app.agent.apiFallbacks.get(M)).toBeUndefined();
+ } finally {
+ delete process.env.AMB_SERVER_COMPACTION_TOKENS;
+ sealedRejects.delete(M);
+ await sc.settled();
+ }
+ }, 300_000);
+
+ it("server compaction: when the unmodified resend is rejected too, the Chat fallback still applies, with the original's reason", async () => {
+ const M = "gpt-6-compact-fb-mock";
+ catalog[M] = ["openai", "openai-response", "openai-response-compact"];
+ const sc = app.agent.serverCompaction!;
+ process.env.AMB_SERVER_COMPACTION_TOKENS = "2000";
+ try {
+ const from = calls.length;
+ let n = 0;
+ while (!callsFor(M, from).some((c) => c.sealed && c.body.stream) && n < 8) {
+ expect((await turnOn("sc-fb", M, `PADDED ${++n}`)).reply).toMatch(/^PADDED-OK z+$/);
+ await sc.settled();
+ }
+ expect(callsFor(M, from).some((c) => c.sealed && c.body.stream && !c.error)).toBe(true);
+ // 改写的被拒(「无效的参数」),原请求重发后也被拒(参数不支持):只有后者报给代理接口回退
+ sealedRejects.add(M);
+ rejects[M] = "always";
+ const next = calls.length;
+ const r = await turnOn("sc-fb", M, `PADDED ${++n}`);
+ expect(r.reply).toMatch(/^PADDED-OK z+$/);
+ const mine = callsFor(M, next).filter((c) => c.body.tools && c.body.stream);
+ expect(mine.map((c) => `${c.api}:${c.sealed ? "sealed" : "plain"}:${c.error ?? "ok"}`)).toEqual(["responses:sealed:400", "responses:plain:400", "chat:plain:ok"]);
+ const fb = app.agent.apiFallbacks.get(M);
+ expect(fb).toMatchObject({ from: "openai-responses", reason: expect.stringContaining("HTTP 400: Unsupported parameter") });
+ expect(fb!.reason).not.toContain("无效的参数");
+ expect(r.steps.find((s) => s.kind === "retry")).toMatchObject({ title: "改用 Chat Completions 重试" });
+ expect(app.agent.host("default").api).toBe("openai-completions");
+ } finally {
+ delete process.env.AMB_SERVER_COMPACTION_TOKENS;
+ sealedRejects.delete(M);
+ delete rejects[M];
+ await sc.settled();
+ }
+ }, 300_000);
+
+ it("server compaction probe on a grok-like upstream: compact works, the follow-up with its item is rejected → unsupported, no rewrite, no Chat fallback", async () => {
+ const M = "gpt-6-grokish-mock";
+ catalog[M] = ["openai", "openai-response", "openai-response-compact"];
+ sealedRejects.add(M);
+ const sc = app.agent.serverCompaction!;
+ process.env.AMB_SERVER_COMPACTION_TOKENS = "2000";
+ try {
+ const from = calls.length;
+ for (let n = 1; n <= 3; n++) {
+ expect((await turnOn("sc-grok", M, `PADDED ${n}`)).reply).toMatch(/^PADDED-OK z+$/);
+ await sc.settled();
+ }
+ expect(compacts.filter((c) => c.model === M)).toHaveLength(1);
+ expect(sc.status()[M]).toMatchObject({ ok: false, reason: expect.stringMatching(/^probe: compact call ok, but the follow-up \/v1\/responses carrying its compaction item was rejected \(HTTP 400\): 无效的参数/) });
+ // 探测的续接不经 bridge:不算这个机器人的请求被拒;真实请求都原样发、都成功
+ const real = callsFor(M, from).filter((c) => c.body.stream);
+ expect(real.length).toBeGreaterThan(0);
+ expect(real.every((c) => c.api === "responses" && !c.sealed && !c.error)).toBe(true);
+ expect(app.agent.apiFallbacks.get(M)).toBeUndefined();
+ expect(app.agent.host("default").api).toBe("openai-responses");
+ } finally {
+ delete process.env.AMB_SERVER_COMPACTION_TOKENS;
+ sealedRejects.delete(M);
+ await sc.settled();
+ }
+ }, 300_000);
});