@privateclaw/privateclaw 0.1.32 → 0.1.34

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 (40) hide show
  1. package/README.md +16 -9
  2. package/dist/bridges/openclaw-agent-bridge.d.ts +7 -0
  3. package/dist/bridges/openclaw-agent-bridge.js +71 -25
  4. package/dist/bridges/openclaw-agent-bridge.js.map +1 -1
  5. package/dist/channel.d.ts +14 -0
  6. package/dist/channel.js +103 -0
  7. package/dist/channel.js.map +1 -0
  8. package/dist/cli.js +16 -2
  9. package/dist/cli.js.map +1 -1
  10. package/dist/compat/openclaw.d.ts +231 -2
  11. package/dist/compat/openclaw.js +1 -0
  12. package/dist/compat/openclaw.js.map +1 -1
  13. package/dist/openclaw-plugin.js +199 -4
  14. package/dist/openclaw-plugin.js.map +1 -1
  15. package/dist/pair-session.d.ts +32 -0
  16. package/dist/pair-session.js +115 -41
  17. package/dist/pair-session.js.map +1 -1
  18. package/dist/provider.d.ts +4 -1
  19. package/dist/provider.js +109 -4
  20. package/dist/provider.js.map +1 -1
  21. package/dist/session-control.d.ts +15 -1
  22. package/dist/session-control.js +184 -5
  23. package/dist/session-control.js.map +1 -1
  24. package/dist/types.d.ts +20 -1
  25. package/openclaw.plugin.json +3 -2
  26. package/package.json +2 -2
  27. package/src/bridges/openclaw-agent-bridge.test.ts +154 -0
  28. package/src/bridges/openclaw-agent-bridge.ts +97 -27
  29. package/src/channel.ts +130 -0
  30. package/src/cli.ts +17 -1
  31. package/src/compat/openclaw.ts +282 -2
  32. package/src/openclaw-plugin.test.ts +392 -3
  33. package/src/openclaw-plugin.ts +262 -3
  34. package/src/pair-session.test.ts +119 -0
  35. package/src/pair-session.ts +144 -47
  36. package/src/provider.test.ts +266 -0
  37. package/src/provider.ts +133 -4
  38. package/src/session-control.test.ts +87 -0
  39. package/src/session-control.ts +252 -5
  40. package/src/types.ts +23 -0
@@ -31,6 +31,18 @@ export interface PairSessionOptions {
31
31
  handoffToBackground?: () => Promise<string | void>;
32
32
  }
33
33
 
