@openclaw/synology-chat 2026.2.22 → 2026.5.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/channel.ts CHANGED
@@ -4,320 +4,367 @@
4
4
  * Implements the ChannelPlugin interface following the LINE pattern.
5
5
  */
6
6
 
7
+ import { DEFAULT_ACCOUNT_ID } from "openclaw/plugin-sdk/account-id";
8
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/account-resolution";
7
9
  import {
8
- DEFAULT_ACCOUNT_ID,
9
- setAccountEnabledInConfigSection,
10
- registerPluginHttpRoute,
11
- buildChannelConfigSchema,
12
- } from "openclaw/plugin-sdk";
13
- import { z } from "zod";
10
+ createHybridChannelConfigAdapter,
11
+ createScopedDmSecurityResolver,
12
+ } from "openclaw/plugin-sdk/channel-config-helpers";
13
+ import { createChatChannelPlugin, type ChannelPlugin } from "openclaw/plugin-sdk/channel-core";
14
+ import { waitUntilAbort } from "openclaw/plugin-sdk/channel-lifecycle";
15
+ import {
16
+ composeWarningCollectors,
17
+ createConditionalWarningCollector,
18
+ projectAccountConfigWarningCollector,
19
+ projectAccountWarningCollector,
20
+ } from "openclaw/plugin-sdk/channel-policy";
21
+ import { attachChannelToResult } from "openclaw/plugin-sdk/channel-send-result";
22
+ import { createEmptyChannelDirectoryAdapter } from "openclaw/plugin-sdk/directory-runtime";
14
23
  import { listAccountIds, resolveAccount } from "./accounts.js";
24
+ import { synologyChatApprovalAuth } from "./approval-auth.js";
15
25
  import { sendMessage, sendFileUrl } from "./client.js";
16
- import { getSynologyRuntime } from "./runtime.js";
26
+ import { SynologyChatChannelConfigSchema } from "./config-schema.js";
27
+ import {
28
+ collectSynologyGatewayRoutingWarnings,
29
+ registerSynologyWebhookRoute,
30
+ validateSynologyGatewayAccountStartup,
31
+ } from "./gateway-runtime.js";
32
+ import { collectSynologyChatSecurityAuditFindings } from "./security-audit.js";
33
+ import { synologyChatSetupAdapter, synologyChatSetupWizard } from "./setup-surface.js";
17
34
  import type { ResolvedSynologyChatAccount } from "./types.js";
18
- import { createWebhookHandler } from "./webhook-handler.js";
19
35
 
20
36
  const CHANNEL_ID = "synology-chat";
