@openclaw/clickclack 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/.setup/{channel-BX2RqmGn.mjs → channel-D3WIuNxS.mjs} +398 -506
  2. package/dist/.setup/{resolve-B-W04sGX.mjs → resolve-BgFJI_p4.mjs} +28 -52
  3. package/dist/.setup/{rolldown-runtime-B4FMCO8f.mjs → rolldown-runtime-BBjsoOtd.mjs} +0 -1
  4. package/dist/.setup/{runtime-api-DIu-sNJs.mjs → runtime-api-CMReYU7v.mjs} +325 -371
  5. package/dist/.setup/secret-contract-api--45pFCg3.mjs +2 -0
  6. package/dist/.setup/{setup-claim-BJPvHiWS.mjs → setup-claim-Ca2nzQHc.mjs} +4 -9
  7. package/dist/.setup/{setup-plugin-api-BiMffAUC.mjs → setup-plugin-api-CFG0EYat.mjs} +1 -1
  8. package/dist/.setup/setup-plugin-api-Cg_ECaNj.mjs +1 -0
  9. package/dist/.setup/{setup-surface-fPdDl0l2.mjs → setup-surface-CSITttSD.mjs} +5 -5
  10. package/dist/.setup/{setup-verify-B5iJBDrk.mjs → setup-verify-DLfG0Fyt.mjs} +12 -24
  11. package/dist/.source-module-urls/aa673c321fe9be084b8926cbe5388ff5e2a41371389e19ca60a1983f2b634030.json +1 -0
  12. package/dist/api.js +3 -3
  13. package/dist/channel-plugin-api.js +1 -2
  14. package/dist/doctor-contract-api.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/runtime-api.js +4 -4
  17. package/dist/secret-contract-api.js +1 -2
  18. package/dist/setup-entry.js +2 -2
  19. package/dist/setup-plugin-api.js +1 -2
  20. package/node_modules/zod/package.json +1 -1
  21. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  22. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  23. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  24. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  25. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  26. package/node_modules/zod/src/v4/core/util.ts +13 -0
  27. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  28. package/node_modules/zod/v4/core/compile.cjs +8 -0
  29. package/node_modules/zod/v4/core/compile.js +8 -0
  30. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  31. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  32. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  33. package/node_modules/zod/v4/core/schemas.js +30 -0
  34. package/node_modules/zod/v4/core/util.cjs +15 -0
  35. package/node_modules/zod/v4/core/util.d.cts +2 -0
  36. package/node_modules/zod/v4/core/util.d.ts +2 -0
  37. package/node_modules/zod/v4/core/util.js +14 -0
  38. package/node_modules/zod/v4/core/versions.cjs +1 -1
  39. package/node_modules/zod/v4/core/versions.js +1 -1
  40. package/package.json +5 -7
  41. package/dist/.setup/secret-contract-api-CBcsgIYZ.mjs +0 -3
  42. package/dist/.setup/setup-plugin-api-bSnZClKM.mjs +0 -2
  43. package/node_modules/ws/LICENSE +0 -20
  44. package/node_modules/ws/README.md +0 -548
  45. package/node_modules/ws/browser.js +0 -8
  46. package/node_modules/ws/index.js +0 -22
  47. package/node_modules/ws/lib/buffer-util.js +0 -131
  48. package/node_modules/ws/lib/constants.js +0 -19
  49. package/node_modules/ws/lib/event-target.js +0 -292
  50. package/node_modules/ws/lib/extension.js +0 -203
  51. package/node_modules/ws/lib/limiter.js +0 -55
  52. package/node_modules/ws/lib/permessage-deflate.js +0 -530
  53. package/node_modules/ws/lib/receiver.js +0 -743
  54. package/node_modules/ws/lib/sender.js +0 -607
  55. package/node_modules/ws/lib/stream.js +0 -161
  56. package/node_modules/ws/lib/subprotocol.js +0 -62
  57. package/node_modules/ws/lib/validation.js +0 -152
  58. package/node_modules/ws/lib/websocket-server.js +0 -562
  59. package/node_modules/ws/lib/websocket.js +0 -1421
  60. package/node_modules/ws/package.json +0 -74
  61. package/node_modules/ws/wrapper.mjs +0 -21
@@ -1,18 +1,21 @@
1
- import { n as __reExport, t as __exportAll } from "./rolldown-runtime-B4FMCO8f.mjs";
2
- import { c as CLICKCLACK_CHANNEL_ID, d as DEFAULT_ACCOUNT_ID, f as isClickClackAccountCurrent, g as resolveClickClackAccountConfig, h as resolveClickClackAccount, l as clickClackConfigAdapter, m as listEnabledClickClackAccounts, n as clickClackSetupContract, s as clickClackConfigSchema, t as clickClackSetupWizard, u as clickClackMeta } from "./setup-surface-fPdDl0l2.mjs";
3
- import { a as createClickClackClient, i as ClickClackHttpError, n as resolveChannelId, r as resolveWorkspaceId, s as normalizeClickClackCorrelationId } from "./resolve-B-W04sGX.mjs";
1
+ import { n as __reExport, t as __exportAll } from "./rolldown-runtime-BBjsoOtd.mjs";
2
+ import { c as CLICKCLACK_CHANNEL_ID, d as DEFAULT_ACCOUNT_ID, f as isClickClackAccountCurrent, g as resolveClickClackAccountConfig, h as resolveClickClackAccount, l as clickClackConfigAdapter, m as listEnabledClickClackAccounts, n as clickClackSetupContract, s as clickClackConfigSchema, t as clickClackSetupWizard, u as clickClackMeta } from "./setup-surface-CSITttSD.mjs";
3
+ import { a as createClickClackClient, i as ClickClackHttpError, n as resolveChannelId, r as resolveWorkspaceId, s as normalizeClickClackCorrelationId } from "./resolve-BgFJI_p4.mjs";
4
4
  import { n as collectRuntimeConfigAssignments, r as secretTargetRegistryEntries } from "./secret-contract-CF7TKtkU.mjs";
5
5
  import { resolveChannelMediaMaxBytes } from "openclaw/plugin-sdk/account-helpers";
6
6
  import { parseDateStringTimestampMs } from "openclaw/plugin-sdk/number-runtime";
7
7
  import { mergePairLoopGuardConfig } from "openclaw/plugin-sdk/pair-loop-guard-runtime";
8
8
  import { normalizeTrimmedStringList, readStringField } from "openclaw/plugin-sdk/string-coerce-runtime";
9
9
  import { buildChannelOutboundSessionRoute, buildThreadAwareOutboundSessionRoute, createChatChannelPlugin } from "openclaw/plugin-sdk/channel-core";
10
- import { buildChannelProgressDraftLine, createChannelMessageReplyPipeline, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, deriveDurableFinalDeliveryRequirements, formatChannelProgressDraftLineForEntry, isCompleteAgentPreamble } from "openclaw/plugin-sdk/channel-outbound";
10
+ import { buildChannelProgressDraftLine, createChannelMessageAdapterFromOutbound, createChannelMessageReplyPipeline, createMessageReceiptFromOutboundResults, defineChannelMessageAdapter, deriveDurableFinalDeliveryRequirements, formatChannelProgressDraftLineForEntry, isCompleteAgentPreamble } from "openclaw/plugin-sdk/channel-outbound";
11
11
  import { createComputedAccountStatusAdapter, createDefaultChannelRuntimeState } from "openclaw/plugin-sdk/status-helpers";
12
12
  import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
13
13
  import { channelReadyPatch, channelStoppedPatch } from "openclaw/plugin-sdk/gateway-runtime";
14
+ import { listNativeCommandSpecsForConfig } from "openclaw/plugin-sdk/native-command-registry";
14
15
  import { sleepWithAbort } from "openclaw/plugin-sdk/runtime-env";
16
+ import { safeParseJson, truncateCodePoints } from "openclaw/plugin-sdk/text-utility-runtime";
15
17
  import { rawDataToString } from "openclaw/plugin-sdk/webhook-ingress";
18
+ import { startWebSocketKeepalive } from "openclaw/plugin-sdk/websocket-runtime";
16
19
  import { isDeepStrictEqual } from "node:util";
17
20
  import { parseAccessGroupAllowFromEntry } from "openclaw/plugin-sdk/access-groups";
18
21
  import { formatNormalizedAllowFromEntries, resolveAllowlistMatchByCandidates } from "openclaw/plugin-sdk/allow-from";
@@ -20,9 +23,10 @@ import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
20
23
  import { createHash, randomUUID } from "node:crypto";
21
24
  import { createAsyncLock } from "openclaw/plugin-sdk/async-lock-runtime";
22
25
  import { assertPluginStateReadAvailable, preparePluginStateRead } from "openclaw/plugin-sdk/plugin-state-runtime";
23
- import { truncateCodePoints } from "openclaw/plugin-sdk/text-utility-runtime";
26
+ import { sha256Hex } from "openclaw/plugin-sdk/node-crypto-runtime";
27
+ import { resolveSessionAgentIdStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
28
+ import { captureSessionEntryCurrentCheckAsync } from "openclaw/plugin-sdk/session-binding-runtime";
24
29
  import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
25
- import { listNativeCommandSpecsForConfig } from "openclaw/plugin-sdk/native-command-registry";
26
30
  import { buildChannelInboundEventContext, createChannelInboundEnvelopeBuilderAsync, createChannelPartialDeliveryError, recordChannelBotPairLoopAndCheckSuppression } from "openclaw/plugin-sdk/channel-inbound";
27
31
  import { extensionForMime } from "openclaw/plugin-sdk/media-mime";
28
32
  import { loadOutboundMediaFromUrl } from "openclaw/plugin-sdk/outbound-media";
@@ -100,7 +104,7 @@ function reserveDiscussionBindingGeneration(params) {
100
104
  },
101
105
  result: existing.generation
102
106
  };
