aicq-openclaw 3.16.3

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/src/channel.js ADDED
@@ -0,0 +1,861 @@
1
+ /**
2
+ * AICQ Channel Plugin — Core Channel Logic
3
+ *
4
+ * Uses the official OpenClaw Channel Plugin SDK:
5
+ * createChatChannelPlugin + createChannelPluginBase
6
+ *
7
+ * Architecture: In-process Channel (no sidecar, no independent port)
8
+ *
9
+ * The runtime store is a mutable object populated by registerFull() in
10
+ * index.js. This keeps the channel-plugin object safe to import during
11
+ * setup-only / discovery modes without pulling in transport clients or
12
+ * database handles.
13
+ */
14
+
15
+ import {
16
+ createChatChannelPlugin,
17
+ createChannelPluginBase,
18
+ } from "openclaw/plugin-sdk/channel-core";
19
+
20
+ // ── Mutable runtime store ────────────────────────────────────────────
21
+ // Populated lazily by the registerFull() callback in index.js.
22
+ // Adapters that need runtime state check these before acting.
23
+ export const runtime = {
24
+ db: null,
25
+ identity: null,
26
+ serverClient: null,
27
+ handshake: null,
28
+ chat: null,
29
+ dataDir: null,
30
+ serverUrl: null,
31
+ handleGateway: null,
32
+ _initialized: false,
33
+ };
34
+
35
+ // ── Template variable resolver ───────────────────────────────────────
36
+ // OpenClaw stores accountId as-is (e.g. "{{agent.id}}") in config.
37
+ // Plugins must resolve template variables at runtime.
38
+ //
39
+ // The default agent ID in OpenClaw is "main" (DEFAULT_AGENT_ID).
40
+ // When cfg.agents.list is empty/undefined (no explicit agent config),
41
+ // the implicit default agent "main" is used.
42
+
43
+ const OPENCLAW_DEFAULT_AGENT_ID = "main";
44
+
45
+ function resolveTemplateVar(cfg, value) {
46
+ if (typeof value !== "string") return value;
47
+ const match = value.match(/^\{\{(\w[\w.]*)\}\}$/);
48
+ if (!match) return value;
49
+
50
+ const tmplPath = match[1]; // e.g. "agent.id"
51
+ if (tmplPath === "agent.id") {
52
+ // Strategy: look for explicit agents in config first
53
+ const agents = cfg.agents?.list;
54
+ if (Array.isArray(agents) && agents.length > 0) {
55
+ // Use the default=true agent, or the first one
56
+ const defaultAgent = agents.find((a) => a.default) || agents[0];
57
+ if (defaultAgent?.id) return defaultAgent.id;
58
+ }
59
+ // Fallback: OpenClaw's implicit default agent ID
60
+ return OPENCLAW_DEFAULT_AGENT_ID;
61
+ }
62
+
63
+ return value; // unknown template — return as-is
64
+ }
65
+
66
+ // ── Resolved account type ────────────────────────────────────────────
67
+ // This is the object returned by resolveAccount() and consumed by
68
+ // security / pairing / outbound adapters.
69
+
70
+ /**
71
+ * Read the AICQ channel section from OpenClaw config and return a typed
72
+ * account object. This is the setup-safe resolver — no network or DB
73
+ * side effects.
74
+ */
75
+ function resolveAccount(cfg, accountId) {
76
+ const section = (cfg.channels || {})["aicq-chat"] || {};
77
+ const rawAccountId = accountId || section.accountId || null;
78
+
79
+ if (!rawAccountId) {
80
+ throw new Error(
81
+ "aicq-chat: accountId is required (set channels.aicq-chat.accountId)"
82
+ );
83
+ }
84
+
85
+ // Resolve template variables like {{agent.id}}
86
+ const resolvedAccountId = resolveTemplateVar(cfg, rawAccountId);
87
+
88
+ // Resolve allowFrom entries (may contain {{agent.id}} or friend IDs)
89
+ const rawAllowFrom = section.allowFrom || [];
90
+ const resolvedAllowFrom = Array.isArray(rawAllowFrom)
91
+ ? rawAllowFrom.map((entry) => resolveTemplateVar(cfg, entry))
92
+ : rawAllowFrom;
93
+
94
+ return {
95
+ accountId: resolvedAccountId,
96
+ serverUrl: section.serverUrl || "https://aicq.me",
97
+ autoAcceptFriends: section.autoAcceptFriends ?? true,
98
+ autoAddFriends: section.autoAddFriends || [],
99
+ enabled: section.enabled ?? true,
100
+ dmPolicy: section.dmPolicy || "allowlist",
101
+ allowFrom: resolvedAllowFrom,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Lightweight account inspection for status / health / setup surfaces.
107
+ * Must not materialise secrets or start transports.
108
+ */
109
+ function inspectAccount(cfg, accountId) {
110
+ const section = (cfg.channels || {})["aicq-chat"] || {};
111
+ const hasAccountId = Boolean(section.accountId || accountId);
112
+ return {
113
+ enabled: hasAccountId && section.enabled !== false,
114
+ configured: hasAccountId,
115
+ accountStatus: hasAccountId ? "available" : "missing",
116
+ };
117
+ }
118
+
119
+ // ── Build the channel plugin ─────────────────────────────────────────
120
+
121
+ const _plugin = createChatChannelPlugin({
122
+ base: createChannelPluginBase({
123
+ id: "aicq-chat",
124
+
125
+ setup: {
126
+ /**
127
+ * Resolve the account ID from setup input.
128
+ * Called by the setup wizard when a user configures the channel.
129
+ */
130
+ resolveAccountId(params) {
131
+ const { cfg, accountId, input } = params;
132
+ return accountId || input?.accountId || resolveTemplateVar(cfg, "{{agent.id}}");
133
+ },
134
+
135
+ /**
136
+ * Apply the account config after the setup wizard completes.
137
+ * Must return the updated OpenClawConfig.
138
+ */
139
+ applyAccountConfig(params) {
140
+ const { cfg, accountId, input } = params;
141
+ const section = (cfg.channels || {})["aicq-chat"] || {};
142
+ return {
143
+ ...cfg,
144
+ channels: {
145
+ ...(cfg.channels || {}),
146
+ "aicq-chat": {
147
+ ...section,
148
+ accountId: accountId || input?.accountId || "{{agent.id}}",
149
+ serverUrl: input?.serverUrl || section.serverUrl || "https://aicq.me",
150
+ autoAcceptFriends: input?.autoAcceptFriends ?? section.autoAcceptFriends ?? true,
151
+ enabled: true,
152
+ dmPolicy: input?.dmPolicy || section.dmPolicy || "allowlist",
153
+ allowFrom: input?.allowFrom || section.allowFrom || [],
154
+ },
155
+ },
156
+ };
157
+ },
158
+
159
+ /**
160
+ * Validate setup input before applying.
161
+ * Return an error message string or null if valid.
162
+ */
163
+ validateInput(params) {
164
+ return null;
165
+ },
166
+ },
167
+
168
+ // Gateway method descriptors — these are the method names the plugin
169
+ // will register via registerFull(). Declaring them here lets OpenClaw
170
+ // surface them in discovery / status surfaces before full activation.
171
+ gatewayMethodDescriptors: [
172
+ "aicq.status",
173
+ "aicq.friends.list",
174
+ "aicq.friends.add",
175
+ "aicq.friends.addByNumber",
176
+ "aicq.friends.remove",
177
+ "aicq.friends.requests",
178
+ "aicq.friends.acceptRequest",
179
+ "aicq.friends.rejectRequest",
180
+ "aicq.identity.info",
181
+ "aicq.agent.create",
182
+ "aicq.agent.delete",
183
+ "aicq.chat.send",
184
+ "aicq.chat.history",
185
+ "aicq.chat.delete",
186
+ "aicq.chat.userUpload",
187
+ "aicq.chat.userfiles",
188
+ "aicq.chat.streamChunk",
189
+ "aicq.chat.streamEnd",
190
+ "aicq.groups.list",
191
+ "aicq.groups.create",
192
+ "aicq.groups.join",
193
+ "aicq.groups.messages",
194
+ "aicq.groups.silent",
195
+ "aicq.sessions.list",
196
+ ],
197
+ }),
198
+
199
+ // ── DM Security ──────────────────────────────────────────────────
200
+ security: {
201
+ dm: {
202
+ channelKey: "aicq-chat",
203
+ resolvePolicy: (account) => account.dmPolicy,
204
+ resolveAllowFrom: (account) => account.allowFrom,
205
+ defaultPolicy: "allowlist",
206
+ },
207
+ },
208
+
209
+ // ── Pairing ──────────────────────────────────────────────────────
210
+ pairing: {
211
+ text: {
212
+ idLabel: "AICQ Friend Code",
213
+ message: "Share this pairing code with the other party:",
214
+ notify: async ({ target, code }) => {
215
+ // AICQ pairing codes are shared out-of-band by the operator.
216
+ // No automatic notification is sent to the peer.
217
+ },
218
+ },
219
+ },
220
+
221
+ // ── Threading ────────────────────────────────────────────────────
222
+ threading: {
223
+ topLevelReplyToMode: "reply",
224
+ },
225
+
226
+ // ── Outbound ─────────────────────────────────────────────────────
227
+ outbound: {
228
+ attachedResults: {
229
+ channel: "aicq-chat",
230
+
231
+ sendText: async (params) => {
232
+ if (!runtime.chat) {
233
+ throw new Error("AICQ runtime not initialized — cannot send text");
234
+ }
235
+ const fromId =
236
+ params.from ||
237
+ params.accountId ||
238
+ (runtime.identity && runtime.identity.listAgents()[0]?.agent_id);
239
+ const result = await runtime.chat.sendMessage(
240
+ fromId,
241
+ params.to,
242
+ params.text,
243
+ { isGroup: false }
244
+ );
245
+ return { messageId: result?.message_id || result?.id || "sent" };
246
+ },
247
+ },
248
+
249
+ base: {
250
+ sendMedia: async (params) => {
251
+ if (!runtime.chat) {
252
+ throw new Error("AICQ runtime not initialized — cannot send media");
253
+ }
254
+ const fromId =
255
+ params.from ||
256
+ params.accountId ||
257
+ (runtime.identity && runtime.identity.listAgents()[0]?.agent_id);
258
+ await runtime.chat.sendMessage(
259
+ fromId,
260
+ params.to,
261
+ params.mediaUrl || params.filePath,
262
+ { type: params.mediaType || "file", isGroup: false }
263
+ );
264
+ },
265
+ },
266
+ },
267
+ });
268
+
269
+ // ── Gateway adapter: startAccount / stopAccount ───────────────────────
270
+ // OpenClaw calls startAccount when the channel is activated (on startup
271
+ // or when re-enabled). This is where we initialise the runtime, connect
272
+ // to the AICQ signalling server, and wire up inbound message delivery
273
+ // via the channelRuntime helpers.
274
+
275
+ _plugin.gateway = {
276
+ /**
277
+ * Start the channel account — connect to the AICQ server and begin
278
+ * listening for inbound messages.
279
+ */
280
+ async startAccount(ctx) {
281
+ const { cfg, accountId, account, setStatus, log, abortSignal } = ctx;
282
+
283
+ const logger = log || console;
284
+ logger.info?.(`[AICQ Channel] startAccount called for ${accountId}`) || console.log(`[AICQ Channel] startAccount called for ${accountId}`);
285
+
286
+ // Ensure the runtime (DB, identity, transport) is initialised.
287
+ // The runtime is populated by registerFull() in index.js, but startAccount
288
+ // may be called before any gateway method is invoked, so we must ensure
289
+ // initialization here too.
290
+ if (!runtime._initialized && typeof runtime.ensureInitialized === "function") {
291
+ try {
292
+ await runtime.ensureInitialized();
293
+ logger.info?.("[AICQ Channel] Runtime initialized via startAccount") || console.log("[AICQ Channel] Runtime initialized via startAccount");
294
+ } catch (e) {
295
+ console.error("[AICQ Channel] Runtime initialization failed:", e.message);
296
+ setStatus({
297
+ accountId,
298
+ enabled: true,
299
+ configured: true,
300
+ running: false,
301
+ lastError: `Initialization failed: ${e.message}`,
302
+ });
303
+ return;
304
+ }
305
+ }
306
+
307
+ // Resolve the agent ID: prefer the resolved accountId from
308
+ // resolveAccount (which already handles {{agent.id}}), then
309
+ // fall back to the OpenClaw default agent ID.
310
+ const agents = cfg.agents?.list;
311
+ const agentId = account?.accountId || accountId || OPENCLAW_DEFAULT_AGENT_ID;
312
+
313
+ // Ensure we have an identity in the plugin DB
314
+ if (runtime.identity) {
315
+ const existing = runtime.identity.listAgents();
316
+ if (existing.length === 0) {
317
+ const agentName = (Array.isArray(agents) && agents.length > 0 && agents[0]?.name)
318
+ ? agents[0].name
319
+ : "AICQ Agent";
320
+ runtime.identity.createAgent(agentId, agentName);
321
+ console.log(`[AICQ Channel] Created agent identity: ${agentId}`);
322
+ }
323
+ }
324
+
325
+ // Connect to the AICQ server
326
+ if (runtime.serverClient) {
327
+ try {
328
+ await runtime.serverClient.ensureAuth(agentId);
329
+ console.log(`[AICQ Channel] Authenticated as ${agentId}`);
330
+
331
+ // Connect WebSocket for real-time messages
332
+ if (typeof runtime.serverClient.start === "function") {
333
+ await runtime.serverClient.start(agentId);
334
+ console.log("[AICQ Channel] WebSocket connected");
335
+ } else if (typeof runtime.serverClient.connectWS === "function") {
336
+ runtime.serverClient.connectWS();
337
+ console.log("[AICQ Channel] WebSocket connecting");
338
+ }
339
+
340
+ // Sync friends and groups from server
341
+ if (runtime.handleGateway) {
342
+ try {
343
+ await runtime.handleGateway("aicq.friends.list", {});
344
+ await runtime.handleGateway("aicq.groups.list", {});
345
+ } catch (e) {
346
+ console.warn("[AICQ Channel] Initial sync failed:", e.message);
347
+ }
348
+ }
349
+
350
+ // Auto-add friends from config (autoAddFriends list)
351
+ const autoAddFriends = account?.autoAddFriends || cfg?.channels?.["aicq-chat"]?.autoAddFriends || [];
352
+ if (Array.isArray(autoAddFriends) && autoAddFriends.length > 0) {
353
+ console.log(`[AICQ Channel] Auto-adding ${autoAddFriends.length} friend(s) from config...`);
354
+ for (const friendEntry of autoAddFriends) {
355
+ try {
356
+ const aicqNumber = typeof friendEntry === 'string' ? friendEntry : friendEntry.number;
357
+ const friendMsg = typeof friendEntry === 'object' ? friendEntry.message : undefined;
358
+ if (!aicqNumber) continue;
359
+ const result = await runtime.handleGateway("aicq.friends.addByNumber", {
360
+ number: aicqNumber,
361
+ message: friendMsg || 'Hi, I\'d like to add you!',
362
+ });
363
+ if (result.error) {
364
+ console.warn(`[AICQ Channel] Auto-add friend ${aicqNumber} failed: ${result.error}`);
365
+ } else {
366
+ console.log(`[AICQ Channel] Auto-add friend ${aicqNumber}: ${result.status}`);
367
+ }
368
+ } catch (e) {
369
+ console.warn(`[AICQ Channel] Auto-add friend failed:`, e.message);
370
+ }
371
+ }
372
+ }
373
+
374
+ // Auto-accept pending friend requests if autoAcceptFriends is true.
375
+ // Read the flag from either the resolved account object (preferred)
376
+ // or the channel config section (fallback — some loaders only pass
377
+ // cfg/accountId and skip account).
378
+ const autoAccept =
379
+ account?.autoAcceptFriends ??
380
+ cfg?.channels?.["aicq-chat"]?.autoAcceptFriends ??
381
+ true; // default true per plugin schema
382
+ if (autoAccept && runtime.handleGateway) {
383
+ try {
384
+ const pendingResult = await runtime.handleGateway("aicq.friends.requests", {});
385
+ if (pendingResult.requests && pendingResult.requests.length > 0) {
386
+ console.log(`[AICQ Channel] Auto-accepting ${pendingResult.requests.length} pending friend request(s)`);
387
+ for (const req of pendingResult.requests) {
388
+ try {
389
+ await runtime.handleGateway("aicq.friends.acceptRequest", { request_id: req.session_id || req.id });
390
+ console.log(`[AICQ Channel] Auto-accepted friend request from ${req.requester_id || req.from_id}`);
391
+ } catch (e) {
392
+ console.warn(`[AICQ Channel] Auto-accept failed:`, e.message);
393
+ }
394
+ }
395
+ }
396
+ } catch (e) {
397
+ console.warn("[AICQ Channel] Auto-accept check failed:", e.message);
398
+ }
399
+ }
400
+ } catch (e) {
401
+ console.error("[AICQ Channel] Failed to connect:", e.message);
402
+ }
403
+ }
404
+
405
+ // Wire up inbound message handling via channelRuntime if available
406
+ if (ctx.channelRuntime) {
407
+ const { reply, routing, inbound, session } = ctx.channelRuntime;
408
+ if (reply && routing && inbound) {
409
+ console.log("[AICQ Channel] channelRuntime available — AI dispatch enabled (inbound.run mode)");
410
+
411
+ // Set up the auto-accept callback for friend_request WS events.
412
+ // When the server pushes a friend_request, the ChatManager calls
413
+ // this callback so we can immediately accept it (if autoAcceptFriends
414
+ // is enabled) without waiting for the next startAccount cycle.
415
+ if (runtime.chat && typeof runtime.chat.setOnAutoAccept === "function") {
416
+ runtime.chat.setOnAutoAccept(async (req) => {
417
+ const autoAccept =
418
+ account?.autoAcceptFriends ??
419
+ cfg?.channels?.["aicq-chat"]?.autoAcceptFriends ??
420
+ true;
421
+ if (!autoAccept) return;
422
+ try {
423
+ await runtime.handleGateway("aicq.friends.acceptRequest", {
424
+ request_id: req.request_id,
425
+ });
426
+ console.log(`[AICQ Channel] Auto-accepted friend request (realtime) from ${req.from_id}`);
427
+ } catch (e) {
428
+ console.warn(`[AICQ Channel] Realtime auto-accept failed:`, e.message);
429
+ }
430
+ });
431
+ }
432
+
433
+ // Set up the onNewMessage callback for the ChatManager
434
+ // This handles both regular text messages and synthetic file notifications
435
+ if (runtime.chat) {
436
+ runtime.chat.setOnNewMessage(async (msg) => {
437
+ try {
438
+ // Skip stream and presence events — not user messages
439
+ if (msg.type === 'stream_chunk' || msg.type === 'stream_end') return;
440
+ // Skip outbound messages (agent's own replies) to avoid
441
+ // echo loop — only inbound user messages should be dispatched.
442
+ if (msg._outbound) return;
443
+
444
+ // ── Real-time preemption ────────────────────────────────
445
+ // If there's an active AI turn in progress, abort it NOW so
446
+ // the user's new message gets immediate attention instead of
447
+ // being queued behind the current (potentially long) reply.
448
+ if (runtime.activeTurnAbort && !runtime.activeTurnAbort.signal.aborted) {
449
+ console.log("[AICQ Channel] New inbound message — aborting current turn for preemption");
450
+ runtime.activeTurnAbort.abort('preempted-by-new-message');
451
+ }
452
+ runtime.activeTurnAbort = null;
453
+
454
+ const fromId = msg.from_id || msg.from || msg.sender_id;
455
+ const isGroup = !!(msg.is_group || msg.isGroup);
456
+ // [FIX v3.16.3 edge #4] Group replies must target the GROUP,
457
+ // not the sender. On inbound group frames chat.js sets
458
+ // to_id = groupId; routing by fromId mis-delivered every
459
+ // group reply into the sender's DM (GROUP-AT-OK bug).
460
+ const replyTargetId = isGroup
461
+ ? (msg.to_id || msg.group_id || msg.groupId || fromId)
462
+ : fromId;
463
+ let textContent = msg.content || msg.text || "";
464
+
465
+ // [FIX v3.16] Use channelRuntime.inbound.run() pattern (same as
466
+ // OpenClaw built-in SMS channel) instead of directly calling
467
+ // reply.dispatchReplyWithBufferedBlockDispatcher(). The old
468
+ // direct call hung silently in OpenClaw 2026.6.8 because the
469
+ // session/context setup that inbound.run() performs was skipped.
470
+ const route = routing.resolveAgentRoute({
471
+ cfg,
472
+ channel: "aicq-chat",
473
+ accountId,
474
+ peer: {
475
+ kind: isGroup ? "group" : "direct",
476
+ id: replyTargetId,
477
+ },
478
+ });
479
+ const sessionKey = route.sessionKey;
480
+ console.log("[AICQ Channel] inbound.run route: agentId=" + route.agentId + " sessionKey=" + sessionKey);
481
+
482
+ // Generate a stream id for this reply turn. The aicq.me server
483
+ // uses stream_id to accumulate chunks and persist the final
484
+ // assembled text on stream_end.
485
+ const streamId = (typeof crypto !== "undefined" && crypto.randomUUID)
486
+ ? crypto.randomUUID()
487
+ : `stream_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
488
+ const streamState = runtime.chat.registerStream(streamId);
489
+ let streamStarted = false;
490
+ let streamEnded = false;
491
+ let streamChunksSent = 0;
492
+ const streamTarget = replyTargetId;
493
+ let accumulatedText = "";
494
+
495
+ // AbortController for this turn — allows real-time interruption
496
+ const turnAbortController = new AbortController();
497
+ runtime.activeTurnAbort = turnAbortController;
498
+ streamState.abortController = turnAbortController;
499
+
500
+ const ensureStreamStart = async () => {
501
+ if (streamStarted) return;
502
+ streamStarted = true;
503
+ };
504
+
505
+ const endStreamSafe = async () => {
506
+ if (streamEnded || !streamStarted) return;
507
+ streamEnded = true;
508
+ runtime.chat.unregisterStream(streamId);
509
+ if (!streamChunksSent) {
510
+ console.log("[AICQ Channel] endStreamSafe: no chunks sent, skipping stream_end");
511
+ if (accumulatedText && runtime.chat) {
512
+ try {
513
+ await runtime.chat.sendMessage(agentId, streamTarget, accumulatedText, { isGroup });
514
+ } catch (e2) {
515
+ console.error("[AICQ Channel] Fallback sendMessage failed:", e2.message);
516
+ }
517
+ }
518
+ return;
519
+ }
520
+ try {
521
+ await runtime.chat.endStream(agentId, streamTarget, streamId);
522
+ } catch (e) {
523
+ console.warn("[AICQ Channel] endStream failed:", e.message);
524
+ if (accumulatedText && runtime.chat) {
525
+ try {
526
+ await runtime.chat.sendMessage(agentId, streamTarget, accumulatedText, { isGroup });
527
+ } catch (e2) {
528
+ console.error("[AICQ Channel] Fallback sendMessage failed:", e2.message);
529
+ }
530
+ }
531
+ }
532
+ };
533
+
534
+ const storePath = session.resolveStorePath
535
+ ? session.resolveStorePath(cfg.session?.store, { agentId: route.agentId })
536
+ : undefined;
537
+
538
+ await inbound.run({
539
+ channel: "aicq-chat",
540
+ accountId,
541
+ raw: msg,
542
+ adapter: {
543
+ ingest: () => ({
544
+ id: msg.id || msg.message_id || `aicq_${Date.now()}`,
545
+ timestamp: Date.now(),
546
+ rawText: textContent,
547
+ textForAgent: textContent,
548
+ textForCommands: textContent,
549
+ raw: msg,
550
+ }),
551
+ resolveTurn: async () => {
552
+ const ctxPayload = inbound.buildContext({
553
+ channel: "aicq-chat",
554
+ accountId,
555
+ timestamp: Date.now(),
556
+ from: `aicq:${fromId}`,
557
+ sender: {
558
+ id: fromId,
559
+ name: fromId,
560
+ },
561
+ conversation: {
562
+ kind: isGroup ? "group" : "direct",
563
+ id: replyTargetId,
564
+ label: replyTargetId,
565
+ },
566
+ route: {
567
+ agentId: route.agentId,
568
+ accountId,
569
+ routeSessionKey: sessionKey,
570
+ dispatchSessionKey: sessionKey,
571
+ },
572
+ reply: { to: `aicq:${replyTargetId}` },
573
+ message: {
574
+ rawBody: textContent,
575
+ commandBody: textContent,
576
+ bodyForAgent: textContent,
577
+ },
578
+ extra: {
579
+ msgId: msg.id || msg.message_id,
580
+ isFile: !!(msg.local_path || msg._synthetic),
581
+ },
582
+ });
583
+ return {
584
+ cfg,
585
+ channel: "aicq-chat",
586
+ accountId,
587
+ agentId: route.agentId,
588
+ routeSessionKey: sessionKey,
589
+ storePath,
590
+ ctxPayload,
591
+ recordInboundSession: session.recordInboundSession,
592
+ dispatchReplyWithBufferedBlockDispatcher: reply.dispatchReplyWithBufferedBlockDispatcher,
593
+ delivery: {
594
+ durable: () => ({ to: replyTargetId }),
595
+ deliver: async (payload) => {
596
+ if (!runtime.chat || !payload.text) return { visibleReplySent: false };
597
+ if (streamState.cancelled) {
598
+ console.log('[AICQ Channel] Stream cancelled, skipping deliver');
599
+ return { visibleReplySent: false };
600
+ }
601
+ await ensureStreamStart();
602
+ accumulatedText += payload.text;
603
+ // [FIX v3.16.3 edge #4] The stream-chunk API is DM-only
604
+ // (server stream frames address a friend id). For groups
605
+ // we accumulate here and endStreamSafe() falls back to a
606
+ // single sendMessage(isGroup: true) when no chunks were
607
+ // streamed — one clean group message instead of a
608
+ // mis-routed DM.
609
+ if (isGroup) return { visibleReplySent: true };
610
+ const text = payload.text;
611
+ const CHUNK_SIZE = 20;
612
+ for (let i = 0; i < text.length; i += CHUNK_SIZE) {
613
+ if (streamState.cancelled) {
614
+ console.log('[AICQ Channel] Stream cancelled mid-deliver, stopping');
615
+ break;
616
+ }
617
+ const slice = text.slice(i, i + CHUNK_SIZE);
618
+ try {
619
+ await runtime.chat.sendStreamChunk(
620
+ agentId,
621
+ streamTarget,
622
+ streamId,
623
+ slice,
624
+ "text"
625
+ );
626
+ streamChunksSent++;
627
+ } catch (e) {
628
+ console.warn("[AICQ Channel] sendStreamChunk failed:", e.message);
629
+ break;
630
+ }
631
+ await new Promise((r) => setTimeout(r, 50));
632
+ }
633
+ return { visibleReplySent: true };
634
+ },
635
+ },
636
+ dispatcherOptions: {
637
+ onReplyStart: async () => {
638
+ await ensureStreamStart();
639
+ },
640
+ abortSignal: turnAbortController.signal,
641
+ onToolResult: async (payload) => {
642
+ try {
643
+ if (payload?.text && !isGroup) {
644
+ await runtime.chat.sendStreamChunk(
645
+ agentId,
646
+ streamTarget,
647
+ streamId,
648
+ payload.text,
649
+ "tool_result"
650
+ );
651
+ streamChunksSent++;
652
+ }
653
+ } catch (e) {
654
+ console.warn("[AICQ Channel] onToolResult send failed:", e.message);
655
+ }
656
+ },
657
+ onAgentToolResult: (event) => {
658
+ try {
659
+ if (isGroup) return;
660
+ const toolData = {
661
+ name: event.toolName,
662
+ input: event.result,
663
+ success: !event.isError,
664
+ };
665
+ runtime.chat.sendStreamChunk(
666
+ agentId,
667
+ streamTarget,
668
+ streamId,
669
+ JSON.stringify(toolData),
670
+ "tool_call",
671
+ toolData
672
+ );
673
+ streamChunksSent++;
674
+ } catch (e) {
675
+ console.warn("[AICQ Channel] onAgentToolResult send failed:", e.message);
676
+ }
677
+ },
678
+ },
679
+ };
680
+ },
681
+ },
682
+ });
683
+ // After inbound.run returns (all delivers completed), end the stream.
684
+ await endStreamSafe();
685
+ if (runtime.activeTurnAbort === turnAbortController) {
686
+ runtime.activeTurnAbort = null;
687
+ }
688
+ } catch (e) {
689
+ console.error("[AICQ Channel] Inbound message handling error:", e.message, e.stack);
690
+ }
691
+ });
692
+ }
693
+ }
694
+ } else {
695
+ console.log("[AICQ Channel] channelRuntime not available — running in standalone mode");
696
+ }
697
+
698
+ // Update health status
699
+ setStatus({
700
+ accountId,
701
+ enabled: true,
702
+ configured: true,
703
+ running: true,
704
+ lastStartAt: Date.now(),
705
+ lastError: null,
706
+ });
707
+
708
+ console.log(`[AICQ Channel] Account ${accountId} started successfully`);
709
+
710
+ // ── Keep startAccount alive until abort signal ──────────────────
711
+ // OpenClaw expects startAccount to be a long-lived task. If it
712
+ // resolves immediately, the gateway treats it as an unexpected
713
+ // exit and enters a restart loop. We wait on the abort signal.
714
+ await new Promise((resolve) => {
715
+ if (abortSignal?.aborted) { resolve(); return; }
716
+ const onAbort = () => { cleanup(); resolve(); };
717
+ const cleanup = () => { abortSignal?.removeEventListener("abort", onAbort); };
718
+ abortSignal?.addEventListener("abort", onAbort, { once: true });
719
+ });
720
+ },
721
+
722
+ /**
723
+ * Stop the channel account — disconnect and clean up.
724
+ */
725
+ async stopAccount(ctx) {
726
+ const { accountId } = ctx;
727
+ console.log(`[AICQ Channel] stopAccount called for ${accountId}`);
728
+
729
+ if (runtime.serverClient) {
730
+ try {
731
+ if (typeof runtime.serverClient.stop === "function") {
732
+ runtime.serverClient.stop();
733
+ } else if (typeof runtime.serverClient.disconnect === "function") {
734
+ runtime.serverClient.disconnect();
735
+ }
736
+ console.log("[AICQ Channel] WebSocket disconnected");
737
+ } catch (e) {
738
+ console.warn("[AICQ Channel] Disconnect error:", e.message);
739
+ }
740
+ }
741
+ },
742
+ };
743
+
744
+ // ── Add config helpers (required by OpenClaw channel loader) ──────────
745
+ // createChatChannelPlugin does not auto-attach config helpers,
746
+ // but the OpenClaw loader requires plugin.config.listAccountIds
747
+ // and plugin.config.resolveAccount for channel registration.
748
+
749
+ // resolveTemplateVar is defined at the top of this file.
750
+
751
+ _plugin.config = {
752
+ /**
753
+ * List all account IDs configured for this channel.
754
+ * Resolves template variables like {{agent.id}}.
755
+ *
756
+ * Signature: (cfg: OpenClawConfig) => string[]
757
+ */
758
+ listAccountIds(cfg) {
759
+ const section = (cfg.channels || {})["aicq-chat"] || {};
760
+ if (section.accountId) {
761
+ const resolved = resolveTemplateVar(cfg, section.accountId);
762
+ return [resolved];
763
+ }
764
+ return [];
765
+ },
766
+
767
+ /**
768
+ * Resolve an account from config. Reuses the setup resolver.
769
+ *
770
+ * Signature: (cfg: OpenClawConfig, accountId?: string | null) => ResolvedAccount
771
+ */
772
+ resolveAccount,
773
+
774
+ /**
775
+ * Lightweight account inspection.
776
+ *
777
+ * Signature: (cfg: OpenClawConfig, accountId?: string | null) => unknown
778
+ */
779
+ inspectAccount,
780
+
781
+ /**
782
+ * Default account ID for this channel.
783
+ *
784
+ * Signature: (cfg: OpenClawConfig) => string
785
+ */
786
+ defaultAccountId(cfg) {
787
+ const section = (cfg.channels || {})["aicq-chat"] || {};
788
+ if (section.accountId) {
789
+ return resolveTemplateVar(cfg, section.accountId);
790
+ }
791
+ return OPENCLAW_DEFAULT_AGENT_ID;
792
+ },
793
+
794
+ /**
795
+ * Check if the account is enabled.
796
+ *
797
+ * IMPORTANT: OpenClaw calls this with (account, cfg) where `account`
798
+ * is the RESOLVED account object from resolveAccount(), not the config.
799
+ *
800
+ * Signature: (account: ResolvedAccount, cfg: OpenClawConfig) => boolean
801
+ */
802
+ isEnabled(account, cfg) {
803
+ return account.enabled !== false;
804
+ },
805
+
806
+ /**
807
+ * Check if the channel account is configured.
808
+ *
809
+ * IMPORTANT: OpenClaw calls this with (account, cfg) where `account`
810
+ * is the RESOLVED account object from resolveAccount(), not the config.
811
+ * Our old code had isConfigured(cfg) which received the account object
812
+ * as `cfg`, causing it to always return false — this was the root cause
813
+ * of the "not-running" bug.
814
+ *
815
+ * Signature: (account: ResolvedAccount, cfg: OpenClawConfig) => boolean
816
+ */
817
+ isConfigured(account, cfg) {
818
+ return Boolean(account && account.accountId);
819
+ },
820
+
821
+ /**
822
+ * Return the reason the channel is not configured.
823
+ *
824
+ * Signature: (account: ResolvedAccount, cfg: OpenClawConfig) => string
825
+ */
826
+ unconfiguredReason(account, cfg) {
827
+ if (!account || !account.accountId) {
828
+ return "accountId is required — set channels.aicq-chat.accountId in openclaw.json";
829
+ }
830
+ return null;
831
+ },
832
+
833
+ /**
834
+ * Describe the account for status surfaces.
835
+ *
836
+ * IMPORTANT: OpenClaw calls this with (account, cfg) where `account`
837
+ * is the RESOLVED account object, not the config.
838
+ *
839
+ * Signature: (account: ResolvedAccount, cfg: OpenClawConfig) => ChannelAccountSnapshot
840
+ */
841
+ describeAccount(account, cfg) {
842
+ return {
843
+ accountId: account?.accountId || null,
844
+ label: "AICQ Encrypted Chat",
845
+ enabled: account?.enabled !== false,
846
+ };
847
+ },
848
+ };
849
+
850
+ // [v3.16] Declare hot-reload config prefixes (OpenClaw >= 2026.5 contract).
851
+ // Without this, config edits under channels.aicq-chat may not trigger the
852
+ // channel restart path on newer hosts.
853
+ _plugin.reload = { configPrefixes: ["channels.aicq-chat"] };
854
+
855
+ // [FIX tts-crash] OpenClaw dispatch (chooseDispatchRoute -> resolveChannelTtsVoiceDelivery)
856
+ // reads getChannelPlugin(id)?.capabilities.tts?.voice at runtime; some beta
857
+ // builds crash when the plugin object lacks a capabilities node. Declare it.
858
+ if (!_plugin.capabilities) _plugin.capabilities = {};
859
+ _plugin.capabilities.tts = { voice: false };
860
+
861
+ export const aicqChatPlugin = _plugin;