21
- const SynologyChatConfigSchema = buildChannelConfigSchema(z.object({}).passthrough());
22
-
23
- export function createSynologyChatPlugin() {
24
- return {
25
- id: CHANNEL_ID,
26
-
27
- meta: {
28
- id: CHANNEL_ID,
29
- label: "Synology Chat",
30
- selectionLabel: "Synology Chat (Webhook)",
31
- detailLabel: "Synology Chat (Webhook)",
32
- docsPath: "/channels/synology-chat",
33
- blurb: "Connect your Synology NAS Chat to OpenClaw",
34
- order: 90,
35
- },
36
37
 
37
- capabilities: {
38
- chatTypes: ["direct" as const],
39
- media: true,
40
- threads: false,
41
- reactions: false,
42
- edit: false,
43
- unsend: false,
44
- reply: false,
45
- effects: false,
46
- blockStreaming: false,
47
- },
48
-
49
- reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
50
-
51
- configSchema: SynologyChatConfigSchema,
52
-
53
- config: {
54
- listAccountIds: (cfg: any) => listAccountIds(cfg),
38
+ function normalizeLowercaseStringOrEmpty(value: unknown): string {
39
+ return typeof value === "string" ? value.trim().toLowerCase() : "";
40
+ }
55
41
 
56
- resolveAccount: (cfg: any, accountId?: string | null) => resolveAccount(cfg, accountId),
42
+ const resolveSynologyChatDmPolicy = createScopedDmSecurityResolver<ResolvedSynologyChatAccount>({
43
+ channelKey: CHANNEL_ID,
44
+ resolvePolicy: (account) => account.dmPolicy,
45
+ resolveAllowFrom: (account) => account.allowedUserIds,
46
+ policyPathSuffix: "dmPolicy",
47
+ defaultPolicy: "allowlist",
48
+ approveHint: "openclaw pairing approve synology-chat <code>",
49
+ normalizeEntry: (raw) => normalizeLowercaseStringOrEmpty(raw),
50
+ });
51
+
52
+ type SynologyChannelGatewayContext = {
53
+ cfg: OpenClawConfig;
54
+ accountId: string;
55
+ abortSignal: AbortSignal;
56
+ log?: {
57
+ info: (message: string) => void;
58
+ warn: (message: string) => void;
59
+ error: (message: string) => void;
60
+ };
61
+ };
62
+ type SynologyChannelOutboundContext = {
63
+ cfg: OpenClawConfig;
64
+ to: string;
65
+ text?: string;
66
+ mediaUrl?: string;
67
+ accountId?: string | null;
68
+ };
69
+ type SynologyChannelSendTextContext = SynologyChannelOutboundContext & { text: string };
70
+ type _SynologyChannelSendMediaContext = SynologyChannelOutboundContext & { mediaUrl: string };
71
+ type SynologySecurityWarningContext = {
72
+ cfg: OpenClawConfig;
73
+ account: ResolvedSynologyChatAccount;
74
+ };
75
+
76
+ const synologyChatConfigAdapter = createHybridChannelConfigAdapter<ResolvedSynologyChatAccount>({
77
+ sectionKey: CHANNEL_ID,
78
+ listAccountIds,
79
+ resolveAccount,
80
+ defaultAccountId: () => DEFAULT_ACCOUNT_ID,
81
+ clearBaseFields: [
82
+ "token",
83
+ "incomingUrl",
84
+ "nasHost",
85
+ "webhookPath",
86
+ "dangerouslyAllowNameMatching",
87
+ "dangerouslyAllowInheritedWebhookPath",
88
+ "dmPolicy",
89
+ "allowedUserIds",
90
+ "rateLimitPerMinute",
91
+ "botName",
92
+ "allowInsecureSsl",
93
+ ],
94
+ resolveAllowFrom: (account) => account.allowedUserIds,
95
+ formatAllowFrom: (allowFrom) =>
96
+ allowFrom.map((entry) => normalizeLowercaseStringOrEmpty(String(entry))).filter(Boolean),
97
+ });
98
+
99
+ const collectSynologyChatSecurityWarnings =
100
+ createConditionalWarningCollector<ResolvedSynologyChatAccount>(
101
+ (account) =>
102
+ !account.token &&
103
+ "- Synology Chat: token is not configured. The webhook will reject all requests.",
104
+ (account) =>
105
+ !account.incomingUrl &&
106
+ "- Synology Chat: incomingUrl is not configured. The bot cannot send replies.",
107
+ (account) =>
108
+ account.allowInsecureSsl &&
109
+ "- Synology Chat: SSL verification is disabled (allowInsecureSsl=true). Only use this for local NAS with self-signed certificates.",
110
+ (account) =>
111
+ account.dangerouslyAllowNameMatching &&
112
+ "- Synology Chat: dangerouslyAllowNameMatching=true re-enables mutable username/nickname recipient matching for replies. Prefer stable numeric user IDs.",
113
+ (account) =>
114
+ account.dangerouslyAllowInheritedWebhookPath &&
115
+ account.webhookPathSource === "inherited-base" &&
116
+ "- Synology Chat: dangerouslyAllowInheritedWebhookPath=true opts a named account into a shared inherited webhook path. Prefer an explicit per-account webhookPath.",
117
+ (account) =>
118
+ account.dmPolicy === "open" &&
119
+ account.allowedUserIds.length === 0 &&
120
+ '- Synology Chat: dmPolicy="open" with empty allowedUserIds blocks all senders. Add allowedUserIds=["*"] for public DMs or set explicit user IDs.',
121
+ (account) =>
122
+ account.dmPolicy === "open" &&
123
+ account.allowedUserIds.includes("*") &&
124
+ '- Synology Chat: dmPolicy="open" allows any user to message the bot. Consider "allowlist" for production use.',
125
+ (account) =>
126
+ account.dmPolicy === "allowlist" &&
127
+ account.allowedUserIds.length === 0 &&
128
+ '- Synology Chat: dmPolicy="allowlist" with empty allowedUserIds blocks all senders. Add users or set dmPolicy="open" with allowedUserIds=["*"].',
129
+ );
130
+
131
+ type SynologyChatOutboundResult = {
132
+ channel: typeof CHANNEL_ID;
133
+ messageId: string;
134
+ chatId: string;
135
+ };
136
+
137
+ type SynologyChatPlugin = Omit<
138
+ ChannelPlugin<ResolvedSynologyChatAccount>,
139
+ "pairing" | "security" | "messaging" | "directory" | "outbound" | "gateway" | "agentPrompt"
140
+ > & {
141
+ pairing: {
142
+ idLabel: string;
143
+ normalizeAllowEntry?: (entry: string) => string;
144
+ notifyApproval: (params: { cfg: OpenClawConfig; id: string }) => Promise<void>;
145
+ };
146
+ security: {
147
+ resolveDmPolicy: (params: { cfg: OpenClawConfig; account: ResolvedSynologyChatAccount }) => {
148
+ policy: string | null | undefined;
149
+ allowFrom?: Array<string | number>;
150
+ normalizeEntry?: (raw: string) => string;
151
+ } | null;
152
+ collectWarnings: (params: {
153
+ cfg: OpenClawConfig;
154
+ account: ResolvedSynologyChatAccount;
155
+ }) => string[];
156
+ };
157
+ messaging: {
158
+ normalizeTarget: (target: string) => string | undefined;
159
+ targetResolver: {
160
+ looksLikeId: (id: string) => boolean;
161
+ hint: string;
162
+ };
163
+ };
164
+ directory: {
165
+ self?: NonNullable<ChannelPlugin<ResolvedSynologyChatAccount>["directory"]>["self"];
166
+ listPeers?: NonNullable<ChannelPlugin<ResolvedSynologyChatAccount>["directory"]>["listPeers"];
167
+ listGroups?: NonNullable<ChannelPlugin<ResolvedSynologyChatAccount>["directory"]>["listGroups"];
168
+ };
169
+ outbound: {
170
+ deliveryMode: "gateway";
171
+ textChunkLimit: number;
172
+ sendText: (ctx: SynologyChannelSendTextContext) => Promise<SynologyChatOutboundResult>;
173
+ sendMedia: (ctx: SynologyChannelOutboundContext) => Promise<SynologyChatOutboundResult>;
174
+ };
175
+ gateway: {
176
+ startAccount: (ctx: SynologyChannelGatewayContext) => Promise<unknown>;
177
+ stopAccount: (ctx: SynologyChannelGatewayContext) => Promise<void>;
178
+ };
179
+ agentPrompt: {
180
+ messageToolHints: () => string[];
181
+ };
182
+ };
183
+
184
+ const collectSynologyChatRoutingWarnings = projectAccountConfigWarningCollector<
185
+ ResolvedSynologyChatAccount,
186
+ OpenClawConfig,
187
+ SynologySecurityWarningContext
188
+ >(
189
+ (cfg) => cfg,
190
+ ({ account, cfg }) => collectSynologyGatewayRoutingWarnings({ account, cfg }),
191
+ );
192
+
193
+ function resolveOutboundAccount(
194
+ cfg: OpenClawConfig,
195
+ accountId?: string | null,
196
+ ): ResolvedSynologyChatAccount {
197
+ return resolveAccount(cfg ?? {}, accountId);
198
+ }
57
199
 
58
- defaultAccountId: (_cfg: any) => DEFAULT_ACCOUNT_ID,
200
+ function requireIncomingUrl(account: ResolvedSynologyChatAccount): string {
201
+ if (!account.incomingUrl) {
202
+ throw new Error("Synology Chat incoming URL not configured");
203
+ }
204
+ return account.incomingUrl;
205
+ }
59
206
 
60
- setAccountEnabled: ({ cfg, accountId, enabled }: any) => {
61
- const channelConfig = cfg?.channels?.[CHANNEL_ID] ?? {};
62
- if (accountId === DEFAULT_ACCOUNT_ID) {
63
- return {
64
- ...cfg,
65
- channels: {
66
- ...cfg.channels,
67
- [CHANNEL_ID]: { ...channelConfig, enabled },
68
- },
69
- };
70
- }
71
- return setAccountEnabledInConfigSection({
72
- cfg,
73
- sectionKey: `channels.${CHANNEL_ID}`,
74
- accountId,
75
- enabled,
76
- });
207
+ export function createSynologyChatPlugin(): SynologyChatPlugin {
208
+ return createChatChannelPlugin({
209
+ base: {
210
+ id: CHANNEL_ID,
211
+ meta: {
212
+ id: CHANNEL_ID,
213
+ label: "Synology Chat",
214
+ selectionLabel: "Synology Chat (Webhook)",
215
+ detailLabel: "Synology Chat (Webhook)",
216
+ docsPath: "/channels/synology-chat",
217
+ blurb: "Connect your Synology NAS Chat to OpenClaw",
218
+ order: 90,
77
219
  },
78
- },
79
-
80
- pairing: {
81
- idLabel: "synologyChatUserId",
82
- normalizeAllowEntry: (entry: string) => entry.toLowerCase().trim(),
83
- notifyApproval: async ({ cfg, id }: { cfg: any; id: string }) => {
84
- const account = resolveAccount(cfg);
85
- if (!account.incomingUrl) return;
86
- await sendMessage(
87
- account.incomingUrl,
88
- "OpenClaw: your access has been approved.",
89
- id,
90
- account.allowInsecureSsl,
91
- );
220
+ capabilities: {
221
+ chatTypes: ["direct" as const],
222
+ media: true,
223
+ threads: false,
224
+ reactions: false,
225
+ edit: false,
226
+ unsend: false,
227
+ reply: false,
228
+ effects: false,
229
+ blockStreaming: false,
92
230
  },
93
- },
94
-
95
- security: {
96
- resolveDmPolicy: ({
97
- cfg,
98
- accountId,
99
- account,
100
- }: {
101
- cfg: any;
102
- accountId?: string | null;
103
- account: ResolvedSynologyChatAccount;
104
- }) => {
105
- const resolvedAccountId = accountId ?? account.accountId ?? DEFAULT_ACCOUNT_ID;
106
- const channelCfg = (cfg as any).channels?.["synology-chat"];
107
- const useAccountPath = Boolean(channelCfg?.accounts?.[resolvedAccountId]);
108
- const basePath = useAccountPath
109
- ? `channels.synology-chat.accounts.${resolvedAccountId}.`
110
- : "channels.synology-chat.";
111
- return {
112
- policy: account.dmPolicy ?? "allowlist",
113
- allowFrom: account.allowedUserIds ?? [],
114
- policyPath: `${basePath}dmPolicy`,
115
- allowFromPath: basePath,
116
- approveHint: "openclaw pairing approve synology-chat <code>",
117
- normalizeEntry: (raw: string) => raw.toLowerCase().trim(),
118
- };
231
+ reload: { configPrefixes: [`channels.${CHANNEL_ID}`] },
232
+ configSchema: SynologyChatChannelConfigSchema,
233
+ setup: synologyChatSetupAdapter,
234
+ setupWizard: synologyChatSetupWizard,
235
+ config: {
236
+ ...synologyChatConfigAdapter,
119
237
  },
120
- collectWarnings: ({ account }: { account: ResolvedSynologyChatAccount }) => {
121
- const warnings: string[] = [];
122
- if (!account.token) {
123
- warnings.push(
124
- "- Synology Chat: token is not configured. The webhook will reject all requests.",
125
- );
126
- }
127
- if (!account.incomingUrl) {
128
- warnings.push(
129
- "- Synology Chat: incomingUrl is not configured. The bot cannot send replies.",
130
- );
131
- }
132
- if (account.allowInsecureSsl) {
133
- warnings.push(
134
- "- Synology Chat: SSL verification is disabled (allowInsecureSsl=true). Only use this for local NAS with self-signed certificates.",
135
- );
136
- }
137
- if (account.dmPolicy === "open") {
138
- warnings.push(
139
- '- Synology Chat: dmPolicy="open" allows any user to message the bot. Consider "allowlist" for production use.',
140
- );
141
- }
142
- return warnings;
238
+ approvalCapability: synologyChatApprovalAuth,
239
+ messaging: {
240
+ normalizeTarget: (target: string) => {
241
+ const trimmed = target.trim();
242
+ if (!trimmed) {
243
+ return undefined;
244
+ }
245
+ // Strip common prefixes
246
+ return trimmed.replace(/^synology[-_]?chat:/i, "").trim();
247
+ },
248
+ targetResolver: {
249
+ looksLikeId: (id: string) => {
250
+ const trimmed = id?.trim();
251
+ if (!trimmed) {
252
+ return false;
253
+ }
254
+ // Synology Chat user IDs are numeric
255
+ return /^\d+$/.test(trimmed) || /^synology[-_]?chat:/i.test(trimmed);
256
+ },
257
+ hint: "<userId>",
258
+ },
143
259
  },
144
- },
260
+ directory: createEmptyChannelDirectoryAdapter(),
261
+ gateway: {
262
+ startAccount: async (ctx: SynologyChannelGatewayContext) => {
263
+ const { cfg, accountId, log, abortSignal } = ctx;
264
+ const account = resolveAccount(cfg, accountId);
265
+ if (!validateSynologyGatewayAccountStartup({ cfg, account, accountId, log }).ok) {
266
+ return waitUntilAbort(abortSignal);
267
+ }
268
+
269
+ log?.info?.(
270
+ `Starting Synology Chat channel (account: ${accountId}, path: ${account.webhookPath})`,
271
+ );
272
+ const unregister = registerSynologyWebhookRoute({ account, accountId, log });
145
273
 
146
- messaging: {
147
- normalizeTarget: (target: string) => {
148
- const trimmed = target.trim();
149
- if (!trimmed) return undefined;
150
- // Strip common prefixes
151
- return trimmed.replace(/^synology[-_]?chat:/i, "").trim();
274
+ log?.info?.(`Registered HTTP route: ${account.webhookPath} for Synology Chat`);
275
+
276
+ // Keep alive until abort signal fires.
277
+ // The gateway expects a Promise that stays pending while the channel is running.
278
+ // Resolving immediately triggers a restart loop.
279
+ return waitUntilAbort(abortSignal, () => {
280
+ log?.info?.(`Stopping Synology Chat channel (account: ${accountId})`);
281
+ unregister();
282
+ });
283
+ },
284
+
285
+ stopAccount: async (ctx: SynologyChannelGatewayContext) => {
286
+ ctx.log?.info?.(`Synology Chat account ${ctx.accountId} stopped`);
287
+ },
288
+ },
289
+ agentPrompt: {
290
+ messageToolHints: () => [
291
+ "",
292
+ "### Synology Chat Formatting",
293
+ "Synology Chat supports limited formatting. Use these patterns:",
294
+ "",
295
+ "**Links**: Use `<URL|display text>` to create clickable links.",
296
+ " Example: `<https://example.com|Click here>` renders as a clickable link.",
297
+ "",
298
+ "**File sharing**: Include a publicly accessible URL to share files or images.",
299
+ " The NAS will download and attach the file (max 32 MB).",
300
+ "",
301
+ "**Limitations**:",
302
+ "- No markdown, bold, italic, or code blocks",
303
+ "- No buttons, cards, or interactive elements",
304
+ "- No message editing after send",
305
+ "- Keep messages under 2000 characters for best readability",
306
+ "",
307
+ "**Best practices**:",
308
+ "- Use short, clear responses (Synology Chat has a minimal UI)",
309
+ "- Use line breaks to separate sections",
310
+ "- Use numbered or bulleted lists for clarity",
311
+ "- Wrap URLs with `<URL|label>` for user-friendly links",
312
+ ],
152
313
  },
153
- targetResolver: {
154
- looksLikeId: (id: string) => {
155
- const trimmed = id?.trim();
156
- if (!trimmed) return false;
157
- // Synology Chat user IDs are numeric
158
- return /^\d+$/.test(trimmed) || /^synology[-_]?chat:/i.test(trimmed);
314
+ },
315
+ pairing: {
316
+ text: {
317
+ idLabel: "synologyChatUserId",
318
+ message: "OpenClaw: your access has been approved.",
319
+ normalizeAllowEntry: (entry: string) => normalizeLowercaseStringOrEmpty(entry),
320
+ notify: async ({ cfg, id, message }) => {
321
+ const account = resolveAccount(cfg);
322
+ if (!account.incomingUrl) {
323
+ return;
324
+ }
325
+ await sendMessage(account.incomingUrl, message, id, account.allowInsecureSsl);
159
326
  },
160
- hint: "<userId>",
161
327
  },
162
328
  },
163
-
164
- directory: {
165
- self: async () => null,
166
- listPeers: async () => [],
167
- listGroups: async () => [],
329
+ security: {
330
+ resolveDmPolicy: resolveSynologyChatDmPolicy,
331
+ collectWarnings: composeWarningCollectors(
332
+ projectAccountWarningCollector<ResolvedSynologyChatAccount, SynologySecurityWarningContext>(
333
+ collectSynologyChatSecurityWarnings,
334
+ ),
335
+ collectSynologyChatRoutingWarnings,
336
+ ),
337
+ collectAuditFindings: collectSynologyChatSecurityAuditFindings,
168
338
  },
169
-
170
339
  outbound: {
171
340
  deliveryMode: "gateway" as const,
172
341
  textChunkLimit: 2000,
173
342
 
174
- sendText: async ({ to, text, accountId, account: ctxAccount }: any) => {
175
- const account: ResolvedSynologyChatAccount = ctxAccount ?? resolveAccount({}, accountId);
176
-
177
- if (!account.incomingUrl) {
178
- throw new Error("Synology Chat incoming URL not configured");
179
- }
180
-
181
- const ok = await sendMessage(account.incomingUrl, text, to, account.allowInsecureSsl);
343
+ sendText: async ({ to, text, accountId, cfg }: SynologyChannelSendTextContext) => {
344
+ const account = resolveOutboundAccount(cfg ?? {}, accountId);
345
+ const incomingUrl = requireIncomingUrl(account);
346
+ const ok = await sendMessage(incomingUrl, text, to, account.allowInsecureSsl);
182
347
  if (!ok) {
183
348
  throw new Error("Failed to send message to Synology Chat");
184
349
  }
185
- return { channel: CHANNEL_ID, messageId: `sc-${Date.now()}`, chatId: to };
350
+ return attachChannelToResult(CHANNEL_ID, { messageId: `sc-${Date.now()}`, chatId: to });
186
351
  },
187
352
 
188
- sendMedia: async ({ to, mediaUrl, accountId, account: ctxAccount }: any) => {
189
- const account: ResolvedSynologyChatAccount = ctxAccount ?? resolveAccount({}, accountId);
190
-
191
- if (!account.incomingUrl) {
192
- throw new Error("Synology Chat incoming URL not configured");
193
- }
353
+ sendMedia: async ({ to, mediaUrl, accountId, cfg }: SynologyChannelOutboundContext) => {
354
+ const account = resolveOutboundAccount(cfg ?? {}, accountId);
355
+ const incomingUrl = requireIncomingUrl(account);
194
356
  if (!mediaUrl) {
195
357
  throw new Error("No media URL provided");
196
358
  }
197
359
 
198
- const ok = await sendFileUrl(account.incomingUrl, mediaUrl, to, account.allowInsecureSsl);
360
+ const ok = await sendFileUrl(incomingUrl, mediaUrl, to, account.allowInsecureSsl);
199
361
  if (!ok) {
200
362
  throw new Error("Failed to send media to Synology Chat");
201
363
  }
202
- return { channel: CHANNEL_ID, messageId: `sc-${Date.now()}`, chatId: to };
364
+ return attachChannelToResult(CHANNEL_ID, { messageId: `sc-${Date.now()}`, chatId: to });
203
365
  },
204
366
  },
205
-
206
- gateway: {
207
- startAccount: async (ctx: any) => {
208
- const { cfg, accountId, log } = ctx;
209
- const account = resolveAccount(cfg, accountId);
210
-
211
- if (!account.enabled) {
212
- log?.info?.(`Synology Chat account ${accountId} is disabled, skipping`);
213
- return { stop: () => {} };
214
- }
215
-
216
- if (!account.token || !account.incomingUrl) {
217
- log?.warn?.(
218
- `Synology Chat account ${accountId} not fully configured (missing token or incomingUrl)`,
219
- );
220
- return { stop: () => {} };
221
- }
222
-
223
- log?.info?.(
224
- `Starting Synology Chat channel (account: ${accountId}, path: ${account.webhookPath})`,
225
- );
226
-
227
- const handler = createWebhookHandler({
228
- account,
229
- deliver: async (msg) => {
230
- const rt = getSynologyRuntime();
231
- const currentCfg = await rt.config.loadConfig();
232
-
233
- // Build MsgContext (same format as LINE/Signal/etc.)
234
- const msgCtx = {
235
- Body: msg.body,
236
- From: msg.from,
237
- To: account.botName,
238
- SessionKey: msg.sessionKey,
239
- AccountId: account.accountId,
240
- OriginatingChannel: CHANNEL_ID as any,
241
- OriginatingTo: msg.from,
242
- ChatType: msg.chatType,
243
- SenderName: msg.senderName,
244
- };
245
-
246
- // Dispatch via the SDK's buffered block dispatcher
247
- await rt.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
248
- ctx: msgCtx,
249
- cfg: currentCfg,
250
- dispatcherOptions: {
251
- deliver: async (payload: { text?: string; body?: string }) => {
252
- const text = payload?.text ?? payload?.body;
253
- if (text) {
254
- await sendMessage(
255
- account.incomingUrl,
256
- text,
257
- msg.from,
258
- account.allowInsecureSsl,
259
- );
260
- }
261
- },
262
- onReplyStart: () => {
263
- log?.info?.(`Agent reply started for ${msg.from}`);
264
- },
265
- },
266
- });
267
-
268
- return null;
269
- },
270
- log,
271
- });
272
-
273
- // Register HTTP route via the SDK
274
- const unregister = registerPluginHttpRoute({
275
- path: account.webhookPath,
276
- pluginId: CHANNEL_ID,
277
- accountId: account.accountId,
278
- log: (msg: string) => log?.info?.(msg),
279
- handler,
280
- });
281
-
282
- log?.info?.(`Registered HTTP route: ${account.webhookPath} for Synology Chat`);
283
-
284
- return {
285
- stop: () => {
286
- log?.info?.(`Stopping Synology Chat channel (account: ${accountId})`);
287
- if (typeof unregister === "function") unregister();
288
- },
289
- };
290
- },
291
-
292
- stopAccount: async (ctx: any) => {
293
- ctx.log?.info?.(`Synology Chat account ${ctx.accountId} stopped`);
294
- },
295
- },
296
-
297
- agentPrompt: {
298
- messageToolHints: () => [
299
- "",
300
- "### Synology Chat Formatting",
301
- "Synology Chat supports limited formatting. Use these patterns:",
302
- "",
303
- "**Links**: Use `<URL|display text>` to create clickable links.",
304
- " Example: `<https://example.com|Click here>` renders as a clickable link.",
305
- "",
306
- "**File sharing**: Include a publicly accessible URL to share files or images.",
307
- " The NAS will download and attach the file (max 32 MB).",
308
- "",
309
- "**Limitations**:",
310
- "- No markdown, bold, italic, or code blocks",
311
- "- No buttons, cards, or interactive elements",
312
- "- No message editing after send",
313
- "- Keep messages under 2000 characters for best readability",
314
- "",
315
- "**Best practices**:",
316
- "- Use short, clear responses (Synology Chat has a minimal UI)",
317
- "- Use line breaks to separate sections",
318
- "- Use numbered or bulleted lists for clarity",
319
- "- Wrap URLs with `<URL|label>` for user-friendly links",
320
- ],
321
- },
322
- };
367
+ }) as unknown as SynologyChatPlugin;
323
368
  }
369
+
370
+ export const synologyChatPlugin = createSynologyChatPlugin();