103
- generation ??= (params.createGeneration ?? randomUUID)();
107
+ generation ??= randomUUID();
104
108
  return {
105
109
  value: {
106
110
  accountId: params.accountId,
@@ -174,6 +178,7 @@ async function hasPendingDiscussionOpenForDestination(params) {
174
178
  }
175
179
  //#endregion
176
180
  //#region extensions/clickclack/src/discussions/binding-store.ts
181
+ /** Retained for the shipped synchronous ScopedSessionAccessProvider contract. */
177
182
  function bindingMatchesActiveSessionIncarnation(runtime, sessionKey, binding) {
178
183
  const entry = runtime.agent.session.getSessionEntry({
179
184
  sessionKey,
@@ -202,10 +207,7 @@ async function attachBindingToCurrentActiveSession(params) {
202
207
  ...retained,
203
208
  sessionId: entry.sessionId
204
209
  };
205
- return await params.store.setIfCurrent(params.sessionKey, params.binding, attached, { assertCurrent: () => {
206
- const current = params.store.get(params.sessionKey);
207
- if (!current || current.externalRef !== params.binding.externalRef || current.serverBaseUrl !== params.binding.serverBaseUrl || current.channelId !== params.binding.channelId || !bindingMatchesActiveSessionIncarnation(params.runtime, params.sessionKey, attached)) throw new Error("ClickClack discussion session changed before attachment committed");
208
- } }) ? attached : void 0;
210
+ return await params.store.setIfCurrent(params.sessionKey, params.binding, attached) ? attached : void 0;
209
211
  }
210
212
  const DISCUSSION_BINDINGS_NAMESPACE = "discussion-bindings";
211
213
  const MAX_DISCUSSION_BINDINGS = 1e4;
@@ -214,7 +216,6 @@ const BINDING_STORE_OPTIONS = {
214
216
  maxEntries: MAX_DISCUSSION_BINDINGS,
215
217
  overflowPolicy: "reject-new"
216
218
  };
217
- const MAX_RETAINED_DETACHED_DISCUSSION_BINDINGS = 1e3;
218
219
  const storesByRuntime$1 = /* @__PURE__ */ new WeakMap();
219
220
  function channelKey(serverBaseUrl, channelId) {
220
221
  return `${serverBaseUrl.replace(/\/+$/u, "")}\0${channelId}`;
@@ -230,7 +231,6 @@ var ClickClackDiscussionBindingStore = class {
230
231
  #withMutation = createAsyncLock();
231
232
  #prepared = false;
232
233
  #preparing;
233
- #changedDuringPreparation = /* @__PURE__ */ new Set();
234
234
  constructor(runtime) {
235
235
  this.#runtime = runtime;
236
236
  }
@@ -298,36 +298,19 @@ var ClickClackDiscussionBindingStore = class {
298
298
  this.#publish(sessionKey, observed.value);
299
299
  return false;
300
300
  }
301
- let authorityRejected = false;
302
- try {
303
- const result = await (options?.assertCurrent ? this.#runtime.state.openKeyedStoreV2(BINDING_STORE_OPTIONS, { assertCurrent: () => {
304
- try {
305
- options.assertCurrent?.();
306
- } catch (error) {
307
- authorityRejected = true;
308
- throw error;
309
- }
310
- } }) : worker).compareAndApply(sessionKey, observed.comparison, next ? {
311
- operation: "update",
312
- action: "set",
313
- value: next
314
- } : {
315
- operation: "delete",
316
- action: "delete"
317
- });
318
- this.#publish(sessionKey, result.status === "conflict" ? result.current.value : next);
319
- return result.status === "applied";
320
- } catch (error) {
321
- if (!authorityRejected) throw error;
322
- const current = await worker.observe(sessionKey);
323
- if (current.comparison === observed.comparison) throw error;
324
- this.#publish(sessionKey, current.value);
325
- return false;
326
- }
301
+ const result = await (options?.assertCurrent ? this.#runtime.state.openKeyedStoreV2(BINDING_STORE_OPTIONS, { assertCurrent: options.assertCurrent }) : worker).compareAndApply(sessionKey, observed.comparison, next ? {
302
+ operation: "update",
303
+ action: "set",
304
+ value: next
305
+ } : {
306
+ operation: "delete",
307
+ action: "delete"
308
+ });
309
+ this.#publish(sessionKey, result.status === "conflict" ? result.current.value : next);
310
+ return result.status === "applied";
327
311
  });
328
312
  }
329
313
  #publish(sessionKey, binding) {
330
- if (!this.#prepared) this.#changedDuringPreparation.add(sessionKey);
331
314
  this.#unindex(sessionKey);
332
315
  if (binding) this.#index(sessionKey, binding);
333
316
  }
@@ -337,10 +320,10 @@ var ClickClackDiscussionBindingStore = class {
337
320
  binding: entry.value
338
321
  }));
