wechat-clawbot 0.9.1
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/LICENSE +21 -0
- package/NOTICE +32 -0
- package/README.md +324 -0
- package/README.zh.md +192 -0
- package/cordis.patch.yml +23 -0
- package/lib/approvals.d.ts +29 -0
- package/lib/approvals.d.ts.map +1 -0
- package/lib/approvals.js +86 -0
- package/lib/approvals.js.map +1 -0
- package/lib/bridge.d.ts +281 -0
- package/lib/bridge.d.ts.map +1 -0
- package/lib/bridge.js +827 -0
- package/lib/bridge.js.map +1 -0
- package/lib/claude-peer.d.ts +44 -0
- package/lib/claude-peer.d.ts.map +1 -0
- package/lib/claude-peer.js +515 -0
- package/lib/claude-peer.js.map +1 -0
- package/lib/cli.d.ts +3 -0
- package/lib/cli.d.ts.map +1 -0
- package/lib/cli.js +128 -0
- package/lib/cli.js.map +1 -0
- package/lib/client.js +597 -0
- package/lib/config.d.ts +160 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +187 -0
- package/lib/config.js.map +1 -0
- package/lib/emoji.d.ts +26 -0
- package/lib/emoji.d.ts.map +1 -0
- package/lib/emoji.js +54 -0
- package/lib/emoji.js.map +1 -0
- package/lib/ilink/api/api.d.ts +134 -0
- package/lib/ilink/api/api.d.ts.map +1 -0
- package/lib/ilink/api/api.js +507 -0
- package/lib/ilink/api/api.js.map +1 -0
- package/lib/ilink/api/session-guard.d.ts +16 -0
- package/lib/ilink/api/session-guard.d.ts.map +1 -0
- package/lib/ilink/api/session-guard.js +49 -0
- package/lib/ilink/api/session-guard.js.map +1 -0
- package/lib/ilink/api/types.d.ts +251 -0
- package/lib/ilink/api/types.d.ts.map +1 -0
- package/lib/ilink/api/types.js +37 -0
- package/lib/ilink/api/types.js.map +1 -0
- package/lib/ilink/auth/accounts.d.ts +67 -0
- package/lib/ilink/auth/accounts.d.ts.map +1 -0
- package/lib/ilink/auth/accounts.js +190 -0
- package/lib/ilink/auth/accounts.js.map +1 -0
- package/lib/ilink/auth/login-qr.d.ts +43 -0
- package/lib/ilink/auth/login-qr.d.ts.map +1 -0
- package/lib/ilink/auth/login-qr.js +333 -0
- package/lib/ilink/auth/login-qr.js.map +1 -0
- package/lib/ilink/cdn/aes-ecb.d.ts +7 -0
- package/lib/ilink/cdn/aes-ecb.d.ts.map +1 -0
- package/lib/ilink/cdn/aes-ecb.js +19 -0
- package/lib/ilink/cdn/aes-ecb.js.map +1 -0
- package/lib/ilink/cdn/cdn-upload.d.ts +18 -0
- package/lib/ilink/cdn/cdn-upload.d.ts.map +1 -0
- package/lib/ilink/cdn/cdn-upload.js +90 -0
- package/lib/ilink/cdn/cdn-upload.js.map +1 -0
- package/lib/ilink/cdn/cdn-url.d.ts +14 -0
- package/lib/ilink/cdn/cdn-url.d.ts.map +1 -0
- package/lib/ilink/cdn/cdn-url.js +14 -0
- package/lib/ilink/cdn/cdn-url.js.map +1 -0
- package/lib/ilink/cdn/pic-decrypt.d.ts +10 -0
- package/lib/ilink/cdn/pic-decrypt.d.ts.map +1 -0
- package/lib/ilink/cdn/pic-decrypt.js +89 -0
- package/lib/ilink/cdn/pic-decrypt.js.map +1 -0
- package/lib/ilink/cdn/upload.d.ts +43 -0
- package/lib/ilink/cdn/upload.d.ts.map +1 -0
- package/lib/ilink/cdn/upload.js +115 -0
- package/lib/ilink/cdn/upload.js.map +1 -0
- package/lib/ilink/media/mime.d.ts +7 -0
- package/lib/ilink/media/mime.d.ts.map +1 -0
- package/lib/ilink/media/mime.js +73 -0
- package/lib/ilink/media/mime.js.map +1 -0
- package/lib/ilink/messaging/send-media.d.ts +23 -0
- package/lib/ilink/messaging/send-media.d.ts.map +1 -0
- package/lib/ilink/messaging/send-media.js +71 -0
- package/lib/ilink/messaging/send-media.js.map +1 -0
- package/lib/ilink/messaging/send.d.ts +55 -0
- package/lib/ilink/messaging/send.d.ts.map +1 -0
- package/lib/ilink/messaging/send.js +182 -0
- package/lib/ilink/messaging/send.js.map +1 -0
- package/lib/ilink/storage/state-dir.d.ts +14 -0
- package/lib/ilink/storage/state-dir.d.ts.map +1 -0
- package/lib/ilink/storage/state-dir.js +22 -0
- package/lib/ilink/storage/state-dir.js.map +1 -0
- package/lib/ilink/storage/sync-buf.d.ts +21 -0
- package/lib/ilink/storage/sync-buf.d.ts.map +1 -0
- package/lib/ilink/storage/sync-buf.js +64 -0
- package/lib/ilink/storage/sync-buf.js.map +1 -0
- package/lib/ilink/util/logger.d.ts +20 -0
- package/lib/ilink/util/logger.d.ts.map +1 -0
- package/lib/ilink/util/logger.js +73 -0
- package/lib/ilink/util/logger.js.map +1 -0
- package/lib/ilink/util/random.d.ts +11 -0
- package/lib/ilink/util/random.d.ts.map +1 -0
- package/lib/ilink/util/random.js +16 -0
- package/lib/ilink/util/random.js.map +1 -0
- package/lib/ilink/util/redact.d.ts +21 -0
- package/lib/ilink/util/redact.d.ts.map +1 -0
- package/lib/ilink/util/redact.js +54 -0
- package/lib/ilink/util/redact.js.map +1 -0
- package/lib/image-compress.d.ts +38 -0
- package/lib/image-compress.d.ts.map +1 -0
- package/lib/image-compress.js +184 -0
- package/lib/image-compress.js.map +1 -0
- package/lib/inbound-media.d.ts +17 -0
- package/lib/inbound-media.d.ts.map +1 -0
- package/lib/inbound-media.js +96 -0
- package/lib/inbound-media.js.map +1 -0
- package/lib/inbound.d.ts +28 -0
- package/lib/inbound.d.ts.map +1 -0
- package/lib/inbound.js +265 -0
- package/lib/inbound.js.map +1 -0
- package/lib/index.d.ts +23 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +321 -0
- package/lib/index.js.map +1 -0
- package/lib/mcp-route.d.ts +33 -0
- package/lib/mcp-route.d.ts.map +1 -0
- package/lib/mcp-route.js +422 -0
- package/lib/mcp-route.js.map +1 -0
- package/lib/memory-auto.d.ts +22 -0
- package/lib/memory-auto.d.ts.map +1 -0
- package/lib/memory-auto.js +144 -0
- package/lib/memory-auto.js.map +1 -0
- package/lib/memory.d.ts +26 -0
- package/lib/memory.d.ts.map +1 -0
- package/lib/memory.js +168 -0
- package/lib/memory.js.map +1 -0
- package/lib/models-route.d.ts +24 -0
- package/lib/models-route.d.ts.map +1 -0
- package/lib/models-route.js +84 -0
- package/lib/models-route.js.map +1 -0
- package/lib/monitor.d.ts +13 -0
- package/lib/monitor.d.ts.map +1 -0
- package/lib/monitor.js +116 -0
- package/lib/monitor.js.map +1 -0
- package/lib/pending.d.ts +23 -0
- package/lib/pending.d.ts.map +1 -0
- package/lib/pending.js +38 -0
- package/lib/pending.js.map +1 -0
- package/lib/prompt.d.ts +36 -0
- package/lib/prompt.d.ts.map +1 -0
- package/lib/prompt.js +246 -0
- package/lib/prompt.js.map +1 -0
- package/lib/questions.d.ts +21 -0
- package/lib/questions.d.ts.map +1 -0
- package/lib/questions.js +116 -0
- package/lib/questions.js.map +1 -0
- package/lib/quote-history.d.ts +18 -0
- package/lib/quote-history.d.ts.map +1 -0
- package/lib/quote-history.js +96 -0
- package/lib/quote-history.js.map +1 -0
- package/lib/state.d.ts +27 -0
- package/lib/state.d.ts.map +1 -0
- package/lib/state.js +154 -0
- package/lib/state.js.map +1 -0
- package/lib/subagent-model.d.ts +26 -0
- package/lib/subagent-model.d.ts.map +1 -0
- package/lib/subagent-model.js +30 -0
- package/lib/subagent-model.js.map +1 -0
- package/lib/tool.d.ts +14 -0
- package/lib/tool.d.ts.map +1 -0
- package/lib/tool.js +518 -0
- package/lib/tool.js.map +1 -0
- package/package.json +94 -0
package/lib/bridge.js
ADDED
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH integration bridge: maps WeChat messages onto one fixed agent session.
|
|
3
|
+
*
|
|
4
|
+
* Every inbound WeChat message (from any allowed sender) is queued into the
|
|
5
|
+
* SAME persisted session (`config.sessionId`), so the conversation keeps one
|
|
6
|
+
* context and is compacted like any other DSH session. Assistant replies are
|
|
7
|
+
* collected from the durable `session/event` feed and sent back to the WeChat
|
|
8
|
+
* user who triggered the turn.
|
|
9
|
+
*/
|
|
10
|
+
import { readFileSync, unlinkSync } from "node:fs";
|
|
11
|
+
import { basename } from "node:path";
|
|
12
|
+
import { installModelSelection, } from "@deepseek-ai/dsh-agent";
|
|
13
|
+
import { SessionId } from "@deepseek-ai/dsh-session";
|
|
14
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
15
|
+
import { compressForUpload } from "./image-compress.js";
|
|
16
|
+
import { registerClaudePeerTools } from "./claude-peer.js";
|
|
17
|
+
import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
|
|
18
|
+
import { markSessionCreated, wasSessionCreated } from "./state.js";
|
|
19
|
+
import { registerSendFileTool } from "./tool.js";
|
|
20
|
+
import { captureTurnMemory } from "./memory-auto.js";
|
|
21
|
+
import { logger } from "./ilink/util/logger.js";
|
|
22
|
+
export class WechatBridge {
|
|
23
|
+
ctx;
|
|
24
|
+
config;
|
|
25
|
+
sendText;
|
|
26
|
+
deps;
|
|
27
|
+
sessionId;
|
|
28
|
+
handle = null;
|
|
29
|
+
disposed = false;
|
|
30
|
+
/** Agent contexts we already installed the model selection on (avoid duplicates). */
|
|
31
|
+
selectionInstalled = new WeakSet();
|
|
32
|
+
/** Queued turns waiting for the serialized worker (oldest first). */
|
|
33
|
+
queue = [];
|
|
34
|
+
/** Whether the WeChat tools are registered on the current agent scope. */
|
|
35
|
+
toolsRegistered = false;
|
|
36
|
+
/** The sender whose turn is currently being driven (approvals go to them). */
|
|
37
|
+
currentSender;
|
|
38
|
+
/** Messages sent in the current turn (cap enforcement, RULE B). */
|
|
39
|
+
turnMessageCount = 0;
|
|
40
|
+
/** Per-turn outbound message cap. */
|
|
41
|
+
static MAX_TURN_MESSAGES = 10;
|
|
42
|
+
/** The serialized turn worker (one followup → idle at a time). */
|
|
43
|
+
worker = null;
|
|
44
|
+
/** Time index of session message events (for quote backfill). */
|
|
45
|
+
sessionIndex = null;
|
|
46
|
+
/**
|
|
47
|
+
* Serialized outbound chain: assistant segments, tool acks, and approvals
|
|
48
|
+
* are delivered one at a time so WeChat messages never interleave.
|
|
49
|
+
*/
|
|
50
|
+
sendChain = Promise.resolve();
|
|
51
|
+
constructor(ctx, config, sendText, deps) {
|
|
52
|
+
this.ctx = ctx;
|
|
53
|
+
this.config = config;
|
|
54
|
+
this.sendText = sendText;
|
|
55
|
+
this.deps = deps;
|
|
56
|
+
this.sessionId = SessionId(config.sessionId);
|
|
57
|
+
}
|
|
58
|
+
/** Outbound context token for a WeChat sender ("" when unknown). */
|
|
59
|
+
contextTokenFor(sender) {
|
|
60
|
+
return this.deps.getContextToken(sender);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Send one text message to a WeChat user, serialized behind every other
|
|
64
|
+
* outbound message so delivery order is preserved.
|
|
65
|
+
*/
|
|
66
|
+
sendTextTo(sender, text) {
|
|
67
|
+
// Per-turn message cap (mirrors RULE B's "约 10 条"): beyond 10 messages
|
|
68
|
+
// in one turn, drop extras and warn. Resets when a new turn starts
|
|
69
|
+
// (drainQueue sets currentSender).
|
|
70
|
+
if (this.turnMessageCount >= WechatBridge.MAX_TURN_MESSAGES) {
|
|
71
|
+
logger.warn(`sendTextTo: turn message cap (${WechatBridge.MAX_TURN_MESSAGES}) reached for ${sender}; dropping: ${text.slice(0, 40)}…`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
this.turnMessageCount += 1;
|
|
75
|
+
this.sendChain = this.sendChain.then(async () => {
|
|
76
|
+
try {
|
|
77
|
+
await this.sendText(sender, text);
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
logger.error(`sendTextTo: failed to ${sender}: ${String(err)}`);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
get id() {
|
|
85
|
+
return this.sessionId;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Ask the user a question THROUGH WeChat and wait for their reply.
|
|
89
|
+
* Used by the WeChat-scoped ask_user_question override so bot questions
|
|
90
|
+
* never pop up in the webapp GUI. Returns the raw reply text, or null on
|
|
91
|
+
* timeout / abort.
|
|
92
|
+
*/
|
|
93
|
+
askWechat(question, timeoutMs = 300_000) {
|
|
94
|
+
const sender = this.currentSender ?? this.deps.getAccount()?.userId;
|
|
95
|
+
if (!sender)
|
|
96
|
+
return Promise.resolve(null);
|
|
97
|
+
this.sendTextTo(sender, question);
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
const timer = setTimeout(() => {
|
|
100
|
+
this.deps.pending.abortFor(sender);
|
|
101
|
+
resolve(null);
|
|
102
|
+
}, timeoutMs);
|
|
103
|
+
this.deps.pending.push({
|
|
104
|
+
tag: "question",
|
|
105
|
+
sender,
|
|
106
|
+
resolve: (reply) => {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
resolve(reply);
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Install the deployment default model selection (provider/model/
|
|
115
|
+
* reasoningEffort from settings.yaml) onto an agent context, once per
|
|
116
|
+
* context. Used both by the agent setup and for agents the harness
|
|
117
|
+
* resumed directly without running the bridge setup.
|
|
118
|
+
*/
|
|
119
|
+
/**
|
|
120
|
+
* One mutable selection shared by every agent context this bridge installs
|
|
121
|
+
* into. `installModelSelection` is documented to snapshot `current` per step,
|
|
122
|
+
* so writing a new value here switches the model from the next step onward —
|
|
123
|
+
* no reinstall, no restart, no dropped WeChat connection.
|
|
124
|
+
*/
|
|
125
|
+
selectionRef = { current: undefined, assembled: undefined };
|
|
126
|
+
/**
|
|
127
|
+
* What this session should route to: the plugin's own pin when configured,
|
|
128
|
+
* otherwise the deployment default.
|
|
129
|
+
*
|
|
130
|
+
* The default-following branch is why choosing a model in the web UI used to
|
|
131
|
+
* move the bot as well — that picker writes through to the global
|
|
132
|
+
* `agent-default-model`, and with nothing pinned here the bot simply adopts
|
|
133
|
+
* it. Setting `model` in this plugin's settings breaks that coupling.
|
|
134
|
+
*/
|
|
135
|
+
desiredSelection() {
|
|
136
|
+
const pinned = this.config.model;
|
|
137
|
+
if (pinned !== undefined) {
|
|
138
|
+
return {
|
|
139
|
+
provider: this.config.provider ?? "deepseek-official",
|
|
140
|
+
model: pinned,
|
|
141
|
+
...(this.config.reasoningEffort === undefined
|
|
142
|
+
? {}
|
|
143
|
+
: { reasoningEffort: this.config.reasoningEffort }),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return this.ctx.get("agentDefaultModel")?.currentSelection();
|
|
147
|
+
}
|
|
148
|
+
installSelection(agentCtx) {
|
|
149
|
+
if (this.selectionInstalled.has(agentCtx))
|
|
150
|
+
return;
|
|
151
|
+
const selection = this.desiredSelection();
|
|
152
|
+
if (!selection)
|
|
153
|
+
return;
|
|
154
|
+
this.selectionRef.current = selection;
|
|
155
|
+
try {
|
|
156
|
+
installModelSelection(agentCtx, this.selectionRef);
|
|
157
|
+
this.selectionInstalled.add(agentCtx);
|
|
158
|
+
logger.info(`ensureAgent: model selection installed (${selection.provider}/${selection.model} reasoningEffort=${selection.reasoningEffort ?? "(default)"}${this.config.model === undefined ? " ,跟随全局默认" : " ,插件自己钉的"})`);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
logger.warn(`ensureAgent: installModelSelection failed: ${String(err)}`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Re-point the live selection after a settings change.
|
|
166
|
+
*
|
|
167
|
+
* A model id that cannot be resolved is REFUSED rather than applied: a typo
|
|
168
|
+
* in the settings box would otherwise brick the bot on its next message, and
|
|
169
|
+
* the failure would surface as a request error with no obvious cause. When
|
|
170
|
+
* the llm service is unavailable the value is taken on trust — refusing
|
|
171
|
+
* everything would be worse than a possible bad pin.
|
|
172
|
+
*/
|
|
173
|
+
async refreshSelection() {
|
|
174
|
+
const next = this.desiredSelection();
|
|
175
|
+
if (next === undefined) {
|
|
176
|
+
logger.warn("refreshSelection: 既没有插件自己的设置,也读不到全局默认,保持原样");
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
// Nothing installed yet means this ran before the agent was set up — the
|
|
180
|
+
// settings hook fires at attach, which can beat provider registration. There
|
|
181
|
+
// is no good selection to protect here, and installSelection() is about to
|
|
182
|
+
// assign one anyway, so refusing would only print a scary warning about a
|
|
183
|
+
// value that turns out to be fine.
|
|
184
|
+
if (this.selectionRef.current === undefined) {
|
|
185
|
+
this.selectionRef.current = next;
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const llm = this.llmService();
|
|
189
|
+
if (llm !== undefined) {
|
|
190
|
+
try {
|
|
191
|
+
await llm.resolveModelInfo(next.provider, next.model);
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
logger.warn(`refreshSelection: 解析不出 ${next.provider}/${next.model}(${String(err).slice(0, 100)}),拒绝换过去,继续用 ${this.selectionRef.current?.provider}/${this.selectionRef.current?.model}`);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
this.selectionRef.current = next;
|
|
199
|
+
logger.info(`refreshSelection: 微信会话现在走 ${next.provider}/${next.model} reasoningEffort=${next.reasoningEffort ?? "(默认)"}`);
|
|
200
|
+
await this.reportVisionReadiness();
|
|
201
|
+
}
|
|
202
|
+
/** Whether the given session id is the WeChat session. */
|
|
203
|
+
isWechatSession(sessionId) {
|
|
204
|
+
return sessionId === this.sessionId;
|
|
205
|
+
}
|
|
206
|
+
/** The sender the current activity is attributed to (for approval routing). */
|
|
207
|
+
get activeSender() {
|
|
208
|
+
return this.currentSender;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Get (or create/resume) the WeChat agent. The agent is composed from the
|
|
212
|
+
* deployment's default agent preset (standard coding tools) and its
|
|
213
|
+
* approval policy is forced to `ask`, so remote access requests arrive in
|
|
214
|
+
* WeChat regardless of the deployment-wide policy.
|
|
215
|
+
*
|
|
216
|
+
* Mirrors the headless runner's creation pattern: wait for the loader to
|
|
217
|
+
* finish composing sibling plugins (otherwise the agent's world is
|
|
218
|
+
* half-composed and the driver can stall) and install the deployment's
|
|
219
|
+
* default model selection into the agent scope.
|
|
220
|
+
*/
|
|
221
|
+
async ensureAgent() {
|
|
222
|
+
if (this.disposed)
|
|
223
|
+
throw new Error("clawbot bridge disposed");
|
|
224
|
+
const live = this.ctx.agents.get(this.sessionId);
|
|
225
|
+
if (live) {
|
|
226
|
+
// The harness may have resumed this session directly (e.g. from a GUI
|
|
227
|
+
// message) without running the bridge setup, so the deployment model
|
|
228
|
+
// selection — including reasoningEffort from settings.yaml — was never
|
|
229
|
+
// installed. Install it now on the live agent so per-request config
|
|
230
|
+
// follows settings instead of the session's persisted header.
|
|
231
|
+
this.installSelection(live.ctx);
|
|
232
|
+
// Same for the WeChat tools: re-register them on the live agent scope
|
|
233
|
+
// so send_wechat_file / preview_wechat_image / send_wechat_text are
|
|
234
|
+
// available even when the agent was resumed outside the bridge setup.
|
|
235
|
+
this.ensureTools(live.ctx);
|
|
236
|
+
return live;
|
|
237
|
+
}
|
|
238
|
+
if (!this.handle) {
|
|
239
|
+
// Loader siblings mount concurrently; never create an Agent before the
|
|
240
|
+
// complete application (tools, adapters, services) is composed.
|
|
241
|
+
try {
|
|
242
|
+
await this.ctx.get("loader")?.await?.();
|
|
243
|
+
}
|
|
244
|
+
catch (err) {
|
|
245
|
+
logger.warn(`ensureAgent: loader await failed (continuing): ${String(err)}`);
|
|
246
|
+
}
|
|
247
|
+
const setup = async (agentCtx) => {
|
|
248
|
+
// Pin the deployment default model for this agent's requests.
|
|
249
|
+
this.installSelection(agentCtx);
|
|
250
|
+
// Join the deployment's default agent preset (standard tools) when a
|
|
251
|
+
// preset roster is composed; degrade gracefully without one. Read via
|
|
252
|
+
// ctx.get() so no inject declaration is needed (works in profiles
|
|
253
|
+
// with and without the agent-presets service).
|
|
254
|
+
try {
|
|
255
|
+
const agentPresets = agentCtx.get?.("agentPresets");
|
|
256
|
+
if (agentPresets) {
|
|
257
|
+
await agentPresets.mount(agentCtx);
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
logger.debug("ensureAgent: no agentPresets service; using global-layer tools");
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
catch (err) {
|
|
264
|
+
logger.warn(`ensureAgent: preset mount failed (agent may have no tools): ${String(err)}`);
|
|
265
|
+
}
|
|
266
|
+
// WeChat conversation norms (concise, split, use the send tool).
|
|
267
|
+
try {
|
|
268
|
+
// WeChat guidance is registered GLOBALLY with a dynamic session
|
|
269
|
+
// filter (see index.ts) so it also covers agents the harness
|
|
270
|
+
// resumes directly from GUI messages.
|
|
271
|
+
logger.info("ensureAgent: wechat guidance section registered");
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
logger.warn(`ensureAgent: guidance section registration failed: ${String(err)}`);
|
|
275
|
+
}
|
|
276
|
+
// The WeChat session can deliver files/images/voice straight to WeChat.
|
|
277
|
+
this.ensureTools(agentCtx);
|
|
278
|
+
};
|
|
279
|
+
// Resume the persisted session when it exists; otherwise create fresh.
|
|
280
|
+
if (wasSessionCreated(this.sessionId)) {
|
|
281
|
+
try {
|
|
282
|
+
this.handle = await this.ctx.agents.resume({
|
|
283
|
+
resumeSessionId: this.sessionId,
|
|
284
|
+
setup,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
catch (err) {
|
|
288
|
+
logger.warn(`ensureAgent: resume failed (${String(err)}); will create a fresh session`);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (!this.handle) {
|
|
292
|
+
const defaultModel = this.ctx.get("agentDefaultModel");
|
|
293
|
+
const selection = defaultModel?.currentSelection();
|
|
294
|
+
this.handle = await this.ctx.agents.create({
|
|
295
|
+
sessionId: this.sessionId,
|
|
296
|
+
meta: { cwd: this.config.cwd ?? process.cwd() },
|
|
297
|
+
agentOptions: selection
|
|
298
|
+
? { provider: selection.provider, model: selection.model }
|
|
299
|
+
: undefined,
|
|
300
|
+
setup,
|
|
301
|
+
});
|
|
302
|
+
markSessionCreated(this.sessionId);
|
|
303
|
+
}
|
|
304
|
+
// The WeChat session answers approvals via WeChat: force `ask`.
|
|
305
|
+
try {
|
|
306
|
+
setApprovalPolicy(this.handle.agent.session, "ask");
|
|
307
|
+
}
|
|
308
|
+
catch (err) {
|
|
309
|
+
logger.warn(`ensureAgent: setApprovalPolicy failed: ${String(err)}`);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return this.handle.agent;
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Deliver one WeChat text message immediately, no waiting window. Normal
|
|
316
|
+
* flow: when the agent is idle the message starts a new turn. Interrupt
|
|
317
|
+
* flow: when the agent is already mid-turn (the user interjects while we
|
|
318
|
+
* are working), the message is STEERED into the running turn (next-step) so
|
|
319
|
+
* the agent absorbs it and rethinks before replying — one reply total.
|
|
320
|
+
* Returns immediately: the monitor loop must NEVER block on an agent turn.
|
|
321
|
+
*/
|
|
322
|
+
/**
|
|
323
|
+
* Whether the model this session will actually route to accepts image input.
|
|
324
|
+
*
|
|
325
|
+
* Read from the session's live request header (the route in force), falling
|
|
326
|
+
* back to the agent's options. Any failure to resolve counts as "no": an
|
|
327
|
+
* unproven route must not be handed an image it may reject, which would fail
|
|
328
|
+
* the whole turn instead of just missing a picture.
|
|
329
|
+
*
|
|
330
|
+
* `llm` and `attachments` are deliberately NOT in this plugin's `inject`
|
|
331
|
+
* list — declaring them makes them hard requirements, and a composition
|
|
332
|
+
* without them (headless, say) would fail the entire loader tree. So they
|
|
333
|
+
* are probed defensively and absence simply degrades to the old
|
|
334
|
+
* path-plus-vision-tool behaviour.
|
|
335
|
+
*/
|
|
336
|
+
visionCtx = null;
|
|
337
|
+
/**
|
|
338
|
+
* Receive a context scoped by `ctx.inject(["llm","attachments"], …)`.
|
|
339
|
+
*
|
|
340
|
+
* The only safe way to reach an optional service here: bare property access
|
|
341
|
+
* THROWS ("cannot get property \"llm\" without inject") and took down a whole
|
|
342
|
+
* inbound message, while listing them in `export const inject` would make
|
|
343
|
+
* them hard requirements and fail the loader tree wherever they are absent.
|
|
344
|
+
* This callback simply never fires in such a composition.
|
|
345
|
+
*/
|
|
346
|
+
useVisionServices(scoped) {
|
|
347
|
+
this.visionCtx = scoped;
|
|
348
|
+
// 这里**不要**立刻自检:本回调比 installSelection() 早约 80ms 触发,那一刻
|
|
349
|
+
// agentDefaultModel 还没解析出配置里的选择,读到的是 harness 的内置默认
|
|
350
|
+
// (deepseek-official/deepseek-v4-flash),自检会报出一个假的路由。
|
|
351
|
+
// 由 index.ts 在 agent 预热完成后再调 reportVisionReadiness()。
|
|
352
|
+
}
|
|
353
|
+
/** Read a service from the injected context; undefined when unavailable. */
|
|
354
|
+
service(name) {
|
|
355
|
+
const from = this.visionCtx;
|
|
356
|
+
if (from === null)
|
|
357
|
+
return undefined;
|
|
358
|
+
try {
|
|
359
|
+
const direct = from[name];
|
|
360
|
+
return direct === undefined || direct === null ? undefined : direct;
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Log at startup exactly what the image probe sees. Without it the only way
|
|
368
|
+
* to learn why a photo was not attached was to ask for another photo, and a
|
|
369
|
+
* genuine "not image capable" looks identical to a broken probe.
|
|
370
|
+
*/
|
|
371
|
+
async reportVisionReadiness() {
|
|
372
|
+
const llm = this.llmService();
|
|
373
|
+
const attachments = this.service("attachments");
|
|
374
|
+
const route = this.currentRoute();
|
|
375
|
+
if (llm === undefined || attachments === undefined || route === null) {
|
|
376
|
+
logger.info(`vision: 关闭 (llm=${llm !== undefined} attachments=${attachments !== undefined} route=${route === null ? "未知" : `${route.provider}/${route.model}`})`);
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
try {
|
|
380
|
+
const info = await llm.resolveModelInfo(route.provider, route.model);
|
|
381
|
+
const mods = info.inputModalities ?? [];
|
|
382
|
+
logger.info(`vision: ${route.provider}/${route.model} 输入模态 = [${mods.join(", ")}] → 附图${mods.includes("image") ? "开启" : "关闭"}`);
|
|
383
|
+
}
|
|
384
|
+
catch (err) {
|
|
385
|
+
logger.info(`vision: 解析 ${route.provider}/${route.model} 模态失败 (${String(err).slice(0, 120)}) → 附图关闭`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
llmService() {
|
|
389
|
+
const llm = this.service("llm");
|
|
390
|
+
return llm?.resolveModelInfo === undefined
|
|
391
|
+
? undefined
|
|
392
|
+
: llm;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* The provider/model this session will actually route to.
|
|
396
|
+
*
|
|
397
|
+
* Three sources, in descending authority. The live request header is the
|
|
398
|
+
* truth once a request has been made. A resumed agent has neither — no
|
|
399
|
+
* request yet in this process, and `options` is only populated on the create
|
|
400
|
+
* path — which is why the first probe reported "route unknown" and quietly
|
|
401
|
+
* disabled attachments. The deployment default is the reliable fallback
|
|
402
|
+
* precisely because installSelection() pins it onto this agent, so it IS the
|
|
403
|
+
* route the next turn takes.
|
|
404
|
+
*/
|
|
405
|
+
currentRoute() {
|
|
406
|
+
const live = this.ctx.agents.get(this.sessionId);
|
|
407
|
+
const routed = live?.session.requestHeader()?.config;
|
|
408
|
+
// 顺序就是权威顺序,排错了会读到别的路由:agent.options 是 harness 的默认
|
|
409
|
+
// (实测是 deepseek-official/deepseek-v4-flash),而 installSelection() 会用
|
|
410
|
+
// 部署默认值把它覆盖掉 —— 所以部署默认值比 options 权威,只有请求头比它更真。
|
|
411
|
+
const selection = this.ctx.get("agentDefaultModel")?.currentSelection();
|
|
412
|
+
const provider = routed?.provider ?? selection?.provider ?? live?.options.provider;
|
|
413
|
+
const model = routed?.model ?? selection?.model ?? live?.options.model;
|
|
414
|
+
return provider === undefined || model === undefined ? null : { provider, model };
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Whether the model this session routes to can take an image in its input.
|
|
418
|
+
* Public: the outbound pre-send check (`look_at_image` in tool.ts) gates on
|
|
419
|
+
* exactly the same answer as the inbound attach.
|
|
420
|
+
*/
|
|
421
|
+
async routeTakesImages() {
|
|
422
|
+
// The settings switch comes first: it exists to force the old
|
|
423
|
+
// path-plus-vision-tool behaviour for comparison, so it has to win over a
|
|
424
|
+
// route that would otherwise accept images.
|
|
425
|
+
if (!this.config.attachImages) {
|
|
426
|
+
logger.info("routeTakesImages: 设置里关掉了附图,走视觉工具");
|
|
427
|
+
return false;
|
|
428
|
+
}
|
|
429
|
+
const llm = this.llmService();
|
|
430
|
+
const route = this.currentRoute();
|
|
431
|
+
if (llm === undefined || route === null) {
|
|
432
|
+
logger.warn(`routeTakesImages: 无法判定(llm=${llm !== undefined} route=${route === null ? "未知" : "已知"}),按不支持处理`);
|
|
433
|
+
return false;
|
|
434
|
+
}
|
|
435
|
+
try {
|
|
436
|
+
const info = await llm.resolveModelInfo(route.provider, route.model);
|
|
437
|
+
const ok = info.inputModalities?.includes("image") === true;
|
|
438
|
+
if (!ok)
|
|
439
|
+
logger.info(`routeTakesImages: ${route.provider}/${route.model} 不接受图片,走视觉工具`);
|
|
440
|
+
return ok;
|
|
441
|
+
}
|
|
442
|
+
catch (err) {
|
|
443
|
+
logger.warn(`routeTakesImages: 解析 ${route.provider}/${route.model} 失败: ${String(err).slice(0, 120)}`);
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Commit one local image to the attachment store and hand back its durable
|
|
449
|
+
* reference — downscaled first, because a camera original is tens of
|
|
450
|
+
* megapixels and would blow the store's per-image limits long before it
|
|
451
|
+
* reached the model.
|
|
452
|
+
*
|
|
453
|
+
* Public, and used by BOTH directions: an inbound WeChat photo (via
|
|
454
|
+
* `imageBlock` below) and an outbound photo the agent is about to send (via
|
|
455
|
+
* `look_at_image` in tool.ts). Those used to differ — inbound attached the
|
|
456
|
+
* bytes natively while outbound handed a *path* to qwen and paid a second
|
|
457
|
+
* round trip for it — and there was never a reason for two mechanisms.
|
|
458
|
+
*
|
|
459
|
+
* @param imagePath - the local image to commit.
|
|
460
|
+
* @param tag - log prefix naming the caller, so the two directions stay
|
|
461
|
+
* distinguishable in the log.
|
|
462
|
+
* @returns the durable reference, or null when anything is missing.
|
|
463
|
+
*/
|
|
464
|
+
async attachImage(imagePath, tag = "imageBlock") {
|
|
465
|
+
// Call the injected store's own method rather than importing the
|
|
466
|
+
// `admitEncodedImages` helper. A bare import resolves nearest-first, which
|
|
467
|
+
// means this plugin's own node_modules copy of dsh-attachment (older than
|
|
468
|
+
// the host's, and without that export) shadowed the host's — so the import
|
|
469
|
+
// succeeded, the export was missing, and the attach returned null in
|
|
470
|
+
// silence. The service object is the host's instance, so there is no module
|
|
471
|
+
// resolution to get wrong. Bytes go straight in; no base64 round trip.
|
|
472
|
+
const store = this.service("attachments");
|
|
473
|
+
if (store?.saveImages === undefined) {
|
|
474
|
+
logger.warn(`${tag}: 附件服务不可用(或没有 saveImages),跳过附图`);
|
|
475
|
+
return null;
|
|
476
|
+
}
|
|
477
|
+
let prep;
|
|
478
|
+
try {
|
|
479
|
+
prep = compressForUpload(imagePath, {
|
|
480
|
+
maxImageEdge: this.config.maxImageEdge,
|
|
481
|
+
imageQuality: this.config.imageQuality,
|
|
482
|
+
compressThresholdBytes: this.config.compressThresholdBytes,
|
|
483
|
+
});
|
|
484
|
+
const data = readFileSync(prep.path);
|
|
485
|
+
const mediaType = prep.path.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
|
|
486
|
+
const refs = await store.saveImages([{ data, mediaType }]);
|
|
487
|
+
const ref = refs[0];
|
|
488
|
+
if (ref === undefined) {
|
|
489
|
+
logger.warn(`${tag}: 附件库没有返回引用,跳过附图`);
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
logger.info(`${tag}: 已附上 ${basename(imagePath)} (${Math.round(prep.bytes / 1024)} KB, ${ref.width}x${ref.height})`);
|
|
493
|
+
return ref;
|
|
494
|
+
}
|
|
495
|
+
catch (err) {
|
|
496
|
+
logger.warn(`${tag}: 附图失败 ${imagePath}: ${String(err)}`);
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
finally {
|
|
500
|
+
if (prep?.temp === true) {
|
|
501
|
+
try {
|
|
502
|
+
unlinkSync(prep.path);
|
|
503
|
+
}
|
|
504
|
+
catch { /* best effort */ }
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Wrap `attachImage` as the content block an inbound message carries. */
|
|
509
|
+
async imageBlock(imagePath) {
|
|
510
|
+
const ref = await this.attachImage(imagePath);
|
|
511
|
+
return ref === null ? null : { type: "image", attachment: ref };
|
|
512
|
+
}
|
|
513
|
+
async enqueueMessage(sender, text, imagePath) {
|
|
514
|
+
if (this.disposed)
|
|
515
|
+
return;
|
|
516
|
+
// Prefix every WeChat-originated message with a visible marker so the
|
|
517
|
+
// agent can distinguish it from system-injected content and knows this
|
|
518
|
+
// message REQUIRES a send_wechat_text reply (see RULE A0-WX).
|
|
519
|
+
let marked = `[微信消息] ${text}`;
|
|
520
|
+
// Attach the picture itself when the route can see one. Before this the
|
|
521
|
+
// model only ever got a filesystem path plus "go call a vision tool",
|
|
522
|
+
// which is why a separate vision provider was needed at all.
|
|
523
|
+
// 附图是增强功能,任何失败都不能挡住消息本身。
|
|
524
|
+
let block = null;
|
|
525
|
+
try {
|
|
526
|
+
if (imagePath !== undefined && await this.routeTakesImages()) {
|
|
527
|
+
block = await this.imageBlock(imagePath);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
catch (err) {
|
|
531
|
+
logger.warn(`enqueueMessage: 附图跳过: ${String(err)}`);
|
|
532
|
+
}
|
|
533
|
+
// 只说真话。上一版由上游 inbound 无条件断言"图片已附上",而它并不知道附图成没成
|
|
534
|
+
// —— 静默失败那次,模型被告知有图、又被禁止用工具,于是给一盘水果编出了一只小熊猫。
|
|
535
|
+
// 只有执行附图的这段代码有资格描述它。
|
|
536
|
+
if (imagePath !== undefined) {
|
|
537
|
+
marked += block === null
|
|
538
|
+
? "\n(图片没有附在本条消息里,请用视觉工具读上面那个路径来查看。)"
|
|
539
|
+
: "\n(上面这张图已附在本条消息里,直接看图回应,不用再调视觉工具。)";
|
|
540
|
+
}
|
|
541
|
+
const message = createUserMessage({
|
|
542
|
+
content: block === null
|
|
543
|
+
? [{ type: "text", text: marked }]
|
|
544
|
+
: [{ type: "text", text: marked }, block],
|
|
545
|
+
source: { kind: "plugin", plugin: "wechat-clawbot" },
|
|
546
|
+
});
|
|
547
|
+
const live = this.ctx.agents.get(this.sessionId);
|
|
548
|
+
if (live && live.status === "running") {
|
|
549
|
+
// Interrupt-style insertion: steer into the running turn (next-step).
|
|
550
|
+
logger.info(`enqueueMessage: steering message (${text.length} chars) into running turn`);
|
|
551
|
+
// Attribute the running turn's reply to the WeChat sender so the
|
|
552
|
+
// steered response (which may merge GUI + WeChat context) reaches the
|
|
553
|
+
// phone and is not dropped as "GUI-only".
|
|
554
|
+
this.currentSender = sender;
|
|
555
|
+
try {
|
|
556
|
+
live.steer(message);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
catch (err) {
|
|
560
|
+
logger.warn(`enqueueMessage: steer failed (${String(err)}); falling back to queue`);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
this.queue.push({ sender, text, message });
|
|
564
|
+
logger.info(`enqueueMessage: queued sender=${sender} msgId=${message.id} queueDepth=${this.queue.length}`);
|
|
565
|
+
void this.runWorker();
|
|
566
|
+
}
|
|
567
|
+
/** Start the serialized worker if it is not already running. */
|
|
568
|
+
runWorker() {
|
|
569
|
+
if (this.worker)
|
|
570
|
+
return;
|
|
571
|
+
this.worker = this.drainQueue().finally(() => {
|
|
572
|
+
this.worker = null;
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
/** Drive queued turns one at a time; never rejects. */
|
|
576
|
+
async drainQueue() {
|
|
577
|
+
while (!this.disposed && this.queue.length > 0) {
|
|
578
|
+
const task = this.queue.shift();
|
|
579
|
+
this.currentSender = task.sender;
|
|
580
|
+
this.turnMessageCount = 0; // 新回合重置发送计数
|
|
581
|
+
const started = Date.now();
|
|
582
|
+
try {
|
|
583
|
+
const agent = await this.ensureAgent();
|
|
584
|
+
if (agent.status === "running") {
|
|
585
|
+
// Mid-turn steer (unexpected via queue): inject into next-step so
|
|
586
|
+
// the running turn absorbs the message instead of starting a new one.
|
|
587
|
+
logger.info(`drainQueue: steering queued message into running turn`);
|
|
588
|
+
agent.steer(task.message);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
agent.followup(task.message);
|
|
592
|
+
}
|
|
593
|
+
await agent.whenIdle();
|
|
594
|
+
// Automatic memory fallback: capture durable user facts from this
|
|
595
|
+
// turn's message without relying on the model calling
|
|
596
|
+
// remember_user_info (which it often skips).
|
|
597
|
+
//
|
|
598
|
+
// Deliberately fire-and-forget (async): the reply is already sent
|
|
599
|
+
// when whenIdle() resolves, and the memory file is re-read on every
|
|
600
|
+
// prompt assembly, so the NEXT user message already benefits. Doing
|
|
601
|
+
// it off the worker's tail keeps rapid consecutive messages from
|
|
602
|
+
// being delayed by file I/O or the LLM confirm call.
|
|
603
|
+
const turnText = task.text;
|
|
604
|
+
void Promise.resolve().then(async () => {
|
|
605
|
+
try {
|
|
606
|
+
await captureTurnMemory([turnText]);
|
|
607
|
+
}
|
|
608
|
+
catch (err) {
|
|
609
|
+
logger.warn(`memory-auto: capture failed: ${String(err)}`);
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
logger.debug(`drainQueue: idle after ${Date.now() - started}ms`);
|
|
613
|
+
}
|
|
614
|
+
catch (err) {
|
|
615
|
+
logger.error(`drainQueue: turn failed sender=${task.sender} err=${String(err)}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
this.currentSender = undefined;
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Session event feed: track the active WeChat recipient for turns NOT
|
|
622
|
+
* driven by the inbound queue. Assistant text is NEVER forwarded
|
|
623
|
+
* automatically — the agent must call the send_wechat_text /
|
|
624
|
+
* send_wechat_file tools explicitly to deliver anything to WeChat. This
|
|
625
|
+
* method only:
|
|
626
|
+
* - sets `currentSender` for scheduled-reminder injections (source plugin
|
|
627
|
+
* "schedule"), so the send tools know whom to deliver to; and
|
|
628
|
+
* - clears the stale sender when a GUI-only turn ends, so GUI messages
|
|
629
|
+
* never get a WeChat recipient.
|
|
630
|
+
*/
|
|
631
|
+
onSessionEvent(session, event) {
|
|
632
|
+
if (session.id !== this.sessionId)
|
|
633
|
+
return;
|
|
634
|
+
logger.debug(`sessionEvent: type=${event.type} seq=${event.seq}`);
|
|
635
|
+
if (event.type === "user/message" && !this.worker) {
|
|
636
|
+
const source = event.data?.source;
|
|
637
|
+
if (source?.plugin === "schedule") {
|
|
638
|
+
// Scheduled-reminder injection: attribute the turn to the WeChat
|
|
639
|
+
// owner so the agent's explicit send tool calls reach the phone.
|
|
640
|
+
const owner = this.deps.getAccount()?.userId;
|
|
641
|
+
if (owner) {
|
|
642
|
+
logger.info(`sessionEvent: schedule turn attributed to owner ${owner}`);
|
|
643
|
+
this.currentSender = owner;
|
|
644
|
+
}
|
|
645
|
+
// dsh-schedule 自己就能把会话唤醒来投递提醒,这条路径**不经过**
|
|
646
|
+
// ensureAgent —— 所以那一轮里工具屏蔽、微信发送工具、配置的模型全都还
|
|
647
|
+
// 没装上。2026-08-21 就是这么出事的:模型在提醒那轮拿到了本该被屏蔽的
|
|
648
|
+
// send_message,拿它乱调一把,用户收到的是
|
|
649
|
+
// `subagent "invalid" is unavailable`;而且那轮用的是会话里残留的旧
|
|
650
|
+
// header(codex + luna + low),不是设置里的模型。
|
|
651
|
+
// 这里补上,而且必须在模型发起请求之前 —— 事件是消息入 inbox 时同步派发的。
|
|
652
|
+
const live = this.ctx.agents.get(this.sessionId);
|
|
653
|
+
if (live) {
|
|
654
|
+
this.installSelection(live.ctx);
|
|
655
|
+
this.ensureTools(live.ctx);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
// Direct GUI message: leave currentSender unset so send tools have
|
|
660
|
+
// no WeChat recipient (the agent will answer in the GUI only).
|
|
661
|
+
logger.debug(`sessionEvent: external turn from ${String(source?.plugin ?? "unknown")}; GUI-only, no wechat recipient`);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Build (or refresh) a time index of all session message events, so quotes
|
|
667
|
+
* of messages that predate the quote-history registry (e.g. before a
|
|
668
|
+
* restart) can still be resolved by timestamp.
|
|
669
|
+
*/
|
|
670
|
+
buildSessionIndex() {
|
|
671
|
+
const session = this.handle?.agent.session;
|
|
672
|
+
if (!session) {
|
|
673
|
+
this.sessionIndex = null;
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
if (this.sessionIndex && this.sessionIndex.seq === session.seq)
|
|
677
|
+
return;
|
|
678
|
+
const entries = [];
|
|
679
|
+
for (const event of session.events) {
|
|
680
|
+
if (event.type === "user/message") {
|
|
681
|
+
const text = (event.data.content ?? [])
|
|
682
|
+
.filter((b) => b.type === "text")
|
|
683
|
+
.map((b) => b.text)
|
|
684
|
+
.join("");
|
|
685
|
+
if (!text.trim())
|
|
686
|
+
continue;
|
|
687
|
+
const pathMatch = /已保存到 ([^\s)]+)/.exec(text);
|
|
688
|
+
entries.push({
|
|
689
|
+
time: event.time,
|
|
690
|
+
text,
|
|
691
|
+
imagePath: pathMatch?.[1] ?? undefined,
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
else if (event.type === "assistant/message") {
|
|
695
|
+
const text = (event.data.message?.content ?? [])
|
|
696
|
+
.filter((b) => b.type === "text")
|
|
697
|
+
.map((b) => b.text)
|
|
698
|
+
.join("");
|
|
699
|
+
if (!text.trim())
|
|
700
|
+
continue;
|
|
701
|
+
entries.push({ time: event.time, text });
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
this.sessionIndex = { seq: session.seq, entries };
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Resolve a quote by the quoted message's server creation time (used when
|
|
708
|
+
* the msg-id lookup misses, e.g. for messages sent before the quote
|
|
709
|
+
* history started). Returns the nearest session message within tolerance.
|
|
710
|
+
*/
|
|
711
|
+
lookupQuoteByTime(createTimeMs) {
|
|
712
|
+
if (createTimeMs === undefined)
|
|
713
|
+
return null;
|
|
714
|
+
this.buildSessionIndex();
|
|
715
|
+
if (!this.sessionIndex)
|
|
716
|
+
return null;
|
|
717
|
+
let best = null;
|
|
718
|
+
let bestDiff = Number.POSITIVE_INFINITY;
|
|
719
|
+
for (const entry of this.sessionIndex.entries) {
|
|
720
|
+
const diff = Math.abs(entry.time - createTimeMs);
|
|
721
|
+
if (diff < bestDiff) {
|
|
722
|
+
bestDiff = diff;
|
|
723
|
+
best = entry;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
return best && bestDiff <= 10_000 ? best : null;
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Register the WeChat-scoped tools (send_wechat_file, preview_wechat_image,
|
|
730
|
+
* (send_wechat_file, preview_wechat_image) on an agent scope. Idempotent
|
|
731
|
+
* per bridge lifetime; safe
|
|
732
|
+
* to call from both the creation setup and the live-agent path.
|
|
733
|
+
*/
|
|
734
|
+
ensureTools(agentCtx) {
|
|
735
|
+
if (this.toolsRegistered)
|
|
736
|
+
return;
|
|
737
|
+
try {
|
|
738
|
+
registerSendFileTool(agentCtx, {
|
|
739
|
+
getBridge: () => this,
|
|
740
|
+
getAccount: this.deps.getAccount,
|
|
741
|
+
config: this.config,
|
|
742
|
+
});
|
|
743
|
+
// Visibility into the user's Claude Code sessions, so a WeChat message can
|
|
744
|
+
// ask "what is Claude doing" or redirect a coding session the user is not
|
|
745
|
+
// sitting in front of. restrictTools below is a DENY list, so these three
|
|
746
|
+
// are visible without needing to be named there.
|
|
747
|
+
registerClaudePeerTools(agentCtx);
|
|
748
|
+
this.restrictTools(agentCtx);
|
|
749
|
+
this.toolsRegistered = true;
|
|
750
|
+
logger.info("ensureTools: WeChat tools registered");
|
|
751
|
+
}
|
|
752
|
+
catch (err) {
|
|
753
|
+
logger.warn(`ensureTools: registration failed (will retry): ${String(err)}`);
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Hide the multi-agent orchestration tools from the WeChat session.
|
|
758
|
+
*
|
|
759
|
+
* Observed failure: the agent called `send_message` with
|
|
760
|
+
* `{subagent_id: "schedule-9", message: "ignore"}`, got
|
|
761
|
+
* `subagent "schedule-9" is unavailable`, then retried with schedule-10,
|
|
762
|
+
* -11, ... past -103 — 158 steps and 4.5M input tokens in about three
|
|
763
|
+
* minutes ($0.11 of a $10 monthly allowance) before it was stopped by hand.
|
|
764
|
+
* Running with reasoning_effort "none" (the only setting this gateway
|
|
765
|
+
* accepts alongside tools) leaves no self-correction to break such a loop.
|
|
766
|
+
*
|
|
767
|
+
* `send_message` is the likeliest trigger: it sits next to this plugin's own
|
|
768
|
+
* `send_wechat_text` in the same tool list, and the two names are easy to
|
|
769
|
+
* conflate. None of these tools have a role in a one-on-one WeChat chat, so
|
|
770
|
+
* denying them removes the whole failure mode rather than guarding it.
|
|
771
|
+
*
|
|
772
|
+
* A deny list, not an allow list: everything the bot actually uses (bash,
|
|
773
|
+
* read/glob/grep, web_search, the vision tools, schedule_*, memory) keeps
|
|
774
|
+
* working untouched. Per-scope restrictions also leave scoped registrations
|
|
775
|
+
* alone, so the WeChat tools registered just above survive.
|
|
776
|
+
*/
|
|
777
|
+
restrictTools(agentCtx) {
|
|
778
|
+
const deny = [
|
|
779
|
+
"send_message",
|
|
780
|
+
"subagent",
|
|
781
|
+
"subagent_fork",
|
|
782
|
+
"list_agents",
|
|
783
|
+
"ralph",
|
|
784
|
+
"workflow",
|
|
785
|
+
];
|
|
786
|
+
try {
|
|
787
|
+
// Direct property access, matching how this plugin already registers its
|
|
788
|
+
// own tools (`agentCtx.tools.register`). cordis isolates services a
|
|
789
|
+
// context has not injected, so `agentCtx.get("tools")` returns nothing
|
|
790
|
+
// here and the restriction would silently never apply.
|
|
791
|
+
const tools = agentCtx.tools;
|
|
792
|
+
if (typeof tools?.restrict !== "function") {
|
|
793
|
+
logger.warn("restrictTools: tools.restrict unavailable, orchestration tools stay visible");
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
tools.restrict({ deny });
|
|
797
|
+
logger.info(`restrictTools: hidden from WeChat session -> ${deny.join(", ")}`);
|
|
798
|
+
}
|
|
799
|
+
catch (err) {
|
|
800
|
+
logger.warn(`restrictTools: failed (non-fatal): ${String(err)}`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/** Tear down the owned agent handle (the persisted session log survives). */
|
|
804
|
+
async dispose() {
|
|
805
|
+
if (this.disposed)
|
|
806
|
+
return;
|
|
807
|
+
this.disposed = true;
|
|
808
|
+
// Dispose the agent first: this stops the driver, so a pending whenIdle
|
|
809
|
+
// resolves and the worker can exit instead of hanging forever.
|
|
810
|
+
try {
|
|
811
|
+
await this.handle?.dispose();
|
|
812
|
+
}
|
|
813
|
+
catch (err) {
|
|
814
|
+
logger.warn(`dispose: ${String(err)}`);
|
|
815
|
+
}
|
|
816
|
+
this.handle = null;
|
|
817
|
+
this.queue.length = 0;
|
|
818
|
+
try {
|
|
819
|
+
await this.worker;
|
|
820
|
+
}
|
|
821
|
+
catch (err) {
|
|
822
|
+
logger.warn(`dispose: worker error ${String(err)}`);
|
|
823
|
+
}
|
|
824
|
+
this.worker = null;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
//# sourceMappingURL=bridge.js.map
|