34
+ type ActiveSessionSource = Pick<PrivateClawProvider, "listActiveSessions">;
35
+
36
+ export type PairSessionForegroundOutcome =
37
+ | { kind: "signal"; signal: NodeJS.Signals }
38
+ | { kind: "session-ended" }
39
+ | { kind: "stdin-eof" };
40
+
41
+ export interface PairSessionWaiter<TOutcome> {
42
+ promise: Promise<TOutcome>;
43
+ cancel(): void;
44
+ }
45
+
34
46
  export function parsePositiveIntegerFlag(
35
47
  value: string | undefined,
36
48
  label: string,
@@ -52,63 +64,155 @@ export function parsePositiveIntegerFlag(
52
64
  return parsed;
53
65
  }
54
66
 
55
- async function waitForShutdownSignal(): Promise<NodeJS.Signals> {
56
- return new Promise((resolve) => {
57
- const handleSigint = () => {
67
+ function createNeverResolvingPromise<T>(): Promise<T> {
68
+ return new Promise<T>(() => undefined);
69
+ }
70
+
71
+ export function createShutdownSignalWaiter(
72
+ signalSource: Pick<NodeJS.Process, "once" | "off"> = process,
73
+ ): PairSessionWaiter<{ kind: "signal"; signal: NodeJS.Signals }> {
74
+ let cancelled = false;
75
+ let handleSigint: (() => void) | undefined;
76
+ let handleSigterm: (() => void) | undefined;
77
+ const cleanup = () => {
78
+ if (cancelled) {
79
+ return;
80
+ }
81
+ cancelled = true;
82
+ if (handleSigint) {
83
+ signalSource.off("SIGINT", handleSigint);
84
+ }
85
+ if (handleSigterm) {
86
+ signalSource.off("SIGTERM", handleSigterm);
87
+ }
88
+ };
89
+ const promise = new Promise<{ kind: "signal"; signal: NodeJS.Signals }>((resolve) => {
90
+ handleSigint = () => {
58
91
  cleanup();
59
- resolve("SIGINT");
92
+ resolve({ kind: "signal", signal: "SIGINT" });
60
93
  };
61
- const handleSigterm = () => {
94
+ handleSigterm = () => {
62
95
  cleanup();
63
- resolve("SIGTERM");
64
- };
65
- const cleanup = () => {
66
- process.off("SIGINT", handleSigint);
67
- process.off("SIGTERM", handleSigterm);
96
+ resolve({ kind: "signal", signal: "SIGTERM" });
68
97
  };
69
98
 
70
- process.once("SIGINT", handleSigint);
71
- process.once("SIGTERM", handleSigterm);
99
+ signalSource.once("SIGINT", handleSigint);
100
+ signalSource.once("SIGTERM", handleSigterm);
72
101
  });
102
+ return {
103
+ promise,
104
+ cancel: cleanup,
105
+ };
73
106
  }
74
107
 
75
- async function waitForStdinEof(): Promise<void> {
76
- if (!process.stdin.isTTY || process.stdin.destroyed) {
77
- return new Promise<void>(() => undefined);
108
+ export function createStdinEofWaiter(
109
+ input: Pick<
110
+ NodeJS.ReadStream,
111
+ "isTTY" | "destroyed" | "isPaused" | "pause" | "resume" | "once" | "off"
112
+ > = process.stdin,
113
+ ): PairSessionWaiter<{ kind: "stdin-eof" }> {
114
+ if (!input.isTTY || input.destroyed) {
115
+ return {
116
+ promise: createNeverResolvingPromise(),
117
+ cancel: () => undefined,
118
+ };
78
119
  }
79
120
 
80
- return new Promise((resolve) => {
81
- const wasPaused = process.stdin.isPaused();
82
- const handleEnd = () => {
121
+ let cancelled = false;
122
+ const wasPaused = input.isPaused();
123
+ let handleEnd: (() => void) | undefined;
124
+ let handleClose: (() => void) | undefined;
125
+ const cleanup = () => {
126
+ if (cancelled) {
127
+ return;
128
+ }
129
+ cancelled = true;
130
+ if (handleEnd) {
131
+ input.off("end", handleEnd);
132
+ }
133
+ if (handleClose) {
134
+ input.off("close", handleClose);
135
+ }
136
+ if (wasPaused && !input.destroyed) {
137
+ input.pause();
138
+ }
139
+ };
140
+ const promise = new Promise<{ kind: "stdin-eof" }>((resolve) => {
141
+ handleEnd = () => {
83
142
  cleanup();
84
- resolve();
143
+ resolve({ kind: "stdin-eof" });
85
144
  };
86
- const handleClose = () => {
145
+ handleClose = () => {
87
146
  cleanup();
88
- resolve();
89
- };
90
- const cleanup = () => {
91
- process.stdin.off("end", handleEnd);
92
- process.stdin.off("close", handleClose);
93
- if (wasPaused && !process.stdin.destroyed) {
94
- process.stdin.pause();
95
- }
147
+ resolve({ kind: "stdin-eof" });
96
148
  };
97
149
 
98
- process.stdin.once("end", handleEnd);
99
- process.stdin.once("close", handleClose);
150
+ input.once("end", handleEnd);
151
+ input.once("close", handleClose);
100
152
  if (wasPaused) {
101
- process.stdin.resume();
153
+ input.resume();
102
154
  }
103
155
  });
156
+ return {
157
+ promise,
158
+ cancel: cleanup,
159
+ };
104
160
  }
105
161
 
106
- async function waitForSessionsToDrain(
107
- provider: PrivateClawProvider,
162
+ export function createSessionsDrainWaiter(
163
+ provider: ActiveSessionSource,
108
164
  pollMs = 250,
109
- ): Promise<void> {
110
- while (provider.listActiveSessions().length > 0) {
111
- await new Promise((resolve) => setTimeout(resolve, pollMs));
165
+ ): PairSessionWaiter<{ kind: "session-ended" }> {
166
+ let timer: NodeJS.Timeout | undefined;
167
+ let cancelled = false;
168
+ const promise = new Promise<{ kind: "session-ended" }>((resolve) => {
169
+ const poll = () => {
170
+ if (cancelled) {
171
+ return;
172
+ }
173
+ if (provider.listActiveSessions().length === 0) {
174
+ cancelled = true;
175
+ resolve({ kind: "session-ended" });
176
+ return;
177
+ }
178
+ timer = setTimeout(poll, pollMs);
179
+ };
180
+ poll();
181
+ });
182
+ return {
183
+ promise,
184
+ cancel: () => {
185
+ cancelled = true;
186
+ if (timer) {
187
+ clearTimeout(timer);
188
+ timer = undefined;
189
+ }
190
+ },
191
+ };
192
+ }
193
+
194
+ export async function waitForForegroundPairOutcome(params: {
195
+ provider: ActiveSessionSource;
196
+ handoffToBackground?: () => Promise<string | void>;
197
+ pollMs?: number;
198
+ createSignalWaiter?: typeof createShutdownSignalWaiter;
199
+ createDrainWaiter?: typeof createSessionsDrainWaiter;
200
+ createInputWaiter?: typeof createStdinEofWaiter;
201
+ }): Promise<PairSessionForegroundOutcome> {
202
+ const createSignalWaiter = params.createSignalWaiter ?? createShutdownSignalWaiter;
203
+ const createDrainWaiter = params.createDrainWaiter ?? createSessionsDrainWaiter;
204
+ const createInputWaiter = params.createInputWaiter ?? createStdinEofWaiter;
205
+ const waiters: PairSessionWaiter<PairSessionForegroundOutcome>[] = [
206
+ createSignalWaiter(),
207
+ createDrainWaiter(params.provider, params.pollMs),
208
+ ...(params.handoffToBackground ? [createInputWaiter()] : []),
209
+ ];
210
+ try {
211
+ return await Promise.race(waiters.map((waiter) => waiter.promise));
212
+ } finally {
213
+ for (const waiter of waiters) {
214
+ waiter.cancel();
215
+ }
112
216
  }
113
217
  }
114
218
 
@@ -203,17 +307,10 @@ export async function runPairSession({
203
307
  );
204
308
  writePrivateClawAppInstallFooter(writeLine);
205
309
  for (;;) {
206
- const outcome = await Promise.race<
207
- | { kind: "signal"; signal: NodeJS.Signals }
208
- | { kind: "session-ended" }
209
- | { kind: "stdin-eof" }
210
- >([
211
- waitForShutdownSignal().then((signal) => ({ kind: "signal", signal })),
212
- waitForSessionsToDrain(provider).then(() => ({ kind: "session-ended" })),
213
- ...(handoffToBackground
214
- ? [waitForStdinEof().then(() => ({ kind: "stdin-eof" as const }))]
215
- : []),
216
- ]);
310
+ const outcome = await waitForForegroundPairOutcome({
311
+ provider,
312
+ ...(handoffToBackground ? { handoffToBackground } : {}),
313
+ });
217
314
  if (outcome.kind === "stdin-eof") {
218
315
  try {
219
316
  const message = await handoffToBackground?.();
@@ -3069,6 +3069,272 @@ test("group bot mode does not greet the same silent participant twice after reco
3069
3069
  assert.deepEqual(bridge.promptKinds, ["silent_join"]);
3070
3070
  });
3071
3071
 
3072
+ test("provider routes app text messages through appMessageRouter before the bridge", async (t) => {
3073
+ const relay = createRelayServer({
3074
+ host: "127.0.0.1",
3075
+ port: 0,
3076
+ sessionTtlMs: 60_000,
3077
+ frameCacheSize: 8,
3078
+ });
3079
+ const { port } = await relay.start();
3080
+ t.after(async () => {
3081
+ await relay.stop();
3082
+ });
3083
+
3084
+ const bridge = new HistoryRecordingBridge();
3085
+ const routedTexts: string[] = [];
3086
+ let provider!: PrivateClawProvider;
3087
+ provider = new PrivateClawProvider({
3088
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
3089
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
3090
+ bridge,
3091
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
3092
+ appMessageRouter: async (message) => {
3093
+ routedTexts.push(message.payload.text);
3094
+ await provider.sendAssistantMessage(message.sessionId, {
3095
+ text: `Routed reply: ${message.payload.text}`,
3096
+ replyTo: message.payload.clientMessageId,
3097
+ });
3098
+ return true;
3099
+ },
3100
+ });
3101
+ await provider.connect();
3102
+ t.after(async () => {
3103
+ await provider.dispose();
3104
+ });
3105
+
3106
+ const inviteBundle = await provider.createInviteBundle();
3107
+ const invite = decodeInviteString(inviteBundle.inviteUri);
3108
+ const appUrl = new URL(invite.appWsUrl);
3109
+ appUrl.searchParams.set("appId", "router-app");
3110
+ const appSocket = new WebSocket(appUrl.toString());
3111
+ const attached = nextMessage(appSocket);
3112
+ await waitForOpen(appSocket);
3113
+ assert.equal((await attached).type, "relay:attached");
3114
+ const initialFrames = nextMessages(appSocket, 2);
3115
+ appSocket.send(
3116
+ JSON.stringify({
3117
+ type: "app:frame",
3118
+ envelope: encryptPayload({
3119
+ sessionId: invite.sessionId,
3120
+ sessionKey: invite.sessionKey,
3121
+ payload: {
3122
+ kind: "client_hello",
3123
+ appId: "router-app",
3124
+ displayName: "Router App",
3125
+ appVersion: "flutter-test",
3126
+ deviceLabel: "Router Device",
3127
+ sentAt: new Date().toISOString(),
3128
+ },
3129
+ }),
3130
+ }),
3131
+ );
3132
+ await initialFrames;
3133
+
3134
+ appSocket.send(
3135
+ JSON.stringify({
3136
+ type: "app:frame",
3137
+ envelope: encryptPayload({
3138
+ sessionId: invite.sessionId,
3139
+ sessionKey: invite.sessionKey,
3140
+ payload: {
3141
+ kind: "user_message",
3142
+ appId: "router-app",
3143
+ text: "hello routed runtime",
3144
+ clientMessageId: "router-msg-1",
3145
+ sentAt: new Date().toISOString(),
3146
+ },
3147
+ }),
3148
+ }),
3149
+ );
3150
+
3151
+ const assistant = await nextRelayPayload(appSocket, invite);
3152
+ assert.equal(assistant.kind, "assistant_message");
3153
+ assert.equal(assistant.text, "Routed reply: hello routed runtime");
3154
+ assert.equal(assistant.replyTo, "router-msg-1");
3155
+ assert.deepEqual(routedTexts, ["hello routed runtime"]);
3156
+ assert.deepEqual(bridge.conversationMessages, []);
3157
+ appSocket.close();
3158
+ await waitForClose(appSocket);
3159
+ });
3160
+
3161
+ test("provider sendAssistantMessage normalizes inline qq media tags before delivery", async (t) => {
3162
+ const relay = createRelayServer({
3163
+ host: "127.0.0.1",
3164
+ port: 0,
3165
+ sessionTtlMs: 60_000,
3166
+ frameCacheSize: 8,
3167
+ });
3168
+ const { port } = await relay.start();
3169
+ t.after(async () => {
3170
+ await relay.stop();
3171
+ });
3172
+
3173
+ const provider = new PrivateClawProvider({
3174
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
3175
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
3176
+ bridge: new EchoBridge("OpenClaw bridge"),
3177
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
3178
+ });
3179
+ await provider.connect();
3180
+ t.after(async () => {
3181
+ await provider.dispose();
3182
+ });
3183
+
3184
+ const inviteBundle = await provider.createInviteBundle();
3185
+ const invite = decodeInviteString(inviteBundle.inviteUri);
3186
+ const appUrl = new URL(invite.appWsUrl);
3187
+ appUrl.searchParams.set("appId", "qq-sanitize-app");
3188
+ const appSocket = new WebSocket(appUrl.toString());
3189
+ const attached = nextMessage(appSocket);
3190
+ await waitForOpen(appSocket);
3191
+ assert.equal((await attached).type, "relay:attached");
3192
+ const initialFrames = nextMessages(appSocket, 2);
3193
+ appSocket.send(
3194
+ JSON.stringify({
3195
+ type: "app:frame",
3196
+ envelope: encryptPayload({
3197
+ sessionId: invite.sessionId,
3198
+ sessionKey: invite.sessionKey,
3199
+ payload: {
3200
+ kind: "client_hello",
3201
+ appId: "qq-sanitize-app",
3202
+ displayName: "QQ sanitize app",
3203
+ appVersion: "flutter-test",
3204
+ deviceLabel: "QQ sanitize device",
3205
+ sentAt: new Date().toISOString(),
3206
+ },
3207
+ }),
3208
+ }),
3209
+ );
3210
+ await initialFrames;
3211
+
3212
+ await provider.sendAssistantMessage(invite.sessionId, {
3213
+ text: [
3214
+ "先看图片",
3215
+ "<qqimg>https://example.com/bridge.png</qqimg>",
3216
+ "再收文件",
3217
+ "<qqfile>https://example.com/manual.txt</qqfile>",
3218
+ ].join("\n"),
3219
+ replyTo: "client-msg-1",
3220
+ });
3221
+
3222
+ const assistant = await nextRelayPayload(appSocket, invite);
3223
+ assert.equal(assistant.kind, "assistant_message");
3224
+ if (assistant.kind !== "assistant_message") {
3225
+ return;
3226
+ }
3227
+ assert.equal(assistant.replyTo, "client-msg-1");
3228
+ assert.equal(assistant.text, "先看图片\n\n再收文件");
3229
+ assert.equal(assistant.attachments?.length, 2);
3230
+ assert.deepEqual(
3231
+ assistant.attachments?.map((attachment) => ({
3232
+ name: attachment.name,
3233
+ mimeType: attachment.mimeType,
3234
+ uri: attachment.uri,
3235
+ })),
3236
+ [
3237
+ {
3238
+ name: "bridge.png",
3239
+ mimeType: "image/png",
3240
+ uri: "https://example.com/bridge.png",
3241
+ },
3242
+ {
3243
+ name: "manual.txt",
3244
+ mimeType: "text/plain",
3245
+ uri: "https://example.com/manual.txt",
3246
+ },
3247
+ ],
3248
+ );
3249
+
3250
+ appSocket.close();
3251
+ await waitForClose(appSocket);
3252
+ });
3253
+
3254
+ test("provider falls back to the bridge when appMessageRouter declines a message", async (t) => {
3255
+ const relay = createRelayServer({
3256
+ host: "127.0.0.1",
3257
+ port: 0,
3258
+ sessionTtlMs: 60_000,
3259
+ frameCacheSize: 8,
3260
+ });
3261
+ const { port } = await relay.start();
3262
+ t.after(async () => {
3263
+ await relay.stop();
3264
+ });
3265
+
3266
+ const bridge = new HistoryRecordingBridge();
3267
+ const routedTexts: string[] = [];
3268
+ const provider = new PrivateClawProvider({
3269
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
3270
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
3271
+ bridge,
3272
+ defaultTtlMs: DEFAULT_SESSION_TTL_MS,
3273
+ appMessageRouter: async (message) => {
3274
+ routedTexts.push(message.payload.text);
3275
+ return false;
3276
+ },
3277
+ });
3278
+ await provider.connect();
3279
+ t.after(async () => {
3280
+ await provider.dispose();
3281
+ });
3282
+
3283
+ const inviteBundle = await provider.createInviteBundle();
3284
+ const invite = decodeInviteString(inviteBundle.inviteUri);
3285
+ const appUrl = new URL(invite.appWsUrl);
3286
+ appUrl.searchParams.set("appId", "fallback-app");
3287
+ const appSocket = new WebSocket(appUrl.toString());
3288
+ const attached = nextMessage(appSocket);
3289
+ await waitForOpen(appSocket);
3290
+ assert.equal((await attached).type, "relay:attached");
3291
+ const initialFrames = nextMessages(appSocket, 2);
3292
+ appSocket.send(
3293
+ JSON.stringify({
3294
+ type: "app:frame",
3295
+ envelope: encryptPayload({
3296
+ sessionId: invite.sessionId,
3297
+ sessionKey: invite.sessionKey,
3298
+ payload: {
3299
+ kind: "client_hello",
3300
+ appId: "fallback-app",
3301
+ displayName: "Fallback App",
3302
+ appVersion: "flutter-test",
3303
+ deviceLabel: "Fallback Device",
3304
+ sentAt: new Date().toISOString(),
3305
+ },
3306
+ }),
3307
+ }),
3308
+ );
3309
+ await initialFrames;
3310
+
3311
+ appSocket.send(
3312
+ JSON.stringify({
3313
+ type: "app:frame",
3314
+ envelope: encryptPayload({
3315
+ sessionId: invite.sessionId,
3316
+ sessionKey: invite.sessionKey,
3317
+ payload: {
3318
+ kind: "user_message",
3319
+ appId: "fallback-app",
3320
+ text: "hello bridge fallback",
3321
+ clientMessageId: "fallback-msg-1",
3322
+ sentAt: new Date().toISOString(),
3323
+ },
3324
+ }),
3325
+ }),
3326
+ );
3327
+
3328
+ const assistant = await nextRelayPayload(appSocket, invite);
3329
+ assert.equal(assistant.kind, "assistant_message");
3330
+ assert.equal(assistant.text, "OpenClaw bridge: hello bridge fallback");
3331
+ assert.equal(assistant.replyTo, "fallback-msg-1");
3332
+ assert.deepEqual(routedTexts, ["hello bridge fallback"]);
3333
+ assert.deepEqual(bridge.conversationMessages, ["hello bridge fallback"]);
3334
+ appSocket.close();
3335
+ await waitForClose(appSocket);
3336
+ });
3337
+
3072
3338
  test("provider forwards unknown slash commands verbatim to the bridge even when bot replies are muted", async (t) => {
3073
3339
  const relay = createRelayServer({
3074
3340
  host: "127.0.0.1",
package/src/provider.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
2
5
  import {
3
6
  decodeInviteString,
4
7
  decryptPayload,
@@ -18,6 +21,10 @@ import {
18
21
  BOT_MODE_IDLE_TOPICS,
19
22
  pickBotModeIdleTopic,
20
23
  } from "./bot-mode-topics.js";
24
+ import {
25
+ extractInlineQqMediaAttachments,
26
+ inferMimeTypeFromFileName,
27
+ } from "./bridges/openclaw-agent-bridge.js";
21
28
  import {
22
29
  PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
23
30
  PRIVATECLAW_QR_IMAGE_MARGIN,
@@ -43,6 +50,7 @@ import type {
43
50
  PrivateClawInviteBundle,
44
51
  PrivateClawProviderHandoffState,
45
52
  PrivateClawManagedSession,
53
+ PrivateClawOpenClawOutboundMessage,
46
54
  PrivateClawProviderOptions,
47
55
  PrivateClawProviderSessionHandoff,
48
56
  ProviderParticipantState,
@@ -428,6 +436,26 @@ function normalizeBridgeSlashCommandText(text: string): string | undefined {
428
436
  return trimmed.startsWith("/") ? trimmed : undefined;
429
437
  }
430
438
 
439
+ function canRouteAppMessageViaOpenClaw(
440
+ payload: UserMessagePayload,
441
+ preparedMessage: PreparedUserMessage,
442
+ ): boolean {
443
+ if ((payload.attachments?.length ?? 0) > 0) {
444
+ return false;
445
+ }
446
+ if (payload.text.trim() === "") {
447
+ return false;
448
+ }
449
+ const directBridgeSlashCommand = normalizeBridgeSlashCommandText(payload.text);
450
+ if (
451
+ preparedMessage.bridgeText &&
452
+ preparedMessage.bridgeText !== directBridgeSlashCommand
453
+ ) {
454
+ return false;
455
+ }
456
+ return true;
457
+ }
458
+
431
459
  function cloneThinkingEntries(
432
460
  entries: ReadonlyArray<PrivateClawThinkingEntry>,
433
461
  ): PrivateClawThinkingEntry[] {
@@ -918,6 +946,10 @@ export class PrivateClawProvider {
918
946
  return [...this.sessions.values()].map(toManagedSessionSnapshot);
919
947
  }
920
948
 
949
+ hasManagedSession(sessionId: string): boolean {
950
+ return this.sessions.has(sessionId);
951
+ }
952
+
921
953
  async getSessionQrBundle(
922
954
  sessionId: string,
923
955
  params?: { notifyParticipants?: boolean },
@@ -948,6 +980,71 @@ export class PrivateClawProvider {
948
980
  return snapshot;
949
981
  }
950
982
 
983
+ private async buildOpenClawOutboundAttachments(
984
+ payload: PrivateClawOpenClawOutboundMessage,
985
+ ): Promise<PrivateClawAttachment[]> {
986
+ const mediaCandidates = [
987
+ ...(readNonEmptyString(payload.mediaUrl)
988
+ ? [readNonEmptyString(payload.mediaUrl)!]
989
+ : []),
990
+ ...((payload.mediaUrls ?? [])
991
+ .map((candidate) => readNonEmptyString(candidate))
992
+ .filter((candidate): candidate is string => candidate != null)),
993
+ ];
994
+ const attachments: PrivateClawAttachment[] = [];
995
+ for (const mediaCandidate of mediaCandidates) {
996
+ const isRemoteUri =
997
+ /^[a-z][a-z0-9+.-]*:\/\//iu.test(mediaCandidate) &&
998
+ !mediaCandidate.startsWith("file://");
999
+ if (isRemoteUri) {
1000
+ const parsedUrl = new URL(mediaCandidate);
1001
+ const fileName = path.basename(parsedUrl.pathname) || "attachment";
1002
+ attachments.push({
1003
+ id: buildMessageId("attachment"),
1004
+ name: fileName,
1005
+ mimeType:
1006
+ inferMimeTypeFromFileName(fileName) ?? "application/octet-stream",
1007
+ sizeBytes: 0,
1008
+ uri: mediaCandidate,
1009
+ });
1010
+ continue;
1011
+ }
1012
+ const filePath = mediaCandidate.startsWith("file://")
1013
+ ? fileURLToPath(mediaCandidate)
1014
+ : mediaCandidate;
1015
+ const fileName = path.basename(filePath) || "attachment";
1016
+ const fileBytes = await readFile(filePath);
1017
+ attachments.push({
1018
+ id: buildMessageId("attachment"),
1019
+ name: fileName,
1020
+ mimeType:
1021
+ inferMimeTypeFromFileName(fileName) ?? "application/octet-stream",
1022
+ sizeBytes: fileBytes.length,
1023
+ dataBase64: fileBytes.toString("base64"),
1024
+ });
1025
+ }
1026
+ return attachments;
1027
+ }
1028
+
1029
+ async deliverOpenClawOutboundMessage(
1030
+ sessionId: string,
1031
+ payload: PrivateClawOpenClawOutboundMessage,
1032
+ ): Promise<void> {
1033
+ this.requireSession(sessionId);
1034
+ const attachments = await this.buildOpenClawOutboundAttachments(payload);
1035
+ const text = readNonEmptyString(payload.text) ?? "";
1036
+ if (text === "" && attachments.length === 0) {
1037
+ return;
1038
+ }
1039
+ await this.sendAssistantMessage(sessionId, {
1040
+ text,
1041
+ ...(typeof payload.replyToId === "string" && payload.replyToId.trim() !== ""
1042
+ ? { replyTo: payload.replyToId }
1043
+ : {}),
1044
+ ...(attachments.length > 0 ? { attachments } : {}),
1045
+ });
1046
+ }
1047
+
951
1048
  exportHandoffState(): PrivateClawProviderHandoffState {
952
1049
  return {
953
1050
  providerId: this.relayClient.getProviderId(),
@@ -1229,6 +1326,32 @@ export class PrivateClawProvider {
1229
1326
  : {}),
1230
1327
  });
1231
1328
 
1329
+ if (
1330
+ this.options.appMessageRouter &&
1331
+ canRouteAppMessageViaOpenClaw(payload, preparedMessage)
1332
+ ) {
1333
+ const handled = await this.options.appMessageRouter({
1334
+ sessionId,
1335
+ ...(session.label ? { sessionLabel: session.label } : {}),
1336
+ groupMode: session.groupMode,
1337
+ ...(participant
1338
+ ? {
1339
+ participant: {
1340
+ appId: participant.appId,
1341
+ displayName: participant.displayName,
1342
+ ...(participant.deviceLabel
1343
+ ? { deviceLabel: participant.deviceLabel }
1344
+ : {}),
1345
+ },
1346
+ }
1347
+ : {}),
1348
+ payload,
1349
+ });
1350
+ if (handled) {
1351
+ return;
1352
+ }
1353
+ }
1354
+
1232
1355
  const bridgeMessage =
1233
1356
  preparedMessage.bridgeText ??
1234
1357
  (session.groupMode && participant
@@ -1827,24 +1950,30 @@ export class PrivateClawProvider {
1827
1950
  const sentAt = params.sentAt ?? nowIso();
1828
1951
  const messageId = params.messageId ?? buildMessageId("assistant");
1829
1952
  const session = this.requireSession(sessionId);
1953
+ const qqMediaResult = extractInlineQqMediaAttachments(params.text);
1954
+ const attachments = [
1955
+ ...(params.attachments ?? []),
1956
+ ...qqMediaResult.attachments,
1957
+ ];
1958
+ const normalizedText = qqMediaResult.text;
1830
1959
  if (params.storeHistory !== false) {
1831
1960
  session.history.push({
1832
1961
  messageId,
1833
1962
  role: "assistant",
1834
- text: params.text,
1963
+ text: normalizedText,
1835
1964
  sentAt,
1836
1965
  ...(params.replyTo ? { replyTo: params.replyTo } : {}),
1837
- ...(params.attachments ? { attachments: params.attachments } : {}),
1966
+ ...(attachments.length > 0 ? { attachments } : {}),
1838
1967
  });
1839
1968
  }
1840
1969
  await this.sendPayload(sessionId, {
1841
1970
  kind: "assistant_message",
1842
1971
  messageId,
1843
- text: params.text,
1972
+ text: normalizedText,
1844
1973
  sentAt,
1845
1974
  ...(params.replyTo ? { replyTo: params.replyTo } : {}),
1846
1975
  ...(params.pending ? { pending: true } : {}),
1847
- ...(params.attachments ? { attachments: params.attachments } : {}),
1976
+ ...(attachments.length > 0 ? { attachments } : {}),
1848
1977
  }, params.targetAppId);
1849
1978
  }
1850
1979