@clawling/clawchat-plugin-openclaw 2026.5.12-28

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.
Files changed (114) hide show
  1. package/INSTALL.md +64 -0
  2. package/README.md +227 -0
  3. package/dist/index.js +20 -0
  4. package/dist/setup-entry.js +3 -0
  5. package/dist/src/api-client.js +263 -0
  6. package/dist/src/api-types.js +17 -0
  7. package/dist/src/api-types.test-d.js +10 -0
  8. package/dist/src/buffered-stream.js +177 -0
  9. package/dist/src/channel.js +66 -0
  10. package/dist/src/channel.setup.js +119 -0
  11. package/dist/src/clawchat-memory.js +403 -0
  12. package/dist/src/clawchat-metadata.js +310 -0
  13. package/dist/src/client.js +35 -0
  14. package/dist/src/commands.js +35 -0
  15. package/dist/src/config.js +274 -0
  16. package/dist/src/group-message-coalescer.js +119 -0
  17. package/dist/src/inbound.js +170 -0
  18. package/dist/src/llm-context-debug.js +86 -0
  19. package/dist/src/login.runtime.js +204 -0
  20. package/dist/src/media-runtime.js +85 -0
  21. package/dist/src/message-mapper.js +146 -0
  22. package/dist/src/mock-transport.js +31 -0
  23. package/dist/src/outbound.js +628 -0
  24. package/dist/src/plugin-prompts.js +89 -0
  25. package/dist/src/profile-prompt.js +269 -0
  26. package/dist/src/profile-sync.js +110 -0
  27. package/dist/src/prompt-injection.js +25 -0
  28. package/dist/src/protocol-types.js +63 -0
  29. package/dist/src/protocol-types.typecheck.js +1 -0
  30. package/dist/src/protocol.js +33 -0
  31. package/dist/src/reply-dispatcher.js +422 -0
  32. package/dist/src/runtime.js +1254 -0
  33. package/dist/src/storage.js +525 -0
  34. package/dist/src/streaming.js +65 -0
  35. package/dist/src/terminal-send.js +36 -0
  36. package/dist/src/tools-schema.js +208 -0
  37. package/dist/src/tools.js +920 -0
  38. package/dist/src/ws-alignment.js +178 -0
  39. package/dist/src/ws-client.js +588 -0
  40. package/dist/src/ws-log.js +19 -0
  41. package/index.ts +24 -0
  42. package/openclaw.plugin.json +169 -0
  43. package/package.json +80 -0
  44. package/prompts/default-group-bio.md +19 -0
  45. package/prompts/default-owner-behavior.md +27 -0
  46. package/prompts/platform.md +13 -0
  47. package/setup-entry.ts +4 -0
  48. package/skills/clawchat/SKILL.md +91 -0
  49. package/src/api-client.test.ts +827 -0
  50. package/src/api-client.ts +414 -0
  51. package/src/api-types.ts +146 -0
  52. package/src/channel.outbound.test.ts +433 -0
  53. package/src/channel.setup.ts +145 -0
  54. package/src/channel.test.ts +262 -0
  55. package/src/channel.ts +81 -0
  56. package/src/clawchat-memory.test.ts +480 -0
  57. package/src/clawchat-memory.ts +533 -0
  58. package/src/clawchat-metadata.test.ts +477 -0
  59. package/src/clawchat-metadata.ts +429 -0
  60. package/src/client.test.ts +169 -0
  61. package/src/client.ts +56 -0
  62. package/src/commands.test.ts +39 -0
  63. package/src/commands.ts +41 -0
  64. package/src/config.test.ts +344 -0
  65. package/src/config.ts +404 -0
  66. package/src/group-message-coalescer.test.ts +237 -0
  67. package/src/group-message-coalescer.ts +171 -0
  68. package/src/inbound.test.ts +508 -0
  69. package/src/inbound.ts +278 -0
  70. package/src/llm-context-debug.test.ts +55 -0
  71. package/src/llm-context-debug.ts +139 -0
  72. package/src/login.runtime.test.ts +737 -0
  73. package/src/login.runtime.ts +277 -0
  74. package/src/manifest.test.ts +352 -0
  75. package/src/media-runtime.test.ts +207 -0
  76. package/src/media-runtime.ts +152 -0
  77. package/src/message-mapper.test.ts +201 -0
  78. package/src/message-mapper.ts +174 -0
  79. package/src/mock-transport.test.ts +35 -0
  80. package/src/mock-transport.ts +38 -0
  81. package/src/outbound.test.ts +1269 -0
  82. package/src/outbound.ts +803 -0
  83. package/src/plugin-entry.test.ts +38 -0
  84. package/src/plugin-prompts.test.ts +94 -0
  85. package/src/plugin-prompts.ts +107 -0
  86. package/src/profile-prompt.test.ts +274 -0
  87. package/src/profile-prompt.ts +351 -0
  88. package/src/profile-sync.test.ts +539 -0
  89. package/src/profile-sync.ts +191 -0
  90. package/src/prompt-injection.test.ts +39 -0
  91. package/src/prompt-injection.ts +45 -0
  92. package/src/protocol-types.test.ts +69 -0
  93. package/src/protocol-types.ts +296 -0
  94. package/src/protocol-types.typecheck.ts +89 -0
  95. package/src/protocol.test.ts +39 -0
  96. package/src/protocol.ts +42 -0
  97. package/src/reply-dispatcher.test.ts +1324 -0
  98. package/src/reply-dispatcher.ts +555 -0
  99. package/src/runtime.test.ts +4719 -0
  100. package/src/runtime.ts +1493 -0
  101. package/src/scripts.test.ts +85 -0
  102. package/src/storage.test.ts +560 -0
  103. package/src/storage.ts +807 -0
  104. package/src/terminal-send.test.ts +81 -0
  105. package/src/terminal-send.ts +56 -0
  106. package/src/tools-schema.ts +337 -0
  107. package/src/tools.test.ts +933 -0
  108. package/src/tools.ts +1185 -0
  109. package/src/ws-alignment.test.ts +103 -0
  110. package/src/ws-alignment.ts +275 -0
  111. package/src/ws-client.test.ts +1217 -0
  112. package/src/ws-client.ts +662 -0
  113. package/src/ws-log.test.ts +32 -0
  114. package/src/ws-log.ts +31 -0
