@openclaw/clickclack 2026.7.2-beta.5 → 2026.7.33

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.
@@ -1,1720 +0,0 @@
1
- import { _ as clickClackMeta, b as listEnabledClickClackAccounts, c as resolveChannelId, d as createClickClackClient, g as clickClackConfigAdapter, h as CLICKCLACK_CHANNEL_ID, l as resolveWorkspaceId, m as clickClackConfigSchema, n as clickClackSetupAdapter, p as normalizeClickClackCorrelationId, r as clickClackSetupContract, t as clickClackSetupWizard, v as DEFAULT_ACCOUNT_ID, x as resolveClickClackAccount } from "./setup-surface-CD6MUC1g.js";
2
- import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-BKkzzjBA.js";
3
- import { buildChannelOutboundSessionRoute, buildThreadAwareOutboundSessionRoute, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
4
- import { buildChannelProgressDraftLine, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, deriveDurableFinalDeliveryRequirements } from "openclaw/plugin-sdk/channel-outbound";
5
- import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
6
- import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
7
- import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
8
- import { resolveStableChannelMessageIngress } from "openclaw/plugin-sdk/channel-ingress-runtime";
9
- import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
10
- import { listNativeCommandSpecsForConfig } from "openclaw/plugin-sdk/native-command-registry";
11
- import { createChannelInboundEnvelopeBuilder } from "openclaw/plugin-sdk/channel-inbound";
12
- import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
13
- import { createHash, randomUUID } from "node:crypto";
14
- import { loadOutboundMediaFromUrl } from "openclaw/plugin-sdk/outbound-media";
15
- import { FormatCapabilityProfile, renderMarkdownWithMarkers, sanitizeAssistantVisibleText } from "openclaw/plugin-sdk/text-chunking";
16
- //#region extensions/clickclack/src/runtime.ts
17
- /**
18
- * Runtime store for host-provided OpenClaw services used by the ClickClack
19
- * bundled plugin.
20
- */
21
- const { setRuntime: setClickClackRuntime, getRuntime: getClickClackRuntime } = createPluginRuntimeStore({
22
- pluginId: "clickclack",
23
- errorMessage: "ClickClack runtime not initialized"
24
- });
25
- //#endregion
26
- //#region extensions/clickclack/src/access.ts
27
- /**
28
- * Maps ClickClack senders and conversations onto the shared channel ingress
29
- * allowlist/command authorization contract.
30
- */
31
- const CHANNEL_ID$2 = "clickclack";
32
- function normalizeClickClackUserId(value) {
33
- const trimmed = value.trim();
34
- if (!trimmed) return null;
35
- const withoutProvider = trimmed.replace(/^(clickclack|cc):/i, "").trim();
36
- return withoutProvider.match(/^dm:(.+)$/i)?.[1]?.trim() || withoutProvider || null;
37
- }
38
- const clickClackIngressIdentity = {
39
- key: "user-id",
40
- normalizeEntry: normalizeClickClackUserId,
41
- normalizeSubject: normalizeClickClackUserId,
42
- isWildcardEntry: (entry) => normalizeClickClackUserId(entry) === "*",
43
- entryIdPrefix: "clickclack-user"
44
- };
45
- /**
46
- * Resolves whether a ClickClack message should enter the agent pipeline and
47
- * whether its command-style body may run tools.
48
- */
49
- async function resolveClickClackInboundAccess(params) {
50
- const runtime = getClickClackRuntime();
51
- const isDirect = Boolean(params.message.direct_conversation_id);
52
- const cfg = params.config;
53
- const shouldCheckCommand = runtime.channel.commands.shouldComputeCommandAuthorized(params.message.body, cfg);
54
- const resolved = await resolveStableChannelMessageIngress({
55
- channelId: CHANNEL_ID$2,
56
- accountId: params.account.accountId,
57
- identity: clickClackIngressIdentity,
58
- cfg,
59
- subject: { stableId: params.message.author_id },
60
- conversation: {
61
- kind: isDirect ? "direct" : "group",
62
- id: isDirect ? params.message.direct_conversation_id ?? params.message.author_id : params.message.channel_id ?? params.message.thread_root_id
63
- },
64
- allowFrom: params.account.allowFrom,
65
- dmPolicy: "allowlist",
66
- groupPolicy: "allowlist",
67
- command: shouldCheckCommand ? {
68
- cfg,
69
- modeWhenAccessGroupsOff: "configured"
70
- } : false
71
- });
72
- return {
73
- shouldDispatch: resolved.ingress.admission === "dispatch",
74
- commandAuthorized: resolved.commandAccess.requested ? resolved.commandAccess.authorized : resolved.senderAccess.allowed
75
- };
76
- }
77
- //#endregion
78
- //#region extensions/clickclack/src/command-menu.ts
79
- const CLICKCLACK_COMMAND_PATTERN = /^[a-z0-9_-]{1,32}$/u;
80
- const CLICKCLACK_MAX_COMMANDS = 100;
81
- const CLICKCLACK_MAX_DESCRIPTION_LENGTH = 100;
82
- const CLICKCLACK_MAX_ARGS_HINT_LENGTH = 100;
83
- function truncateCodePoints(value, maxLength) {
84
- return Array.from(value).slice(0, maxLength).join("");
85
- }
86
- function commandArgsHint(spec) {
87
- if (spec.args?.length) return truncateCodePoints(spec.args.map((arg) => arg.required ? `<${arg.name}>` : `[${arg.name}]`).join(" "), CLICKCLACK_MAX_ARGS_HINT_LENGTH);
88
- return spec.acceptsArgs ? "[args]" : "";
89
- }
90
- function errorStatus(error) {
91
- if (!error || typeof error !== "object" || !("status" in error)) return;
92
- const status = error.status;
93
- return typeof status === "number" ? status : void 0;
94
- }
95
- function mapNativeCommandSpecsToClickClackMenu(specs, log) {
96
- const commands = [];
97
- const seen = /* @__PURE__ */ new Set();
98
- const invalidNames = /* @__PURE__ */ new Set();
99
- for (const spec of specs) {
100
- if (spec.isAlias) continue;
101
- const command = spec.name.trim().toLowerCase();
102
- if (!CLICKCLACK_COMMAND_PATTERN.test(command)) {
103
- invalidNames.add(spec.name.trim() || "<empty>");
104
- continue;
105
- }
106
- if (seen.has(command)) continue;
107
- seen.add(command);
108
- const description = spec.description.trim() || command;
109
- commands.push({
110
- command,
111
- description: truncateCodePoints(description, CLICKCLACK_MAX_DESCRIPTION_LENGTH),
112
- args_hint: commandArgsHint(spec)
113
- });
114
- }
115
- if (invalidNames.size > 0) log?.warn?.(`ClickClack command menu skipped invalid native command names: ${[...invalidNames].map((name) => JSON.stringify(name)).join(", ")}`);
116
- return commands.slice(0, CLICKCLACK_MAX_COMMANDS);
117
- }
118
- async function syncClickClackCommandMenu(params) {
119
- try {
120
- const commands = mapNativeCommandSpecsToClickClackMenu(listNativeCommandSpecsForConfig(params.cfg, { provider: "clickclack" }), params.log);
121
- await params.client.setBotCommands(commands);
122
- } catch (error) {
123
- const status = errorStatus(error);
124
- if (status === 403) {
125
- params.log?.warn?.("ClickClack command menu sync skipped: bot token lacks commands:write");
126
- return;
127
- }
128
- if (status === 404) {
129
- params.log?.debug?.("ClickClack command menu sync skipped: server does not support /api/bots/self/commands");
130
- return;
131
- }
132
- params.log?.warn?.(`ClickClack command menu sync failed: ${formatErrorMessage(error)}`);
133
- }
134
- }
135
- //#endregion
136
- //#region extensions/clickclack/src/activity.ts
137
- /**
138
- * Publishes agent activity (streamed commentary + tool progress) into
139
- * ClickClack as durable `agent_commentary` / `agent_tool` message rows,
140
- * coalesced so one logical step becomes one row instead of a row per frame.
141
- *
142
- * Ported from the clickglass agent-bridge sidecar, adapted from gateway
143
- * websocket frames to the in-process `replyOptions.onItemEvent` seam:
144
- *
145
- * - Commentary/reasoning arrives as cumulative text snapshots per item id.
146
- * Each segment becomes one durable row: POSTed when the segment starts
147
- * streaming and PATCHed (debounced) as the snapshot grows, so prose
148
- * interleaves chronologically with tool rows.
149
- * - Tool/step items can emit several frames (start/update/complete) for the
150
- * same call, sometimes with lane-prefixed ids (`tool:X`, `command:X`).
151
- * Normalize the prefix away to one key per call, POST one row on the first
152
- * frame, and PATCH it when a later frame carries a strictly longer body.
153
- */
154
- /** Debounce window for PATCHing streaming commentary snapshots. */
155
- const CLICKCLACK_COMMENTARY_FLUSH_MS = 700;
156
- /** Item kinds rendered as agent_tool rows; everything else is commentary. */
157
- const TOOL_ITEM_KINDS = /* @__PURE__ */ new Set([
158
- "tool",
159
- "command",
160
- "command_output",
161
- "patch",
162
- "search",
163
- "api"
164
- ]);
165
- /** Item kinds that never become durable rows (ephemeral or plumbing lanes). */
166
- const SKIPPED_ITEM_KINDS = /* @__PURE__ */ new Set(["lifecycle"]);
167
- /** Item kinds emitted as cumulative commentary snapshots. */
168
- const STREAMING_COMMENTARY_ITEM_KINDS = /* @__PURE__ */ new Set([
169
- "preamble",
170
- "commentary",
171
- "analysis",
172
- "thinking",
173
- "reasoning"
174
- ]);
175
- /** Provider-specific reasoning lanes normalized into one ClickClack label. */
176
- const THINKING_ITEM_KINDS = /* @__PURE__ */ new Set([
177
- "analysis",
178
- "thinking",
179
- "reasoning"
180
- ]);
181
- function normalizedItemKind(payload) {
182
- return payload.kind?.trim().toLowerCase() ?? "";
183
- }
184
- function commentaryBody(payload) {
185
- const text = payload.progressText?.trim() || payload.summary?.trim() || payload.meta?.trim() || "";
186
- if (!text) return "";
187
- const kind = normalizedItemKind(payload);
188
- if (THINKING_ITEM_KINDS.has(kind)) return `**Thinking**\n\n${text}`;
189
- return text;
190
- }
191
- function activityBody(payload) {
192
- const line = buildChannelProgressDraftLine({
193
- event: "item",
194
- itemId: payload.itemId,
195
- toolCallId: payload.toolCallId,
196
- itemKind: payload.kind,
197
- title: payload.title,
198
- name: payload.name,
199
- phase: payload.phase,
200
- status: payload.status,
201
- summary: payload.summary,
202
- progressText: payload.progressText,
203
- meta: payload.meta
204
- })?.text?.trim();
205
- if (line) return line;
206
- const head = payload.name?.trim() || payload.title?.trim();
207
- const text = payload.progressText?.trim() || payload.summary?.trim();
208
- if (head && text) return `**${head}**\n\n${text}`;
209
- if (text) return text;
210
- if (head) return head;
211
- return payload.status?.trim() || payload.kind?.trim() || "";
212
- }
213
- /**
214
- * Creates a per-turn activity publisher. Publishing is best-effort: transport
215
- * failures are reported through `onError` and never interrupt the reply turn.
216
- */
217
- function createClickClackActivityPublisher(params) {
218
- const flushMs = params.flushMs ?? CLICKCLACK_COMMENTARY_FLUSH_MS;
219
- const commentaryByItem = /* @__PURE__ */ new Map();
220
- const toolRows = /* @__PURE__ */ new Map();
221
- let provenance;
222
- let chain = Promise.resolve();
223
- const enqueue = (work) => {
224
- chain = chain.then(work).catch((error) => {
225
- params.onError?.(error);
226
- });
227
- return chain;
228
- };
229
- const postRow = (kind, body) => params.client.createActivityMessage({
230
- channelId: params.target.channelId,
231
- conversationId: params.target.conversationId,
232
- body,
233
- kind,
234
- turnId: params.turnId,
235
- provenance
236
- });
237
- const flushCommentary = (segmentKey) => {
238
- const segment = commentaryByItem.get(segmentKey);
239
- if (!segment) return Promise.resolve();
240
- if (segment.timer) {
241
- clearTimeout(segment.timer);
242
- segment.timer = void 0;
243
- }
244
- if (!segment.dirty || !segment.body.trim()) return Promise.resolve();
245
- segment.dirty = false;
246
- const body = segment.body;
247
- return enqueue(async () => {
248
- if (segment.messageId) {
249
- await params.client.updateMessageBody(segment.messageId, body);
250
- return;
251
- }
252
- const posted = await postRow("agent_commentary", body);
253
- segment.messageId = posted.id;
254
- });
255
- };
256
- const flushAllCommentary = () => {
257
- const flushes = [...commentaryByItem.keys()].map((key) => flushCommentary(key));
258
- return Promise.all(flushes).then(() => void 0);
259
- };
260
- const handleCommentary = (payload) => {
261
- const body = commentaryBody(payload);
262
- if (!body.trim()) return;
263
- const key = payload.itemId?.trim() || "turn";
264
- let segment = commentaryByItem.get(key);
265
- if (!segment) {
266
- segment = {
267
- body: "",
268
- dirty: false
269
- };
270
- commentaryByItem.set(key, segment);
271
- }
272
- if (body.length < segment.body.length || body === segment.body) return;
273
- segment.body = body;
274
- segment.dirty = true;
275
- if (!segment.timer) segment.timer = setTimeout(() => {
276
- segment.timer = void 0;
277
- flushCommentary(key);
278
- }, flushMs);
279
- };
280
- const toolRowKey = (payload) => {
281
- const toolCallId = payload.toolCallId?.trim();
282
- if (toolCallId) return toolCallId;
283
- return (payload.itemId?.trim() ?? "").replace(/^(tool|command):/, "");
284
- };
285
- const handleDiscreteItem = (payload) => {
286
- const body = activityBody(payload);
287
- if (!body) return;
288
- const kind = TOOL_ITEM_KINDS.has(payload.kind?.trim().toLowerCase() ?? "") ? "agent_tool" : "agent_commentary";
289
- flushAllCommentary();
290
- const key = `${kind}:${toolRowKey(payload)}`;
291
- const existing = toolRows.get(key);
292
- if (!existing || !toolRowKey(payload)) {
293
- const row = { body };
294
- if (toolRowKey(payload)) toolRows.set(key, row);
295
- enqueue(async () => {
296
- const posted = await postRow(kind, row.body);
297
- row.messageId = posted.id;
298
- row.sentBody = row.body;
299
- });
300
- return;
301
- }
302
- if (body.length <= existing.body.length) return;
303
- existing.body = body;
304
- enqueue(async () => {
305
- if (existing.messageId && existing.body !== existing.sentBody) {
306
- await params.client.updateMessageBody(existing.messageId, existing.body);
307
- existing.sentBody = existing.body;
308
- }
309
- });
310
- };
311
- return {
312
- onItemEvent: (payload) => {
313
- const kind = normalizedItemKind(payload);
314
- if (STREAMING_COMMENTARY_ITEM_KINDS.has(kind)) {
315
- handleCommentary(payload);
316
- return;
317
- }
318
- if (SKIPPED_ITEM_KINDS.has(kind)) return;
319
- handleDiscreteItem(payload);
320
- },
321
- setProvenance: (next) => {
322
- provenance = next;
323
- },
324
- finalize: async () => {
325
- await flushAllCommentary();
326
- await chain;
327
- }
328
- };
329
- }
330
- //#endregion
331
- //#region extensions/clickclack/src/discussions/binding-generation.ts
332
- const DISCUSSION_GENERATIONS_NAMESPACE = "discussion-binding-generations";
333
- const MAX_PENDING_DISCUSSION_GENERATIONS = 1e4;
334
- const storesByRuntime$2 = /* @__PURE__ */ new WeakMap();
335
- function getGenerationStore(runtime) {
336
- const existing = storesByRuntime$2.get(runtime);
337
- if (existing) return existing;
338
- const created = runtime.state.openSyncKeyedStore({
339
- namespace: DISCUSSION_GENERATIONS_NAMESPACE,
340
- maxEntries: MAX_PENDING_DISCUSSION_GENERATIONS,
341
- overflowPolicy: "reject-new"
342
- });
343
- storesByRuntime$2.set(runtime, created);
344
- return created;
345
- }
346
- /** Reserves a generation so an interrupted channel create can be adopted on retry. */
347
- function reserveDiscussionBindingGeneration(params) {
348
- const store = getGenerationStore(params.runtime);
349
- const existing = store.lookup(params.sessionKey);
350
- if (existing?.destinationIdentity === params.destinationIdentity) return existing.generation;
351
- const generation = (params.createGeneration ?? randomUUID)();
352
- store.register(params.sessionKey, {
353
- destinationIdentity: params.destinationIdentity,
354
- generation
355
- });
356
- return generation;
357
- }
358
- /** Clears only the completed reservation; future opens must mint a new ownership ref. */
359
- function clearDiscussionBindingGeneration(params) {
360
- const store = getGenerationStore(params.runtime);
361
- const existing = store.lookup(params.sessionKey);
362
- if (!existing) return;
363
- if (params.expectedGeneration && existing.generation !== params.expectedGeneration) return;
364
- store.delete(params.sessionKey);
365
- }
366
- /** Quarantines a destination before the first fallible channel create. */
367
- function recordPendingDiscussionOpen(params) {
368
- const store = getGenerationStore(params.runtime);
369
- const existing = store.lookup(params.sessionKey);
370
- if (!existing || existing.generation !== params.generation) throw new Error("ClickClack discussion generation changed before channel creation");
371
- store.register(params.sessionKey, {
372
- ...existing,
373
- pending: params.pending
374
- });
375
- }
376
- function listPendingDiscussionOpens(runtime) {
377
- return getGenerationStore(runtime).entries().flatMap((entry) => entry.value.pending ? [{
378
- sessionKey: entry.key,
379
- generation: entry.value.generation,
380
- ...entry.value.pending
381
- }] : []);
382
- }
383
- function hasPendingDiscussionOpenForDestination(params) {
384
- const serverBaseUrl = params.serverBaseUrl.replace(/\/+$/u, "");
385
- return listPendingDiscussionOpens(params.runtime).some((pending) => pending.serverBaseUrl === serverBaseUrl && pending.workspaceId === params.workspaceId);
386
- }
387
- //#endregion
388
- //#region extensions/clickclack/src/discussions/naming.ts
389
- function shortSessionHash(sessionKey) {
390
- return createHash("sha256").update(sessionKey).digest("hex").slice(0, 32);
391
- }
392
- function slugifyLabel(label) {
393
- return label.normalize("NFKD").replace(/[\u0300-\u036f]/gu, "").toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 80).replace(/-+$/gu, "");
394
- }
395
- function fallbackDiscussionLabel(sessionKey, agentId) {
396
- const agentSegment = agentId?.trim() ? slugifyLabel(agentId) : "";
397
- const hash = shortSessionHash(sessionKey).slice(0, 8);
398
- return `s-${agentSegment ? `${agentSegment}-` : ""}${hash}`;
399
- }
400
- function resolveDiscussionLabel(entry, sessionKey, agentId) {
401
- return entry.label?.trim() || entry.displayName?.trim() || entry.subject?.trim() || fallbackDiscussionLabel(sessionKey, agentId);
402
- }
403
- function truncateDiscussionDisplayTitle(label) {
404
- return Array.from(label).slice(0, 200).join("").trim();
405
- }
406
- function slugifyDiscussionLabel(label, sessionKey) {
407
- return slugifyLabel(label) || fallbackDiscussionLabel(sessionKey);
408
- }
409
- function discussionSessionPeerId(identity) {
410
- return `disc-${createHash("sha256").update([
411
- identity.mainSessionKey,
412
- identity.sessionId,
413
- identity.serverBaseUrl,
414
- identity.channelId,
415
- identity.externalRef
416
- ].join("\0")).digest("hex").slice(0, 32)}`;
417
- }
418
- function isDiscussionSessionKey(sessionKey) {
419
- return sessionKey.includes(":clickclack:") && /:channel:disc-[0-9a-f]{32}$/u.test(sessionKey);
420
- }
421
- function discussionExternalRef(installationId, mainSessionKey, sessionId, destinationIdentity, bindingGeneration) {
422
- return `openclaw:${installationId}:${shortSessionHash([
423
- mainSessionKey,
424
- sessionId,
425
- destinationIdentity,
426
- bindingGeneration
427
- ].join("\0"))}`;
428
- }
429
- function discussionCredentialFingerprint(token) {
430
- return createHash("sha256").update(token).digest("hex");
431
- }
432
- function discussionSessionKey(params) {
433
- return params.runtime.channel.routing.buildAgentSessionKey({
434
- agentId: params.agentId,
435
- channel: "clickclack",
436
- accountId: params.accountId,
437
- peer: {
438
- kind: "channel",
439
- id: discussionSessionPeerId(params)
440
- }
441
- });
442
- }
443
- //#endregion
444
- //#region extensions/clickclack/src/discussions/binding-store.ts
445
- function bindingMatchesSessionIncarnation(runtime, sessionKey, binding) {
446
- const entry = runtime.agent.session.getSessionEntry({
447
- sessionKey,
448
- readConsistency: "latest"
449
- });
450
- return Boolean(entry && binding.sessionId && entry.sessionId === binding.sessionId);
451
- }
452
- function bindingMatchesActiveSessionIncarnation(runtime, sessionKey, binding) {
453
- const entry = runtime.agent.session.getSessionEntry({
454
- sessionKey,
455
- readConsistency: "latest"
456
- });
457
- return Boolean(entry && binding.sessionId && entry.sessionId === binding.sessionId && entry.archivedAt === void 0);
458
- }
459
- const DISCUSSION_BINDINGS_NAMESPACE = "discussion-bindings";
460
- const MAX_DISCUSSION_BINDINGS = 1e4;
461
- const storesByRuntime$1 = /* @__PURE__ */ new WeakMap();
462
- function channelKey(serverBaseUrl, channelId) {
463
- return `${serverBaseUrl.replace(/\/+$/u, "")}\0${channelId}`;
464
- }
465
- /** SQLite-backed session/channel bindings with a process-local inbound lookup index. */
466
- var ClickClackDiscussionBindingStore = class {
467
- #store;
468
- #sessionByChannel = /* @__PURE__ */ new Map();
469
- #mainByDiscussionSession = /* @__PURE__ */ new Map();
470
- #runtime;
471
- constructor(runtime) {
472
- this.#runtime = runtime;
473
- this.#store = runtime.state.openSyncKeyedStore({
474
- namespace: DISCUSSION_BINDINGS_NAMESPACE,
475
- maxEntries: MAX_DISCUSSION_BINDINGS,
476
- overflowPolicy: "reject-new"
477
- });
478
- for (const entry of this.#store.entries()) this.#index(entry.key, entry.value);
479
- }
480
- get(sessionKey) {
481
- return this.#store.lookup(sessionKey);
482
- }
483
- hasCapacity(sessionKey) {
484
- return this.get(sessionKey) !== void 0 || this.#store.entries().length < MAX_DISCUSSION_BINDINGS;
485
- }
486
- getByChannel(serverBaseUrl, channelId) {
487
- const key = channelKey(serverBaseUrl, channelId);
488
- const sessionKey = this.#sessionByChannel.get(key);
489
- if (!sessionKey) return;
490
- const binding = this.get(sessionKey);
491
- if (!binding) {
492
- this.#sessionByChannel.delete(key);
493
- return;
494
- }
495
- return {
496
- sessionKey,
497
- binding
498
- };
499
- }
500
- set(sessionKey, binding) {
501
- const previous = this.get(sessionKey);
502
- this.#store.register(sessionKey, binding);
503
- if (previous) this.#unindex(sessionKey, previous);
504
- this.#index(sessionKey, binding);
505
- }
506
- delete(sessionKey) {
507
- const previous = this.get(sessionKey);
508
- const deleted = this.#store.delete(sessionKey);
509
- if (deleted && previous) this.#unindex(sessionKey, previous);
510
- return deleted;
511
- }
512
- getByDiscussionSession(sideSessionKey) {
513
- const sessionKey = this.#mainByDiscussionSession.get(sideSessionKey);
514
- if (!sessionKey) return;
515
- const binding = this.get(sessionKey);
516
- return binding ? {
517
- sessionKey,
518
- binding
519
- } : void 0;
520
- }
521
- entries() {
522
- return this.#store.entries().map((entry) => ({
523
- sessionKey: entry.key,
524
- binding: entry.value
525
- }));
526
- }
527
- #index(sessionKey, binding) {
528
- this.#sessionByChannel.set(channelKey(binding.serverBaseUrl, binding.channelId), sessionKey);
529
- const sideSessionKey = discussionSessionKey({
530
- runtime: this.#runtime,
531
- agentId: binding.agentId,
532
- mainSessionKey: sessionKey,
533
- sessionId: binding.sessionId,
534
- accountId: binding.accountId,
535
- serverBaseUrl: binding.serverBaseUrl,
536
- channelId: binding.channelId,
537
- externalRef: binding.externalRef
538
- });
539
- if (sideSessionKey) this.#mainByDiscussionSession.set(sideSessionKey, sessionKey);
540
- }
541
- #unindex(sessionKey, binding) {
542
- this.#sessionByChannel.delete(channelKey(binding.serverBaseUrl, binding.channelId));
543
- const sideSessionKey = discussionSessionKey({
544
- runtime: this.#runtime,
545
- agentId: binding.agentId,
546
- mainSessionKey: sessionKey,
547
- sessionId: binding.sessionId,
548
- accountId: binding.accountId,
549
- serverBaseUrl: binding.serverBaseUrl,
550
- channelId: binding.channelId,
551
- externalRef: binding.externalRef
552
- });
553
- if (sideSessionKey) this.#mainByDiscussionSession.delete(sideSessionKey);
554
- }
555
- };
556
- function getClickClackDiscussionBindingStore(runtime) {
557
- const existing = storesByRuntime$1.get(runtime);
558
- if (existing) return existing;
559
- const created = new ClickClackDiscussionBindingStore(runtime);
560
- storesByRuntime$1.set(runtime, created);
561
- return created;
562
- }
563
- //#endregion
564
- //#region extensions/clickclack/src/discussions/eligibility.ts
565
- function discussionAccounts(cfg) {
566
- return listEnabledClickClackAccounts(cfg).filter((account) => account.configured && account.discussions.enabled);
567
- }
568
- function normalizedServerBaseUrl(account) {
569
- return account.baseUrl.replace(/\/+$/u, "");
570
- }
571
- /** Resolves the sole live account and rejects bindings pinned to an older destination. */
572
- function resolveDiscussionBindingAccount(cfg, binding) {
573
- const accounts = discussionAccounts(cfg);
574
- if (accounts.length !== 1) return { state: "unavailable" };
575
- const account = accounts[0];
576
- if (!account) return { state: "unavailable" };
577
- if (account.accountId !== binding.accountId || normalizedServerBaseUrl(account) !== binding.serverBaseUrl || account.discussions.workspace !== binding.workspaceRef || binding.credentialFingerprint !== void 0 && discussionCredentialFingerprint(account.token) !== binding.credentialFingerprint) return {
578
- state: "stale",
579
- account
580
- };
581
- return {
582
- state: "active",
583
- account
584
- };
585
- }
586
- /** Public embed/open URLs for one bound discussion channel. */
587
- function discussionInfoForBinding(binding, account) {
588
- const baseUrl = normalizedServerBaseUrl(account);
589
- return {
590
- state: "open",
591
- embedUrl: `${baseUrl}/embed/channel/${encodeURIComponent(binding.workspaceRouteId)}/${encodeURIComponent(binding.channelRouteId)}?openclawHostTheme=1`,
592
- openUrl: `${baseUrl}/app/${encodeURIComponent(binding.workspaceRouteId)}/${encodeURIComponent(binding.channelRouteId)}`
593
- };
594
- }
595
- //#endregion
596
- //#region extensions/clickclack/src/discussions/revoked-channel-store.ts
597
- const REVOKED_CHANNELS_NAMESPACE = "discussion-revoked-channels";
598
- const MAX_REVOKED_CHANNELS = 1e5;
599
- const storesByRuntime = /* @__PURE__ */ new WeakMap();
600
- function revokedChannelKey(params) {
601
- return [params.serverBaseUrl.replace(/\/+$/u, ""), params.channelId].join("\0");
602
- }
603
- function getStore(runtime) {
604
- const existing = storesByRuntime.get(runtime);
605
- if (existing) return existing;
606
- const created = runtime.state.openSyncKeyedStore({
607
- namespace: REVOKED_CHANNELS_NAMESPACE,
608
- maxEntries: MAX_REVOKED_CHANNELS,
609
- overflowPolicy: "reject-new"
610
- });
611
- storesByRuntime.set(runtime, created);
612
- return created;
613
- }
614
- /** Records managed ownership before its live binding is released. */
615
- function markClickClackDiscussionChannelRevoked(runtime, binding) {
616
- const value = {
617
- accountId: binding.accountId,
618
- serverBaseUrl: binding.serverBaseUrl,
619
- channelId: binding.channelId,
620
- revokedAt: Date.now()
621
- };
622
- getStore(runtime).register(revokedChannelKey(value), value);
623
- }
624
- function markClickClackDiscussionChannelIdentityRevoked(params) {
625
- const value = {
626
- accountId: params.accountId,
627
- serverBaseUrl: params.serverBaseUrl.replace(/\/+$/u, ""),
628
- channelId: params.channelId,
629
- revokedAt: Date.now()
630
- };
631
- getStore(params.runtime).register(revokedChannelKey(value), value);
632
- }
633
- function clearClickClackDiscussionChannelRevoked(params) {
634
- getStore(params.runtime).delete(revokedChannelKey(params));
635
- }
636
- /** Distinguishes a released managed channel from a genuinely ordinary channel. */
637
- function isClickClackDiscussionChannelRevoked(params) {
638
- return Boolean(getStore(params.runtime).lookup(revokedChannelKey(params)));
639
- }
640
- //#endregion
641
- //#region extensions/clickclack/src/discussions/routing.ts
642
- function resolveClickClackDiscussionRoute(params) {
643
- if (isClickClackDiscussionChannelRevoked(params)) return { state: "revoked" };
644
- const matched = getClickClackDiscussionBindingStore(params.runtime).getByChannel(params.serverBaseUrl, params.channelId);
645
- if (!matched) return { state: hasPendingDiscussionOpenForDestination(params) ? "revoked" : "unbound" };
646
- if (matched.binding.accountId !== params.accountId) return { state: "revoked" };
647
- if (matched.binding.serverBaseUrl !== params.serverBaseUrl.replace(/\/+$/u, "")) return { state: "revoked" };
648
- if (matched.binding.archived) return { state: "revoked" };
649
- if (resolveDiscussionBindingAccount(params.config, matched.binding).state !== "active") return { state: "revoked" };
650
- if (!bindingMatchesActiveSessionIncarnation(params.runtime, matched.sessionKey, matched.binding)) return { state: "revoked" };
651
- const sessionKey = discussionSessionKey({
652
- runtime: params.runtime,
653
- agentId: matched.binding.agentId,
654
- mainSessionKey: matched.sessionKey,
655
- sessionId: matched.binding.sessionId,
656
- accountId: params.accountId,
657
- serverBaseUrl: matched.binding.serverBaseUrl,
658
- channelId: matched.binding.channelId,
659
- externalRef: matched.binding.externalRef
660
- });
661
- if (!sessionKey) return { state: "revoked" };
662
- return {
663
- state: "active",
664
- route: {
665
- agentId: matched.binding.agentId,
666
- sessionKey,
667
- systemPrompt: [
668
- "You are the side agent for a ClickClack discussion attached to an OpenClaw session.",
669
- `The main session key is ${matched.sessionKey}.`,
670
- "Observe it with sessions_history and session_status (using changesSince for incremental checks).",
671
- "Use sessions_send to relay or steer the main session only when the humans in this discussion ask you to.",
672
- "These session tools are host-scoped to the attached main session; do not attempt session discovery or alternate targets."
673
- ].join(" ")
674
- }
675
- };
676
- }
677
- //#endregion
678
- //#region extensions/clickclack/src/target.ts
679
- /**
680
- * Parses `channel:name`, `thread:msg_id`, `dm:usr_id`, or a bare channel name.
681
- */
682
- function parseClickClackTarget(raw) {
683
- const value = raw.trim();
684
- if (!value) throw new Error("ClickClack target is required");
685
- const [prefix, ...rest] = value.split(":");
686
- const body = rest.join(":").trim();
687
- if (prefix === "channel" && body) return {
688
- chatType: "group",
689
- kind: "channel",
690
- id: body
691
- };
692
- if (prefix === "thread" && body) return {
693
- chatType: "group",
694
- kind: "thread",
695
- id: body
696
- };
697
- if (prefix === "dm" && body) return {
698
- chatType: "direct",
699
- kind: "dm",
700
- id: body
701
- };
702
- if (!body) return {
703
- chatType: "group",
704
- kind: "channel",
705
- id: value
706
- };
707
- throw new Error(`Unsupported ClickClack target: ${raw}`);
708
- }
709
- /** Formats a parsed ClickClack target back into canonical target syntax. */
710
- function buildClickClackTarget(target) {
711
- return `${target.kind}:${target.id}`;
712
- }
713
- /** Normalizes user-entered ClickClack target text for channel routing. */
714
- function normalizeClickClackTarget(raw) {
715
- return buildClickClackTarget(parseClickClackTarget(raw));
716
- }
717
- /** Reports whether a target string can be offered to the ClickClack parser. */
718
- function looksLikeClickClackTarget(raw) {
719
- return /^(channel|thread|dm):/i.test(raw.trim()) || raw.trim().length > 0;
720
- }
721
- //#endregion
722
- //#region extensions/clickclack/src/outbound.ts
723
- /**
724
- * Outbound ClickClack delivery helpers for channel messages, thread replies,
725
- * and direct messages.
726
- */
727
- const CLICKCLACK_MAX_UPLOAD_BYTES = 64 * 1024 * 1024;
728
- const CLICKCLACK_FORMAT_PROFILE = FormatCapabilityProfile.define({
729
- mechanism: "markdown",
730
- chunk: {
731
- limit: 1024 * 1024,
732
- unit: "bytes"
733
- }
734
- });
735
- function renderClickClackMarkdown(markdown) {
736
- return renderMarkdownWithMarkers({
737
- text: markdown,
738
- styles: [],
739
- links: []
740
- }, {
741
- styleMarkers: {},
742
- escapeText: (text) => text
743
- }, CLICKCLACK_FORMAT_PROFILE);
744
- }
745
- async function createTargetMessage(params) {
746
- const parsed = parseClickClackTarget(params.to);
747
- const explicitThreadId = params.threadId == null ? "" : String(params.threadId);
748
- const replyToId = params.replyToId == null ? "" : String(params.replyToId);
749
- if (explicitThreadId || parsed.kind === "thread") {
750
- const rootId = explicitThreadId || parsed.id;
751
- await params.onPlatformSendDispatch?.();
752
- return await params.client.createThreadReply(rootId, params.text, {
753
- provenance: params.provenance,
754
- nonce: params.nonce
755
- });
756
- }
757
- if (parsed.kind === "dm") {
758
- await params.onPlatformSendDispatch?.();
759
- const dm = await params.client.createDirectConversation(params.workspaceId, [parsed.id]);
760
- return await params.client.createDirectMessage(dm.id, params.text, {
761
- quotedMessageId: replyToId || void 0,
762
- nonce: params.nonce
763
- });
764
- }
765
- const channelId = await resolveChannelId(params.client, params.workspaceId, parsed.id);
766
- await params.onPlatformSendDispatch?.();
767
- return await params.client.createChannelMessage(channelId, params.text, {
768
- provenance: params.provenance,
769
- quotedMessageId: replyToId || void 0,
770
- nonce: params.nonce
771
- });
772
- }
773
- function durableDeliveryDigest(params) {
774
- if (!params.deliveryQueueId) return;
775
- if (!Number.isSafeInteger(params.deliveryPartIndex) || (params.deliveryPartIndex ?? -1) < 0) throw new Error("ClickClack durable delivery requires a stable delivery part index");
776
- return createHash("sha256").update(`${params.deliveryQueueId}\n${params.deliveryPartIndex}`).digest("hex");
777
- }
778
- function mediaDeliveryNonces(params) {
779
- const digest = durableDeliveryDigest(params);
780
- if (!digest) return {};
781
- return {
782
- message: `openclaw-media:${digest}`,
783
- upload: `openclaw-upload:${digest}`
784
- };
785
- }
786
- function textDeliveryNonce(params) {
787
- const digest = durableDeliveryDigest(params);
788
- return digest ? `openclaw-text:${digest}` : void 0;
789
- }
790
- function createDispatchOnce(onPlatformSendDispatch) {
791
- let dispatched = false;
792
- return async () => {
793
- if (dispatched) return;
794
- await onPlatformSendDispatch?.();
795
- dispatched = true;
796
- };
797
- }
798
- async function attachUploadRetrySafe(params) {
799
- try {
800
- await params.client.attachUpload(params.messageId, params.uploadId);
801
- } catch (firstError) {
802
- try {
803
- if ((await params.client.message(params.messageId)).attachments?.some((attachment) => attachment.id === params.uploadId)) return;
804
- } catch {}
805
- try {
806
- await params.client.attachUpload(params.messageId, params.uploadId);
807
- } catch {
808
- throw firstError;
809
- }
810
- }
811
- }
812
- function createOutboundContext(params) {
813
- const account = resolveClickClackAccount({
814
- cfg: params.cfg,
815
- accountId: params.accountId
816
- });
817
- return {
818
- account,
819
- client: createClickClackClient({
820
- baseUrl: account.apiEndpoint,
821
- token: account.token,
822
- correlationId: params.correlationId
823
- })
824
- };
825
- }
826
- /**
827
- * Sends visible text to a normalized ClickClack target and returns the created
828
- * message id, or undefined when sanitization removes all content.
829
- */
830
- async function sendClickClackText(params) {
831
- const text = renderClickClackMarkdown(sanitizeAssistantVisibleText(params.text));
832
- if (!text) return;
833
- const { account, client } = createOutboundContext(params);
834
- const workspaceId = await resolveWorkspaceId(client, account.workspace);
835
- const dispatch = createDispatchOnce(params.onPlatformSendDispatch);
836
- return (await createTargetMessage({
837
- client,
838
- workspaceId,
839
- to: params.to,
840
- text,
841
- threadId: params.threadId,
842
- replyToId: params.replyToId,
843
- provenance: params.provenance,
844
- nonce: textDeliveryNonce({
845
- deliveryQueueId: params.deliveryQueueId,
846
- deliveryPartIndex: params.deliveryPartIndex
847
- }),
848
- onPlatformSendDispatch: dispatch
849
- })).id;
850
- }
851
- /** Resolves, uploads, sends, then attaches one file to a ClickClack message. */
852
- async function sendClickClackMedia(params) {
853
- const nonces = mediaDeliveryNonces({
854
- deliveryQueueId: params.deliveryQueueId,
855
- deliveryPartIndex: params.deliveryPartIndex
856
- });
857
- const preloadedMedia = nonces.upload ? void 0 : await loadOutboundMediaFromUrl(params.mediaUrl, {
858
- maxBytes: CLICKCLACK_MAX_UPLOAD_BYTES,
859
- mediaAccess: params.mediaAccess,
860
- mediaLocalRoots: params.mediaLocalRoots,
861
- mediaReadFile: params.mediaReadFile
862
- });
863
- const { account, client } = createOutboundContext(params);
864
- const workspaceId = await resolveWorkspaceId(client, account.workspace);
865
- const persistedUpload = nonces.upload ? await client.findUploadByNonce({
866
- workspaceId,
867
- nonce: nonces.upload
868
- }) : void 0;
869
- const dispatch = createDispatchOnce(params.onPlatformSendDispatch);
870
- let upload = persistedUpload;
871
- let mediaFilename = preloadedMedia?.fileName?.trim();
872
- if (!upload) {
873
- const media = preloadedMedia ?? await loadOutboundMediaFromUrl(params.mediaUrl, {
874
- maxBytes: CLICKCLACK_MAX_UPLOAD_BYTES,
875
- mediaAccess: params.mediaAccess,
876
- mediaLocalRoots: params.mediaLocalRoots,
877
- mediaReadFile: params.mediaReadFile
878
- });
879
- const filename = media.fileName?.trim() || "attachment";
880
- mediaFilename = filename;
881
- const contentType = media.contentType?.trim() || "application/octet-stream";
882
- await dispatch();
883
- upload = await client.createUpload({
884
- workspaceId,
885
- buffer: media.buffer,
886
- filename,
887
- contentType,
888
- ...nonces.upload ? { nonce: nonces.upload } : {}
889
- });
890
- }
891
- const text = renderClickClackMarkdown(sanitizeAssistantVisibleText(params.text)) || mediaFilename || upload.filename || "attachment";
892
- const message = await createTargetMessage({
893
- client,
894
- workspaceId,
895
- to: params.to,
896
- text,
897
- threadId: params.threadId,
898
- replyToId: params.replyToId,
899
- nonce: nonces.message,
900
- onPlatformSendDispatch: dispatch
901
- });
902
- await attachUploadRetrySafe({
903
- client,
904
- messageId: message.id,
905
- uploadId: upload.id
906
- });
907
- return message.id;
908
- }
909
- function collectReconciliationMediaUrls(ctx) {
910
- const planned = ctx.renderedBatchPlan?.items[0]?.mediaUrls;
911
- if (planned?.length) return planned.map((url) => url.trim()).filter(Boolean);
912
- const payload = ctx.payloads[0];
913
- return [payload?.mediaUrl, ...payload?.mediaUrls ?? []].map((url) => url?.trim()).filter((url) => Boolean(url));
914
- }
915
- /**
916
- * Completes an unknown durable send through ClickClack's message/upload nonces.
917
- * Media recovery never rereads the original source after restart.
918
- */
919
- async function reconcileClickClackUnknownSend(ctx) {
920
- if (ctx.payloads.length !== 1 || (ctx.renderedBatchPlan?.items.length ?? 1) !== 1) return {
921
- status: "unresolved",
922
- error: "ClickClack reconciliation requires exactly one payload"
923
- };
924
- const mediaUrls = collectReconciliationMediaUrls(ctx);
925
- const { account, client } = createOutboundContext({
926
- cfg: ctx.cfg,
927
- accountId: ctx.accountId
928
- });
929
- const workspaceId = await resolveWorkspaceId(client, account.workspace);
930
- const effectiveReplyToId = ctx.effectiveReplyToId !== void 0 ? ctx.effectiveReplyToId : ctx.replyToMode === "off" ? void 0 : ctx.replyToId;
931
- const payload = ctx.payloads[0];
932
- const caption = ctx.renderedBatchPlan?.items[0]?.text ?? payload?.text ?? "";
933
- if (mediaUrls.length === 0) {
934
- const nonce = textDeliveryNonce({
935
- deliveryQueueId: ctx.queueId,
936
- deliveryPartIndex: 0
937
- });
938
- if (!nonce || !sanitizeAssistantVisibleText(caption)) return { status: "not_sent" };
939
- const message = await client.findMessageByNonce({
940
- workspaceId,
941
- nonce
942
- });
943
- if (!message) return { status: "not_sent" };
944
- const receipt = createMessageReceiptFromOutboundResults({
945
- results: [{
946
- channel: "clickclack",
947
- messageId: message.id
948
- }],
949
- threadId: ctx.threadId == null ? void 0 : String(ctx.threadId),
950
- replyToId: effectiveReplyToId ?? void 0,
951
- kind: "text"
952
- });
953
- return {
954
- status: "sent",
955
- messageId: message.id,
956
- receipt
957
- };
958
- }
959
- const parts = await Promise.all(mediaUrls.map(async (_mediaUrl, index) => {
960
- const nonces = mediaDeliveryNonces({
961
- deliveryQueueId: ctx.queueId,
962
- deliveryPartIndex: index
963
- });
964
- if (!nonces.upload || !nonces.message) throw new Error("ClickClack durable media nonces were not derived");
965
- const [upload, message] = await Promise.all([client.findUploadByNonce({
966
- workspaceId,
967
- nonce: nonces.upload
968
- }), client.findMessageByNonce({
969
- workspaceId,
970
- nonce: nonces.message
971
- })]);
972
- return {
973
- upload,
974
- message
975
- };
976
- }));
977
- for (const part of parts) {
978
- if (part.message && !part.upload) return {
979
- status: "unresolved",
980
- error: `ClickClack message ${part.message.id} exists without its nonce-keyed upload`,
981
- retryable: false
982
- };
983
- if (!part.message) return { status: "not_sent" };
984
- }
985
- const messageIds = [];
986
- for (const part of parts) {
987
- const message = part.message;
988
- const upload = part.upload;
989
- if (!message || !upload) throw new Error("ClickClack reconciliation state changed unexpectedly");
990
- if (!message.attachments?.some((attachment) => attachment.id === upload.id)) await attachUploadRetrySafe({
991
- client,
992
- messageId: message.id,
993
- uploadId: upload.id
994
- });
995
- messageIds.push(message.id);
996
- }
997
- const receipt = createMessageReceiptFromOutboundResults({
998
- results: messageIds.map((messageId) => ({
999
- channel: "clickclack",
1000
- messageId
1001
- })),
1002
- threadId: ctx.threadId == null ? void 0 : String(ctx.threadId),
1003
- replyToId: effectiveReplyToId ?? void 0,
1004
- kind: "media"
1005
- });
1006
- const messageId = messageIds.at(-1);
1007
- return {
1008
- status: "sent",
1009
- ...messageId ? { messageId } : {},
1010
- receipt
1011
- };
1012
- }
1013
- //#endregion
1014
- //#region extensions/clickclack/src/inbound.ts
1015
- const CHANNEL_ID$1 = "clickclack";
1016
- const CLICKCLACK_MESSAGE_ID_PATTERN = /^msg_[0-9a-hjkmnp-tv-z]{26}$/u;
1017
- function hasClickClackReplyMedia(payload) {
1018
- return Boolean(payload.mediaUrl?.trim() || payload.mediaUrls?.some((mediaUrl) => typeof mediaUrl === "string" && mediaUrl.trim()));
1019
- }
1020
- function resolveClickClackAgentRunId(messageId) {
1021
- return CLICKCLACK_MESSAGE_ID_PATTERN.test(messageId) ? `${CHANNEL_ID$1}:${messageId}` : void 0;
1022
- }
1023
- function resolveAccountAgentRoute(params) {
1024
- const runtime = getClickClackRuntime();
1025
- const route = runtime.channel.routing.resolveAgentRoute({
1026
- cfg: params.cfg,
1027
- channel: CHANNEL_ID$1,
1028
- accountId: params.account.accountId,
1029
- peer: {
1030
- kind: params.isDirect ? "direct" : "channel",
1031
- id: params.target
1032
- }
1033
- });
1034
- const agentId = normalizeAgentId(params.account.agentId ?? route.agentId);
1035
- if (agentId === route.agentId) return route;
1036
- const peer = {
1037
- kind: params.isDirect ? "direct" : "channel",
1038
- id: params.target
1039
- };
1040
- const dmScope = params.cfg.session?.dmScope ?? "main";
1041
- const sessionKey = runtime.channel.routing.buildAgentSessionKey({
1042
- agentId,
1043
- mainKey: params.cfg.session?.mainKey,
1044
- channel: CHANNEL_ID$1,
1045
- accountId: params.account.accountId,
1046
- peer,
1047
- dmScope,
1048
- identityLinks: params.cfg.session?.identityLinks
1049
- });
1050
- const mainSessionKey = runtime.channel.routing.buildAgentSessionKey({
1051
- agentId,
1052
- mainKey: params.cfg.session?.mainKey,
1053
- channel: CHANNEL_ID$1,
1054
- accountId: params.account.accountId,
1055
- dmScope: "main"
1056
- });
1057
- return {
1058
- ...route,
1059
- agentId,
1060
- dmScope,
1061
- sessionKey,
1062
- mainSessionKey,
1063
- lastRoutePolicy: sessionKey === mainSessionKey ? "main" : "session"
1064
- };
1065
- }
1066
- async function dispatchModelReply(params) {
1067
- const runtime = getClickClackRuntime();
1068
- const text = (await runtime.llm.complete({
1069
- agentId: params.route.agentId,
1070
- model: params.account.model,
1071
- purpose: "clickclack bot reply",
1072
- systemPrompt: params.account.systemPrompt,
1073
- messages: [{
1074
- role: "user",
1075
- content: params.message.body
1076
- }]
1077
- })).text.trim();
1078
- if (!text) {
1079
- runtime.logging.getChildLogger({
1080
- plugin: "clickclack",
1081
- feature: "model-reply"
1082
- }).warn(`[${params.account.accountId}] ClickClack model reply produced no sendable text`);
1083
- return;
1084
- }
1085
- await sendClickClackText({
1086
- cfg: params.cfg,
1087
- accountId: params.account.accountId,
1088
- to: params.target,
1089
- text,
1090
- threadId: params.message.parent_message_id ? params.message.thread_root_id : void 0,
1091
- replyToId: params.message.id,
1092
- correlationId: params.correlationId
1093
- });
1094
- }
1095
- /**
1096
- * Dispatches one already-fetched ClickClack message through the configured
1097
- * reply mode for its account.
1098
- */
1099
- async function handleClickClackInbound(params) {
1100
- const runtime = getClickClackRuntime();
1101
- const message = params.message;
1102
- const access = params.access ?? await resolveClickClackInboundAccess({
1103
- account: params.account,
1104
- config: params.config,
1105
- message
1106
- });
1107
- if (!access.shouldDispatch) return;
1108
- const conversationId = message.channel_id || message.direct_conversation_id;
1109
- if (!conversationId) return;
1110
- const isDirect = Boolean(message.direct_conversation_id);
1111
- const target = buildClickClackTarget(isDirect ? {
1112
- chatType: "direct",
1113
- kind: "dm",
1114
- id: message.author_id
1115
- } : {
1116
- chatType: "group",
1117
- kind: "channel",
1118
- id: message.channel_id ?? ""
1119
- });
1120
- const accountRoute = resolveAccountAgentRoute({
1121
- cfg: params.config,
1122
- account: params.account,
1123
- target,
1124
- isDirect
1125
- });
1126
- const discussionResolution = !isDirect && message.channel_id ? resolveClickClackDiscussionRoute({
1127
- runtime,
1128
- config: params.config,
1129
- accountId: params.account.accountId,
1130
- serverBaseUrl: params.account.baseUrl,
1131
- workspaceId: message.workspace_id,
1132
- channelId: message.channel_id
1133
- }) : { state: "unbound" };
1134
- if (discussionResolution.state === "revoked") return;
1135
- const discussionRoute = discussionResolution.state === "active" ? discussionResolution.route : void 0;
1136
- const route = discussionRoute ? {
1137
- ...accountRoute,
1138
- agentId: discussionRoute.agentId,
1139
- sessionKey: discussionRoute.sessionKey,
1140
- lastRoutePolicy: "session"
1141
- } : accountRoute;
1142
- if (params.account.replyMode === "model" && !discussionRoute) {
1143
- await dispatchModelReply({
1144
- account: params.account,
1145
- cfg: params.config,
1146
- message,
1147
- route,
1148
- target,
1149
- correlationId: params.correlationId
1150
- });
1151
- return;
1152
- }
1153
- let turnProvenance;
1154
- let activity;
1155
- if (params.account.agentActivity && (message.channel_id || message.direct_conversation_id)) activity = createClickClackActivityPublisher({
1156
- client: createClickClackClient({
1157
- baseUrl: params.account.apiEndpoint,
1158
- token: params.account.token,
1159
- correlationId: params.correlationId
1160
- }),
1161
- target: message.channel_id ? { channelId: message.channel_id } : { conversationId: message.direct_conversation_id },
1162
- turnId: message.id,
1163
- onError: (error) => {
1164
- runtime.logging.getChildLogger({
1165
- plugin: "clickclack",
1166
- feature: "agent-activity"
1167
- }).warn(`clickclack activity publish failed: ${String(error)}`);
1168
- }
1169
- });
1170
- const senderName = message.author?.display_name || message.author_id;
1171
- const body = createChannelInboundEnvelopeBuilder({
1172
- cfg: params.config,
1173
- route
1174
- })({
1175
- channel: "ClickClack",
1176
- from: senderName,
1177
- timestamp: new Date(message.created_at),
1178
- body: message.body
1179
- });
1180
- const ctxPayload = runtime.channel.inbound.buildContext({
1181
- channel: CHANNEL_ID$1,
1182
- accountId: route.accountId ?? params.account.accountId,
1183
- messageId: message.id,
1184
- messageIdFull: message.id,
1185
- timestamp: new Date(message.created_at).getTime(),
1186
- from: target,
1187
- sender: {
1188
- id: message.author_id,
1189
- name: senderName
1190
- },
1191
- conversation: {
1192
- kind: isDirect ? "direct" : "group",
1193
- id: conversationId,
1194
- label: isDirect ? senderName : message.channel_id,
1195
- threadId: message.parent_message_id ? message.thread_root_id : void 0,
1196
- nativeChannelId: conversationId
1197
- },
1198
- route: {
1199
- agentId: route.agentId,
1200
- dmScope: route.dmScope,
1201
- accountId: route.accountId,
1202
- routeSessionKey: route.sessionKey
1203
- },
1204
- reply: {
1205
- to: target,
1206
- originatingTo: target,
1207
- replyToId: message.id,
1208
- messageThreadId: message.parent_message_id ? message.thread_root_id : void 0,
1209
- threadParentId: message.parent_message_id ? message.thread_root_id : void 0
1210
- },
1211
- message: {
1212
- body,
1213
- bodyForAgent: message.body,
1214
- rawBody: message.body,
1215
- commandBody: message.body
1216
- },
1217
- access: {
1218
- commands: { authorized: access.commandAuthorized },
1219
- mentions: {
1220
- canDetectMention: !isDirect,
1221
- wasMentioned: !isDirect
1222
- }
1223
- },
1224
- extra: {
1225
- GroupChannel: message.channel_id,
1226
- ...discussionRoute ? { GroupSystemPrompt: discussionRoute.systemPrompt } : {}
1227
- }
1228
- });
1229
- const runId = resolveClickClackAgentRunId(message.id);
1230
- const activityReplyOptions = activity ? {
1231
- onModelSelected: (ctx) => {
1232
- turnProvenance = {
1233
- model: ctx.provider && ctx.model ? `${ctx.provider}/${ctx.model}` : ctx.model,
1234
- thinking: ctx.thinkLevel
1235
- };
1236
- activity?.setProvenance(turnProvenance);
1237
- },
1238
- onItemEvent: activity.onItemEvent,
1239
- commentaryProgressEnabled: true,
1240
- suppressDefaultToolProgressMessages: true,
1241
- allowProgressCallbacksWhenSourceDeliverySuppressed: true
1242
- } : void 0;
1243
- const dispatchPromise = runtime.channel.inbound.dispatch({
1244
- cfg: params.config,
1245
- channel: CHANNEL_ID$1,
1246
- accountId: params.account.accountId,
1247
- route: {
1248
- agentId: route.agentId,
1249
- dmScope: route.dmScope,
1250
- sessionKey: route.sessionKey
1251
- },
1252
- ctxPayload,
1253
- toolsAllow: params.account.toolsAllow,
1254
- replyOptions: runId || activityReplyOptions ? {
1255
- ...runId ? { runId } : {},
1256
- ...activityReplyOptions
1257
- } : void 0,
1258
- delivery: {
1259
- deliver: async (payload) => {
1260
- if (hasClickClackReplyMedia(payload)) throw new Error("ClickClack media reply requires durable delivery");
1261
- const text = payload && typeof payload === "object" && "text" in payload ? payload.text ?? "" : "";
1262
- if (!text.trim()) return;
1263
- await sendClickClackText({
1264
- cfg: params.config,
1265
- accountId: params.account.accountId,
1266
- to: target,
1267
- text,
1268
- threadId: message.parent_message_id ? message.thread_root_id : void 0,
1269
- replyToId: message.id,
1270
- provenance: turnProvenance,
1271
- correlationId: params.correlationId
1272
- });
1273
- },
1274
- durable: (payload) => {
1275
- if (!hasClickClackReplyMedia(payload)) return false;
1276
- const threadId = message.parent_message_id ? message.thread_root_id : void 0;
1277
- return {
1278
- to: target,
1279
- threadId,
1280
- replyToId: message.id,
1281
- requiredCapabilities: deriveDurableFinalDeliveryRequirements({
1282
- payload,
1283
- threadId,
1284
- replyToId: message.id,
1285
- reconcileUnknownSend: true
1286
- })
1287
- };
1288
- },
1289
- onError: (error) => {
1290
- throw error instanceof Error ? error : /* @__PURE__ */ new Error(`clickclack dispatch failed: ${String(error)}`);
1291
- }
1292
- },
1293
- replyPipeline: {},
1294
- record: { onRecordError: (error) => {
1295
- throw error instanceof Error ? error : /* @__PURE__ */ new Error(`clickclack session record failed: ${String(error)}`);
1296
- } }
1297
- });
1298
- try {
1299
- await dispatchPromise;
1300
- } finally {
1301
- await activity?.finalize();
1302
- }
1303
- }
1304
- //#endregion
1305
- //#region extensions/clickclack/src/gateway.ts
1306
- const CLICKCLACK_EVENT_PAGE_LIMIT = 500;
1307
- function payloadString(event, key) {
1308
- const value = event.payload?.[key];
1309
- return typeof value === "string" ? value : "";
1310
- }
1311
- function eventCorrelationId(event) {
1312
- return normalizeClickClackCorrelationId(event.payload?.correlation_id);
1313
- }
1314
- async function resolveEventMessage(params) {
1315
- const messageId = payloadString(params.event, "message_id");
1316
- if (!messageId) return null;
1317
- const directConversationId = payloadString(params.event, "direct_conversation_id");
1318
- if (directConversationId && typeof params.event.seq === "number") return (await params.client.directMessages(directConversationId, params.event.seq - 1, 10)).find((message) => message.id === messageId) ?? null;
1319
- if (params.event.type === "thread.reply_created") {
1320
- const rootId = payloadString(params.event, "root_message_id");
1321
- if (!rootId) return null;
1322
- return (await params.client.thread(rootId)).replies.find((message) => message.id === messageId) ?? null;
1323
- }
1324
- if (params.event.channel_id && typeof params.event.seq === "number") return (await params.client.channelMessages(params.event.channel_id, params.event.seq - 1, 10)).find((message) => message.id === messageId) ?? null;
1325
- return null;
1326
- }
1327
- function decodeSocketMessage(data) {
1328
- if (typeof data === "string") return data;
1329
- if (Buffer.isBuffer(data)) return data.toString("utf8");
1330
- if (data instanceof ArrayBuffer) return Buffer.from(data).toString("utf8");
1331
- return Buffer.concat(data).toString("utf8");
1332
- }
1333
- function parseSocketEvent(data) {
1334
- try {
1335
- return JSON.parse(decodeSocketMessage(data));
1336
- } catch {
1337
- return null;
1338
- }
1339
- }
1340
- async function processEvent(params) {
1341
- if (params.event.type !== "message.created" && params.event.type !== "thread.reply_created") return;
1342
- if (payloadString(params.event, "author_id") === params.botUserId) return;
1343
- const correlationId = eventCorrelationId(params.event);
1344
- const message = await resolveEventMessage({
1345
- client: correlationId ? createClickClackClient({
1346
- baseUrl: params.account.apiEndpoint,
1347
- token: params.account.token,
1348
- correlationId
1349
- }) : params.client,
1350
- event: params.event
1351
- });
1352
- if (!message || message.author_id === params.botUserId) return;
1353
- if (message.author?.kind === "bot") return;
1354
- const access = await resolveClickClackInboundAccess({
1355
- account: params.account,
1356
- config: params.config,
1357
- message
1358
- });
1359
- if (!access.shouldDispatch) return;
1360
- await handleClickClackInbound({
1361
- account: params.account,
1362
- config: params.config,
1363
- message,
1364
- access,
1365
- ...correlationId ? { correlationId } : {}
1366
- });
1367
- }
1368
- async function drainEventBacklog(params) {
1369
- let afterCursor = params.afterCursor;
1370
- while (!params.abortSignal.aborted) {
1371
- const events = (await params.client.eventPage(params.workspaceId, {
1372
- afterCursor,
1373
- limit: CLICKCLACK_EVENT_PAGE_LIMIT
1374
- })).events;
1375
- for (const event of events) {
1376
- if (params.abortSignal.aborted) return afterCursor;
1377
- if (!event.cursor || event.cursor === afterCursor) throw new Error("ClickClack event backlog returned a non-advancing cursor");
1378
- await params.onEvent(event);
1379
- afterCursor = event.cursor;
1380
- }
1381
- if (events.length === 0) return afterCursor;
1382
- }
1383
- return afterCursor;
1384
- }
1385
- async function startClickClackGatewayAccount(ctx) {
1386
- const configuredAccount = resolveClickClackAccount({
1387
- cfg: ctx.cfg,
1388
- accountId: ctx.account.accountId
1389
- });
1390
- if (!configuredAccount.configured) throw new Error(`ClickClack is not configured for account "${configuredAccount.accountId}"`);
1391
- const client = createClickClackClient({
1392
- baseUrl: configuredAccount.apiEndpoint,
1393
- token: configuredAccount.token
1394
- });
1395
- const workspaceId = await resolveWorkspaceId(client, configuredAccount.workspace);
1396
- const me = await client.me();
1397
- const account = {
1398
- ...configuredAccount,
1399
- workspace: workspaceId,
1400
- botUserId: configuredAccount.botUserId ?? me.id
1401
- };
1402
- const processIncomingEvent = (event) => processEvent({
1403
- account,
1404
- config: ctx.cfg,
1405
- client,
1406
- event,
1407
- botUserId: account.botUserId
1408
- });
1409
- if (account.commandMenu) await syncClickClackCommandMenu({
1410
- cfg: ctx.cfg,
1411
- client,
1412
- log: ctx.log
1413
- });
1414
- ctx.setStatus({
1415
- accountId: account.accountId,
1416
- running: true,
1417
- configured: true,
1418
- enabled: account.enabled,
1419
- baseUrl: account.baseUrl
1420
- });
1421
- let afterCursor = "";
1422
- let initialized = false;
1423
- try {
1424
- while (!ctx.abortSignal.aborted) {
1425
- if (!initialized) {
1426
- const page = await client.eventPage(workspaceId, { includeTail: true });
1427
- if (page.tailCursor !== void 0) afterCursor = page.tailCursor;
1428
- else for (const event of page.events) afterCursor = event.cursor || afterCursor;
1429
- initialized = true;
1430
- } else afterCursor = await drainEventBacklog({
1431
- client,
1432
- workspaceId,
1433
- afterCursor,
1434
- abortSignal: ctx.abortSignal,
1435
- onEvent: processIncomingEvent
1436
- });
1437
- if (ctx.abortSignal.aborted) break;
1438
- const socket = client.websocket(workspaceId, afterCursor);
1439
- await new Promise((resolve) => {
1440
- let settled = false;
1441
- let closing = false;
1442
- let loggedMessageFailure = false;
1443
- let messageQueue = Promise.resolve();
1444
- let removeAbortListener;
1445
- const finishSocketCycle = () => {
1446
- if (settled) return;
1447
- settled = true;
1448
- removeAbortListener?.();
1449
- removeAbortListener = void 0;
1450
- resolve();
1451
- };
1452
- const finishAfterQueuedMessages = () => {
1453
- messageQueue.then(() => finishSocketCycle(), () => finishSocketCycle());
1454
- };
1455
- const reconnectAfterMessageFailure = (error) => {
1456
- if (settled || ctx.abortSignal.aborted) return;
1457
- if (!loggedMessageFailure) {
1458
- loggedMessageFailure = true;
1459
- ctx.log?.warn?.(`[${account.accountId}] ClickClack event processing failed; reconnecting: ${error instanceof Error ? error.message : formatErrorMessage(error)}`);
1460
- }
1461
- if (!closing) {
1462
- closing = true;
1463
- socket.close();
1464
- }
1465
- };
1466
- const abort = () => {
1467
- socket.close();
1468
- finishSocketCycle();
1469
- };
1470
- ctx.abortSignal.addEventListener("abort", abort, { once: true });
1471
- removeAbortListener = () => ctx.abortSignal.removeEventListener("abort", abort);
1472
- socket.on("message", (data) => {
1473
- if (closing || settled) return;
1474
- messageQueue = messageQueue.then(async () => {
1475
- const event = parseSocketEvent(data);
1476
- if (!event) {
1477
- ctx.log?.warn?.(`[${account.accountId}] skipped malformed ClickClack websocket event`);
1478
- return;
1479
- }
1480
- await processIncomingEvent(event);
1481
- afterCursor = event.cursor || afterCursor;
1482
- });
1483
- messageQueue.catch(reconnectAfterMessageFailure);
1484
- });
1485
- socket.on("close", () => {
1486
- closing = true;
1487
- finishAfterQueuedMessages();
1488
- });
1489
- socket.on("error", (error) => {
1490
- if (settled || ctx.abortSignal.aborted) {
1491
- finishSocketCycle();
1492
- return;
1493
- }
1494
- if (closing) return;
1495
- ctx.log?.warn?.(`[${account.accountId}] ClickClack websocket error; reconnecting: ${error instanceof Error ? error.message : String(error)}`);
1496
- closing = true;
1497
- socket.close();
1498
- });
1499
- });
1500
- if (!ctx.abortSignal.aborted) try {
1501
- await sleepWithAbort(account.reconnectMs, ctx.abortSignal);
1502
- } catch (error) {
1503
- if (!ctx.abortSignal.aborted) throw error;
1504
- }
1505
- }
1506
- } finally {
1507
- ctx.setStatus({
1508
- accountId: account.accountId,
1509
- running: false
1510
- });
1511
- }
1512
- }
1513
- //#endregion
1514
- //#region extensions/clickclack/src/channel.ts
1515
- /**
1516
- * ClickClack channel plugin definition: target parsing, account config, status,
1517
- * gateway startup, and outbound delivery wiring.
1518
- */
1519
- const CHANNEL_ID = CLICKCLACK_CHANNEL_ID;
1520
- const clickClackMessageAdapter = defineChannelMessageAdapter({
1521
- id: CHANNEL_ID,
1522
- durableFinal: {
1523
- capabilities: {
1524
- text: true,
1525
- media: true,
1526
- replyTo: true,
1527
- thread: true,
1528
- messageSendingHooks: true,
1529
- reconcileUnknownSend: true
1530
- },
1531
- reconcileUnknownSendKinds: {
1532
- text: true,
1533
- media: true
1534
- },
1535
- reconcileUnknownSend: reconcileClickClackUnknownSend
1536
- },
1537
- send: {
1538
- text: async (ctx) => {
1539
- const messageId = await sendClickClackText({
1540
- cfg: ctx.cfg,
1541
- accountId: ctx.accountId,
1542
- to: ctx.to,
1543
- text: ctx.text,
1544
- threadId: ctx.threadId,
1545
- replyToId: ctx.replyToId,
1546
- deliveryQueueId: ctx.deliveryQueueId,
1547
- deliveryPartIndex: ctx.deliveryPartIndex,
1548
- onPlatformSendDispatch: ctx.onPlatformSendDispatch
1549
- });
1550
- const threadId = ctx.threadId == null ? void 0 : String(ctx.threadId);
1551
- const replyToId = ctx.replyToId ?? void 0;
1552
- return {
1553
- ...messageId ? { messageId } : {},
1554
- receipt: createMessageReceiptFromOutboundResults({
1555
- results: messageId ? [{
1556
- channel: CHANNEL_ID,
1557
- messageId
1558
- }] : [],
1559
- threadId,
1560
- replyToId,
1561
- kind: "text"
1562
- })
1563
- };
1564
- },
1565
- media: async (ctx) => {
1566
- const messageId = await sendClickClackMedia({
1567
- cfg: ctx.cfg,
1568
- accountId: ctx.accountId,
1569
- to: ctx.to,
1570
- text: ctx.text,
1571
- mediaUrl: ctx.mediaUrl,
1572
- mediaAccess: ctx.mediaAccess,
1573
- mediaLocalRoots: ctx.mediaLocalRoots,
1574
- mediaReadFile: ctx.mediaReadFile,
1575
- threadId: ctx.threadId,
1576
- replyToId: ctx.replyToId,
1577
- deliveryQueueId: ctx.deliveryQueueId,
1578
- deliveryPartIndex: ctx.deliveryPartIndex,
1579
- onPlatformSendDispatch: ctx.onPlatformSendDispatch
1580
- });
1581
- const threadId = ctx.threadId == null ? void 0 : String(ctx.threadId);
1582
- const replyToId = ctx.replyToId ?? void 0;
1583
- return {
1584
- messageId,
1585
- receipt: createMessageReceiptFromOutboundResults({
1586
- results: [{
1587
- channel: CHANNEL_ID,
1588
- messageId
1589
- }],
1590
- threadId,
1591
- replyToId,
1592
- kind: "media"
1593
- })
1594
- };
1595
- }
1596
- }
1597
- });
1598
- /**
1599
- * Channel plugin instance registered by the bundled ClickClack entry.
1600
- */
1601
- const clickClackPlugin = createChatChannelPlugin({
1602
- base: {
1603
- id: CHANNEL_ID,
1604
- meta: clickClackMeta,
1605
- capabilities: {
1606
- chatTypes: ["direct", "group"],
1607
- threads: true,
1608
- blockStreaming: true
1609
- },
1610
- reload: { configPrefixes: ["channels.clickclack"] },
1611
- configSchema: clickClackConfigSchema,
1612
- config: clickClackConfigAdapter,
1613
- setup: clickClackSetupAdapter,
1614
- setupContract: clickClackSetupContract,
1615
- setupWizard: clickClackSetupWizard,
1616
- secrets: {
1617
- secretTargetRegistryEntries,
1618
- collectRuntimeConfigAssignments
1619
- },
1620
- messaging: {
1621
- targetPrefixes: ["clickclack", "cc"],
1622
- normalizeTarget: normalizeClickClackTarget,
1623
- inferTargetChatType: ({ to }) => parseClickClackTarget(to).chatType,
1624
- targetResolver: {
1625
- looksLikeId: looksLikeClickClackTarget,
1626
- hint: "<channel:name|dm:usr_id|thread:msg_id>"
1627
- },
1628
- resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target, replyToId, threadId, currentSessionKey }) => {
1629
- const parsed = parseClickClackTarget(target);
1630
- return buildThreadAwareOutboundSessionRoute({
1631
- route: buildChannelOutboundSessionRoute({
1632
- cfg,
1633
- agentId,
1634
- channel: CHANNEL_ID,
1635
- accountId,
1636
- recipientSessionExact: parsed.kind === "dm",
1637
- peer: {
1638
- kind: parsed.chatType === "direct" ? "direct" : "channel",
1639
- id: buildClickClackTarget(parsed)
1640
- },
1641
- chatType: parsed.chatType,
1642
- from: `clickclack:${accountId ?? DEFAULT_ACCOUNT_ID}`,
1643
- to: buildClickClackTarget(parsed)
1644
- }),
1645
- replyToId,
1646
- threadId: threadId ?? (parsed.kind === "thread" ? parsed.id : void 0),
1647
- currentSessionKey,
1648
- useSuffix: false,
1649
- canRecoverCurrentThread: () => true
1650
- });
1651
- },
1652
- resolveSessionConversation: ({ rawId }) => {
1653
- const parsed = parseClickClackTarget(rawId);
1654
- if (parsed.kind === "dm") return null;
1655
- return {
1656
- id: parsed.id,
1657
- threadId: parsed.kind === "thread" ? parsed.id : void 0,
1658
- baseConversationId: parsed.id,
1659
- parentConversationCandidates: [parsed.id]
1660
- };
1661
- }
1662
- },
1663
- status: createComputedAccountStatusAdapter({
1664
- defaultRuntime: createDefaultChannelRuntimeState(DEFAULT_ACCOUNT_ID),
1665
- buildChannelSummary: ({ snapshot }) => ({
1666
- ok: snapshot.configured,
1667
- label: snapshot.configured ? "configured" : "missing config",
1668
- detail: snapshot.baseUrl ?? ""
1669
- }),
1670
- resolveAccountSnapshot: ({ account }) => ({
1671
- accountId: account.accountId,
1672
- name: account.name,
1673
- enabled: account.enabled,
1674
- configured: account.configured,
1675
- baseUrl: account.baseUrl
1676
- })
1677
- }),
1678
- gateway: { startAccount: startClickClackGatewayAccount },
1679
- message: clickClackMessageAdapter
1680
- },
1681
- outbound: {
1682
- base: { deliveryMode: "direct" },
1683
- attachedResults: {
1684
- channel: CHANNEL_ID,
1685
- sendText: async ({ cfg, to, text, accountId, threadId, replyToId, deliveryQueueId, deliveryPartIndex, onPlatformSendDispatch }) => {
1686
- return { messageId: await sendClickClackText({
1687
- cfg,
1688
- accountId,
1689
- to,
1690
- text,
1691
- threadId,
1692
- replyToId,
1693
- deliveryQueueId,
1694
- deliveryPartIndex,
1695
- onPlatformSendDispatch
1696
- }) ?? "" };
1697
- },
1698
- sendMedia: async ({ cfg, to, text, mediaUrl, mediaAccess, mediaLocalRoots, mediaReadFile, accountId, threadId, replyToId, deliveryQueueId, deliveryPartIndex, onPlatformSendDispatch }) => {
1699
- if (!mediaUrl) throw new Error("ClickClack media send requires mediaUrl");
1700
- return { messageId: await sendClickClackMedia({
1701
- cfg,
1702
- accountId,
1703
- to,
1704
- text,
1705
- mediaUrl,
1706
- mediaAccess,
1707
- mediaLocalRoots,
1708
- mediaReadFile,
1709
- threadId,
1710
- replyToId,
1711
- deliveryQueueId,
1712
- deliveryPartIndex,
1713
- onPlatformSendDispatch
1714
- }) };
1715
- }
1716
- }
1717
- }
1718
- });
1719
- //#endregion
1720
- export { listPendingDiscussionOpens as C, setClickClackRuntime as D, getClickClackRuntime as E, clearDiscussionBindingGeneration as S, reserveDiscussionBindingGeneration as T, fallbackDiscussionLabel as _, isClickClackDiscussionChannelRevoked as a, slugifyDiscussionLabel as b, discussionAccounts as c, resolveDiscussionBindingAccount as d, bindingMatchesActiveSessionIncarnation as f, discussionExternalRef as g, discussionCredentialFingerprint as h, clearClickClackDiscussionChannelRevoked as i, discussionInfoForBinding as l, getClickClackDiscussionBindingStore as m, buildClickClackTarget as n, markClickClackDiscussionChannelIdentityRevoked as o, bindingMatchesSessionIncarnation as p, parseClickClackTarget as r, markClickClackDiscussionChannelRevoked as s, clickClackPlugin as t, normalizedServerBaseUrl as u, isDiscussionSessionKey as v, recordPendingDiscussionOpen as w, truncateDiscussionDisplayTitle as x, resolveDiscussionLabel as y };