wechat-clawbot 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -3
- package/README.zh.md +14 -3
- package/lib/backlog.d.ts +108 -0
- package/lib/backlog.d.ts.map +1 -0
- package/lib/backlog.js +187 -0
- package/lib/backlog.js.map +1 -0
- package/lib/bridge.d.ts +114 -0
- package/lib/bridge.d.ts.map +1 -1
- package/lib/bridge.js +505 -28
- package/lib/bridge.js.map +1 -1
- package/lib/claude-peer.d.ts +30 -0
- package/lib/claude-peer.d.ts.map +1 -1
- package/lib/claude-peer.js +292 -28
- package/lib/claude-peer.js.map +1 -1
- package/lib/coalesce.d.ts +72 -0
- package/lib/coalesce.d.ts.map +1 -0
- package/lib/coalesce.js +58 -0
- package/lib/coalesce.js.map +1 -0
- package/lib/codex-rpc.js +1 -1
- package/lib/dsh-sessions.d.ts +124 -0
- package/lib/dsh-sessions.d.ts.map +1 -0
- package/lib/dsh-sessions.js +343 -0
- package/lib/dsh-sessions.js.map +1 -0
- package/lib/inbound.d.ts +2 -0
- package/lib/inbound.d.ts.map +1 -1
- package/lib/inbound.js +12 -0
- package/lib/inbound.js.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +34 -1
- package/lib/index.js.map +1 -1
- package/lib/mcp-route.d.ts +3 -0
- package/lib/mcp-route.d.ts.map +1 -1
- package/lib/mcp-route.js +50 -163
- package/lib/mcp-route.js.map +1 -1
- package/lib/mcp-server.d.ts.map +1 -1
- package/lib/mcp-server.js +8 -3
- package/lib/mcp-server.js.map +1 -1
- package/lib/owner-notify.d.ts +90 -0
- package/lib/owner-notify.d.ts.map +1 -0
- package/lib/owner-notify.js +200 -0
- package/lib/owner-notify.js.map +1 -0
- package/lib/tool.d.ts +30 -0
- package/lib/tool.d.ts.map +1 -1
- package/lib/tool.js +166 -100
- package/lib/tool.js.map +1 -1
- package/package.json +1 -1
- package/wechat-clawbot-INSTALL.md +234 -237
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
2
|
+
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
3
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
4
|
+
import { logger } from "./ilink/util/logger.js";
|
|
5
|
+
import { isSendWindowClosed, oneSentence } from "./backlog.js";
|
|
6
|
+
import { listDshSessions } from "./dsh-sessions.js";
|
|
7
|
+
/** The name every DSH conversation sees. */
|
|
8
|
+
export const NOTIFY_TOOL = "notify_wechat";
|
|
9
|
+
/**
|
|
10
|
+
* Put a copy of an outbound notify into the WeChat session's history.
|
|
11
|
+
*
|
|
12
|
+
* Without this the bot is blind to whatever another agent told the user: reply "那怎么办"
|
|
13
|
+
* to one of these messages and the bot has no idea what "那" refers to.
|
|
14
|
+
*
|
|
15
|
+
* `session.append`, not `followup`: an inbox item starts a turn, and the bot
|
|
16
|
+
* would answer a message that was already sent. `user/message`, not
|
|
17
|
+
* `assistant/message`: the latter carries turn/step bookkeeping that cannot be
|
|
18
|
+
* invented safely. The prefix is what makes it legible, and prompt rule C.6
|
|
19
|
+
* tells the bot what to do with one: already delivered, do not repeat.
|
|
20
|
+
*
|
|
21
|
+
* Best effort: the WeChat message is already out, so a mirroring failure must
|
|
22
|
+
* never turn a delivered notify into a reported failure.
|
|
23
|
+
*/
|
|
24
|
+
export function mirrorIntoSession(ctx, sessionId, text, sender, note) {
|
|
25
|
+
try {
|
|
26
|
+
const agent = ctx.agents.get(SessionId(sessionId));
|
|
27
|
+
if (agent === undefined)
|
|
28
|
+
return false;
|
|
29
|
+
const message = createUserMessage({
|
|
30
|
+
// "Claude 发给用户的", but "DSH 会话「X」发给用户的": no space after a closing bracket.
|
|
31
|
+
content: [{ type: "text", text: `[${sender}${sender.endsWith("」") ? "" : " "}发给用户的${note === undefined ? "" : `,${note}`}] ${text}` }],
|
|
32
|
+
// v4 refuses the retired `plugin` wrapper; this is the kind the v3→v4
|
|
33
|
+
// converter assigns this producer, so migrated history matches.
|
|
34
|
+
source: { kind: "plugin:clawbot-mcp" },
|
|
35
|
+
});
|
|
36
|
+
agent.session.append("user/message", message, { surfaceOp: "append" });
|
|
37
|
+
logger.info(`notify: mirrored ${text.length} chars into ${sessionId}`);
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
catch (err) {
|
|
41
|
+
logger.warn(`notify: mirror failed (message was still delivered): ${String(err).slice(0, 160)}`);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Send `text` to the owner. When WeChat will not let the bot write first, keep
|
|
47
|
+
* one sentence for the digest after the owner's next message instead.
|
|
48
|
+
*
|
|
49
|
+
* @param source - who is talking, for the digest ("Claude 的通知").
|
|
50
|
+
* @param origin - which conversation, when there is one worth naming.
|
|
51
|
+
*/
|
|
52
|
+
export async function notifyOwner(ctx, deps, input) {
|
|
53
|
+
const account = deps.getAccount();
|
|
54
|
+
if (account === null || !account.configured) {
|
|
55
|
+
return { ok: false, status: 503, message: "no bound WeChat account — run `clawbot login` first" };
|
|
56
|
+
}
|
|
57
|
+
const owner = account.userId;
|
|
58
|
+
if (owner === undefined || owner === "") {
|
|
59
|
+
return { ok: false, status: 503, message: "the bound account has no linked userId; re-run the QR login so it is recorded" };
|
|
60
|
+
}
|
|
61
|
+
const { text, source, origin } = input;
|
|
62
|
+
const sender = origin === undefined ? source : `${source} 会话「${origin}」`;
|
|
63
|
+
try {
|
|
64
|
+
await deps.sendText(owner, text);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
if (!isSendWindowClosed(err) || deps.backlog === undefined)
|
|
68
|
+
throw err;
|
|
69
|
+
const given = (input.summary ?? "").trim();
|
|
70
|
+
const summary = given !== "" ? given.slice(0, 120) : oneSentence(text);
|
|
71
|
+
deps.backlog.add(owner, {
|
|
72
|
+
kind: "notice", at: new Date().toISOString(), source, summary,
|
|
73
|
+
...(origin === undefined ? {} : { origin }),
|
|
74
|
+
});
|
|
75
|
+
logger.info(`notify: WeChat will not let the bot write first now; kept "${summary}" for the owner's next message`);
|
|
76
|
+
const mirrored = mirrorIntoSession(ctx, deps.config.sessionId, text, sender, "暂未送达,对方下次发消息后合并补发");
|
|
77
|
+
return {
|
|
78
|
+
ok: true,
|
|
79
|
+
deferred: true,
|
|
80
|
+
to: owner,
|
|
81
|
+
chars: text.length,
|
|
82
|
+
summary,
|
|
83
|
+
mirrored,
|
|
84
|
+
message: "微信现在不让 bot 主动发消息(机主有一段时间没发消息了)。这条已存下,机主下次发消息、bot 回复之后,"
|
|
85
|
+
+ "会和其他没送达的消息按时间合并成一条补发,这条只保留一句:" + summary,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
logger.info(`notify: sent ${text.length} chars to the owner (${sender})`);
|
|
89
|
+
const mirrored = mirrorIntoSession(ctx, deps.config.sessionId, text, sender);
|
|
90
|
+
return { ok: true, to: owner, chars: text.length, mirrored };
|
|
91
|
+
}
|
|
92
|
+
/** A conversation's title, else its folder, else its short id: how the owner will recognise it. */
|
|
93
|
+
async function originOf(ctx, sessionId) {
|
|
94
|
+
try {
|
|
95
|
+
const { rows } = await listDshSessions(ctx);
|
|
96
|
+
const row = rows.find((r) => r.id === sessionId);
|
|
97
|
+
if (row?.title !== undefined)
|
|
98
|
+
return row.title;
|
|
99
|
+
const folder = row?.cwd?.split(/[\\/]/).filter((s) => s !== "").pop();
|
|
100
|
+
if (folder !== undefined)
|
|
101
|
+
return folder;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// fall through to the id
|
|
105
|
+
}
|
|
106
|
+
return sessionId.slice(0, 8);
|
|
107
|
+
}
|
|
108
|
+
const SLOT = Symbol.for("clawbot.notify-wechat");
|
|
109
|
+
const slots = globalThis;
|
|
110
|
+
/**
|
|
111
|
+
* Register `notify_wechat` for every DSH conversation.
|
|
112
|
+
*
|
|
113
|
+
* @param ctx - the plugin's ROOT context: a tool registered there is global.
|
|
114
|
+
*/
|
|
115
|
+
export function registerOwnerNotifyTool(ctx, deps) {
|
|
116
|
+
const existing = slots[SLOT];
|
|
117
|
+
if (existing?.registered === true) {
|
|
118
|
+
existing.ctx = ctx;
|
|
119
|
+
existing.deps = deps;
|
|
120
|
+
logger.info(`${NOTIFY_TOOL}: already registered in this process; now served by the newest instance`);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
const slot = { ctx, deps, registered: false };
|
|
124
|
+
slots[SLOT] = slot;
|
|
125
|
+
const serving = () => slots[SLOT] ?? slot;
|
|
126
|
+
const tool = (defineTool({
|
|
127
|
+
name: NOTIFY_TOOL,
|
|
128
|
+
description: "Send a WeChat message to the owner of this computer (the person who linked the WeChat bot). "
|
|
129
|
+
+ "Use it when the owner asked to be told on WeChat, when a long task finishes or fails, or when it "
|
|
130
|
+
+ "needs a decision while they are away. Keep it short and self-contained: they read it on their phone "
|
|
131
|
+
+ "without this conversation in front of them, so say which task it is about. Do not use it for "
|
|
132
|
+
+ "ordinary replies — they are shown here. If WeChat will not let the bot write first right now "
|
|
133
|
+
+ "(the owner has been silent for about a day), the message is kept and delivered after their next "
|
|
134
|
+
+ "WeChat message; the result says so.",
|
|
135
|
+
parameters: {
|
|
136
|
+
text: { type: "string", required: true, description: "The message, as the owner should read it." },
|
|
137
|
+
summary: {
|
|
138
|
+
type: "string",
|
|
139
|
+
description: "Optional one-sentence version, used if the message has to wait and is folded into a digest.",
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
output: {
|
|
143
|
+
schema: {
|
|
144
|
+
type: "object",
|
|
145
|
+
additionalProperties: false,
|
|
146
|
+
properties: {
|
|
147
|
+
ok: { type: "boolean", required: true },
|
|
148
|
+
summary: { type: "string", required: true },
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
render: (_args, value) => [{ type: "text", text: value.summary }],
|
|
152
|
+
},
|
|
153
|
+
async execute(args, exec) {
|
|
154
|
+
const { ctx, deps } = serving();
|
|
155
|
+
const { text, summary } = args;
|
|
156
|
+
const body = (text ?? "").trim();
|
|
157
|
+
if (body === "")
|
|
158
|
+
return { ok: false, summary: "消息是空的,没有发送" };
|
|
159
|
+
const caller = String(exec?.agent?.session?.id ?? "");
|
|
160
|
+
if (caller !== "" && caller === deps.config.sessionId) {
|
|
161
|
+
return { ok: false, summary: "这是微信会话本身:直接用 send_wechat_text 回复。" };
|
|
162
|
+
}
|
|
163
|
+
const origin = caller === "" ? undefined : await originOf(ctx, caller);
|
|
164
|
+
try {
|
|
165
|
+
const outcome = await notifyOwner(ctx, deps, {
|
|
166
|
+
text: body,
|
|
167
|
+
...(typeof summary === "string" ? { summary } : {}),
|
|
168
|
+
source: "DSH",
|
|
169
|
+
...(origin === undefined ? {} : { origin }),
|
|
170
|
+
});
|
|
171
|
+
if (!outcome.ok)
|
|
172
|
+
return { ok: false, summary: `没发出去:${outcome.message}` };
|
|
173
|
+
if (outcome.deferred === true)
|
|
174
|
+
return { ok: true, summary: outcome.message };
|
|
175
|
+
return { ok: true, summary: `已发到机主微信(${outcome.chars} 字)。` };
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
logger.warn(`${NOTIFY_TOOL}: ${String(err).slice(0, 200)}`);
|
|
179
|
+
return { ok: false, summary: `没发出去:${String(err).slice(0, 200)}` };
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
}));
|
|
183
|
+
const register = () => {
|
|
184
|
+
const off = ctx.tools.register(tool);
|
|
185
|
+
slot.registered = true;
|
|
186
|
+
return () => {
|
|
187
|
+
off();
|
|
188
|
+
// If the host ever does dispose this instance, the next one registers again.
|
|
189
|
+
if (slots[SLOT] === slot)
|
|
190
|
+
slot.registered = false;
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
const scoped = ctx;
|
|
194
|
+
if (typeof scoped.effect === "function")
|
|
195
|
+
scoped.effect(register, `clawbot: ${NOTIFY_TOOL}`);
|
|
196
|
+
else
|
|
197
|
+
register();
|
|
198
|
+
logger.info(`${NOTIFY_TOOL}: registered for every DSH conversation except ${deps.config.sessionId}`);
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=owner-notify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"owner-notify.js","sourceRoot":"","sources":["../src/owner-notify.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAGpD,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,WAAW,EAAmC,MAAM,cAAc,CAAC;AAChG,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAapD,4CAA4C;AAC5C,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC;AAE3C;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAC/B,GAAY,EACZ,SAAiB,EACjB,IAAY,EACZ,MAAc,EACd,IAAa;IAEb,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;QACnD,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QACtC,MAAM,OAAO,GAAG,iBAAiB,CAAC;YAChC,0EAA0E;YAC1E,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,QAAQ,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,KAAK,IAAI,EAAE,EAAE,CA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,IAAI,CAAC,GAAG,WAAW,kDAAkD,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC;AACvG,CAAC"}
|
package/lib/tool.d.ts
CHANGED
|
@@ -11,4 +11,34 @@ export type SendFileToolDeps = {
|
|
|
11
11
|
};
|
|
12
12
|
/** Register the tool into one agent's scoped world (call from setup). */
|
|
13
13
|
export declare function registerSendFileTool(agentCtx: Context, deps: SendFileToolDeps): void;
|
|
14
|
+
/** What one upload came to; `windowClosed` = WeChat would not let the bot write first. */
|
|
15
|
+
/** `permanent`: WeChat will never take it (over the CDN ceiling); anything else may work later. */
|
|
16
|
+
export type FileUploadResult = {
|
|
17
|
+
ok: true;
|
|
18
|
+
} | {
|
|
19
|
+
ok: false;
|
|
20
|
+
windowClosed: boolean;
|
|
21
|
+
permanent: boolean;
|
|
22
|
+
message: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Compress (unless `original`), refuse what the CDN will reject, then upload
|
|
26
|
+
* and send one file. send_wechat_file and the backlog's later delivery share it.
|
|
27
|
+
*/
|
|
28
|
+
export declare function uploadFileTo(params: {
|
|
29
|
+
config: ClawbotConfig;
|
|
30
|
+
account: ResolvedWeixinAccount;
|
|
31
|
+
to: string;
|
|
32
|
+
contextToken: string;
|
|
33
|
+
resolved: string;
|
|
34
|
+
bytes: number;
|
|
35
|
+
caption?: string;
|
|
36
|
+
original?: boolean;
|
|
37
|
+
/** Gets a 「正在发送…」 line when the upload will make the user wait. */
|
|
38
|
+
announce?: (label: string) => void;
|
|
39
|
+
/** Right before the upload starts (after the size check). */
|
|
40
|
+
beforeUpload?: () => void;
|
|
41
|
+
/** When the upload has finished or failed. */
|
|
42
|
+
afterUpload?: () => void;
|
|
43
|
+
}): Promise<FileUploadResult>;
|
|
14
44
|
//# sourceMappingURL=tool.d.ts.map
|
package/lib/tool.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.d.ts","sourceRoot":"","sources":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,EAAE,MAAM,CAAC;IACX,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,mEAAmE;IACnE,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACnC,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,IAAI,CAAC;IAC1B,8CAA8C;IAC9C,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;CAC1B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAqG5B"}
|
package/lib/tool.js
CHANGED
|
@@ -15,6 +15,7 @@ import { compressForUpload, makePreviewCopy } from "./image-compress.js";
|
|
|
15
15
|
import { getMimeFromFilename } from "./ilink/media/mime.js";
|
|
16
16
|
import { stripEmoji, stripWechatCodes } from "./emoji.js";
|
|
17
17
|
import { appendMemoryEntry, oneOffReminderReason } from "./memory.js";
|
|
18
|
+
import { isSendWindowClosed } from "./backlog.js";
|
|
18
19
|
import { logger } from "./ilink/util/logger.js";
|
|
19
20
|
/**
|
|
20
21
|
* Payload sizes above which the WeChat C2C CDN refuses an upload.
|
|
@@ -237,18 +238,24 @@ export function registerSendFileTool(agentCtx, deps) {
|
|
|
237
238
|
properties: {
|
|
238
239
|
ok: { type: "boolean", required: true },
|
|
239
240
|
message: { type: "string", required: true },
|
|
241
|
+
deferred: { type: "boolean" },
|
|
242
|
+
held: { type: "boolean" },
|
|
240
243
|
},
|
|
241
244
|
},
|
|
242
245
|
render: (_args, value) => [
|
|
243
246
|
{
|
|
244
247
|
type: "text",
|
|
245
|
-
text: value.
|
|
246
|
-
?
|
|
247
|
-
:
|
|
248
|
+
text: value.held
|
|
249
|
+
? `先没发,对方又发来了新消息: ${value.message}`
|
|
250
|
+
: value.deferred
|
|
251
|
+
? `⏳ 已存下,稍后补发: ${value.message}`
|
|
252
|
+
: value.ok
|
|
253
|
+
? `✅ 文件已发送到微信: ${value.message}`
|
|
254
|
+
: `❌ 发送失败: ${value.message}`,
|
|
248
255
|
},
|
|
249
256
|
],
|
|
250
257
|
},
|
|
251
|
-
async execute(args) {
|
|
258
|
+
async execute(args, exec) {
|
|
252
259
|
const { path: rawPath, caption, original } = args;
|
|
253
260
|
const bridge = deps.getBridge();
|
|
254
261
|
if (!bridge) {
|
|
@@ -262,6 +269,11 @@ export function registerSendFileTool(agentCtx, deps) {
|
|
|
262
269
|
if (!sender) {
|
|
263
270
|
return { ok: false, message: "无法确定收件人(没有活跃的微信会话)" };
|
|
264
271
|
}
|
|
272
|
+
// Read before replying: they wrote more that this reply has not seen.
|
|
273
|
+
if (await bridge.holdReply(sender, exec?.signal))
|
|
274
|
+
return { ok: false, held: true, message: bridge.holdMessage };
|
|
275
|
+
if (exec?.signal?.aborted)
|
|
276
|
+
return { ok: false, message: "这一轮已经停止,文件没有发出。" };
|
|
265
277
|
const resolved = path.isAbsolute(rawPath)
|
|
266
278
|
? path.normalize(rawPath)
|
|
267
279
|
: path.resolve(deps.config.cwd ?? process.cwd(), rawPath);
|
|
@@ -276,108 +288,148 @@ export function registerSendFileTool(agentCtx, deps) {
|
|
|
276
288
|
return { ok: false, message: `不是普通文件: ${resolved}` };
|
|
277
289
|
}
|
|
278
290
|
logger.info(`send_wechat_file: sending ${resolved} (${stat.size} bytes) to ${sender}`);
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
// is measured against the ceiling that will actually apply.
|
|
306
|
-
const isImage = getMimeFromFilename(prep.path).startsWith("image/");
|
|
307
|
-
const ceiling = isImage ? CDN_REJECT_ABOVE_IMAGE_BYTES : CDN_REJECT_ABOVE_FILE_BYTES;
|
|
308
|
-
if (prep.bytes > ceiling) {
|
|
309
|
-
const mb = (prep.bytes / (1024 * 1024)).toFixed(1);
|
|
310
|
-
const limit = (ceiling / (1024 * 1024)).toFixed(1);
|
|
311
|
-
logger.warn(`send_wechat_file: ${prep.bytes} bytes exceeds the CDN ceiling; refused without uploading`);
|
|
312
|
-
if (prep.temp) {
|
|
313
|
-
try {
|
|
314
|
-
fs.unlinkSync(prep.path);
|
|
315
|
-
}
|
|
316
|
-
catch { /* best effort */ }
|
|
317
|
-
}
|
|
291
|
+
const upload = await uploadFileTo({
|
|
292
|
+
config: deps.config,
|
|
293
|
+
account,
|
|
294
|
+
to: sender,
|
|
295
|
+
contextToken: bridge.contextTokenFor(sender),
|
|
296
|
+
resolved,
|
|
297
|
+
bytes: stat.size,
|
|
298
|
+
caption,
|
|
299
|
+
original,
|
|
300
|
+
announce: (label) => { bridge.sendTextTo(sender, label, { transient: true }); },
|
|
301
|
+
// 「正在输入」 while the upload runs. Usually already up for the whole
|
|
302
|
+
// turn (see typing.ts); this covers a file sent from a reminder turn.
|
|
303
|
+
beforeUpload: () => {
|
|
304
|
+
bridge.noteAnswered();
|
|
305
|
+
bridge.showTyping(sender);
|
|
306
|
+
},
|
|
307
|
+
// The file (or the failure) lands now: restart the keepalive clock so
|
|
308
|
+
// the indicator does not flash back right after it.
|
|
309
|
+
afterUpload: () => bridge.noteDelivered(sender),
|
|
310
|
+
});
|
|
311
|
+
if (upload.ok)
|
|
312
|
+
return { ok: true, message: resolved };
|
|
313
|
+
if (upload.windowClosed) {
|
|
314
|
+
// WeChat will not let the bot write first right now: keep it and send
|
|
315
|
+
// it after the user's next message (see backlog.ts).
|
|
316
|
+
bridge.keepFile(sender, { path: resolved, caption, original });
|
|
318
317
|
return {
|
|
319
|
-
ok:
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
? "把设置里的「图片长边上限」或「JPEG 质量」调低一点再试(压缩阈值也要低于这个上限才有用)。"
|
|
323
|
-
: "非图片走的是另一条上传通道,上限低得多,而且没法压缩 —— 只能换个方式给:压缩分卷、或者放云盘/AirDrop 发链接。"),
|
|
318
|
+
ok: true,
|
|
319
|
+
deferred: true,
|
|
320
|
+
message: `${resolved}(微信现在不让 bot 主动发消息,这个文件已存下,对方下次发消息、你回复完之后会自动补发,不用重试)`,
|
|
324
321
|
};
|
|
325
322
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
323
|
+
return { ok: false, message: upload.message };
|
|
324
|
+
},
|
|
325
|
+
}));
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Compress (unless `original`), refuse what the CDN will reject, then upload
|
|
329
|
+
* and send one file. send_wechat_file and the backlog's later delivery share it.
|
|
330
|
+
*/
|
|
331
|
+
export async function uploadFileTo(params) {
|
|
332
|
+
const { config, account, to, contextToken, resolved, bytes, caption, original, announce, beforeUpload, afterUpload } = params;
|
|
333
|
+
// Originals were sent verbatim here until full-resolution camera files
|
|
334
|
+
// (5568x3712, 5-12MB) started making the C2C CDN answer HTTP 500 —
|
|
335
|
+
// opaque, and each failure burned the whole retry ladder, so one photo
|
|
336
|
+
// hung for ~4 minutes and then failed. Downscale first unless the
|
|
337
|
+
// caller explicitly asked for the untouched file.
|
|
338
|
+
const prep = original === true
|
|
339
|
+
? { path: resolved, bytes, temp: false, note: undefined }
|
|
340
|
+
: compressForUpload(resolved, {
|
|
341
|
+
maxImageEdge: config.maxImageEdge,
|
|
342
|
+
imageQuality: config.imageQuality,
|
|
343
|
+
compressThresholdBytes: config.compressThresholdBytes,
|
|
344
|
+
});
|
|
345
|
+
// Refuse before uploading what the CDN will certainly reject.
|
|
346
|
+
//
|
|
347
|
+
// Measured on this account: a 2.26MB payload uploads fine, a 4.1MB image
|
|
348
|
+
// gets an opaque HTTP 500, and 7.2MB / 18.3MB files get the same. The
|
|
349
|
+
// CDN never says "too large" — it just fails, three times, ~20s each.
|
|
350
|
+
//
|
|
351
|
+
// Two reasons this guard is worth having rather than letting it fail.
|
|
352
|
+
// Compression only exists for images (downscale + quality ladder); an
|
|
353
|
+
// archive or an .xpi cannot be shrunk, so for those a rejection is the
|
|
354
|
+
// final answer and spending a minute to reach it is pure waste. And the
|
|
355
|
+
// old failure text advised "downscale before sending", which is not
|
|
356
|
+
// something the user can do to a browser extension — advice that cannot
|
|
357
|
+
// be followed is worse than none.
|
|
358
|
+
// Same test `sendWeixinMediaFile` uses to pick the upload, so the guard
|
|
359
|
+
// is measured against the ceiling that will actually apply.
|
|
360
|
+
const isImage = getMimeFromFilename(prep.path).startsWith("image/");
|
|
361
|
+
const ceiling = isImage ? CDN_REJECT_ABOVE_IMAGE_BYTES : CDN_REJECT_ABOVE_FILE_BYTES;
|
|
362
|
+
if (prep.bytes > ceiling) {
|
|
363
|
+
const mb = (prep.bytes / (1024 * 1024)).toFixed(1);
|
|
364
|
+
const limit = (ceiling / (1024 * 1024)).toFixed(1);
|
|
365
|
+
logger.warn(`send_wechat_file: ${prep.bytes} bytes exceeds the CDN ceiling; refused without uploading`);
|
|
366
|
+
if (prep.temp) {
|
|
367
|
+
try {
|
|
368
|
+
fs.unlinkSync(prep.path);
|
|
339
369
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
370
|
+
catch { /* best effort */ }
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
ok: false,
|
|
374
|
+
windowClosed: false,
|
|
375
|
+
permanent: true,
|
|
376
|
+
message: `这个文件 ${mb} MB,超过微信 CDN 实测能收的上限(约 ${limit} MB),传上去只会拿到一个没有说明的 500。`
|
|
377
|
+
+ (isImage
|
|
378
|
+
? "把设置里的「图片长边上限」或「JPEG 质量」调低一点再试(压缩阈值也要低于这个上限才有用)。"
|
|
379
|
+
: "非图片走的是另一条上传通道,上限低得多,而且没法压缩 —— 只能换个方式给:压缩分卷、或者放云盘/AirDrop 发链接。"),
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
// Announce the upload only when it is actually going to make the user
|
|
383
|
+
// wait. A downscaled photo is a few hundred KB and lands within a
|
|
384
|
+
// second or two, so a "正在发送…" line arriving just ahead of the image
|
|
385
|
+
// reads as a duplicate of the image itself — the typing indicator below
|
|
386
|
+
// already covers that case. Big files (untouched originals, PDFs,
|
|
387
|
+
// archives, video) can take a minute, and there the notice is the only
|
|
388
|
+
// thing telling the user to wait.
|
|
389
|
+
if (prep.bytes >= config.noticeMinBytes) {
|
|
390
|
+
const sizeMb = (prep.bytes / (1024 * 1024)).toFixed(1);
|
|
391
|
+
const label = prep.note !== undefined
|
|
392
|
+
? `正在发送 \`${path.basename(resolved)}\`(已压缩 ${prep.note}),可能需要一会儿…`
|
|
393
|
+
: `正在发送 \`${path.basename(resolved)}\`(${sizeMb} MB),大文件可能需要一会儿…`;
|
|
394
|
+
announce?.(label);
|
|
395
|
+
}
|
|
396
|
+
beforeUpload?.();
|
|
397
|
+
try {
|
|
398
|
+
await sendWeixinMediaFile({
|
|
399
|
+
filePath: prep.path,
|
|
400
|
+
to,
|
|
401
|
+
text: config.stripEmoji ? stripEmoji(caption ?? "") : stripWechatCodes(caption ?? ""),
|
|
402
|
+
opts: {
|
|
403
|
+
baseUrl: account.baseUrl,
|
|
404
|
+
token: account.token,
|
|
405
|
+
contextToken,
|
|
406
|
+
timeoutMs: 30_000,
|
|
407
|
+
},
|
|
408
|
+
cdnBaseUrl: account.cdnBaseUrl,
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
logger.error(`send_wechat_file: failed ${resolved}: ${String(err)}`);
|
|
413
|
+
return {
|
|
414
|
+
ok: false,
|
|
415
|
+
windowClosed: isSendWindowClosed(err),
|
|
416
|
+
permanent: false,
|
|
417
|
+
message: `发送失败: ${err instanceof Error ? err.message : String(err)}`,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
finally {
|
|
421
|
+
// Drop the downscaled copy; the original on disk is never touched.
|
|
422
|
+
if (prep.temp) {
|
|
343
423
|
try {
|
|
344
|
-
|
|
345
|
-
filePath: prep.path,
|
|
346
|
-
to: sender,
|
|
347
|
-
text: deps.config.stripEmoji ? stripEmoji(caption ?? "") : stripWechatCodes(caption ?? ""),
|
|
348
|
-
opts: {
|
|
349
|
-
baseUrl: account.baseUrl,
|
|
350
|
-
token: account.token,
|
|
351
|
-
contextToken: bridge.contextTokenFor(sender),
|
|
352
|
-
timeoutMs: 30_000,
|
|
353
|
-
},
|
|
354
|
-
cdnBaseUrl: account.cdnBaseUrl,
|
|
355
|
-
});
|
|
424
|
+
fs.rmSync(prep.path, { force: true });
|
|
356
425
|
}
|
|
357
426
|
catch (err) {
|
|
358
|
-
logger.
|
|
359
|
-
return {
|
|
360
|
-
ok: false,
|
|
361
|
-
message: `发送失败: ${err instanceof Error ? err.message : String(err)}`,
|
|
362
|
-
};
|
|
427
|
+
logger.debug(`send_wechat_file: temp cleanup failed (non-fatal): ${String(err)}`);
|
|
363
428
|
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
fs.rmSync(prep.path, { force: true });
|
|
369
|
-
}
|
|
370
|
-
catch (err) {
|
|
371
|
-
logger.debug(`send_wechat_file: temp cleanup failed (non-fatal): ${String(err)}`);
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
// The file (or the failure) lands now: restart the keepalive clock so
|
|
375
|
-
// the indicator does not flash back right after it.
|
|
376
|
-
bridge.noteDelivered(sender);
|
|
377
|
-
}
|
|
378
|
-
return { ok: true, message: resolved };
|
|
379
|
-
},
|
|
380
|
-
}));
|
|
429
|
+
}
|
|
430
|
+
afterUpload?.();
|
|
431
|
+
}
|
|
432
|
+
return { ok: true };
|
|
381
433
|
}
|
|
382
434
|
/**
|
|
383
435
|
* Register `remember_user_info`: lets the WeChat agent append durable facts
|
|
@@ -471,16 +523,19 @@ function registerSendTextTool(agentCtx, deps) {
|
|
|
471
523
|
properties: {
|
|
472
524
|
ok: { type: "boolean", required: true },
|
|
473
525
|
message: { type: "string", required: true },
|
|
526
|
+
held: { type: "boolean" },
|
|
474
527
|
},
|
|
475
528
|
},
|
|
476
529
|
render: (_args, value) => [
|
|
477
530
|
{
|
|
478
531
|
type: "text",
|
|
479
|
-
text: value.
|
|
532
|
+
text: value.held
|
|
533
|
+
? `先没发,对方又发来了新消息: ${value.message}`
|
|
534
|
+
: value.ok ? `微信消息已发送: ${value.message}` : `微信消息发送失败: ${value.message}`,
|
|
480
535
|
},
|
|
481
536
|
],
|
|
482
537
|
},
|
|
483
|
-
async execute(args) {
|
|
538
|
+
async execute(args, exec) {
|
|
484
539
|
const { text } = args;
|
|
485
540
|
const content = (text ?? "").trim();
|
|
486
541
|
if (!content) {
|
|
@@ -498,6 +553,11 @@ function registerSendTextTool(agentCtx, deps) {
|
|
|
498
553
|
if (!sender) {
|
|
499
554
|
return { ok: false, message: "无法确定收件人(没有活跃的微信会话)" };
|
|
500
555
|
}
|
|
556
|
+
// Read before replying: they wrote more that this reply has not seen.
|
|
557
|
+
if (await bridge.holdReply(sender, exec?.signal))
|
|
558
|
+
return { ok: false, held: true, message: bridge.holdMessage };
|
|
559
|
+
if (exec?.signal?.aborted)
|
|
560
|
+
return { ok: false, message: "这一轮已经停止,这条没有发出。" };
|
|
501
561
|
const finalText = deps.config.stripEmoji ? stripEmoji(content) : stripWechatCodes(content);
|
|
502
562
|
if (!bridge.sendTextTo(sender, finalText)) {
|
|
503
563
|
return { ok: false, message: "这一轮已经发满 10 条,这条没有发出,本轮也不能再发了。" };
|
|
@@ -550,6 +610,12 @@ function registerWechatAskTool(agentCtx, deps) {
|
|
|
550
610
|
const bridge = deps.getBridge();
|
|
551
611
|
if (!bridge)
|
|
552
612
|
return { ok: false, message: "微信桥接未运行(监控未启动)" };
|
|
613
|
+
// Read before asking: what they just wrote may already answer it.
|
|
614
|
+
const recipient = bridge.activeSender ?? deps.getAccount()?.userId;
|
|
615
|
+
if (recipient && await bridge.holdReply(recipient, exec.signal))
|
|
616
|
+
return { ok: false, message: bridge.holdMessage };
|
|
617
|
+
if (exec.signal?.aborted)
|
|
618
|
+
return { ok: false, message: "这一轮已经停止,没有提问。" };
|
|
553
619
|
// Forward the turn's signal: a stopped turn withdraws its question
|
|
554
620
|
// instead of leaving it to swallow the user's next message.
|
|
555
621
|
const answer = await bridge.askWechat(q, undefined, exec.signal);
|