@@ -0,0 +1,1254 @@
1
+ import { AckTimeoutError, AuthError, ProtocolError, StateError, TransportError, EVENT, } from "./protocol-types.js";
2
+ import { waitUntilAbort } from "openclaw/plugin-sdk/channel-lifecycle";
3
+ import { hasControlCommand } from "openclaw/plugin-sdk/command-detection";
4
+ import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
5
+ import { createOpenclawClawlingClient } from "./client.js";
6
+ import { createOpenclawClawlingApiClient } from "./api-client.js";
7
+ import { ClawlingApiError } from "./api-types.js";
8
+ import { CHANNEL_ID, effectiveGroupCommandMode, } from "./config.js";
9
+ import { dispatchOpenclawClawlingInbound } from "./inbound.js";
10
+ import { fetchInboundMedia } from "./media-runtime.js";
11
+ import { createOpenclawClawlingReplyDispatcher } from "./reply-dispatcher.js";
12
+ import { runWithTerminalClawChatSendScope } from "./terminal-send.js";
13
+ import { flushAlignedOutboundQueue, getAlignedOutboundQueueSize, setAlignedOutboundLogContext, } from "./outbound.js";
14
+ import { formatWsLog } from "./ws-log.js";
15
+ import { createProtocolControlHandler, createReconnectTracker } from "./ws-alignment.js";
16
+ import { clawChatDbPathForStateDir, getClawChatStore, } from "./storage.js";
17
+ import { getClawChatGroupPrompt, getClawChatUserPrompt } from "./plugin-prompts.js";
18
+ import { loadClawChatPromptMetadata, renderClawChatProfilePrompt, resolveSenderRelation, } from "./profile-prompt.js";
19
+ import { refreshGroupProfile, syncFirstSeenClawChatProfiles } from "./profile-sync.js";
20
+ import { pullGroupMetadata, pullOwnerMetadata } from "./clawchat-metadata.js";
21
+ import { deleteClawChatMemoryFile, readClawChatMemoryFile } from "./clawchat-memory.js";
22
+ import { clearClawChatPromptInjectionForSession, stageClawChatPromptInjection, } from "./prompt-injection.js";
23
+ import { createGroupMessageCoalescer } from "./group-message-coalescer.js";
24
+ import { openclawLlmContextDebug } from "./llm-context-debug.js";
25
+ const { setRuntime: setOpenclawClawlingRuntime, getRuntime: getOpenclawClawlingRuntime } = createPluginRuntimeStore("clawchat-plugin-openclaw runtime not initialized");
26
+ export { setOpenclawClawlingRuntime, getOpenclawClawlingRuntime };
27
+ const activeClients = new Map();
28
+ const CLAWCHAT_PLUGIN_SLASH_COMMANDS = new Set(["clawchat-activate"]);
29
+ const CLAWCHAT_MEMORY_ROOT_UNAVAILABLE = "ClawChat memory root unavailable: OpenClaw workspaceDir could not be resolved";
30
+ const OPENCLAW_CONFIRM_SLASH_COMMANDS = new Set([
31
+ "approve",
32
+ "deny",
33
+ "always",
34
+ "cancel",
35
+ "yes",
36
+ "no",
37
+ "ok",
38
+ "confirm",
39
+ "remember",
40
+ "nevermind",
41
+ ]);
42
+ function resolveChannelContextBuilder(rt) {
43
+ const channel = rt;
44
+ const buildContext = channel.inbound?.buildContext ?? channel.turn?.buildContext;
45
+ if (!buildContext) {
46
+ throw new Error("OpenClaw channel runtime missing inbound/turn buildContext");
47
+ }
48
+ return buildContext;
49
+ }
50
+ function parseSlashCommandName(rawBody) {
51
+ const stripped = rawBody.trimStart();
52
+ if (!stripped.startsWith("/"))
53
+ return null;
54
+ const token = stripped.split(/\s+/, 1)[0] ?? "";
55
+ const name = token.slice(1).replace(/_/g, "-").toLowerCase();
56
+ if (!name || name.includes("/"))
57
+ return null;
58
+ return name;
59
+ }
60
+ function isKnownOpenClawGroupSlashCommand(rawBody, cfg) {
61
+ const name = parseSlashCommandName(rawBody);
62
+ if (!name)
63
+ return false;
64
+ return hasControlCommand(rawBody, cfg)
65
+ || CLAWCHAT_PLUGIN_SLASH_COMMANDS.has(name)
66
+ || OPENCLAW_CONFIRM_SLASH_COMMANDS.has(name);
67
+ }
68
+ export function getOpenclawClawlingClient(accountId) {
69
+ return activeClients.get(accountId);
70
+ }
71
+ export function resolveClawChatMemoryRoot(runtime, cfg, agentId) {
72
+ const resolver = runtime.agent?.resolveAgentWorkspaceDir;
73
+ if (typeof resolver !== "function") {
74
+ throw new Error(CLAWCHAT_MEMORY_ROOT_UNAVAILABLE);
75
+ }
76
+ let workspaceDir;
77
+ try {
78
+ workspaceDir = resolver(cfg, agentId);
79
+ }
80
+ catch {
81
+ throw new Error(CLAWCHAT_MEMORY_ROOT_UNAVAILABLE);
82
+ }
83
+ const memoryRoot = typeof workspaceDir === "string" ? workspaceDir.trim() : "";
84
+ if (!memoryRoot) {
85
+ throw new Error(CLAWCHAT_MEMORY_ROOT_UNAVAILABLE);
86
+ }
87
+ return memoryRoot;
88
+ }
89
+ export async function waitForOpenclawClawlingClient(accountId, options = {}) {
90
+ const timeoutMs = options.timeoutMs ?? 15_000;
91
+ const pollMs = options.pollMs ?? 100;
92
+ const deadline = Date.now() + timeoutMs;
93
+ for (;;) {
94
+ const client = activeClients.get(accountId);
95
+ if (client && client.state === "connected") {
96
+ return client;
97
+ }
98
+ if (Date.now() >= deadline) {
99
+ throw new Error(`clawchat-plugin-openclaw client did not activate within ${timeoutMs}ms for account ${accountId}`);
100
+ }
101
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
102
+ }
103
+ }
104
+ export function mapClawlingStateToStatus(state) {
105
+ const now = Date.now();
106
+ switch (state) {
107
+ case "connected":
108
+ return { connected: true, running: true, lastStartAt: now };
109
+ case "reconnecting":
110
+ return { connected: false, running: true };
111
+ case "disconnected":
112
+ return { connected: false, running: false, lastStopAt: now };
113
+ default:
114
+ return { connected: false, running: true };
115
+ }
116
+ }
117
+ export function classifyClawlingClientError(err) {
118
+ if (err instanceof AuthError)
119
+ return { kind: "auth", retry: false, message: err.message };
120
+ if (err instanceof TransportError)
121
+ return { kind: "transport", retry: true, message: err.message };
122
+ if (err instanceof AckTimeoutError)
123
+ return { kind: "ack-timeout", retry: false, message: err.message };
124
+ if (err instanceof ProtocolError)
125
+ return { kind: "protocol", retry: false, message: err.message };
126
+ if (err instanceof StateError)
127
+ return { kind: "state", retry: false, message: err.message };
128
+ return {
129
+ kind: "unknown",
130
+ retry: false,
131
+ message: err instanceof Error ? err.message : String(err),
132
+ };
133
+ }
134
+ function formatConversationSubject(peer) {
135
+ return peer.kind === "group" ? `group:${peer.id}` : peer.id;
136
+ }
137
+ function asRecord(value) {
138
+ return value && typeof value === "object" ? value : null;
139
+ }
140
+ function optionalString(value) {
141
+ return typeof value === "string" ? value : undefined;
142
+ }
143
+ function hasOwn(record, key) {
144
+ return Object.prototype.hasOwnProperty.call(record, key);
145
+ }
146
+ function optionalNullableString(record, key) {
147
+ if (!hasOwn(record, key))
148
+ return undefined;
149
+ const value = record[key];
150
+ if (value === null)
151
+ return null;
152
+ return optionalString(value);
153
+ }
154
+ function isConversationNotFoundError(err) {
155
+ if (!(err instanceof ClawlingApiError))
156
+ return false;
157
+ return err.meta?.status === 404 || err.meta?.status === 410 ||
158
+ err.meta?.code === 404 || err.meta?.code === 410 || err.meta?.code === 40401 ||
159
+ err.message.toLowerCase().includes("conversation not found");
160
+ }
161
+ function metadataVersionFromEnvelope(env) {
162
+ const payload = asRecord(env.payload);
163
+ const version = payload?.version;
164
+ return typeof version === "number" && Number.isFinite(version) ? version : undefined;
165
+ }
166
+ function metadataScopesFromEnvelope(env) {
167
+ const scope = asRecord(env.payload)?.scope;
168
+ return Array.isArray(scope) ? scope.filter((item) => typeof item === "string") : [];
169
+ }
170
+ function shouldRefreshBehaviorForScopes(scopes) {
171
+ return scopes.includes("behavior");
172
+ }
173
+ function shouldRefreshConversationForScopes(scopes) {
174
+ if (scopes.length === 0)
175
+ return true;
176
+ return scopes.some((scope) => scope === "title" || scope === "description" || scope !== "behavior");
177
+ }
178
+ function withClawChatSessionScope(cfg) {
179
+ return {
180
+ ...cfg,
181
+ session: {
182
+ ...(cfg.session ?? {}),
183
+ dmScope: "per-account-channel-peer",
184
+ },
185
+ };
186
+ }
187
+ function buildActivationBootstrapText() {
188
+ return [
189
+ "ClawChat activation bootstrap: You are now connected to this ClawChat direct conversation.",
190
+ "Please do both:",
191
+ "1. Send a brief, friendly greeting to the user in this ClawChat direct conversation.",
192
+ "2. If you have local profile information for yourself, such as display name, bio, or avatar, update the connected ClawChat account profile using the available ClawChat tools. Use `clawchat_update_account_profile` for display name/bio/avatar URL, and use `clawchat_upload_avatar_image` first if the avatar is only available as a local image path. If you do not have local profile information, skip profile updates and only greet the user.",
193
+ "Do not ask the user for profile information just for this bootstrap.",
194
+ ].join("\n");
195
+ }
196
+ function buildActivationBootstrapEnvelope(params) {
197
+ const text = buildActivationBootstrapText();
198
+ const now = Date.now();
199
+ return {
200
+ version: "2",
201
+ event: EVENT.MESSAGE_SEND,
202
+ trace_id: `clawchat-plugin-openclaw-bootstrap-${now}`,
203
+ emitted_at: now,
204
+ chat_id: params.conversationId,
205
+ chat_type: "direct",
206
+ to: { id: params.account.userId, type: "direct" },
207
+ sender: {
208
+ id: "clawchat-bootstrap",
209
+ type: "direct",
210
+ nick_name: "ClawChat Activation",
211
+ },
212
+ payload: {
213
+ message_id: `clawchat-plugin-openclaw-bootstrap-${params.conversationId}-${now}`,
214
+ message_mode: "normal",
215
+ message: {
216
+ body: { fragments: [{ kind: "text", text }] },
217
+ context: { mentions: [], reply: null },
218
+ streaming: {
219
+ status: "static",
220
+ sequence: 0,
221
+ mutation_policy: "sealed",
222
+ started_at: null,
223
+ completed_at: null,
224
+ },
225
+ },
226
+ },
227
+ };
228
+ }
229
+ function resolveConnectionStore(params, runtime) {
230
+ if (params.store !== undefined)
231
+ return params.store;
232
+ if (params.transport)
233
+ return null;
234
+ try {
235
+ const stateDir = runtime.state?.resolveStateDir?.();
236
+ return getClawChatStore({
237
+ ...(stateDir ? { dbPath: clawChatDbPathForStateDir(stateDir) } : {}),
238
+ log: { error: (message) => params.log?.error?.(message) },
239
+ });
240
+ }
241
+ catch {
242
+ params.log?.error?.("clawchat-plugin-openclaw sqlite connection persistence unavailable; continuing.");
243
+ return null;
244
+ }
245
+ }
246
+ export async function startOpenclawClawlingGateway(params) {
247
+ const { cfg, account, abortSignal, setStatus, getStatus, log } = params;
248
+ // Obtain PluginRuntime from the stored runtime set via setOpenclawClawlingRuntime.
249
+ const runtime = getOpenclawClawlingRuntime();
250
+ const accountId = account.accountId;
251
+ const store = resolveConnectionStore(params, runtime);
252
+ let conversationApiClient;
253
+ const getConversationApiClient = () => {
254
+ conversationApiClient ??= createOpenclawClawlingApiClient({
255
+ baseUrl: account.baseUrl,
256
+ token: account.token,
257
+ userId: account.userId,
258
+ });
259
+ return conversationApiClient;
260
+ };
261
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime start entered configured=${account.configured} enabled=${account.enabled} hasToken=${Boolean(account.token)} hasUserId=${Boolean(account.userId)} hasOwnerUserId=${Boolean(account.ownerUserId)} websocketUrl=${account.websocketUrl || "(empty)"}`);
262
+ let lastHelloFailTraceId = "-";
263
+ let lastHelloFailReason = "";
264
+ let lastConnectTraceId = "-";
265
+ let lastHelloOkDeviceId;
266
+ let lastHelloOkDeliveryMode;
267
+ let currentAttemptStartedAt = 0;
268
+ let authFailureLogged = false;
269
+ let closingForAbort = false;
270
+ let wsReady = false;
271
+ let currentConnectionId = null;
272
+ let currentConnectionFinished = false;
273
+ const reconnectTracker = createReconnectTracker({
274
+ accountId,
275
+ log: (msg) => log?.info?.(msg),
276
+ maxDelayMs: account.reconnect.maxDelay,
277
+ });
278
+ const wsLogContext = () => {
279
+ const snapshot = reconnectTracker.snapshot();
280
+ return {
281
+ attempt: snapshot.attempt || 1,
282
+ reconnectCount: snapshot.reconnectCount,
283
+ state: snapshot.state === "connected" ? "ready" : snapshot.state,
284
+ };
285
+ };
286
+ const recordConnection = (action, fn) => {
287
+ try {
288
+ return fn();
289
+ }
290
+ catch {
291
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw sqlite ${action} failed; continuing`);
292
+ return undefined;
293
+ }
294
+ };
295
+ const finishCurrentConnection = (input) => {
296
+ if (!store || currentConnectionId == null || currentConnectionFinished)
297
+ return;
298
+ const connectionId = currentConnectionId;
299
+ recordConnection("finish", () => store.finishConnection(connectionId, input));
300
+ currentConnectionFinished = true;
301
+ currentConnectionId = null;
302
+ };
303
+ const refreshConversationDetails = async (conversationId, options) => {
304
+ try {
305
+ const memoryRoot = options.memoryRoot;
306
+ if (!memoryRoot) {
307
+ await getConversationApiClient().getConversation(conversationId);
308
+ return;
309
+ }
310
+ const result = await pullGroupMetadata({
311
+ memoryRoot,
312
+ groupId: conversationId,
313
+ api: getConversationApiClient(),
314
+ skipUserIds: [account.userId, account.ownerUserId],
315
+ });
316
+ if (result.failures.length > 0) {
317
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw group participant metadata refresh partially failed: ${result.failures.map((failure) => `${failure.targetId}: ${failure.error}`).join("; ")}`);
318
+ }
319
+ if (!result.conversation)
320
+ throw new Error("ClawChat conversation metadata response is missing conversation");
321
+ }
322
+ catch (err) {
323
+ if (isConversationNotFoundError(err)) {
324
+ if (options.memoryRoot) {
325
+ await deleteClawChatMemoryFile(options.memoryRoot, {
326
+ targetType: "group",
327
+ targetId: conversationId,
328
+ }).catch((deleteError) => {
329
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw group metadata file delete failed conversation=${conversationId}: ${deleteError instanceof Error ? deleteError.message : String(deleteError)}`);
330
+ });
331
+ }
332
+ return;
333
+ }
334
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw metadata refresh failed source=${options.source} conversation=${conversationId}: ${err instanceof Error ? err.message : String(err)}`);
335
+ }
336
+ };
337
+ const refreshAgentBehavior = async (options) => {
338
+ try {
339
+ await pullOwnerMetadata({
340
+ memoryRoot: options.memoryRoot,
341
+ agentId: account.agentId,
342
+ accountUserId: account.userId,
343
+ accountOwnerUserId: account.ownerUserId,
344
+ api: getConversationApiClient(),
345
+ });
346
+ }
347
+ catch (err) {
348
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw behavior refresh failed source=${options.source} agent=${account.userId}: ${err instanceof Error ? err.message : String(err)}`);
349
+ }
350
+ };
351
+ const refreshConversationCacheAfterReady = async () => {
352
+ void store;
353
+ };
354
+ const resolveMemoryRootForPeer = (peer) => {
355
+ try {
356
+ const route = runtime.channel.routing.resolveAgentRoute({
357
+ cfg: withClawChatSessionScope(cfg),
358
+ channel: CHANNEL_ID,
359
+ accountId,
360
+ peer,
361
+ });
362
+ return resolveClawChatMemoryRoot(runtime, cfg, route.agentId);
363
+ }
364
+ catch (err) {
365
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw metadata refresh memory root unavailable: ${err instanceof Error ? err.message : String(err)}`);
366
+ return null;
367
+ }
368
+ };
369
+ const handleMetadataInvalidation = async (env) => {
370
+ const conversationId = typeof env.chat_id === "string" && env.chat_id.trim()
371
+ ? env.chat_id
372
+ : "";
373
+ if (!conversationId) {
374
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw metadata invalidation missing chat_id trace=${env.trace_id}`);
375
+ return;
376
+ }
377
+ const version = metadataVersionFromEnvelope(env);
378
+ const scopes = metadataScopesFromEnvelope(env);
379
+ const refreshBehavior = shouldRefreshBehaviorForScopes(scopes);
380
+ const refreshConversation = shouldRefreshConversationForScopes(scopes);
381
+ if (!refreshBehavior && !refreshConversation)
382
+ return;
383
+ const peer = {
384
+ kind: env.chat_type === "group" ? "group" : "direct",
385
+ id: conversationId,
386
+ };
387
+ const memoryRoot = resolveMemoryRootForPeer(peer);
388
+ if (!memoryRoot)
389
+ return;
390
+ if (refreshBehavior) {
391
+ await refreshAgentBehavior({
392
+ source: "metadata_invalidation",
393
+ ...(version !== undefined ? { metadataVersion: version } : {}),
394
+ memoryRoot,
395
+ });
396
+ }
397
+ if (!refreshConversation)
398
+ return;
399
+ await refreshConversationDetails(conversationId, {
400
+ source: "metadata_invalidation",
401
+ ...(version !== undefined ? { metadataVersion: version } : {}),
402
+ memoryRoot,
403
+ });
404
+ };
405
+ const syncMessagePathProfiles = async (turn, memoryRoot) => {
406
+ if (turn.senderId === "clawchat-bootstrap") {
407
+ await pullOwnerMetadata({
408
+ memoryRoot,
409
+ agentId: account.agentId,
410
+ accountUserId: account.userId,
411
+ accountOwnerUserId: account.ownerUserId,
412
+ api: getConversationApiClient(),
413
+ });
414
+ return;
415
+ }
416
+ if (turn.peer.kind === "direct" && (turn.senderId === account.ownerUserId || turn.senderId === account.userId)) {
417
+ await pullOwnerMetadata({
418
+ memoryRoot,
419
+ agentId: account.agentId,
420
+ accountUserId: account.userId,
421
+ accountOwnerUserId: account.ownerUserId,
422
+ api: getConversationApiClient(),
423
+ });
424
+ return;
425
+ }
426
+ if (turn.peer.kind === "group") {
427
+ await refreshGroupProfile({
428
+ platform: "openclaw",
429
+ accountId,
430
+ accountUserId: account.userId,
431
+ accountOwnerUserId: account.ownerUserId,
432
+ conversationId: turn.peer.id,
433
+ api: getConversationApiClient(),
434
+ store: {},
435
+ memoryRoot,
436
+ log: { error: (message) => log?.error?.(`[${accountId}] ${message}`) },
437
+ });
438
+ return;
439
+ }
440
+ await syncFirstSeenClawChatProfiles({
441
+ platform: "openclaw",
442
+ accountId,
443
+ accountUserId: account.userId,
444
+ accountOwnerUserId: account.ownerUserId,
445
+ chat: {
446
+ id: turn.peer.id,
447
+ type: "direct",
448
+ lastSeenAt: turn.timestamp,
449
+ },
450
+ sender: {
451
+ id: turn.senderId,
452
+ ...(turn.senderNickName ? { nickname: turn.senderNickName } : {}),
453
+ },
454
+ api: getConversationApiClient(),
455
+ store: {},
456
+ memoryRoot,
457
+ log: { error: (message) => log?.error?.(`[${accountId}] ${message}`) },
458
+ });
459
+ };
460
+ const client = createOpenclawClawlingClient(account, {
461
+ ...(params.transport ? { transport: params.transport } : {}),
462
+ wsLifecycle: {
463
+ onConnectFrameSent: (env) => {
464
+ lastConnectTraceId = typeof env.trace_id === "string" ? env.trace_id : "-";
465
+ if (store && currentConnectionId != null) {
466
+ const connectionId = currentConnectionId;
467
+ recordConnection("connect-sent", () => store.markConnectSent(connectionId));
468
+ }
469
+ const deviceId = typeof env.payload?.device_id === "string" ? env.payload.device_id : "-";
470
+ const current = wsLogContext();
471
+ log?.info?.(formatWsLog({
472
+ event: "connect_sent",
473
+ accountId,
474
+ attempt: current.attempt,
475
+ reconnectCount: current.reconnectCount,
476
+ state: "handshaking",
477
+ action: "await_hello",
478
+ fields: [
479
+ ["trace_id", lastConnectTraceId],
480
+ ["device_id", deviceId],
481
+ ],
482
+ }));
483
+ },
484
+ },
485
+ });
486
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime client created`);
487
+ setAlignedOutboundLogContext(client, wsLogContext);
488
+ client.on("hello:ok", (env) => {
489
+ const payload = env.payload && typeof env.payload === "object"
490
+ ? env.payload
491
+ : {};
492
+ lastHelloOkDeviceId = typeof payload.device_id === "string" ? payload.device_id : undefined;
493
+ lastHelloOkDeliveryMode = typeof payload.delivery_mode === "string" ? payload.delivery_mode : undefined;
494
+ });
495
+ const protocolControlLogger = createProtocolControlHandler({
496
+ accountId,
497
+ log: (msg) => log?.info?.(msg),
498
+ send: () => { },
499
+ context: wsLogContext,
500
+ });
501
+ const logAuthFailure = (reason) => {
502
+ if (authFailureLogged)
503
+ return;
504
+ authFailureLogged = true;
505
+ const current = wsLogContext();
506
+ log?.error?.(formatWsLog({
507
+ event: "auth_failed",
508
+ accountId,
509
+ attempt: current.attempt,
510
+ reconnectCount: current.reconnectCount,
511
+ state: "auth_failed",
512
+ action: "stop_reconnect",
513
+ fields: [
514
+ ["trace_id", lastHelloFailTraceId],
515
+ ["reason", reason || lastHelloFailReason],
516
+ ],
517
+ }));
518
+ };
519
+ let dispatchActivationBootstrap = async () => { };
520
+ client.on("state", ({ from, to }) => {
521
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw state ${from} -> ${to}`);
522
+ wsReady = to === "connected";
523
+ if (to === "connecting") {
524
+ reconnectTracker.connectStart();
525
+ currentAttemptStartedAt = Date.now();
526
+ const current = wsLogContext();
527
+ if (store) {
528
+ recordConnection("start", () => {
529
+ currentConnectionId = store.startConnection({
530
+ platform: "openclaw",
531
+ accountId,
532
+ attempt: current.attempt,
533
+ reconnectCount: current.reconnectCount,
534
+ connectStartedAt: currentAttemptStartedAt,
535
+ });
536
+ currentConnectionFinished = false;
537
+ });
538
+ }
539
+ log?.info?.(formatWsLog({
540
+ event: "connect_start",
541
+ accountId,
542
+ attempt: current.attempt,
543
+ reconnectCount: current.reconnectCount,
544
+ state: "connecting",
545
+ action: "connect",
546
+ fields: [
547
+ ["url", account.websocketUrl],
548
+ ["queue_size", getAlignedOutboundQueueSize(client)],
549
+ ],
550
+ }));
551
+ }
552
+ else if (to === "connected") {
553
+ const elapsedMs = Math.max(0, Date.now() - currentAttemptStartedAt);
554
+ const queueSize = getAlignedOutboundQueueSize(client);
555
+ reconnectTracker.markReady();
556
+ const current = wsLogContext();
557
+ if (store && currentConnectionId != null) {
558
+ const connectionId = currentConnectionId;
559
+ recordConnection("ready", () => {
560
+ if (lastHelloOkDeviceId === undefined && lastHelloOkDeliveryMode === undefined) {
561
+ store.markConnectionReady(connectionId);
562
+ return;
563
+ }
564
+ store.markConnectionReady(connectionId, {
565
+ ...(lastHelloOkDeviceId !== undefined ? { resolvedDeviceId: lastHelloOkDeviceId } : {}),
566
+ ...(lastHelloOkDeliveryMode !== undefined ? { deliveryMode: lastHelloOkDeliveryMode } : {}),
567
+ });
568
+ });
569
+ }
570
+ log?.info?.(formatWsLog({
571
+ event: "handshake_ok",
572
+ accountId,
573
+ attempt: current.attempt,
574
+ reconnectCount: current.reconnectCount,
575
+ state: "ready",
576
+ action: "flush_queue",
577
+ fields: [
578
+ ["trace_id", lastConnectTraceId],
579
+ ["elapsed_ms", elapsedMs],
580
+ ["queue_size", queueSize],
581
+ ],
582
+ }));
583
+ try {
584
+ flushAlignedOutboundQueue(client);
585
+ }
586
+ catch {
587
+ // The queue keeps the failed frame at the head and will retry after the next reconnect.
588
+ }
589
+ void refreshConversationCacheAfterReady();
590
+ void dispatchActivationBootstrap();
591
+ }
592
+ else if (to === "disconnected") {
593
+ reconnectTracker.markClosed();
594
+ }
595
+ const next = { ...getStatus(), ...mapClawlingStateToStatus(to) };
596
+ setStatus(next);
597
+ });
598
+ client.on("close", ({ code, reason }) => {
599
+ if (closingForAbort || (code === 1000 && reason === "client close"))
600
+ return;
601
+ finishCurrentConnection({
602
+ state: "disconnected",
603
+ closeCode: code ?? null,
604
+ closeReason: reason ?? null,
605
+ });
606
+ const current = wsLogContext();
607
+ log?.info?.(formatWsLog({
608
+ event: "connection_lost",
609
+ accountId,
610
+ attempt: current.attempt,
611
+ reconnectCount: current.reconnectCount,
612
+ state: current.state,
613
+ action: "reconnect",
614
+ fields: [
615
+ ["code", code],
616
+ ["reason", reason],
617
+ ],
618
+ }));
619
+ });
620
+ client.on("reconnect:scheduled", ({ delay }) => {
621
+ reconnectTracker.scheduleReconnect("connection_lost", {
622
+ delayMs: delay,
623
+ maxDelayMs: account.reconnect.maxDelay,
624
+ });
625
+ });
626
+ client.on("raw", (env) => {
627
+ if (env.event === "connect.challenge") {
628
+ const payload = env.payload;
629
+ const current = wsLogContext();
630
+ log?.info?.(formatWsLog({
631
+ event: "challenge_received",
632
+ accountId,
633
+ attempt: current.attempt,
634
+ reconnectCount: current.reconnectCount,
635
+ state: "handshaking",
636
+ action: "send_connect",
637
+ fields: [
638
+ ["challenge_trace_id", env.trace_id],
639
+ ["has_nonce", typeof payload?.nonce === "string" && payload.nonce.length > 0],
640
+ ],
641
+ }));
642
+ }
643
+ if (env.event === "ping" || env.event === "pong") {
644
+ protocolControlLogger.handleInbound(env);
645
+ }
646
+ if (wsReady) {
647
+ const sender = env.sender;
648
+ const senderId = typeof sender?.id === "string" ? sender.id : "-";
649
+ if (env.event === "message.send" || env.event === "message.reply") {
650
+ const current = wsLogContext();
651
+ log?.info?.(formatWsLog({
652
+ event: "inbound_dispatch",
653
+ accountId,
654
+ attempt: current.attempt,
655
+ reconnectCount: current.reconnectCount,
656
+ state: "ready",
657
+ action: "dispatch",
658
+ fields: [
659
+ ["event_name", env.event],
660
+ ["trace_id", env.trace_id],
661
+ ["chat_id", env.chat_id],
662
+ ["sender_id", senderId],
663
+ ],
664
+ }));
665
+ }
666
+ else if (env.event === "message.ack") {
667
+ const current = wsLogContext();
668
+ log?.info?.(formatWsLog({
669
+ event: "inbound_control",
670
+ accountId,
671
+ attempt: current.attempt,
672
+ reconnectCount: current.reconnectCount,
673
+ state: "ready",
674
+ action: "ack",
675
+ fields: [
676
+ ["event_name", env.event],
677
+ ["trace_id", env.trace_id],
678
+ ],
679
+ }));
680
+ }
681
+ else if (env.event === "offline.batch" ||
682
+ env.event === "offline.ack" ||
683
+ env.event === "offline.done") {
684
+ const current = wsLogContext();
685
+ log?.info?.(formatWsLog({
686
+ event: "inbound_control",
687
+ accountId,
688
+ attempt: current.attempt,
689
+ reconnectCount: current.reconnectCount,
690
+ state: "ready",
691
+ action: "ignore_legacy",
692
+ fields: [
693
+ ["event_name", env.event],
694
+ ["trace_id", env.trace_id],
695
+ ],
696
+ }));
697
+ }
698
+ else if (env.event !== "ping" && env.event !== "pong") {
699
+ const current = wsLogContext();
700
+ log?.info?.(formatWsLog({
701
+ event: "inbound_ignored",
702
+ accountId,
703
+ attempt: current.attempt,
704
+ reconnectCount: current.reconnectCount,
705
+ state: "ready",
706
+ action: "ignore",
707
+ fields: [
708
+ ["event_name", env.event],
709
+ ["trace_id", env.trace_id],
710
+ ],
711
+ }));
712
+ }
713
+ }
714
+ if (env.event !== "hello-fail")
715
+ return;
716
+ lastHelloFailTraceId = env.trace_id;
717
+ const payload = env.payload;
718
+ lastHelloFailReason = typeof payload?.reason === "string" ? payload.reason : "";
719
+ });
720
+ client.on("metadata:invalidated", (env) => {
721
+ void handleMetadataInvalidation(env);
722
+ });
723
+ client.on("error", (err) => {
724
+ const classified = classifyClawlingClientError(err);
725
+ if (classified.kind === "auth") {
726
+ finishCurrentConnection({
727
+ state: "auth_failed",
728
+ error: lastHelloFailReason || classified.message,
729
+ });
730
+ logAuthFailure(classified.message);
731
+ setStatus({
732
+ ...getStatus(),
733
+ connected: false,
734
+ configured: false,
735
+ running: false,
736
+ lastError: classified.message,
737
+ });
738
+ }
739
+ else if (classified.kind === "transport") {
740
+ finishCurrentConnection({ state: "transport_error", error: classified.message });
741
+ const current = wsLogContext();
742
+ log?.info?.(formatWsLog({
743
+ event: "connection_lost",
744
+ accountId,
745
+ attempt: current.attempt,
746
+ reconnectCount: current.reconnectCount,
747
+ state: current.state,
748
+ action: "reconnect",
749
+ fields: [
750
+ ["code", "-"],
751
+ ["reason", classified.message],
752
+ ],
753
+ }));
754
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw transport error (reconnecting): ${classified.message}`);
755
+ setStatus({ ...getStatus(), connected: false, running: true });
756
+ }
757
+ else if (classified.kind === "ack-timeout") {
758
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw ack timeout: ${classified.message}`);
759
+ }
760
+ else if (classified.kind === "protocol") {
761
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw protocol error: ${classified.message}`);
762
+ }
763
+ else if (classified.kind === "state") {
764
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw state error: ${classified.message}`);
765
+ }
766
+ else {
767
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw client error: ${classified.message}`);
768
+ }
769
+ });
770
+ const loadGroupParticipantsForPrompt = async (params) => {
771
+ const groupFile = await readClawChatMemoryFile(params.memoryRoot, {
772
+ targetType: "group",
773
+ targetId: params.groupId,
774
+ });
775
+ const participantIds = (groupFile.metadata.participant_ids ?? "")
776
+ .split(",")
777
+ .map((value) => value.trim())
778
+ .filter((value) => value.length > 0);
779
+ const agentOwnerId = params.ownerMetadata?.agent_owner_id ?? account.ownerUserId;
780
+ const groupOwnerId = groupFile.metadata.group_owner_id;
781
+ const participants = [];
782
+ for (const userId of participantIds) {
783
+ let metadata = null;
784
+ try {
785
+ const file = await readClawChatMemoryFile(params.memoryRoot, {
786
+ targetType: "user",
787
+ targetId: userId,
788
+ });
789
+ metadata = file.exists ? file.metadata : null;
790
+ }
791
+ catch {
792
+ metadata = null;
793
+ }
794
+ const isAgentOwner = Boolean(agentOwnerId && userId === agentOwnerId);
795
+ const isGroupOwner = Boolean(groupOwnerId && userId === groupOwnerId);
796
+ const name = isAgentOwner
797
+ ? params.ownerMetadata?.agent_owner_nickname ?? metadata?.nickname ?? userId
798
+ : userId === account.userId
799
+ ? params.ownerMetadata?.agent_nickname ?? metadata?.nickname ?? userId
800
+ : isGroupOwner
801
+ ? groupFile.metadata.group_owner_nickname ?? metadata?.nickname ?? userId
802
+ : metadata?.nickname ?? userId;
803
+ const profileType = metadata?.profile_type ?? (userId === account.userId ? "agent" : "user");
804
+ participants.push({ id: userId, name, profileType, isAgentOwner, isGroupOwner });
805
+ }
806
+ return participants;
807
+ };
808
+ const buildPromptForTurn = async (turn, memoryRoot) => {
809
+ const senderRelation = resolveSenderRelation({
810
+ senderId: turn.senderId,
811
+ accountUserId: account.userId,
812
+ accountOwnerUserId: account.ownerUserId,
813
+ senderProfileType: turn.senderProfileType,
814
+ });
815
+ const promptChatType = turn.peer.kind === "group" ? "group" : "dm";
816
+ const promptMetadata = await loadClawChatPromptMetadata({
817
+ memoryRoot,
818
+ turn: {
819
+ chatType: promptChatType,
820
+ senderId: turn.senderId,
821
+ senderIsOwner: senderRelation === "owner",
822
+ groupId: turn.peer.kind === "group" ? turn.peer.id : null,
823
+ },
824
+ log: { error: (message) => log?.error?.(`[${accountId}] ${message}`) },
825
+ });
826
+ const metadataSenderProfileType = promptMetadata.userMetadata?.profile_type ?? null;
827
+ const promptSenderProfileType = metadataSenderProfileType ?? turn.senderProfileType ?? (senderRelation === "self_agent" || senderRelation === "peer_agent" ? "agent" : "user");
828
+ const groupParticipants = turn.peer.kind === "group"
829
+ ? await loadGroupParticipantsForPrompt({
830
+ memoryRoot,
831
+ groupId: turn.peer.id,
832
+ ownerMetadata: promptMetadata.ownerMetadata,
833
+ })
834
+ : [];
835
+ return renderClawChatProfilePrompt({
836
+ basePrompt: turn.peer.kind === "group" ? getClawChatGroupPrompt() : getClawChatUserPrompt(),
837
+ ...promptMetadata,
838
+ ownerIdFallback: account.ownerUserId,
839
+ groupParticipants,
840
+ turn: {
841
+ chatType: promptChatType,
842
+ chatId: turn.peer.id,
843
+ senderId: turn.senderId,
844
+ senderName: promptMetadata.userMetadata?.nickname ?? (turn.senderNickName || turn.senderId),
845
+ senderProfileType: promptSenderProfileType,
846
+ senderIsOwner: senderRelation === "owner",
847
+ groupId: turn.peer.kind === "group" ? turn.peer.id : null,
848
+ coalescedGroupBatch: turn.coalescedGroupBatch === true,
849
+ wasMentioned: turn.wasMentioned,
850
+ mentionedUserIds: turn.mentionedUserIds,
851
+ mentionedUsers: turn.mentionedUsers,
852
+ messageText: turn.rawBody,
853
+ },
854
+ });
855
+ };
856
+ const resolveSenderNickNameForTurn = (turn) => {
857
+ if (turn.senderNickName && turn.senderNickName !== turn.senderId)
858
+ return turn.senderNickName;
859
+ return turn.senderNickName || turn.senderId;
860
+ };
861
+ const resolveSenderBatchIdentityForTurn = (turn) => {
862
+ const senderRelation = resolveSenderRelation({
863
+ senderId: turn.senderId,
864
+ accountUserId: account.userId,
865
+ accountOwnerUserId: account.ownerUserId,
866
+ senderProfileType: turn.senderProfileType,
867
+ });
868
+ return {
869
+ senderRelation,
870
+ senderProfileType: turn.senderProfileType ??
871
+ (senderRelation === "self_agent" || senderRelation === "peer_agent" ? "agent" : "user"),
872
+ senderIsOwner: senderRelation === "owner",
873
+ senderIsGroupOwner: turn.senderIsGroupOwner ?? false,
874
+ };
875
+ };
876
+ const claimInboundTurn = (turn) => {
877
+ const env = turn.envelope;
878
+ if (store?.claimMessageOnce) {
879
+ const claimed = recordConnection("message claim", () => store.claimMessageOnce?.({
880
+ platform: "openclaw",
881
+ accountId,
882
+ kind: "message",
883
+ direction: "inbound",
884
+ eventType: String(env.event),
885
+ traceId: turn.traceId,
886
+ chatId: turn.peer.id,
887
+ messageId: turn.messageId,
888
+ text: turn.rawBody,
889
+ raw: env,
890
+ }));
891
+ if (claimed === false) {
892
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw skip duplicate stored msg=${turn.messageId}`);
893
+ return "skipped";
894
+ }
895
+ }
896
+ return "claimed";
897
+ };
898
+ const dispatchTurnToAgent = async (turn) => {
899
+ const rt = runtime.channel;
900
+ const storePath = rt.session.resolveStorePath(cfg.session?.store);
901
+ const routeCfg = withClawChatSessionScope(cfg);
902
+ const route = rt.routing.resolveAgentRoute({
903
+ cfg: routeCfg,
904
+ channel: CHANNEL_ID,
905
+ accountId,
906
+ peer: turn.peer,
907
+ });
908
+ const memoryRoot = resolveClawChatMemoryRoot(runtime, cfg, route.agentId);
909
+ const body = rt.reply.formatAgentEnvelope({
910
+ channel: "Clawling Chat",
911
+ from: formatConversationSubject(turn.peer),
912
+ body: turn.rawBody,
913
+ timestamp: turn.timestamp,
914
+ ...rt.reply.resolveEnvelopeFormatOptions(cfg),
915
+ });
916
+ try {
917
+ await syncMessagePathProfiles(turn, memoryRoot);
918
+ }
919
+ catch (err) {
920
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw message metadata refresh failed: ${err instanceof Error ? err.message : String(err)}`);
921
+ }
922
+ const conversationTarget = `${CHANNEL_ID}:${formatConversationSubject(turn.peer)}`;
923
+ const turnPrompt = await buildPromptForTurn(turn, memoryRoot);
924
+ const ctxPayload = resolveChannelContextBuilder(rt)({
925
+ channel: CHANNEL_ID,
926
+ accountId: route.accountId ?? accountId,
927
+ provider: CHANNEL_ID,
928
+ surface: CHANNEL_ID,
929
+ messageId: turn.messageId,
930
+ messageIdFull: turn.messageId,
931
+ timestamp: turn.timestamp,
932
+ from: conversationTarget,
933
+ sender: {
934
+ id: turn.senderId,
935
+ name: turn.senderNickName || turn.senderId,
936
+ displayLabel: turn.senderNickName || turn.senderId,
937
+ },
938
+ conversation: {
939
+ kind: turn.peer.kind,
940
+ id: turn.peer.id,
941
+ label: formatConversationSubject(turn.peer),
942
+ routePeer: turn.peer,
943
+ },
944
+ route: {
945
+ agentId: route.agentId,
946
+ accountId: route.accountId ?? accountId,
947
+ routeSessionKey: route.sessionKey,
948
+ },
949
+ reply: {
950
+ to: `${CHANNEL_ID}:${account.userId}`,
951
+ originatingTo: conversationTarget,
952
+ },
953
+ message: {
954
+ body,
955
+ rawBody: turn.rawBody,
956
+ bodyForAgent: turn.rawBody,
957
+ commandBody: turn.rawBody,
958
+ envelopeFrom: conversationTarget,
959
+ },
960
+ access: {
961
+ mentions: {
962
+ canDetectMention: true,
963
+ wasMentioned: turn.wasMentioned,
964
+ hasAnyMention: turn.mentionedUserIds.length > 0,
965
+ },
966
+ },
967
+ ...(memoryRoot ? { extra: { memoryRoot } } : {}),
968
+ ...(turn.peer.kind === "group"
969
+ ? { supplemental: { groupSystemPrompt: turnPrompt } }
970
+ : {}),
971
+ });
972
+ if (memoryRoot) {
973
+ ctxPayload.memoryRoot = memoryRoot;
974
+ }
975
+ if (turn.mentionedUserIds.length > 0) {
976
+ ctxPayload.MentionedUserIds = turn.mentionedUserIds;
977
+ }
978
+ // Fetch any inbound media attachments and populate MediaPath/MediaPaths in context.
979
+ const inboundPaths = turn.mediaItems.length > 0
980
+ ? await fetchInboundMedia(turn.mediaItems, {
981
+ runtime,
982
+ log,
983
+ maxBytes: 20 * 1024 * 1024,
984
+ })
985
+ : [];
986
+ if (inboundPaths.length > 0) {
987
+ ctxPayload.MediaPath = inboundPaths[0];
988
+ ctxPayload.MediaPaths = inboundPaths;
989
+ }
990
+ const resolvedSessionKey = optionalString(ctxPayload.SessionKey) ?? route.sessionKey;
991
+ openclawLlmContextDebug.writeSnapshot({
992
+ visibility: "injected_only",
993
+ trace: {
994
+ traceId: turn.traceId,
995
+ messageId: turn.messageId,
996
+ chatId: turn.peer.id,
997
+ chatType: turn.peer.kind,
998
+ senderId: turn.senderId,
999
+ sessionKey: resolvedSessionKey,
1000
+ },
1001
+ input: {
1002
+ injectedPrompt: turnPrompt,
1003
+ eventText: turn.rawBody,
1004
+ },
1005
+ });
1006
+ clearClawChatPromptInjectionForSession(resolvedSessionKey);
1007
+ const stagedDirectPrompt = turn.peer.kind !== "group";
1008
+ if (stagedDirectPrompt) {
1009
+ stageClawChatPromptInjection({
1010
+ sessionKey: resolvedSessionKey,
1011
+ prompt: turnPrompt,
1012
+ });
1013
+ }
1014
+ try {
1015
+ try {
1016
+ await rt.session.recordInboundSession({
1017
+ storePath,
1018
+ sessionKey: resolvedSessionKey,
1019
+ ctx: ctxPayload,
1020
+ onRecordError: (err) => {
1021
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw failed to record inbound session: ${String(err)}`);
1022
+ },
1023
+ });
1024
+ }
1025
+ catch (err) {
1026
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw failed to record inbound session: ${String(err)}`);
1027
+ }
1028
+ const replyCtx = turn.replyCtx;
1029
+ const terminalSendScopeId = `${account.accountId}\0${turn.peer.id}\0${turn.messageId}`;
1030
+ const { dispatcher, replyOptions, markDispatchIdle } = createOpenclawClawlingReplyDispatcher({
1031
+ cfg,
1032
+ runtime,
1033
+ account,
1034
+ client,
1035
+ target: { chatId: turn.peer.id, chatType: turn.peer.kind },
1036
+ ...(replyCtx ? { replyCtx } : {}),
1037
+ inboundMessageId: turn.messageId,
1038
+ terminalSendScopeId,
1039
+ inboundForFinalReply: {
1040
+ chatId: turn.peer.id,
1041
+ senderId: turn.senderId,
1042
+ senderNickName: turn.senderNickName || turn.senderId,
1043
+ bodyText: turn.rawBody,
1044
+ },
1045
+ store: store
1046
+ ? {
1047
+ insertMessage: (input) => store.insertMessage?.(input) ?? null,
1048
+ claimMessageOnce: (input) => store.claimMessageOnce?.(input) ?? null,
1049
+ markMessageAcknowledged: (input) => store.markMessageAcknowledged?.(input) ?? null,
1050
+ updateMessageByIdentity: (input) => store.updateMessageByIdentity?.(input),
1051
+ }
1052
+ : null,
1053
+ log,
1054
+ });
1055
+ const agentsConfigured = Object.keys(cfg.agents ?? {});
1056
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw dispatching reply msg=${turn.messageId} session=${resolvedSessionKey} agent=${route.agentId} agentsConfigured=[${agentsConfigured.join(",")}]`);
1057
+ try {
1058
+ const dispatchResult = await rt.reply.withReplyDispatcher({
1059
+ dispatcher,
1060
+ onSettled: () => markDispatchIdle(),
1061
+ run: () => runWithTerminalClawChatSendScope(terminalSendScopeId, () => rt.reply.dispatchReplyFromConfig({ ctx: ctxPayload, cfg, dispatcher, replyOptions })),
1062
+ });
1063
+ const counts = dispatchResult?.counts ?? {};
1064
+ const queuedFinal = Boolean(dispatchResult?.queuedFinal);
1065
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw dispatch complete msg=${turn.messageId} queuedFinal=${queuedFinal} counts=${JSON.stringify(counts)}`);
1066
+ if (!queuedFinal && Object.values(counts).every((n) => !n)) {
1067
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw NO reply was produced (no final / block / tool dispatched). ` +
1068
+ `Likely causes: agent='${route.agentId}' not configured in cfg.agents (configured: [${agentsConfigured.join(",")}]); ` +
1069
+ `or send-policy denied; or a plugin claimed the binding.`);
1070
+ }
1071
+ return "submitted";
1072
+ }
1073
+ catch (err) {
1074
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw dispatch failed msg=${turn.messageId}: ${String(err)}`);
1075
+ return "failed";
1076
+ }
1077
+ }
1078
+ finally {
1079
+ if (stagedDirectPrompt) {
1080
+ clearClawChatPromptInjectionForSession(resolvedSessionKey);
1081
+ }
1082
+ }
1083
+ };
1084
+ const groupCoalescer = createGroupMessageCoalescer({
1085
+ idleMs: 10_000,
1086
+ maxWaitMs: 30_000,
1087
+ dispatch: async (turn) => {
1088
+ await dispatchTurnToAgent(turn);
1089
+ },
1090
+ onError: (err) => {
1091
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw coalesced group dispatch failed: ${String(err)}`);
1092
+ },
1093
+ onDrop: (chatId, count) => {
1094
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw dropped pending group batch chat_id=${chatId} count=${count} reason=shutdown`);
1095
+ },
1096
+ });
1097
+ const ingestTurn = async (rawTurn) => {
1098
+ const senderBatchIdentity = rawTurn.peer.kind === "group"
1099
+ ? resolveSenderBatchIdentityForTurn(rawTurn)
1100
+ : {};
1101
+ const turn = {
1102
+ ...rawTurn,
1103
+ senderNickName: resolveSenderNickNameForTurn(rawTurn),
1104
+ ...senderBatchIdentity,
1105
+ };
1106
+ const claimed = claimInboundTurn(turn);
1107
+ if (claimed === "skipped")
1108
+ return "skipped";
1109
+ if (turn.peer.kind === "group") {
1110
+ if (isKnownOpenClawGroupSlashCommand(turn.rawBody, cfg)) {
1111
+ const commandMode = effectiveGroupCommandMode(account, turn.peer.id);
1112
+ const commandAllowed = commandMode === "all"
1113
+ || (commandMode === "owner" && turn.senderIsOwner === true);
1114
+ if (!commandAllowed) {
1115
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw group command dropped chat_id=${turn.peer.id} msg=${turn.messageId} mode=${commandMode} owner=${turn.senderIsOwner === true}`);
1116
+ return "skipped";
1117
+ }
1118
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw dispatching group command chat_id=${turn.peer.id} msg=${turn.messageId} mode=${commandMode}`);
1119
+ return dispatchTurnToAgent(turn);
1120
+ }
1121
+ if (turn.wasMentioned) {
1122
+ groupCoalescer.enqueue(turn);
1123
+ groupCoalescer.flushNow(turn.peer.id);
1124
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw dispatching mentioned group batch chat_id=${turn.peer.id} msg=${turn.messageId}`);
1125
+ return "submitted";
1126
+ }
1127
+ groupCoalescer.enqueue(turn);
1128
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw queued group batch chat_id=${turn.peer.id} msg=${turn.messageId}`);
1129
+ return "submitted";
1130
+ }
1131
+ return dispatchTurnToAgent(turn);
1132
+ };
1133
+ const handleInboundEnvelope = async (env) => {
1134
+ let ingestResult;
1135
+ try {
1136
+ await dispatchOpenclawClawlingInbound({
1137
+ envelope: env,
1138
+ cfg,
1139
+ runtime,
1140
+ account,
1141
+ log,
1142
+ ingest: async (turn) => {
1143
+ ingestResult = await ingestTurn(turn);
1144
+ },
1145
+ });
1146
+ }
1147
+ catch (err) {
1148
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw message handler error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
1149
+ return "failed";
1150
+ }
1151
+ return ingestResult;
1152
+ };
1153
+ dispatchActivationBootstrap = async () => {
1154
+ if (!store?.claimPendingActivationBootstrap || !store.markActivationBootstrapSent)
1155
+ return;
1156
+ let bootstrap;
1157
+ const releaseBootstrap = () => {
1158
+ if (!bootstrap || !store.releaseActivationBootstrapClaim)
1159
+ return;
1160
+ const claimedBootstrap = bootstrap;
1161
+ recordConnection("activation bootstrap release", () => store.releaseActivationBootstrapClaim?.({
1162
+ platform: "openclaw",
1163
+ accountId,
1164
+ conversationId: claimedBootstrap.conversationId,
1165
+ }));
1166
+ };
1167
+ try {
1168
+ bootstrap = recordConnection("activation bootstrap claim", () => store.claimPendingActivationBootstrap?.({ platform: "openclaw", accountId }));
1169
+ if (!bootstrap)
1170
+ return;
1171
+ const claimedBootstrap = bootstrap;
1172
+ const result = await handleInboundEnvelope(buildActivationBootstrapEnvelope({ account, conversationId: claimedBootstrap.conversationId }));
1173
+ if (result !== "submitted") {
1174
+ releaseBootstrap();
1175
+ return;
1176
+ }
1177
+ recordConnection("activation bootstrap sent", () => store.markActivationBootstrapSent?.({
1178
+ platform: "openclaw",
1179
+ accountId,
1180
+ conversationId: claimedBootstrap.conversationId,
1181
+ }));
1182
+ }
1183
+ catch (err) {
1184
+ releaseBootstrap();
1185
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw activation bootstrap failed: ${err instanceof Error ? err.message : String(err)}`);
1186
+ }
1187
+ };
1188
+ client.on("message", (env) => {
1189
+ void (async () => {
1190
+ await handleInboundEnvelope(env);
1191
+ })();
1192
+ });
1193
+ // `client.connect()` resolves on `hello-ok` or rejects on `hello-fail`
1194
+ // (auth). Transport failures (server unreachable, DNS error, etc.) do
1195
+ // NOT reject this promise — the local client handles them internally and
1196
+ // drives its own exponential-backoff reconnect loop (`initialDelay * 2^attempt`
1197
+ // capped at `maxDelay`, with jitter). So we never throw here on anything
1198
+ // other than auth failure; on auth we tear the account down cleanly and
1199
+ // return without throwing (which would make the gateway supervisor
1200
+ // restart us immediately in a tight loop).
1201
+ try {
1202
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime calling client.connect()`);
1203
+ await client.connect();
1204
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime client.connect() resolved`);
1205
+ }
1206
+ catch (err) {
1207
+ const classified = classifyClawlingClientError(err);
1208
+ setStatus({
1209
+ ...getStatus(),
1210
+ connected: false,
1211
+ configured: classified.kind !== "auth",
1212
+ running: false,
1213
+ lastError: classified.message,
1214
+ });
1215
+ if (classified.kind === "auth") {
1216
+ finishCurrentConnection({
1217
+ state: "auth_failed",
1218
+ error: lastHelloFailReason || classified.message,
1219
+ });
1220
+ logAuthFailure(classified.message);
1221
+ return;
1222
+ }
1223
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw connect failed (${classified.kind}): ${classified.message}`);
1224
+ return;
1225
+ }
1226
+ activeClients.set(accountId, client);
1227
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime active client registered`);
1228
+ setStatus({
1229
+ ...getStatus(),
1230
+ connected: true,
1231
+ running: true,
1232
+ lastStartAt: Date.now(),
1233
+ });
1234
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw connected`);
1235
+ await waitUntilAbort(abortSignal, async () => {
1236
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw runtime abort received; closing client`);
1237
+ activeClients.delete(accountId);
1238
+ closingForAbort = true;
1239
+ groupCoalescer.cancelAll();
1240
+ finishCurrentConnection({
1241
+ state: "disconnected",
1242
+ closeCode: 1000,
1243
+ closeReason: "client close",
1244
+ });
1245
+ client.close();
1246
+ setStatus({
1247
+ ...getStatus(),
1248
+ connected: false,
1249
+ running: false,
1250
+ lastStopAt: Date.now(),
1251
+ });
1252
+ log?.info?.(`[${accountId}] clawchat-plugin-openclaw disconnected`);
1253
+ });
1254
+ }