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.

Phase 2: present → WeChat CDN media / Feishu file upload; ask_user_question tool enabled; tests

Marlaf05d56060c61
diff --git a/src/agent/host.ts b/src/agent/host.ts
index 47c5756..f37e0de 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -44,6 +44,44 @@ export function locateDshRuntime(appRoot: string): string | undefined {
return cands.find((d) => fs.existsSync(path.join(d, "node_modules", "@deepseek-ai", "dsh-sdk-client", "package.json")));
}
+/** present 工具参数里的文件路径(原样,相对路径以工作区为准)。 */
+export function presentPaths(args: string): string[] {
+ try {
+ const a = JSON.parse(args) as { files?: Array<{ path?: unknown }> };
+ return (a.files ?? []).map((f) => String(f?.path ?? "")).filter(Boolean);
+ } catch {
+ return [];
+ }
+}
+
+export const MAX_DELIVERABLE_BYTES = 50 * 1024 * 1024;
+
+/**
+ * 只交付工作区内(解析符号链接后)真实存在的普通文件,去重,最多 8 个、单个 ≤ 50 MB。
+ * 防止模型借 present 把工作区外的文件(如 ~/.ssh、数据目录)发到聊天里。
+ */
+export function deliverables(workspace: string, paths: string[]): string[] {
+ let root: string;
+ try {
+ root = fs.realpathSync(workspace);
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (const p of paths) {
+ try {
+ const real = fs.realpathSync(path.resolve(workspace, p));
+ if (real !== root && !real.startsWith(root + path.sep)) continue;
+ const st = fs.statSync(real);
+ if (!st.isFile() || st.size === 0 || st.size > MAX_DELIVERABLE_BYTES) continue;
+ if (!out.includes(real)) out.push(real);
+ } catch {
+ /* 不存在则忽略 */
+ }
+ }
+ return out.slice(0, 8);
+}
+
let sdkPromise: Promise<SdkModule> | undefined;
function loadSdk(runtimeDir: string): Promise<SdkModule> {
sdkPromise ??= import(pathToFileURL(path.join(runtimeDir, "node_modules", "@deepseek-ai", "dsh-sdk-client", "lib", "index.js")).href) as Promise<SdkModule>;
@@ -165,6 +203,12 @@ export class AgentHost {
"- insert:",
" - id: amb-bridge",
` name: ${yamlStr(plugin)}`,
+ // sdk 配置默认不带这两个工具:ask_user_question 走 user-questions → 插件 → 审批中心;
+ // present 只声明交付文件,由宿主在回合结束后经渠道发送。
+ " - id: amb-tool-ask-user",
+ " name: '@deepseek-ai/dsh-tool-ask-user'",
+ " - id: amb-present",
+ " name: '@deepseek-ai/dsh-tool-present'",
"",
].join("\n");
const f = path.join(this.home, "amb.patch.yml");
@@ -381,12 +425,13 @@ exec "$REAL" "$@"
this.o.store.clearAgentSession(conversationId);
}
- async runTurn(input: { conversationId: string; text: string; model: string; observer?: TurnObserver }): Promise<{ text: string; sessionId: string }> {
+ async runTurn(input: { conversationId: string; text: string; model: string; observer?: TurnObserver }): Promise<{ text: string; sessionId: string; files: string[] }> {
const h = await this.ensure(input.model);
const s = await this.sessionFor(h, input.conversationId);
this.active++;
let timer: NodeJS.Timeout | undefined;
let turnError: string | undefined;
+ const presented: string[] = [];
try {
const timeoutMs = this.o.turnTimeoutMs ?? 30 * 60_000;
const run = s.run(input.text, {
@@ -398,6 +443,7 @@ exec "$REAL" "$@"
if (ev?.type === "tool/call") {
this.calls.set(String(data.callId), { name: String(data.name), args: String(data.arguments ?? ""), at: Date.now() });
if (this.calls.size > 500) this.calls.delete(this.calls.keys().next().value!);
+ if (data.name === "present") presented.push(...presentPaths(String(data.arguments ?? "")));
input.observer?.onProgress?.(`🔧 ${summarizeCall(String(data.name), String(data.arguments ?? "")).split(this.workspace + "/").join("")}`);
}
if (ev?.type === "turn/end" && data?.reason?.kind === "error") turnError = String(data.reason.error?.message ?? "unknown error");
@@ -410,7 +456,7 @@ exec "$REAL" "$@"
const r = await Promise.race([run, timeout]);
this.failures = 0;
if (!r.finalResponse && turnError) throw new Error(turnError);
- return { text: r.finalResponse, sessionId: s.id };
+ return { text: r.finalResponse, sessionId: s.id, files: deliverables(this.workspace, presented) };
} catch (e) {
if (/timed out/.test((e as Error).message)) await this.closeHarness();
throw e;
diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.ts
index 865a4ba..7bdeaa1 100644
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@ -47,6 +47,17 @@ export class FeishuReply implements ReplySession {
return this.finish(op.text);
case "text":
return this.sendText(op.text);
+ case "file":
+ await this.inflight;
+ if (this.transport.replyFile) {
+ try {
+ await this.transport.replyFile(this.replyTo, op.path);
+ return;
+ } catch (e) {
+ log.warn("feishu file upload failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
+ }
+ }
+ return this.sendText(`⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`);
case "interactive":
if (op.buttons?.length && this.transport.replyActionCard) {
try {
diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.ts
index 11eab72..42a256b 100644
--- a/src/channels/feishu/transport.ts
+++ b/src/channels/feishu/transport.ts
@@ -1,7 +1,14 @@
+import fsp from "node:fs/promises";
+import path from "node:path";
import * as Lark from "@larksuiteoapi/node-sdk";
import { randomUUID } from "node:crypto";
import { logger } from "../../log.js";
+const FEISHU_IMAGE_EXT = new Set(["png", "jpg", "jpeg", "gif", "webp", "bmp"]);
+const FEISHU_FILE_TYPES: Record<string, string> = {
+ pdf: "pdf", doc: "doc", docx: "doc", xls: "xls", xlsx: "xls", csv: "xls", ppt: "ppt", pptx: "ppt", mp4: "mp4", opus: "opus",
+};
+
/** 归一化后的飞书 im.message.receive_v1 关键字段 */
export interface FeishuMessageEvent {
eventId?: string;
@@ -41,6 +48,8 @@ export interface FeishuTransport {
updateCardText(cardId: string, elementId: string, text: string, sequence: number): Promise<void>;
finishCard(cardId: string, sequence: number, summary: string): Promise<void>;
replyText(replyToMessageId: string, text: string): Promise<void>;
+ /** 上传本地文件并作为图片/文件消息回复(present 交付物) */
+ replyFile?(replyToMessageId: string, filePath: string): Promise<void>;
}
export const CARD_ELEMENT_ID = "md";
@@ -218,6 +227,31 @@ export class LarkTransport implements FeishuTransport {
check(res, "im.message.reply(action card)");
}
+ async replyFile(replyToMessageId: string, filePath: string): Promise<void> {
+ const buf = await fsp.readFile(filePath);
+ const name = path.basename(filePath);
+ const ext = path.extname(name).toLowerCase().slice(1);
+ let msgType: "image" | "file";
+ let content: string;
+ if (FEISHU_IMAGE_EXT.has(ext) && buf.length <= 10 * 1024 * 1024) {
+ const res: any = await this.client.im.v1.image.create({ data: { image_type: "message", image: buf } as any });
+ const key = res?.image_key ?? res?.data?.image_key;
+ if (!key) throw new Error(`im.image.create failed${res?.code ? ` (code ${res.code})` : ""}`);
+ msgType = "image";
+ content = JSON.stringify({ image_key: key });
+ } else {
+ if (buf.length > 30 * 1024 * 1024) throw new Error("file too large for feishu (>30MB)");
+ const fileType = FEISHU_FILE_TYPES[ext] ?? "stream";
+ const res: any = await this.client.im.v1.file.create({ data: { file_type: fileType, file_name: name, file: buf } as any });
+ const key = res?.file_key ?? res?.data?.file_key;
+ if (!key) throw new Error(`im.file.create failed${res?.code ? ` (code ${res.code})` : ""}`);
+ msgType = "file";
+ content = JSON.stringify({ file_key: key });
+ }
+ const res: any = await this.client.im.v1.message.reply({ path: { message_id: replyToMessageId }, data: { msg_type: msgType, content } });
+ check(res, `im.message.reply(${msgType})`);
+ }
+
async replyText(replyToMessageId: string, text: string): Promise<void> {
const res: any = await this.client.im.v1.message.reply({
path: { message_id: replyToMessageId },
diff --git a/src/channels/weixin/api.ts b/src/channels/weixin/api.ts
index 26bf31b..df26737 100644
--- a/src/channels/weixin/api.ts
+++ b/src/channels/weixin/api.ts
@@ -5,9 +5,30 @@
* Portions Copyright (C) 2026 Tencent. All rights reserved. Licensed under the MIT, see ./LICENSE.openclaw-weixin.
*/
import crypto from "node:crypto";
+import fs from "node:fs/promises";
+import path from "node:path";
export const ILINK_APP_ID = "bot";
export const DEFAULT_ILINK_BASE = "https://ilinkai.weixin.qq.com";
+export const DEFAULT_CDN_BASE = "https://novac2c.cdn.weixin.qq.com/c2c";
+/** proto: UploadMediaType */
+export const UploadMediaType = { IMAGE: 1, VIDEO: 2, FILE: 3 } as const;
+
+const IMAGE_EXT = new Set([".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"]);
+const VIDEO_EXT = new Set([".mp4", ".mov", ".m4v", ".webm"]);
+export function mediaKind(file: string): "image" | "video" | "file" {
+ const ext = path.extname(file).toLowerCase();
+ return IMAGE_EXT.has(ext) ? "image" : VIDEO_EXT.has(ext) ? "video" : "file";
+}
+
+/** AES-128-ECB(PKCS7)加密,CDN 上传要求。 */
+export function encryptAesEcb(plain: Buffer, key: Buffer): Buffer {
+ const c = crypto.createCipheriv("aes-128-ecb", key, null);
+ return Buffer.concat([c.update(plain), c.final()]);
+}
+export function aesEcbPaddedSize(n: number): number {
+ return Math.ceil((n + 1) / 16) * 16;
+}
export const SESSION_EXPIRED_ERRCODE = -14;
const CHANNEL_VERSION = "0.1.0";
const BOT_AGENT = "AnymodelBot/0.1.0";
@@ -77,11 +98,19 @@ export function parseWeixinApiJson<T>(rawText: string): T {
export const MessageType = { USER: 1, BOT: 2 } as const;
export const MessageItemType = { TEXT: 1, IMAGE: 2, VOICE: 3, FILE: 4, VIDEO: 5 } as const;
+export interface CdnMedia {
+ encrypt_query_param?: string;
+ aes_key?: string;
+ encrypt_type?: number;
+}
+
export interface MessageItem {
type?: number;
text_item?: { text?: string };
voice_item?: { text?: string };
- file_item?: { file_name?: string };
+ file_item?: { file_name?: string; media?: CdnMedia; len?: string };
+ image_item?: { media?: CdnMedia; mid_size?: number };
+ video_item?: { media?: CdnMedia; video_size?: number };
ref_msg?: { title?: string; message_item?: MessageItem };
}
@@ -136,6 +165,7 @@ export interface IlinkClientOptions {
token?: string;
routeTag?: string;
fetchImpl?: typeof fetch;
+ cdnBaseUrl?: string;
}
export class IlinkClient {
@@ -224,6 +254,66 @@ export class IlinkClient {
}
async sendText(toUserId: string, text: string, contextToken: string): Promise<void> {
+ await this.sendItem(toUserId, { type: MessageItemType.TEXT, text_item: { text } }, contextToken);
+ }
+
+ /**
+ * 发送本地文件:getuploadurl → AES-128-ECB 加密后 POST 到 CDN → sendmessage 媒体条目。
+ * 移植自 openclaw-weixin src/cdn/upload.ts、src/cdn/cdn-upload.ts、src/messaging/send.ts。
+ */
+ async sendMedia(toUserId: string, filePath: string, contextToken: string): Promise<void> {
+ const plain = await fs.readFile(filePath);
+ const kind = mediaKind(filePath);
+ const filekey = crypto.randomBytes(16).toString("hex");
+ const aeskey = crypto.randomBytes(16);
+ const filesize = aesEcbPaddedSize(plain.length);
+ const raw = await this.request(
+ "POST",
+ "ilink/bot/getuploadurl",
+ {
+ filekey,
+ media_type: kind === "image" ? UploadMediaType.IMAGE : kind === "video" ? UploadMediaType.VIDEO : UploadMediaType.FILE,
+ to_user_id: toUserId,
+ rawsize: plain.length,
+ rawfilemd5: crypto.createHash("md5").update(plain).digest("hex"),
+ filesize,
+ no_need_thumb: true,
+ aeskey: aeskey.toString("hex"),
+ },
+ 15_000,
+ );
+ const up = parseWeixinApiJson<{ ret?: number; errmsg?: string; upload_full_url?: string; upload_param?: string }>(raw || "{}");
+ const cdnBase = (this.opts.cdnBaseUrl || DEFAULT_CDN_BASE).replace(/\/+$/, "");
+ const url = up.upload_full_url?.trim() || (up.upload_param ? `${cdnBase}/upload?encrypted_query_param=${encodeURIComponent(up.upload_param)}&filekey=${encodeURIComponent(filekey)}` : "");
+ if (!url) throw new WeixinApiError(`getuploadurl returned no upload url (ret=${up.ret ?? ""})`, up.ret);
+ const cipher = encryptAesEcb(plain, aeskey);
+ let param = "";
+ let lastErr: unknown;
+ for (let attempt = 1; attempt <= 3 && !param; attempt++) {
+ try {
+ const res = await this.fetchImpl(url, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: new Uint8Array(cipher) });
+ if (res.status >= 400 && res.status < 500) throw Object.assign(new Error(`CDN upload client error ${res.status}`), { fatal: true });
+ if (res.status !== 200) throw new Error(`CDN upload server error ${res.status}`);
+ param = res.headers.get("x-encrypted-param") ?? "";
+ if (!param) throw new Error("CDN upload response missing x-encrypted-param");
+ } catch (e) {
+ lastErr = e;
+ if ((e as { fatal?: boolean }).fatal) throw e;
+ }
+ }
+ if (!param) throw lastErr instanceof Error ? lastErr : new Error("CDN upload failed");
+ // 与上游一致:aes_key 为十六进制密钥字符串的 base64
+ const media = { encrypt_query_param: param, aes_key: Buffer.from(aeskey.toString("hex")).toString("base64"), encrypt_type: 1 };
+ const item: MessageItem =
+ kind === "image"
+ ? { type: MessageItemType.IMAGE, image_item: { media, mid_size: filesize } }
+ : kind === "video"
+ ? { type: MessageItemType.VIDEO, video_item: { media, video_size: filesize } }
+ : { type: MessageItemType.FILE, file_item: { media, file_name: path.basename(filePath), len: String(plain.length) } };
+ await this.sendItem(toUserId, item, contextToken);
+ }
+
+ private async sendItem(toUserId: string, item: MessageItem, contextToken: string): Promise<void> {
const raw = await this.request(
"POST",
"ilink/bot/sendmessage",
@@ -235,7 +325,7 @@ export class IlinkClient {
message_type: MessageType.BOT,
message_state: 2, // FINISH
context_token: contextToken || undefined,
- item_list: [{ type: MessageItemType.TEXT, text_item: { text } }],
+ item_list: [item],
},
},
15_000,
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index 70031c8..722130b 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -108,6 +108,26 @@ export class WeixinReply implements ReplySession {
case "text":
this.dropProgress();
return this.enqueue(() => this.send(op.text));
+ case "file":
+ return this.enqueue(async () => {
+ if (this.quota.remaining(this.userId) <= 0) {
+ this.log.warn("weixin quota exhausted, file dropped", { userId: this.userId });
+ return;
+ }
+ try {
+ // 上传失败不占配额;发送串行,先查后扣不会超发
+ await this.client.sendMedia(this.userId, op.path, this.contextToken);
+ this.quota.tryConsume(this.userId);
+ this.sent.push(`[文件] ${op.name}`);
+ } catch (e) {
+ this.log.warn("weixin media send failed", { name: op.name, message: (e as Error).message.slice(0, 200) });
+ if (this.quota.tryConsume(this.userId)) {
+ const t = `⚠️ 文件「${op.name}」发送失败,可在工作区中查看。`;
+ await this.client.sendText(this.userId, t, this.contextToken);
+ this.sent.push(t);
+ }
+ }
+ });
case "interactive": {
if (this.progressTimer) clearTimeout(this.progressTimer);
this.progressTimer = undefined;
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 84acb03..6d81886 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -1,3 +1,4 @@
+import path from "node:path";
import type { InboundEvent, ReplySession } from "./types.js";
import { eventText } from "./types.js";
import type { ModelClient, ChatMessage } from "../llm/client.js";
@@ -157,6 +158,13 @@ export class BotRuntime {
const finalText = r.text.trim() || "(已完成,没有文字回复)";
store.addMessage(convId, "assistant", finalText);
await out.apply({ type: "stream.finish", text: finalText });
+ for (const f of r.files ?? []) {
+ try {
+ await out.apply({ type: "file", path: f, name: path.basename(f) });
+ } catch (e) {
+ log.warn("deliver file failed", { name: path.basename(f), message: (e as Error).message.slice(0, 200) });
+ }
+ }
return true;
} catch (e) {
const err = e as Error;
diff --git a/src/core/types.ts b/src/core/types.ts
index 29f538c..2c948b9 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -32,6 +32,8 @@ export type OutboundOp =
| { type: "text"; text: string }
/** 代理执行中的进度(工具调用等):微信批量发送并受配额约束,飞书写入卡片,网页收集 */
| { type: "progress"; text: string }
+ /** 代理交付的本地文件(present):微信走 CDN 媒体消息,飞书上传文件/图片,网页列出文件名 */
+ | { type: "file"; path: string; name: string }
/**
* ask_user / approval / secret_request 等交互,按能力映射到卡片按钮或编号文本。
* prompt 为完整的纯文本提示(文本渠道直接发送);buttons 供卡片渠道使用,value 会原样回传。
diff --git a/src/web/server.ts b/src/web/server.ts
index 8aaaa56..ea6e4a8 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -92,7 +92,9 @@ class CollectReply implements ReplySession {
text = "";
progress: string[] = [];
prompts: Array<{ kind: string; prompt: string; requestId?: string; code?: string }> = [];
+ files: string[] = [];
async apply(op: OutboundOp): Promise<void> {
+ if (op.type === "file") this.files.push(op.name);
if (op.type === "stream.finish" || op.type === "text") this.text += (this.text ? "\n" : "") + op.text;
else if (op.type === "progress") this.progress.push(op.text);
else if (op.type === "interactive") this.prompts.push({ kind: op.kind, prompt: op.prompt, requestId: op.requestId, code: op.code });
@@ -335,7 +337,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
if (intercepted.handled) return send(res, 200, { reply: intercepted.ack ?? "", progress: [], prompts: [] });
const out = new CollectReply();
await app.queue.run(`web:${id}:console`, () => app.runtime.handle(ev, out));
- return send(res, 200, { reply: out.text, progress: out.progress, prompts: out.prompts });
+ return send(res, 200, { reply: out.text, progress: out.progress, prompts: out.prompts, files: out.files });
}
}
throw new HttpError(404, "not found");
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index a1443e6..ea44f09 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -39,7 +39,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
function plan(messages: any[]): { tool?: { name: string; args: any }; text?: string } {
let lastUser = -1;
for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }
+ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|\[用户消息\]/.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");
@@ -48,6 +48,8 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
[/ESCALATE/, [{ name: "bash", args: { description: "run", command: "echo escalated-$((40+2))", sandbox_permissions: "danger-full-access", justification: "测试提权" } }]],
[/SECRET/, [{ name: "bash", args: { description: "run", command: `ls ${dataDir} 2>&1; cat ${path.join(dataDir, "anymodel.db")} >/dev/null 2>&1 && echo DB-READABLE || echo DB-HIDDEN` } }]],
[/READFILE/, [{ name: "read", args: { file_path: path.join(dataDir, "config.json") } }, { name: "read", args: { file_path: "qs.py" } }]],
+ [/PRESENT/, [{ name: "bash", args: { description: "run", command: "printf 'hello deliverable' > report.txt" } }, { name: "present", args: { files: [{ path: "report.txt", description: "报告" }, { path: "/etc/hostname" }] } }]],
+ [/ASKQ/, [{ name: "ask_user_question", args: { questions: [{ id: "lang", question: "用哪种语言?", options: [{ label: "Python" }, { label: "Go" }] }] } }]],
[/LOOPBACK/, [{ name: "bash", args: { description: "run", command: `python3 -c "import urllib.request as u\ntry:\n print('API', u.urlopen('${base}/amb/api/status').status)\nexcept Exception as e:\n print('API', getattr(e,'code',e))"` } }]],
];
for (const [re, steps] of scripts) {
@@ -103,7 +105,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const chat = async (text: string) => {
const r = await fetch(`${base}/amb/api/bots/default/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ text }) });
expect(r.status).toBe(200);
- return (await r.json()) as { reply: string; progress: string[]; prompts: any[] };
+ return (await r.json()) as { reply: string; progress: string[]; prompts: any[]; files?: string[] };
};
it("runs a sandboxed bash tool in the bot workspace (quicksort)", async () => {
@@ -161,6 +163,26 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
expect(r.reply).toContain("def qs");
}, 120_000);
+ it("present delivers workspace files only", async () => {
+ const r = await chat("PRESENT report");
+ expect(r.files).toEqual(["report.txt"]);
+ }, 120_000);
+
+ it("ask_user_question becomes a numbered prompt answered by reply", async () => {
+ const pending = chat("ASKQ please");
+ let row: any;
+ for (let i = 0; i < 300 && !row; i++) {
+ await new Promise((r) => setTimeout(r, 100));
+ row = ((await (await fetch(`${base}/amb/api/approvals?status=pending`)).json()) as any).approvals[0];
+ }
+ expect(row?.kind).toBe("question");
+ await chat("2");
+ const r = await pending;
+ expect(r.prompts[0]?.prompt).toContain("1. Python");
+ expect(r.prompts[0]?.prompt).toContain("2. Go");
+ expect(r.reply).toContain("Go");
+ }, 120_000);
+
it("blocks loopback management API calls from the agent", async () => {
const r = await chat("LOOPBACK check");
expect(r.reply).toContain("API 403");
diff --git a/test/agent.unit.test.ts b/test/agent.unit.test.ts
index 277e68e..b1b7d80 100644
--- a/test/agent.unit.test.ts
+++ b/test/agent.unit.test.ts
@@ -135,3 +135,72 @@ describe("WeixinReply progress batching", () => {
expect(sent).toEqual(["⏳ 进行中:\n🔧 bash ls", "需批准: bash `rm -rf build` — 回复 y 1234 / n 1234"]);
});
});
+
+describe("WeChat media delivery", () => {
+ it("IlinkClient.sendMedia: getuploadurl → encrypted CDN upload → file item", async () => {
+ const { IlinkClient } = await import("../src/channels/weixin/api.js");
+ const crypto = await import("node:crypto");
+ const f = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "amb-media-")), "report.txt");
+ fs.writeFileSync(f, "hello deliverable");
+ const calls: Array<{ url: string; body: any; raw?: Buffer }> = [];
+ let aeskey = "";
+ const fetchImpl = (async (url: string, init: any) => {
+ if (url.includes("getuploadurl")) {
+ const b = JSON.parse(init.body);
+ aeskey = b.aeskey;
+ calls.push({ url, body: b });
+ return new Response(JSON.stringify({ ret: 0, upload_param: "UP+/=" }), { status: 200 });
+ }
+ if (url.includes("/upload?")) {
+ calls.push({ url, body: null, raw: Buffer.from(init.body) });
+ return new Response("", { status: 200, headers: { "x-encrypted-param": "DOWN" } });
+ }
+ calls.push({ url, body: JSON.parse(init.body) });
+ return new Response(JSON.stringify({ ret: 0 }), { status: 200 });
+ }) as any;
+ const c = new IlinkClient({ baseUrl: "http://ilink", token: "t", fetchImpl, cdnBaseUrl: "http://cdn/c2c" });
+ await c.sendMedia("u1", f, "ctx");
+ expect(calls).toHaveLength(3);
+ expect(calls[0].body).toMatchObject({ media_type: 3, to_user_id: "u1", rawsize: 17, filesize: 32, no_need_thumb: true });
+ expect(calls[1].url).toBe("http://cdn/c2c/upload?encrypted_query_param=UP%2B%2F%3D&filekey=" + calls[0].body.filekey);
+ const d = crypto.createDecipheriv("aes-128-ecb", Buffer.from(aeskey, "hex"), null);
+ expect(Buffer.concat([d.update(calls[1].raw!), d.final()]).toString()).toBe("hello deliverable");
+ const item = calls[2].body.msg.item_list[0];
+ expect(item.type).toBe(4);
+ expect(item.file_item).toMatchObject({ file_name: "report.txt", len: "17", media: { encrypt_query_param: "DOWN", encrypt_type: 1 } });
+ expect(Buffer.from(item.file_item.media.aes_key, "base64").toString()).toBe(aeskey);
+ expect(calls[2].body.msg.context_token).toBe("ctx");
+ });
+
+ it("WeixinReply file op consumes quota and falls back to text on failure", async () => {
+ store.upsertWeixinPeer({ botId: "b", userId: "u1", contextToken: "ctx", quotaRemaining: 2, windowStartedAt: Date.now() });
+ const sent: string[] = [];
+ let fail = false;
+ const client = {
+ sendText: async (_u: string, t: string) => void sent.push(t),
+ sendMedia: async (_u: string, p: string) => {
+ if (fail) throw new Error("cdn down");
+ sent.push("media:" + p);
+ },
+ } as any;
+ const quota = new WeixinQuota(store, "b");
+ const reply = new WeixinReply(client, "u1", "ctx", quota, 30);
+ await reply.apply({ type: "file", path: "/w/a.png", name: "a.png" });
+ expect(sent).toEqual(["media:/w/a.png"]);
+ expect(quota.remaining("u1")).toBe(1);
+ fail = true;
+ await reply.apply({ type: "file", path: "/w/b.png", name: "b.png" });
+ expect(sent[1]).toContain("b.png");
+ expect(quota.remaining("u1")).toBe(0);
+ });
+
+ it("deliverables() keeps only regular files inside the workspace", async () => {
+ const { deliverables, presentPaths } = await import("../src/agent/host.js");
+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-ws-"));
+ fs.writeFileSync(path.join(ws, "ok.txt"), "x");
+ fs.writeFileSync(path.join(ws, "empty.txt"), "");
+ fs.symlinkSync("/etc/hostname", path.join(ws, "link.txt"));
+ const args = JSON.stringify({ files: [{ path: "ok.txt" }, { path: path.join(ws, "ok.txt") }, { path: "../../etc/passwd" }, { path: "/etc/hostname" }, { path: "link.txt" }, { path: "empty.txt" }, { path: "missing" }] });
+ expect(deliverables(ws, presentPaths(args))).toEqual([path.join(fs.realpathSync(ws), "ok.txt")]);
+ });
+});
diff --git a/ui/app.js b/ui/app.js
index 924ac58..22508c2 100644
--- a/ui/app.js
+++ b/ui/app.js
@@ -101,7 +101,8 @@ function TestChat({ botId }) {
try {
const r = await api(`/bots/${botId}/chat`, { method: "POST", body: { text: t } });
const extra = [...(r.progress || []).map((p) => ({ role: "assistant progress", content: "⏳ " + p })), ...(r.prompts || []).map((p) => ({ role: "assistant prompt", content: p.prompt }))];
- setLog((l) => [...l, ...extra, { role: "assistant", content: r.reply }]);
+ const files = (r.files || []).map((f) => ({ role: "assistant progress", content: "📎 已交付文件:" + f + "(微信/飞书会直接发送;网页端请在机器人工作区查看)" }));
+ setLog((l) => [...l, ...extra, { role: "assistant", content: r.reply }, ...files]);
}
catch (e) { setLog((l) => [...l, { role: "assistant", content: "✗ " + e.message }]); }
setBusy(false);