339
322
  if (this.#prepared) return await load();
340
- this.#preparing ??= load().then((entries) => {
341
- for (const { sessionKey, binding } of entries) if (!this.#changedDuringPreparation.has(sessionKey)) this.#index(sessionKey, binding);
323
+ this.#preparing ??= this.#withMutation(async () => {
324
+ const entries = await load();
325
+ for (const { sessionKey, binding } of entries) this.#index(sessionKey, binding);
342
326
  this.#prepared = true;
343
- this.#changedDuringPreparation.clear();
344
327
  return entries;
345
328
  }).finally(() => {
346
329
  this.#preparing = void 0;
@@ -397,7 +380,7 @@ function getClickClackDiscussionBindingStore(runtime) {
397
380
  //#endregion
398
381
  //#region extensions/clickclack/src/discussions/naming.ts
399
382
  function shortSessionHash(sessionKey) {
400
- return createHash("sha256").update(sessionKey).digest("hex").slice(0, 32);
383
+ return sha256Hex(sessionKey).slice(0, 32);
401
384
  }
402
385
  function slugifyLabel(label) {
403
386
  return label.normalize("NFKD").replace(/[\u0300-\u036f]/gu, "").toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 80).replace(/-+$/gu, "");
@@ -417,13 +400,13 @@ function slugifyDiscussionLabel(label, sessionKey) {
417
400
  return slugifyLabel(label) || fallbackDiscussionLabel(sessionKey);
418
401
  }
419
402
  function discussionSessionPeerId(identity) {
420
- return `disc-${createHash("sha256").update([
403
+ return `disc-${sha256Hex([
421
404
  identity.mainSessionKey,
422
405
  identity.sessionId,
423
406
  identity.serverBaseUrl,
424
407
  identity.channelId,
425
408
  identity.externalRef
426
- ].join("\0")).digest("hex").slice(0, 32)}`;
409
+ ].join("\0")).slice(0, 32)}`;
427
410
  }
428
411
  function isDiscussionSessionKey(sessionKey) {
429
412
  return sessionKey.includes(":clickclack:") && /:channel:disc-[0-9a-f]{32}$/u.test(sessionKey);
@@ -436,7 +419,7 @@ function discussionExternalRef(installationId, mainSessionKey, destinationIdenti
436
419
  ].join("\0"))}`;
437
420
  }
438
421
  function discussionCredentialFingerprint(token) {
439
- return createHash("sha256").update(token).digest("hex");
422
+ return sha256Hex(token);
440
423
  }
441
424
  function discussionSessionKey(params) {
442
425
  return params.runtime.channel.routing.buildAgentSessionKey({
@@ -460,8 +443,7 @@ function normalizedServerBaseUrl(account) {
460
443
  /** Resolves the sole live account and rejects bindings pinned to an older destination. */
461
444
  function resolveDiscussionBindingAccount(cfg, binding) {
462
445
  const accounts = discussionAccounts(cfg);
463
- if (accounts.length !== 1) return { state: "unavailable" };
464
- const account = accounts[0];
446
+ const account = accounts.length === 1 ? accounts[0] : void 0;
465
447
  if (!account) return { state: "unavailable" };
466
448
  if (account.accountId !== binding.accountId || normalizedServerBaseUrl(account) !== binding.serverBaseUrl || account.discussions.workspace !== binding.workspaceRef || binding.credentialFingerprint !== void 0 && discussionCredentialFingerprint(account.token) !== binding.credentialFingerprint) return {
467
449
  state: "stale",
@@ -490,8 +472,36 @@ const STORE_OPTIONS = {
490
472
  };
491
473
  const storesByRuntime = /* @__PURE__ */ new WeakMap();
492
474
  const nativeStoresByRuntime = /* @__PURE__ */ new WeakMap();
475
+ const legacyAdoptionsByRuntime = /* @__PURE__ */ new WeakMap();
476
+ const legacyAdoptedRuntimes = /* @__PURE__ */ new WeakSet();
493
477
  function revokedChannelKey(params) {
494
- return [params.serverBaseUrl.replace(/\/+$/u, ""), params.channelId].join("\0");
478
+ return createHash("sha256").update(JSON.stringify([params.serverBaseUrl.replace(/\/+$/u, ""), params.channelId]), "utf8").digest("hex").slice(0, 32);
479
+ }
480
+ function adoptLegacyMarkers(runtime) {
481
+ let adoption = legacyAdoptionsByRuntime.get(runtime);
482
+ if (!adoption) {
483
+ adoption = (async () => {
484
+ const store = getStore(runtime);
485
+ for (const entry of await store.entries()) if (entry.key.includes("\0")) {
486
+ const key = revokedChannelKey(entry.value);
487
+ for (;;) {
488
+ const current = await store.observe(key);
489
+ if (current.value && (!current.value.binding || isDeepStrictEqual(current.value.binding, entry.value.binding))) break;
490
+ if (current.value && entry.value.binding) throw new Error("Conflicting ClickClack revocation evidence; legacy marker retained");
491
+ if ((await store.compareAndApply(key, current.comparison, {
492
+ operation: "update",
493
+ action: "set",
494
+ value: entry.value
495
+ })).status !== "conflict") break;
496
+ }
497
+ await store.delete(entry.key);
498
+ }
499
+ legacyAdoptedRuntimes.add(runtime);
500
+ })();
501
+ adoption.catch(() => legacyAdoptionsByRuntime.delete(runtime));
502
+ legacyAdoptionsByRuntime.set(runtime, adoption);
503
+ }
504
+ return adoption;
495
505
  }
496
506
  function getStore(runtime) {
497
507
  const existing = storesByRuntime.get(runtime);
@@ -509,6 +519,7 @@ async function markClickClackDiscussionChannelRevoked(runtime, sessionKey, bindi
509
519
  revokedAt: Date.now(),
510
520
  binding
511
521
  };
522
+ await adoptLegacyMarkers(runtime);
512
523
  const bindings = getClickClackDiscussionBindingStore(runtime);
513
524
  for (;;) {
514
525
  const owner = await bindings.observeCurrent(sessionKey);
@@ -546,13 +557,16 @@ async function markClickClackDiscussionChannelIdentityRevoked(params) {
546
557
  channelId: params.channelId,
547
558
  revokedAt: Date.now()
548
559
  };
560
+ await adoptLegacyMarkers(params.runtime);
549
561
  await getStore(params.runtime).register(revokedChannelKey(value), value);
550
562
  }
551
563
  async function clearClickClackDiscussionChannelRevoked(params) {
564
+ await adoptLegacyMarkers(params.runtime);
552
565
  await getStore(params.runtime).delete(revokedChannelKey(params));
553
566
  }
554
567
  /** Distinguishes a released managed channel from a genuinely ordinary channel. */
555
568
  function isClickClackDiscussionChannelRevoked(params) {
569
+ if (!legacyAdoptedRuntimes.has(params.runtime)) return true;
556
570
  let store = nativeStoresByRuntime.get(params.runtime);
557
571
  if (!store) {
558
572
  store = params.runtime.state.openSyncKeyedStore(STORE_OPTIONS);
@@ -561,6 +575,7 @@ function isClickClackDiscussionChannelRevoked(params) {
561
575
  return revocationApplies(store.lookup(revokedChannelKey(params)), params.binding);
562
576
  }
563
577
  async function prepareClickClackDiscussionChannelRevocation(params) {
578
+ await adoptLegacyMarkers(params.runtime);
564
579
  const facts = await preparePluginStateRead(getStore(params.runtime), revokedChannelKey(params));
565
580
  return {
566
581
  isRevoked: (binding) => {
@@ -574,12 +589,30 @@ async function prepareClickClackDiscussionChannelRevocation(params) {
574
589
  };
575
590
  }
576
591
  async function isClickClackDiscussionChannelRevokedAsync(params) {
592
+ await adoptLegacyMarkers(params.runtime);
577
593
  return revocationApplies(await getStore(params.runtime).lookup(revokedChannelKey(params)), params.binding);
578
594
  }
579
595
  function revocationApplies(revoked, binding) {
580
596
  return Boolean(revoked && (!binding || !revoked.binding || isDeepStrictEqual(revoked.binding, binding)));
581
597
  }
582
598
  //#endregion
599
+ //#region extensions/clickclack/src/discussions/session-authority.ts
600
+ /** Retain the session owner's receipt-backed facts until the external effect completes. */
601
+ async function prepareDiscussionSessionEntry(runtime, sessionKey) {
602
+ const config = runtime.config.current();
603
+ const agentId = resolveSessionAgentIdStrict({
604
+ config,
605
+ sessionKey
606
+ });
607
+ return await captureSessionEntryCurrentCheckAsync({
608
+ agentId,
609
+ sessionKey,
610
+ storePath: runtime.agent.session.resolveStorePath(config.session?.store, { agentId }),
611
+ matchGeneration: false,
612
+ fields: ["sessionId", "archivedAt"]
613
+ });
614
+ }
615
+ //#endregion
583
616
  //#region extensions/clickclack/src/discussions/routing.ts
584
617
  async function resolveClickClackDiscussionRoute(params) {
585
618
  const store = getClickClackDiscussionBindingStore(params.runtime);
@@ -592,6 +625,7 @@ async function resolveClickClackDiscussionRoute(params) {
592
625
  }
593
626
  let revocation;
594
627
  let bindingFacts;
628
+ let session;
595
629
  try {
596
630
  revocation = await prepareClickClackDiscussionChannelRevocation(params);
597
631
  if (revocation.isRevoked(matched?.binding)) return { state: "revoked" };
@@ -616,8 +650,10 @@ async function resolveClickClackDiscussionRoute(params) {
616
650
  return { state: "revoked" };
617
651
  }
618
652
  if (!binding) return { state: "revoked" };
653
+ session = await prepareDiscussionSessionEntry(params.runtime, matched.sessionKey);
654
+ session.source();
619
655
  const current = bindingFacts.read();
620
- if (!current || current.externalRef !== binding.externalRef || current.channelId !== binding.channelId || revocation.isRevoked(current) || !bindingMatchesActiveSessionIncarnation(params.runtime, matched.sessionKey, binding) || resolveDiscussionBindingAccount(params.runtime.config.current(), binding).state !== "active") return { state: "revoked" };
656
+ if (!current || current.externalRef !== binding.externalRef || current.channelId !== binding.channelId || revocation.isRevoked(current) || session.entry?.sessionId !== binding.sessionId || session.entry.archivedAt !== void 0 || resolveDiscussionBindingAccount(params.runtime.config.current(), binding).state !== "active") return { state: "revoked" };
621
657
  const sessionKey = discussionSessionKey({
622
658
  runtime: params.runtime,
623
659
  agentId: binding.agentId,
@@ -646,6 +682,7 @@ async function resolveClickClackDiscussionRoute(params) {
646
682
  } catch {
647
683
  return { state: "revoked" };
648
684
  } finally {
685
+ session?.release();
649
686
  bindingFacts?.release();
650
687
  revocation?.release();
651
688
  }
@@ -667,66 +704,7 @@ function resolveClickClackGroupPolicy(params) {
667
704
  };
668
705
  }
669
706
  //#endregion
670
- //#region extensions/clickclack/src/mention-facts.ts
671
- const CLICKCLACK_MENTION_PATTERN = /(?:^|[^a-z0-9_@-])@([a-z0-9][a-z0-9_-]{1,31})(?![a-z0-9_-])/giu;
672
- function buildLocalMentionRegexes(params) {
673
- if (params.mentionPatterns.length === 0) return [];
674
- const cfg = params.cfg;
675
- const syntheticCfg = {
676
- ...cfg,
677
- messages: {
678
- ...cfg?.messages,
679
- groupChat: {
680
- ...cfg?.messages?.groupChat,
681
- mentionPatterns: params.mentionPatterns
682
- }
683
- }
684
- };
685
- return (0, channel_mention_gating_exports.buildMentionRegexes)(syntheticCfg, void 0, {
686
- provider: "clickclack",
687
- conversationId: params.channelId
688
- });
689
- }
690
- function resolveMentionHandles(body) {
691
- return [...body.matchAll(CLICKCLACK_MENTION_PATTERN)].map((match) => match[1]?.toLowerCase()).filter((handle) => Boolean(handle));
692
- }
693
- function resolveClickClackMentionFacts(params) {
694
- const { isDirect, body, mentionPatterns, botHandle, cfg, agentId, channelId } = params;
695
- if (isDirect) return {
696
- canDetectMention: false,
697
- wasMentioned: false
698
- };
699
- if (!body) return {
700
- canDetectMention: true,
701
- wasMentioned: false,
702
- hasAnyMention: false
703
- };
704
- const sharedMentionRegexes = (0, channel_mention_gating_exports.buildMentionRegexes)(cfg, agentId, {
705
- provider: "clickclack",
706
- conversationId: channelId
707
- });
708
- const localMentionRegexes = buildLocalMentionRegexes({
709
- cfg,
710
- mentionPatterns,
711
- channelId
712
- });
713
- const mentionRegexes = [...sharedMentionRegexes, ...localMentionRegexes];
714
- const bodyForRegex = (0, channel_mention_gating_exports.normalizeMentionText)(body);
715
- const hasConfiguredMention = mentionRegexes.some((regex) => regex.test(bodyForRegex));
716
- const mentionHandles = resolveMentionHandles(body);
717
- const normalizedBotHandle = botHandle?.replace(/^@/u, "").trim().toLowerCase();
718
- return {
719
- canDetectMention: true,
720
- wasMentioned: (normalizedBotHandle ? mentionHandles.includes(normalizedBotHandle) : false) || hasConfiguredMention,
721
- hasAnyMention: mentionHandles.length > 0 || hasConfiguredMention
722
- };
723
- }
724
- //#endregion
725
707
  //#region extensions/clickclack/src/runtime.ts
726
- /**
727
- * Runtime store for host-provided OpenClaw services used by the ClickClack
728
- * bundled plugin.
729
- */
730
708
  const { setRuntime: setClickClackRuntime, getRuntime: getClickClackRuntime } = createPluginRuntimeStore({
731
709
  pluginId: "clickclack",
732
710
  errorMessage: "ClickClack runtime not initialized"
@@ -766,15 +744,10 @@ function parseClickClackTarget(raw) {
766
744
  function buildClickClackTarget(target) {
767
745
  return `${target.kind}:${target.id}`;
768
746
  }
769
- function normalizeClickClackTarget(raw) {
770
- return buildClickClackTarget(parseClickClackTarget(raw));
771
- }
772
- function looksLikeClickClackTarget(raw) {
773
- return raw.trim().length > 0;
774
- }
775
747
  //#endregion
776
748
  //#region extensions/clickclack/src/access.ts
777
749
  const CHANNEL_ID$2 = "clickclack";
750
+ const CLICKCLACK_MENTION_PATTERN = /(?:^|[^a-z0-9_@-])@([a-z0-9][a-z0-9_-]{1,31})(?![a-z0-9_-])/giu;
778
751
  function normalizeClickClackUserId(value) {
779
752
  const trimmed = value.trim();
780
753
  if (!trimmed) return null;
@@ -801,77 +774,83 @@ async function isClickClackBotOwnedThread(params) {
801
774
  return false;
802
775
  }
803
776
  }
804
- function resolveClickClackBotLoopConversationId(params) {
805
- if (params.message.parent_message_id && params.message.thread_root_id) return params.message.thread_root_id;
806
- return params.isDirect ? params.message.direct_conversation_id ?? params.message.author_id : params.message.channel_id ?? params.message.thread_root_id ?? params.message.author_id;
807
- }
808
- function resolveAccountAgentRoute(params) {
777
+ async function resolveClickClackInboundAccess(params) {
809
778
  const runtime = getClickClackRuntime();
810
- const peer = {
811
- kind: params.isDirect ? "direct" : "channel",
812
- id: params.target
813
- };
814
- const route = runtime.channel.routing.resolveAgentRoute({
815
- cfg: params.cfg,
816
- channel: CHANNEL_ID$2,
817
- accountId: params.account.accountId,
818
- peer
819
- });
820
- const agentId = normalizeAgentId(params.account.agentId ?? route.agentId);
821
- if (agentId === route.agentId) return route;
822
- const dmScope = params.cfg.session?.dmScope ?? "main";
823
- const sessionKey = runtime.channel.routing.buildAgentSessionKey({
824
- agentId,
825
- mainKey: params.cfg.session?.mainKey,
826
- channel: CHANNEL_ID$2,
827
- accountId: params.account.accountId,
828
- peer,
829
- dmScope,
830
- identityLinks: params.cfg.session?.identityLinks
831
- });
832
- const mainSessionKey = runtime.channel.routing.buildAgentSessionKey({
833
- agentId,
834
- mainKey: params.cfg.session?.mainKey,
835
- channel: CHANNEL_ID$2,
836
- accountId: params.account.accountId,
837
- dmScope: "main"
779
+ const rootPolicyConfigured = resolveClickClackGroupPolicy({
780
+ account: params.account,
781
+ channelId: params.message.channel_id
782
+ }).requireMentionInBotThreads !== void 0;
783
+ const isCurrent = () => isClickClackAccountCurrent({
784
+ cfg: runtime.config.current(),
785
+ account: params.account
838
786
  });
839
- return {
840
- ...route,
841
- agentId,
842
- dmScope,
843
- sessionKey,
844
- mainSessionKey,
845
- lastRoutePolicy: sessionKey === mainSessionKey ? "main" : "session"
787
+ const isBotOwnedThread = rootPolicyConfigured && await isClickClackBotOwnedThread(params);
788
+ const routeConfig = rootPolicyConfigured ? runtime.config.current() : params.config;
789
+ const routeAccountConfig = rootPolicyConfigured ? resolveClickClackAccountConfig(routeConfig, params.account.accountId) : params.account;
790
+ const routingMessage = params.message;
791
+ const routingAccount = {
792
+ ...params.account,
793
+ agentId: routeAccountConfig.agentId
846
794
  };
847
- }
848
- async function resolvePreparedInboundRoute(params) {
849
- const runtime = getClickClackRuntime();
850
- const isDirect = Boolean(params.message.direct_conversation_id);
795
+ const routeRuntime = getClickClackRuntime();
796
+ const isDirect = Boolean(routingMessage.direct_conversation_id);
851
797
  const target = buildClickClackTarget(isDirect ? {
852
798
  chatType: "direct",
853
799
  kind: "dm",
854
- id: params.message.author_id
800
+ id: routingMessage.author_id
855
801
  } : {
856
802
  chatType: "group",
857
803
  kind: "channel",
858
- id: params.message.channel_id ?? ""
804
+ id: routingMessage.channel_id ?? ""
859
805
  });
860
- const accountRoute = resolveAccountAgentRoute({
861
- cfg: params.config,
862
- account: params.account,
863
- target,
864
- isDirect
806
+ const routingConfig = routeConfig;
807
+ const peer = {
808
+ kind: isDirect ? "direct" : "channel",
809
+ id: target
810
+ };
811
+ let accountRoute = routeRuntime.channel.routing.resolveAgentRoute({
812
+ cfg: routingConfig,
813
+ channel: CHANNEL_ID$2,
814
+ accountId: routingAccount.accountId,
815
+ peer
865
816
  });
866
- const discussionResolution = !isDirect && params.message.channel_id ? await resolveClickClackDiscussionRoute({
867
- runtime,
868
- accountId: params.account.accountId,
869
- serverBaseUrl: params.account.baseUrl,
870
- workspaceId: params.message.workspace_id,
871
- channelId: params.message.channel_id
872
- }) : { state: "unbound" };
817
+ const agentId = normalizeAgentId(routingAccount.agentId ?? accountRoute.agentId);
818
+ if (agentId !== accountRoute.agentId) {
819
+ const dmScope = routingConfig.session?.dmScope ?? "main";
820
+ const sessionKey = routeRuntime.channel.routing.buildAgentSessionKey({
821
+ agentId,
822
+ mainKey: routingConfig.session?.mainKey,
823
+ channel: CHANNEL_ID$2,
824
+ accountId: routingAccount.accountId,
825
+ peer,
826
+ dmScope,
827
+ identityLinks: routingConfig.session?.identityLinks
828
+ });
829
+ const mainSessionKey = routeRuntime.channel.routing.buildAgentSessionKey({
830
+ agentId,
831
+ mainKey: routingConfig.session?.mainKey,
832
+ channel: CHANNEL_ID$2,
833
+ accountId: routingAccount.accountId,
834
+ dmScope: "main"
835
+ });
836
+ accountRoute = {
837
+ ...accountRoute,
838
+ agentId,
839
+ dmScope,
840
+ sessionKey,
841
+ mainSessionKey,
842
+ lastRoutePolicy: sessionKey === mainSessionKey ? "main" : "session"
843
+ };
844
+ }
845
+ const discussionResolution = await (!isDirect && routingMessage.channel_id ? resolveClickClackDiscussionRoute({
846
+ runtime: routeRuntime,
847
+ accountId: routingAccount.accountId,
848
+ serverBaseUrl: routingAccount.baseUrl,
849
+ workspaceId: routingMessage.workspace_id,
850
+ channelId: routingMessage.channel_id
851
+ }) : { state: "unbound" });
873
852
  const discussionRoute = discussionResolution.state === "active" ? discussionResolution.route : void 0;
874
- return {
853
+ const preparedRoute = {
875
854
  isDirect,
876
855
  target,
877
856
  route: discussionRoute ? {
@@ -883,28 +862,44 @@ async function resolvePreparedInboundRoute(params) {
883
862
  discussionRoute,
884
863
  revoked: discussionResolution.state === "revoked"
885
864
  };
886
- }
887
- async function resolveClickClackInboundAccess(params) {
888
- const runtime = getClickClackRuntime();
889
- const rootPolicyConfigured = resolveClickClackGroupPolicy({
890
- account: params.account,
891
- channelId: params.message.channel_id
892
- }).requireMentionInBotThreads !== void 0;
893
- const isCurrent = () => isClickClackAccountCurrent({
894
- cfg: runtime.config.current(),
895
- account: params.account
896
- });
897
- const isBotOwnedThread = rootPolicyConfigured && await isClickClackBotOwnedThread(params);
898
- const routeConfig = rootPolicyConfigured ? runtime.config.current() : params.config;
899
- const routeAccountConfig = rootPolicyConfigured ? resolveClickClackAccountConfig(routeConfig, params.account.accountId) : params.account;
900
- const preparedRoute = await resolvePreparedInboundRoute({
901
- ...params,
902
- config: routeConfig,
903
- account: {
904
- ...params.account,
905
- agentId: routeAccountConfig.agentId
906
- }
907
- });
865
+ const resolveMentionFacts = (mentionConfig, mentionPatterns) => {
866
+ if (preparedRoute.isDirect) return {
867
+ canDetectMention: false,
868
+ wasMentioned: false
869
+ };
870
+ const body = params.message.body;
871
+ if (!body) return {
872
+ canDetectMention: true,
873
+ wasMentioned: false,
874
+ hasAnyMention: false
875
+ };
876
+ const sharedMentionRegexes = (0, channel_mention_gating_exports.buildMentionRegexes)(mentionConfig, preparedRoute.route.agentId, {
877
+ provider: CHANNEL_ID$2,
878
+ conversationId: params.message.channel_id
879
+ });
880
+ const localMentionRegexes = mentionPatterns.length ? (0, channel_mention_gating_exports.buildMentionRegexes)({
881
+ ...mentionConfig,
882
+ messages: {
883
+ ...mentionConfig.messages,
884
+ groupChat: {
885
+ ...mentionConfig.messages?.groupChat,
886
+ mentionPatterns
887
+ }
888
+ }
889
+ }, void 0, {
890
+ provider: CHANNEL_ID$2,
891
+ conversationId: params.message.channel_id
892
+ }) : [];
893
+ const bodyForRegex = (0, channel_mention_gating_exports.normalizeMentionText)(body);
894
+ const hasConfiguredMention = [...sharedMentionRegexes, ...localMentionRegexes].some((regex) => regex.test(bodyForRegex));
895
+ const mentionHandles = [...body.matchAll(CLICKCLACK_MENTION_PATTERN)].map((match) => match[1]?.toLowerCase()).filter((handle) => Boolean(handle));
896
+ const botHandle = params.account.botHandle?.replace(/^@/u, "").trim().toLowerCase();
897
+ return {
898
+ canDetectMention: true,
899
+ wasMentioned: (botHandle ? mentionHandles.includes(botHandle) : false) || hasConfiguredMention,
900
+ hasAnyMention: mentionHandles.length > 0 || hasConfiguredMention
901
+ };
902
+ };
908
903
  const cfg = rootPolicyConfigured ? runtime.config.current() : params.config;
909
904
  const accountPolicy = rootPolicyConfigured ? resolveClickClackAccountConfig(cfg, params.account.accountId) : params.account;
910
905
  const effectiveGroupPolicy = resolveClickClackGroupPolicy({
@@ -917,16 +912,10 @@ async function resolveClickClackInboundAccess(params) {
917
912
  requireMention: effectiveGroupPolicy.requireMention
918
913
  });
919
914
  const shouldCheckCommand = runtime.channel.commands.shouldComputeCommandAuthorized(params.message.body, cfg);
920
- const mentionFacts = resolveClickClackMentionFacts({
921
- isDirect: preparedRoute.isDirect,
922
- body: params.message.body,
923
- mentionPatterns: effectiveGroupPolicy.mentionPatterns,
924
- botHandle: params.account.botHandle,
925
- cfg,
926
- agentId: preparedRoute.route.agentId,
927
- channelId: params.message.channel_id
928
- });
929
- if (!isCurrent() || params.message.kind !== void 0 && params.message.kind !== "message") return {
915
+ const mentionFacts = resolveMentionFacts(cfg, effectiveGroupPolicy.mentionPatterns);
916
+ const isBotAuthor = params.message.author?.kind === "bot";
917
+ const botMentionAllowed = !isBotAuthor || effectiveGroupPolicy.allowBots === true || effectiveGroupPolicy.allowBots === "mentions" && (preparedRoute.isDirect || mentionFacts.wasMentioned);
918
+ if (!isCurrent() || params.message.kind !== void 0 && params.message.kind !== "message" || !botMentionAllowed) return {
930
919
  shouldDispatch: false,
931
920
  isCurrent,
932
921
  commandAuthorized: false,
@@ -934,24 +923,12 @@ async function resolveClickClackInboundAccess(params) {
934
923
  mentionFacts,
935
924
  preparedRoute
936
925
  };
937
- const isBotAuthor = params.message.author?.kind === "bot";
938
926
  const allowFrom = accountPolicy.allowFrom ?? ["*"];
939
927
  const ingressAllowFrom = isBotAuthor ? allowFrom.filter((entry) => normalizeClickClackUserId(entry) !== "*") : allowFrom;
940
- if (!(!isBotAuthor || effectiveGroupPolicy.allowBots === true || effectiveGroupPolicy.allowBots === "mentions" && (preparedRoute.isDirect || mentionFacts.wasMentioned))) return {
941
- shouldDispatch: false,
942
- isCurrent,
943
- commandAuthorized: false,
944
- requireMention: threadMentionPolicy.requireMention,
945
- mentionFacts,
946
- preparedRoute
947
- };
948
928
  const botLoopNowMs = parseDateStringTimestampMs(params.message.created_at);
949
929
  const botLoopProtection = isBotAuthor && params.message.author_id !== params.account.botUserId && params.account.botUserId ? {
950
930
  scopeId: params.account.workspace,
951
- conversationId: resolveClickClackBotLoopConversationId({
952
- message: params.message,
953
- isDirect: preparedRoute.isDirect
954
- }),
931
+ conversationId: params.message.parent_message_id && params.message.thread_root_id ? params.message.thread_root_id : preparedRoute.isDirect ? params.message.direct_conversation_id ?? params.message.author_id : params.message.channel_id ?? params.message.thread_root_id ?? params.message.author_id,
955
932
  senderId: params.message.author_id,
956
933
  receiverId: params.account.botUserId,
957
934
  eventId: params.message.id,
@@ -992,7 +969,8 @@ async function resolveClickClackInboundAccess(params) {
992
969
  } },
993
970
  command: shouldCheckCommand ? {
994
971
  cfg,
995
- modeWhenAccessGroupsOff: "configured"
972
+ modeWhenAccessGroupsOff: "configured",
973
+ hasControlCommand: runtime.channel.text.hasControlCommand(params.message.body, cfg)
996
974
  } : false
997
975
  });
998
976
  const isAdmissionCurrent = () => {
@@ -1022,15 +1000,7 @@ async function resolveClickClackInboundAccess(params) {
1022
1000
  return group?.type === "message.senders" && resolved.state.allowlists[preparedRoute.isDirect ? "dm" : "group"].accessGroups.matched.includes(name) && isDeepStrictEqual(group, cfg.accessGroups?.[name]);
1023
1001
  });
1024
1002
  if (!directSenderAllowed && !staticGroupAllowed) return false;
1025
- const currentMentionFacts = resolveClickClackMentionFacts({
1026
- isDirect: preparedRoute.isDirect,
1027
- body: params.message.body,
1028
- mentionPatterns: currentGroupPolicy.mentionPatterns,
1029
- botHandle: params.account.botHandle,
1030
- cfg: currentCfg,
1031
- agentId: preparedRoute.route.agentId,
1032
- channelId: params.message.channel_id
1033
- });
1003
+ const currentMentionFacts = resolveMentionFacts(currentCfg, currentGroupPolicy.mentionPatterns);
1034
1004
  if (isBotAuthor && currentGroupPolicy.allowBots !== true && !(currentGroupPolicy.allowBots === "mentions" && (preparedRoute.isDirect || currentMentionFacts.wasMentioned))) return false;
1035
1005
  const currentThreadPolicy = resolveBotThreadMentionPolicy({
1036
1006
  isBotOwnedThread,
@@ -1047,7 +1017,7 @@ async function resolveClickClackInboundAccess(params) {
1047
1017
  surface: CHANNEL_ID$2,
1048
1018
  commandSource: "text"
1049
1019
  }),
1050
- hasControlCommand: shouldCheckCommand && runtime.channel.commands.shouldComputeCommandAuthorized(params.message.body, currentCfg),
1020
+ hasControlCommand: shouldCheckCommand && runtime.channel.text.hasControlCommand(params.message.body, currentCfg),
1051
1021
  commandAuthorized: resolved.commandAccess.authorized
1052
1022
  }
1053
1023
  }).shouldSkip;
@@ -1064,62 +1034,6 @@ async function resolveClickClackInboundAccess(params) {
1064
1034
  };
1065
1035
  }
1066
1036
  //#endregion
1067
- //#region extensions/clickclack/src/command-menu.ts
1068
- const CLICKCLACK_COMMAND_PATTERN = /^[a-z0-9_-]{1,32}$/u;
1069
- const CLICKCLACK_MAX_COMMANDS = 100;
1070
- const CLICKCLACK_MAX_DESCRIPTION_LENGTH = 100;
1071
- const CLICKCLACK_MAX_ARGS_HINT_LENGTH = 100;
1072
- function commandArgsHint(spec) {
1073
- if (spec.args?.length) return truncateCodePoints(spec.args.map((arg) => arg.required ? `<${arg.name}>` : `[${arg.name}]`).join(" "), CLICKCLACK_MAX_ARGS_HINT_LENGTH);
1074
- return spec.acceptsArgs ? "[args]" : "";
1075
- }
1076
- function errorStatus(error) {
1077
- if (!error || typeof error !== "object" || !("status" in error)) return;
1078
- const status = error.status;
1079
- return typeof status === "number" ? status : void 0;
1080
- }
1081
- function mapNativeCommandSpecsToClickClackMenu(specs, log) {
1082
- const commands = [];
1083
- const seen = /* @__PURE__ */ new Set();
1084
- const invalidNames = /* @__PURE__ */ new Set();
1085
- for (const spec of specs) {
1086
- if (spec.isAlias) continue;
1087
- const command = spec.name.trim().toLowerCase();
1088
- if (!CLICKCLACK_COMMAND_PATTERN.test(command)) {
1089
- invalidNames.add(spec.name.trim() || "<empty>");
1090
- continue;
1091
- }
1092
- if (seen.has(command)) continue;
1093
- seen.add(command);
1094
- const description = spec.description.trim() || command;
1095
- commands.push({
1096
- command,
1097
- description: truncateCodePoints(description, CLICKCLACK_MAX_DESCRIPTION_LENGTH),
1098
- args_hint: commandArgsHint(spec)
1099
- });
1100
- }
1101
- if (invalidNames.size > 0) log?.warn?.(`ClickClack command menu skipped invalid native command names: ${[...invalidNames].map((name) => JSON.stringify(name)).join(", ")}`);
1102
- return commands.slice(0, CLICKCLACK_MAX_COMMANDS);
1103
- }
1104
- async function syncClickClackCommandMenu(params) {
1105
- try {
1106
- const commands = mapNativeCommandSpecsToClickClackMenu(listNativeCommandSpecsForConfig(params.cfg, { provider: "clickclack" }), params.log);
1107
- await params.client.setBotCommands(commands);
1108
- } catch (error) {
1109
- const status = errorStatus(error);
1110
- const messagePrefix = `[${params.accountId}] ClickClack command menu sync`;
1111
- if (status === 403) {
1112
- params.log?.warn?.(`${messagePrefix} skipped: ${formatErrorMessage(error)}; verify token/workspace command permissions or set commandMenu: false if menus are not needed`);
1113
- return;
1114
- }
1115
- if (status === 404) {
1116
- params.log?.debug?.(`${messagePrefix} skipped: server does not support /api/bots/self/commands`);
1117
- return;
1118
- }
1119
- params.log?.warn?.(`${messagePrefix} failed: ${formatErrorMessage(error)}`);
1120
- }
1121
- }
1122
- //#endregion
1123
1037
  //#region extensions/clickclack/src/activity.ts
1124
1038
  const CLICKCLACK_COMMENTARY_FLUSH_MS = 700;
1125
1039
  /** Item kinds rendered as agent_tool rows; everything else is commentary. */
@@ -1149,31 +1063,11 @@ const THINKING_ITEM_KINDS = /* @__PURE__ */ new Set([
1149
1063
  function normalizedItemKind(payload) {
1150
1064
  return payload.kind?.trim().toLowerCase() ?? "";
1151
1065
  }
1152
- function commentaryBody(payload) {
1153
- const text = payload.progressText?.trim() || payload.summary?.trim() || payload.meta?.trim() || "";
1154
- if (!text) return "";
1155
- const kind = normalizedItemKind(payload);
1156
- if (THINKING_ITEM_KINDS.has(kind)) return `**Thinking**\n\n${text}`;
1157
- return text;
1158
- }
1159
- function activityBody(payload) {
1160
- const line = formatChannelProgressDraftLineForEntry(void 0, {
1161
- ...payload,
1162
- event: "item",
1163
- itemKind: payload.kind
1164
- })?.trim();
1165
- if (line) return line;
1166
- const head = payload.name?.trim() || payload.title?.trim();
1167
- const text = payload.progressText?.trim() || payload.summary?.trim();
1168
- if (head && text) return `**${head}**\n\n${text}`;
1169
- return text || head || payload.status?.trim() || payload.kind?.trim() || "";
1170
- }
1171
1066
  /**
1172
1067
  * Creates a per-turn activity publisher. Publishing is best-effort: transport
1173
1068
  * failures are reported through `onError` and never interrupt the reply turn.
1174
1069
  */
1175
1070
  function createClickClackActivityPublisher(params) {
1176
- const flushMs = params.flushMs ?? CLICKCLACK_COMMENTARY_FLUSH_MS;
1177
1071
  const commentaryByItem = /* @__PURE__ */ new Map();
1178
1072
  const toolRows = /* @__PURE__ */ new Map();
1179
1073
  let provenance;
@@ -1195,10 +1089,8 @@ function createClickClackActivityPublisher(params) {
1195
1089
  const flushCommentary = (segmentKey) => {
1196
1090
  const segment = commentaryByItem.get(segmentKey);
1197
1091
  if (!segment) return Promise.resolve();
1198
- if (segment.timer) {
1199
- clearTimeout(segment.timer);
1200
- segment.timer = void 0;
1201
- }
1092
+ clearTimeout(segment.timer);
1093
+ segment.timer = void 0;
1202
1094
  if (!segment.dirty || !segment.body) return Promise.resolve();
1203
1095
  segment.dirty = false;
1204
1096
  const body = segment.body;
@@ -1216,7 +1108,8 @@ function createClickClackActivityPublisher(params) {
1216
1108
  return Promise.all(flushes).then(() => void 0);
1217
1109
  };
1218
1110
  const handleCommentary = (payload) => {
1219
- const body = commentaryBody(payload);
1111
+ const text = payload.progressText?.trim() || payload.summary?.trim() || payload.meta?.trim() || "";
1112
+ const body = text && THINKING_ITEM_KINDS.has(normalizedItemKind(payload)) ? `**Thinking**\n\n${text}` : text;
1220
1113
  const key = payload.itemId?.trim() || "turn";
1221
1114
  let segment = commentaryByItem.get(key);
1222
1115
  if (!body) {
@@ -1243,13 +1136,22 @@ function createClickClackActivityPublisher(params) {
1243
1136
  if (!segment.timer) segment.timer = setTimeout(() => {
1244
1137
  segment.timer = void 0;
1245
1138
  flushCommentary(key);
1246
- }, flushMs);
1139
+ }, CLICKCLACK_COMMENTARY_FLUSH_MS);
1247
1140
  };
1248
1141
  const toolRowKey = (payload) => {
1249
1142
  return payload.itemId?.trim() || payload.toolCallId?.trim() || "";
1250
1143
  };
1251
1144
  const handleDiscreteItem = (payload) => {
1252
- const body = activityBody(payload);
1145
+ let body = formatChannelProgressDraftLineForEntry(void 0, {
1146
+ ...payload,
1147
+ event: "item",
1148
+ itemKind: payload.kind
1149
+ });
1150
+ if (!body) {
1151
+ const head = payload.name?.trim() || payload.title?.trim();
1152
+ const text = payload.progressText?.trim() || payload.summary?.trim();
1153
+ body = head && text ? `**${head}**\n\n${text}` : text || head || payload.status?.trim() || payload.kind?.trim() || "";
1154
+ }
1253
1155
  if (!body) return;
1254
1156
  const kind = TOOL_ITEM_KINDS.has(normalizedItemKind(payload)) ? "agent_tool" : "agent_commentary";
1255
1157
  flushAllCommentary();
@@ -1260,9 +1162,10 @@ function createClickClackActivityPublisher(params) {
1260
1162
  const row = { body };
1261
1163
  if (itemKey) toolRows.set(key, row);
1262
1164
  enqueue(async () => {
1263
- const posted = await postRow(kind, row.body);
1165
+ const submittedBody = row.body;
1166
+ const posted = await postRow(kind, submittedBody);
1264
1167
  row.messageId = posted.id;
1265
- row.sentBody = row.body;
1168
+ row.sentBody = submittedBody;
1266
1169
  });
1267
1170
  return;
1268
1171
  }
@@ -1270,8 +1173,9 @@ function createClickClackActivityPublisher(params) {
1270
1173
  existing.body = body;
1271
1174
  enqueue(async () => {
1272
1175
  if (existing.messageId && existing.body !== existing.sentBody) {
1273
- await params.client.updateMessageBody(existing.messageId, existing.body);
1274
- existing.sentBody = existing.body;
1176
+ const submittedBody = existing.body;
1177
+ await params.client.updateMessageBody(existing.messageId, submittedBody);
1178
+ existing.sentBody = submittedBody;
1275
1179
  }
1276
1180
  });
1277
1181
  };
@@ -1346,7 +1250,7 @@ async function createTargetMessage(params) {
1346
1250
  function durableDeliveryDigest(params) {
1347
1251
  if (!params.deliveryQueueId) return;
1348
1252
  if (!Number.isSafeInteger(params.deliveryPartIndex) || (params.deliveryPartIndex ?? -1) < 0) throw new Error("ClickClack durable delivery requires a stable delivery part index");
1349
- return createHash("sha256").update(`${params.deliveryQueueId}\n${params.deliveryPartIndex}`).digest("hex");
1253
+ return sha256Hex(`${params.deliveryQueueId}\n${params.deliveryPartIndex}`);
1350
1254
  }
1351
1255
  function mediaDeliveryNonces(params) {
1352
1256
  const digest = durableDeliveryDigest(params);
@@ -1594,7 +1498,7 @@ function progressText(payload) {
1594
1498
  ...payload,
1595
1499
  event: "item",
1596
1500
  itemKind: payload.kind
1597
- })?.text?.trim();
1501
+ })?.text;
1598
1502
  if (line) return line;
1599
1503
  return payload.progressText?.trim() || payload.summary?.trim() || payload.title?.trim() || payload.name?.trim() || payload.meta?.trim() || payload.status?.trim() || "Working";
1600
1504
  }
@@ -1639,25 +1543,18 @@ function createClickClackAgentProgressPublisher(params) {
1639
1543
  const drain = () => {
1640
1544
  if (drainPromise) return drainPromise;
1641
1545
  drainPromise = (async () => {
1642
- while (queue.length > 0) {
1643
- const frame = queue.shift();
1644
- if (!frame) continue;
1645
- if (frame.lineId) queuedLines.delete(frame.lineId);
1646
- try {
1647
- await params.client.publishEphemeral({
1648
- ...params.target,
1649
- type: "agent.progress",
1650
- payload: {
1651
- turn_id: params.turnId,
1652
- seq: ++sequence,
1653
- ...frame.payload
1654
- }
1655
- });
1656
- } catch (error) {
1657
- try {
1658
- params.onError?.(error);
1659
- } catch {}
1660
- }
1546
+ for (let frame = queue.shift(); frame; frame = queue.shift()) try {
1547
+ await params.client.publishEphemeral({
1548
+ ...params.target,
1549
+ type: "agent.progress",
1550
+ payload: {
1551
+ turn_id: params.turnId,
1552
+ seq: ++sequence,
1553
+ ...frame.payload
1554
+ }
1555
+ });
1556
+ } catch (error) {
1557
+ params.onError?.(error);
1661
1558
  }
1662
1559
  })().finally(() => {
1663
1560
  drainPromise = void 0;
@@ -1723,25 +1620,26 @@ function createClickClackAgentProgressPublisher(params) {
1723
1620
  if (!started || cleared) return false;
1724
1621
  if (payload.suppressChannelProgress || payload.kind === "preamble" && !isCompleteAgentPreamble(payload)) return false;
1725
1622
  const id = resolveLineId(payload);
1726
- if (payload.hideFromChannelProgress) {
1623
+ const kind = normalizedKind(payload);
1624
+ const hidesLine = payload.hideFromChannelProgress || payload.kind === "model-wait" && payload.phase === "end";
1625
+ const retractsExistingCommentary = kind === "commentary" && seenLines.has(id) && payload.progressText !== void 0 && payload.progressText.trim() === "";
1626
+ if ((hidesLine || retractsExistingCommentary) && queuedLines.get(id)?.payload.op === "append") {
1627
+ queuedLines.delete(id);
1628
+ seenLines.delete(id);
1629
+ return false;
1630
+ }
1631
+ if (hidesLine) {
1727
1632
  if (seenLines.delete(id)) enqueueLine(id, {
1728
1633
  op: "update",
1729
1634
  line: {
1730
1635
  id,
1731
- kind: normalizedKind(payload),
1636
+ kind,
1732
1637
  text: ""
1733
1638
  }
1734
1639
  });
1735
1640
  return false;
1736
1641
  }
1737
1642
  const final = isFinal(payload);
1738
- const kind = normalizedKind(payload);
1739
- const retractsExistingCommentary = kind === "commentary" && seenLines.has(id) && payload.progressText !== void 0 && payload.progressText.trim() === "";
1740
- if (retractsExistingCommentary && queuedLines.get(id)?.payload.op === "append") {
1741
- queuedLines.delete(id);
1742
- seenLines.delete(id);
1743
- return false;
1744
- }
1745
1643
  const line = {
1746
1644
  id,
1747
1645
  kind,
@@ -1779,49 +1677,6 @@ function hasClickClackReplyMedia(payload) {
1779
1677
  function resolveClickClackAgentRunId(messageId) {
1780
1678
  return CLICKCLACK_MESSAGE_ID_PATTERN.test(messageId) ? `${CHANNEL_ID$1}:${messageId}` : void 0;
1781
1679
  }
1782
- async function dispatchModelReply(params) {
1783
- const runtime = getClickClackRuntime();
1784
- const result = await runtime.llm.complete({
1785
- agentId: params.route.agentId,
1786
- model: params.account.model,
1787
- purpose: "clickclack bot reply",
1788
- systemPrompt: params.account.systemPrompt,
1789
- messages: [{
1790
- role: "user",
1791
- content: params.message.body
1792
- }]
1793
- });
1794
- const completion = result.text.trim();
1795
- if (!completion) {
1796
- runtime.logging.getChildLogger({
1797
- plugin: "clickclack",
1798
- feature: "model-reply"
1799
- }).warn(`[${params.account.accountId}] ClickClack model reply produced no sendable text`);
1800
- return;
1801
- }
1802
- const replyPipeline = createChannelMessageReplyPipeline({
1803
- cfg: params.cfg,
1804
- agentId: params.route.agentId,
1805
- channel: CHANNEL_ID$1,
1806
- accountId: params.account.accountId
1807
- });
1808
- replyPipeline.onModelSelected?.({
1809
- provider: result.provider,
1810
- model: result.model,
1811
- thinkLevel: void 0
1812
- });
1813
- const responsePrefix = replyPipeline.resolveResponsePrefix?.();
1814
- const text = responsePrefix && !completion.startsWith(responsePrefix) ? `${responsePrefix} ${completion}` : completion;
1815
- await sendClickClackText({
1816
- cfg: params.cfg,
1817
- accountId: params.account.accountId,
1818
- to: params.target,
1819
- text,
1820
- threadId: params.message.parent_message_id ? params.message.thread_root_id : void 0,
1821
- replyToId: params.message.id,
1822
- correlationId: params.correlationId
1823
- });
1824
- }
1825
1680
  async function handleClickClackInbound(params) {
1826
1681
  const runtime = getClickClackRuntime();
1827
1682
  const message = params.message;
@@ -1848,7 +1703,7 @@ async function handleClickClackInbound(params) {
1848
1703
  conversationId
1849
1704
  },
1850
1705
  turnId: message.id,
1851
- agentLabel: params.account.name?.trim() || params.account.botHandle?.trim() || params.account.agentId?.trim() || params.account.accountId,
1706
+ agentLabel: params.account.name || params.account.botHandle?.trim() || params.account.agentId || params.account.accountId,
1852
1707
  onError: (error) => {
1853
1708
  runtime.logging.getChildLogger({
1854
1709
  plugin: "clickclack",
@@ -1869,13 +1724,49 @@ async function handleClickClackInbound(params) {
1869
1724
  }
1870
1725
  progress?.start();
1871
1726
  try {
1872
- await dispatchModelReply({
1873
- account: params.account,
1874
- cfg: params.config,
1875
- message,
1876
- route,
1877
- target,
1878
- correlationId: params.correlationId
1727
+ const modelAccount = params.account;
1728
+ const modelConfig = params.config;
1729
+ const correlationId = params.correlationId;
1730
+ const modelRuntime = getClickClackRuntime();
1731
+ const result = await modelRuntime.llm.complete({
1732
+ agentId: route.agentId,
1733
+ model: modelAccount.model,
1734
+ purpose: "clickclack bot reply",
1735
+ systemPrompt: modelAccount.systemPrompt,
1736
+ messages: [{
1737
+ role: "user",
1738
+ content: message.body
1739
+ }]
1740
+ });
1741
+ const completion = result.text.trim();
1742
+ if (!completion) {
1743
+ modelRuntime.logging.getChildLogger({
1744
+ plugin: "clickclack",
1745
+ feature: "model-reply"
1746
+ }).warn(`[${modelAccount.accountId}] ClickClack model reply produced no sendable text`);
1747
+ return;
1748
+ }
1749
+ const replyPipeline = createChannelMessageReplyPipeline({
1750
+ cfg: modelConfig,
1751
+ agentId: route.agentId,
1752
+ channel: CHANNEL_ID$1,
1753
+ accountId: modelAccount.accountId
1754
+ });
1755
+ replyPipeline.onModelSelected?.({
1756
+ provider: result.provider,
1757
+ model: result.model,
1758
+ thinkLevel: void 0
1759
+ });
1760
+ const responsePrefix = replyPipeline.resolveResponsePrefix?.();
1761
+ const text = responsePrefix && !completion.startsWith(responsePrefix) ? `${responsePrefix} ${completion}` : completion;
1762
+ await sendClickClackText({
1763
+ cfg: modelConfig,
1764
+ accountId: modelAccount.accountId,
1765
+ to: target,
1766
+ text,
1767
+ threadId: message.parent_message_id ? message.thread_root_id : void 0,
1768
+ replyToId: message.id,
1769
+ correlationId
1879
1770
  });
1880
1771
  } finally {
1881
1772
  await progress?.finalize();
@@ -2043,6 +1934,37 @@ async function handleClickClackInbound(params) {
2043
1934
  //#endregion
2044
1935
  //#region extensions/clickclack/src/gateway.ts
2045
1936
  const CLICKCLACK_EVENT_PAGE_LIMIT = 500;
1937
+ const CLICKCLACK_COMMAND_PATTERN = /^[a-z0-9_-]{1,32}$/u;
1938
+ const CLICKCLACK_MAX_COMMANDS = 100;
1939
+ const CLICKCLACK_MAX_DESCRIPTION_LENGTH = 100;
1940
+ const CLICKCLACK_MAX_ARGS_HINT_LENGTH = 100;
1941
+ function commandArgsHint(spec) {
1942
+ if (spec.args?.length) return truncateCodePoints(spec.args.map((arg) => arg.required ? `<${arg.name}>` : `[${arg.name}]`).join(" "), CLICKCLACK_MAX_ARGS_HINT_LENGTH);
1943
+ return spec.acceptsArgs ? "[args]" : "";
1944
+ }
1945
+ function mapNativeCommandSpecsToClickClackMenu(specs, log) {
1946
+ const commands = [];
1947
+ const seen = /* @__PURE__ */ new Set();
1948
+ const invalidNames = /* @__PURE__ */ new Set();
1949
+ for (const spec of specs) {
1950
+ if (spec.isAlias) continue;
1951
+ const command = spec.name.trim().toLowerCase();
1952
+ if (!CLICKCLACK_COMMAND_PATTERN.test(command)) {
1953
+ invalidNames.add(spec.name.trim() || "<empty>");
1954
+ continue;
1955
+ }
1956
+ if (seen.has(command)) continue;
1957
+ seen.add(command);
1958
+ const description = spec.description.trim() || command;
1959
+ commands.push({
1960
+ command,
1961
+ description: truncateCodePoints(description, CLICKCLACK_MAX_DESCRIPTION_LENGTH),
1962
+ args_hint: commandArgsHint(spec)
1963
+ });
1964
+ }
1965
+ if (invalidNames.size > 0) log?.warn?.(`ClickClack command menu skipped invalid native command names: ${[...invalidNames].map((name) => JSON.stringify(name)).join(", ")}`);
1966
+ return commands.slice(0, CLICKCLACK_MAX_COMMANDS);
1967
+ }
2046
1968
  function payloadString(event, key) {
2047
1969
  return readStringField(event.payload, key) ?? "";
2048
1970
  }
@@ -2056,66 +1978,6 @@ async function resolveEventMessage(params) {
2056
1978
  throw error;
2057
1979
  }
2058
1980
  }
2059
- function parseSocketEvent(data) {
2060
- try {
2061
- return JSON.parse(rawDataToString(data));
2062
- } catch {
2063
- return null;
2064
- }
2065
- }
2066
- async function processEvent(params) {
2067
- if (params.event.type !== "message.created" && params.event.type !== "thread.reply_created") return;
2068
- if (params.abortSignal.aborted || payloadString(params.event, "author_id") === params.botUserId) return;
2069
- const correlationId = normalizeClickClackCorrelationId(params.event.payload?.correlation_id);
2070
- const message = await resolveEventMessage({
2071
- client: correlationId ? createClickClackClient({
2072
- baseUrl: params.account.apiEndpoint,
2073
- token: params.account.token,
2074
- correlationId
2075
- }) : params.client,
2076
- event: params.event
2077
- });
2078
- if (!message) {
2079
- params.log?.warn?.(`[${params.account.accountId}] skipped unreadable ClickClack message before agent dispatch: type=${params.event.type} messageId=${payloadString(params.event, "message_id") || "unknown"}`);
2080
- return;
2081
- }
2082
- if (params.abortSignal.aborted || message.author_id === params.botUserId) return;
2083
- const access = await resolveClickClackInboundAccess({
2084
- account: params.account,
2085
- config: params.config,
2086
- message
2087
- });
2088
- if (params.abortSignal.aborted) return;
2089
- if (!access.shouldDispatch) {
2090
- params.log?.info(`[${params.account.accountId}] skipped ClickClack message before agent dispatch: kind=${message.direct_conversation_id ? "dm" : "group"} requireMention=${access.requireMention ?? "unknown"} wasMentioned=${access.mentionFacts.wasMentioned} hasAnyMention=${access.mentionFacts.hasAnyMention ?? "unknown"} commandAuthorized=${access.commandAuthorized}`);
2091
- return;
2092
- }
2093
- await handleClickClackInbound({
2094
- account: params.account,
2095
- config: params.config,
2096
- message,
2097
- access,
2098
- buildContext: params.buildContext,
2099
- ...correlationId ? { correlationId } : {}
2100
- });
2101
- }
2102
- async function drainEventBacklog(params) {
2103
- let afterCursor = params.afterCursor;
2104
- while (!params.abortSignal.aborted) {
2105
- const page = await params.client.eventPage(params.workspaceId, {
2106
- afterCursor,
2107
- limit: CLICKCLACK_EVENT_PAGE_LIMIT
2108
- });
2109
- for (const event of page.events) {
2110
- if (params.abortSignal.aborted) return afterCursor;
2111
- if (!event.cursor || event.cursor === afterCursor) throw new Error("ClickClack event backlog returned a non-advancing cursor");
2112
- await params.onEvent(event);
2113
- afterCursor = event.cursor;
2114
- }
2115
- if (page.events.length === 0) return afterCursor;
2116
- }
2117
- return afterCursor;
2118
- }
2119
1981
  async function startClickClackGatewayAccount(ctx) {
2120
1982
  const configuredAccount = resolveClickClackAccount({
2121
1983
  cfg: ctx.cfg,
@@ -2134,22 +1996,55 @@ async function startClickClackGatewayAccount(ctx) {
2134
1996
  botUserId: configuredAccount.botUserId ?? me.id,
2135
1997
  botHandle: me.handle
2136
1998
  };
2137
- const processIncomingEvent = (event) => processEvent({
2138
- abortSignal: ctx.abortSignal,
2139
- account,
2140
- config: ctx.cfg,
2141
- client,
2142
- event,
2143
- botUserId: account.botUserId,
2144
- buildContext: ctx.channelRuntime?.inbound.buildContext,
2145
- log: ctx.log
2146
- });
2147
- if (account.commandMenu) await syncClickClackCommandMenu({
2148
- cfg: ctx.cfg,
2149
- client,
2150
- log: ctx.log,
2151
- accountId: account.accountId
2152
- });
1999
+ const processIncomingEvent = async (event) => {
2000
+ const { abortSignal, cfg: config, log } = ctx;
2001
+ const botUserId = account.botUserId;
2002
+ const buildContext = ctx.channelRuntime?.inbound.buildContext;
2003
+ if (event.type !== "message.created" && event.type !== "thread.reply_created") return;
2004
+ if (abortSignal.aborted || payloadString(event, "author_id") === botUserId) return;
2005
+ const correlationId = normalizeClickClackCorrelationId(event.payload?.correlation_id);
2006
+ const message = await resolveEventMessage({
2007
+ client: correlationId ? createClickClackClient({
2008
+ baseUrl: account.apiEndpoint,
2009
+ token: account.token,
2010
+ correlationId
2011
+ }) : client,
2012
+ event
2013
+ });
2014
+ if (!message) {
2015
+ log?.warn?.(`[${account.accountId}] skipped unreadable ClickClack message before agent dispatch: type=${event.type} messageId=${payloadString(event, "message_id") || "unknown"}`);
2016
+ return;
2017
+ }
2018
+ if (abortSignal.aborted || message.author_id === botUserId) return;
2019
+ const access = await resolveClickClackInboundAccess({
2020
+ account,
2021
+ config,
2022
+ message
2023
+ });
2024
+ if (abortSignal.aborted) return;
2025
+ if (!access.shouldDispatch) {
2026
+ log?.info(`[${account.accountId}] skipped ClickClack message before agent dispatch: kind=${message.direct_conversation_id ? "dm" : "group"} requireMention=${access.requireMention ?? "unknown"} wasMentioned=${access.mentionFacts.wasMentioned} hasAnyMention=${access.mentionFacts.hasAnyMention ?? "unknown"} commandAuthorized=${access.commandAuthorized}`);
2027
+ return;
2028
+ }
2029
+ await handleClickClackInbound({
2030
+ account,
2031
+ config,
2032
+ message,
2033
+ access,
2034
+ buildContext,
2035
+ ...correlationId ? { correlationId } : {}
2036
+ });
2037
+ };
2038
+ if (account.commandMenu) try {
2039
+ const commands = mapNativeCommandSpecsToClickClackMenu(listNativeCommandSpecsForConfig(ctx.cfg, { provider: "clickclack" }), ctx.log);
2040
+ await client.setBotCommands(commands);
2041
+ } catch (error) {
2042
+ const status = error instanceof ClickClackHttpError ? error.status : void 0;
2043
+ const messagePrefix = `[${account.accountId}] ClickClack command menu sync`;
2044
+ if (status === 403) ctx.log?.warn?.(`${messagePrefix} skipped: ${formatErrorMessage(error)}; verify token/workspace command permissions or set commandMenu: false if menus are not needed`);
2045
+ else if (status === 404) ctx.log?.debug?.(`${messagePrefix} skipped: server does not support /api/bots/self/commands`);
2046
+ else ctx.log?.warn?.(`${messagePrefix} failed: ${formatErrorMessage(error)}`);
2047
+ }
2153
2048
  ctx.setStatus({
2154
2049
  accountId: account.accountId,
2155
2050
  running: true,
@@ -2167,13 +2062,19 @@ async function startClickClackGatewayAccount(ctx) {
2167
2062
  if (page.tailCursor !== void 0) afterCursor = page.tailCursor;
2168
2063
  else for (const event of page.events) afterCursor = event.cursor || afterCursor;
2169
2064
  initialized = true;
2170
- } else afterCursor = await drainEventBacklog({
2171
- client,
2172
- workspaceId,
2173
- afterCursor,
2174
- abortSignal: ctx.abortSignal,
2175
- onEvent: processIncomingEvent
2176
- });
2065
+ } else while (!ctx.abortSignal.aborted) {
2066
+ const page = await client.eventPage(workspaceId, {
2067
+ afterCursor,
2068
+ limit: CLICKCLACK_EVENT_PAGE_LIMIT
2069
+ });
2070
+ for (const event of page.events) {
2071
+ if (ctx.abortSignal.aborted) break;
2072
+ if (!event.cursor || event.cursor === afterCursor) throw new Error("ClickClack event backlog returned a non-advancing cursor");
2073
+ await processIncomingEvent(event);
2074
+ afterCursor = event.cursor;
2075
+ }
2076
+ if (page.events.length === 0) break;
2077
+ }
2177
2078
  if (ctx.abortSignal.aborted) break;
2178
2079
  const socket = client.websocket(workspaceId, afterCursor);
2179
2080
  await new Promise((resolve) => {
@@ -2182,9 +2083,11 @@ async function startClickClackGatewayAccount(ctx) {
2182
2083
  let loggedMessageFailure = false;
2183
2084
  let messageQueue = Promise.resolve();
2184
2085
  let removeAbortListener;
2086
+ let stopKeepalive;
2185
2087
  const finishSocketCycle = () => {
2186
2088
  if (settled) return;
2187
2089
  settled = true;
2090
+ stopKeepalive?.();
2188
2091
  removeAbortListener?.();
2189
2092
  removeAbortListener = void 0;
2190
2093
  resolve();
@@ -2211,12 +2114,16 @@ async function startClickClackGatewayAccount(ctx) {
2211
2114
  removeAbortListener = () => ctx.abortSignal.removeEventListener("abort", abort);
2212
2115
  socket.on("open", () => {
2213
2116
  ctx.setStatus(channelReadyPatch({ accountId: account.accountId }));
2117
+ stopKeepalive = startWebSocketKeepalive(socket, () => {
2118
+ ctx.log?.warn?.(`[${account.accountId}] ClickClack websocket heartbeat timed out; reconnecting`);
2119
+ socket.terminate();
2120
+ });
2214
2121
  });
2215
2122
  socket.on("message", (data) => {
2216
2123
  if (closing || settled) return;
2217
2124
  messageQueue = messageQueue.then(async () => {
2218
2125
  if (ctx.abortSignal.aborted) return;
2219
- const event = parseSocketEvent(data);
2126
+ const event = safeParseJson(rawDataToString(data));
2220
2127
  if (!event) {
2221
2128
  ctx.log?.warn?.(`[${account.accountId}] skipped malformed ClickClack websocket event`);
2222
2129
  return;
@@ -2265,6 +2172,10 @@ async function startClickClackGatewayAccount(ctx) {
2265
2172
  //#endregion
2266
2173
  //#region extensions/clickclack/src/channel.ts
2267
2174
  const CHANNEL_ID = CLICKCLACK_CHANNEL_ID;
2175
+ const clickClackTextMessageAdapter = createChannelMessageAdapterFromOutbound({ outbound: { sendText: async (ctx) => ({
2176
+ channel: CHANNEL_ID,
2177
+ ...await sendClickClackText(ctx)
2178
+ }) } });
2268
2179
  const clickClackMessageAdapter = defineChannelMessageAdapter({
2269
2180
  id: CHANNEL_ID,
2270
2181
  durableFinal: {
@@ -2283,26 +2194,7 @@ const clickClackMessageAdapter = defineChannelMessageAdapter({
2283
2194
  reconcileUnknownSend: reconcileClickClackUnknownSend
2284
2195
  },
2285
2196
  send: {
2286
- text: async (ctx) => {
2287
- const result = await sendClickClackText({
2288
- ...ctx,
2289
- cfg: ctx.cfg
2290
- });
2291
- const threadId = ctx.threadId == null ? void 0 : String(ctx.threadId);
2292
- const replyToId = ctx.replyToId ?? void 0;
2293
- return {
2294
- ...result,
2295
- receipt: createMessageReceiptFromOutboundResults({
2296
- results: "messageId" in result ? [{
2297
- channel: CHANNEL_ID,
2298
- messageId: result.messageId
2299
- }] : [],
2300
- threadId,
2301
- replyToId,
2302
- kind: "text"
2303
- })
2304
- };
2305
- },
2197
+ ...clickClackTextMessageAdapter.send,
2306
2198
  media: async (ctx) => {
2307
2199
  const messageId = await sendClickClackMedia({
2308
2200
  ...ctx,
@@ -2346,10 +2238,10 @@ const clickClackPlugin = createChatChannelPlugin({
2346
2238
  },
2347
2239
  messaging: {
2348
2240
  targetPrefixes: ["clickclack", "cc"],
2349
- normalizeTarget: normalizeClickClackTarget,
2241
+ normalizeTarget: (raw) => buildClickClackTarget(parseClickClackTarget(raw)),
2350
2242
  inferTargetChatType: ({ to }) => parseClickClackTarget(to).chatType,
2351
2243
  targetResolver: {
2352
- looksLikeId: looksLikeClickClackTarget,
2244
+ looksLikeId: (raw) => raw.trim().length > 0,
2353
2245
  hint: "<channel:name|dm:usr_id|thread:msg_id>"
2354
2246
  },
2355
2247
  resolveOutboundSessionRoute: ({ cfg, agentId, accountId, target, replyToId, threadId, currentSessionKey }) => {
@@ -2439,4 +2331,4 @@ const clickClackPlugin = createChatChannelPlugin({
2439
2331
  }
2440
2332
  });
2441
2333
  //#endregion
2442
- export { clearPendingDiscussionOpen as A, truncateDiscussionDisplayTitle as C, getClickClackDiscussionBindingStore as D, bindingMatchesActiveSessionIncarnation as E, listPendingDiscussionOpens as M, recordPendingDiscussionOpen as N, readDiscussionSessionEntry as O, reserveDiscussionBindingGeneration as P, slugifyDiscussionLabel as S, attachBindingToCurrentActiveSession as T, discussionExternalRef as _, setClickClackRuntime as a, isDiscussionSessionKey as b, isClickClackDiscussionChannelRevokedAsync as c, prepareClickClackDiscussionChannelRevocation as d, discussionAccounts as f, discussionCredentialFingerprint as g, resolveDiscussionBindingAccount as h, getClickClackRuntime as i, getPendingDiscussionOpen as j, clearDiscussionBindingGeneration as k, markClickClackDiscussionChannelIdentityRevoked as l, normalizedServerBaseUrl as m, buildClickClackTarget as n, clearClickClackDiscussionChannelRevoked as o, discussionInfoForBinding as p, parseClickClackTarget as r, isClickClackDiscussionChannelRevoked as s, clickClackPlugin as t, markClickClackDiscussionChannelRevoked as u, discussionSessionKey as v, MAX_RETAINED_DETACHED_DISCUSSION_BINDINGS as w, resolveDiscussionLabel as x, fallbackDiscussionLabel as y };
2334
+ export { clearDiscussionBindingGeneration as A, resolveDiscussionLabel as C, bindingMatchesActiveSessionIncarnation as D, attachBindingToCurrentActiveSession as E, reserveDiscussionBindingGeneration as F, getPendingDiscussionOpen as M, listPendingDiscussionOpens as N, getClickClackDiscussionBindingStore as O, recordPendingDiscussionOpen as P, isDiscussionSessionKey as S, truncateDiscussionDisplayTitle as T, resolveDiscussionBindingAccount as _, setClickClackRuntime as a, discussionSessionKey as b, clearClickClackDiscussionChannelRevoked as c, markClickClackDiscussionChannelIdentityRevoked as d, markClickClackDiscussionChannelRevoked as f, normalizedServerBaseUrl as g, discussionInfoForBinding as h, getClickClackRuntime as i, clearPendingDiscussionOpen as j, readDiscussionSessionEntry as k, isClickClackDiscussionChannelRevoked as l, discussionAccounts as m, buildClickClackTarget as n, prepareDiscussionSessionEntry as o, prepareClickClackDiscussionChannelRevocation as p, parseClickClackTarget as r, adoptLegacyMarkers as s, clickClackPlugin as t, isClickClackDiscussionChannelRevokedAsync as u, discussionCredentialFingerprint as v, slugifyDiscussionLabel as w, fallbackDiscussionLabel as x, discussionExternalRef as y };