@openclaw/clickclack 2026.10.10 → 2026.11.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/.setup/{channel-CaLQ1zSw.mjs → channel-ByAANbh8.mjs} +363 -504
  2. package/dist/.setup/{resolve-C2XmZanM.mjs → resolve-CRj6QjdF.mjs} +27 -41
  3. package/dist/.setup/{rolldown-runtime-nwUcYXjP.mjs → rolldown-runtime-782esTHO.mjs} +0 -1
  4. package/dist/.setup/{runtime-api-HO9-jJAP.mjs → runtime-api-BsRK-sfA.mjs} +324 -368
  5. package/dist/.setup/{setup-claim-D50o9egr.mjs → setup-claim-BAKxfObl.mjs} +4 -9
  6. package/dist/.setup/{setup-plugin-api-COv8knUv.mjs → setup-plugin-api-BTqE973B.mjs} +1 -1
  7. package/dist/.setup/setup-plugin-api-CfuhJJvK.mjs +1 -0
  8. package/dist/.setup/{setup-surface-BuNtdRQY.mjs → setup-surface-5wSYr6p2.mjs} +5 -5
  9. package/dist/.setup/{setup-verify-CSI-GwUA.mjs → setup-verify-IayKkFWq.mjs} +12 -24
  10. package/dist/.source-module-urls/aa673c321fe9be084b8926cbe5388ff5e2a41371389e19ca60a1983f2b634030.json +1 -1
  11. package/dist/api.js +3 -3
  12. package/dist/channel-plugin-api.js +1 -1
  13. package/dist/doctor-contract-api.js +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/runtime-api.js +4 -4
  16. package/dist/setup-entry.js +1 -1
  17. package/dist/setup-plugin-api.js +1 -1
  18. package/node_modules/zod/package.json +1 -1
  19. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  20. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  21. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  22. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  23. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  24. package/node_modules/zod/src/v4/core/util.ts +13 -0
  25. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  26. package/node_modules/zod/v4/core/compile.cjs +8 -0
  27. package/node_modules/zod/v4/core/compile.js +8 -0
  28. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  29. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  30. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  31. package/node_modules/zod/v4/core/schemas.js +30 -0
  32. package/node_modules/zod/v4/core/util.cjs +15 -0
  33. package/node_modules/zod/v4/core/util.d.cts +2 -0
  34. package/node_modules/zod/v4/core/util.d.ts +2 -0
  35. package/node_modules/zod/v4/core/util.js +14 -0
  36. package/node_modules/zod/v4/core/versions.cjs +1 -1
  37. package/node_modules/zod/v4/core/versions.js +1 -1
  38. package/package.json +5 -7
  39. package/dist/.setup/setup-plugin-api-wzfSSaGz.mjs +0 -1
  40. package/node_modules/ws/LICENSE +0 -20
  41. package/node_modules/ws/README.md +0 -548
  42. package/node_modules/ws/browser.js +0 -8
  43. package/node_modules/ws/index.js +0 -22
  44. package/node_modules/ws/lib/buffer-util.js +0 -131
  45. package/node_modules/ws/lib/constants.js +0 -19
  46. package/node_modules/ws/lib/event-target.js +0 -292
  47. package/node_modules/ws/lib/extension.js +0 -203
  48. package/node_modules/ws/lib/limiter.js +0 -55
  49. package/node_modules/ws/lib/permessage-deflate.js +0 -530
  50. package/node_modules/ws/lib/receiver.js +0 -743
  51. package/node_modules/ws/lib/sender.js +0 -607
  52. package/node_modules/ws/lib/stream.js +0 -161
  53. package/node_modules/ws/lib/subprotocol.js +0 -62
  54. package/node_modules/ws/lib/validation.js +0 -152
  55. package/node_modules/ws/lib/websocket-server.js +0 -562
  56. package/node_modules/ws/lib/websocket.js +0 -1421
  57. package/node_modules/ws/package.json +0 -74
  58. package/node_modules/ws/wrapper.mjs +0 -21
@@ -1,24 +1,23 @@
1
- import { h as resolveClickClackAccount, p as listClickClackAccountIds } from "./setup-surface-BuNtdRQY.mjs";
2
- import { A as clearPendingDiscussionOpen, C as truncateDiscussionDisplayTitle, D as getClickClackDiscussionBindingStore, E as bindingMatchesActiveSessionIncarnation, M as listPendingDiscussionOpens, N as recordPendingDiscussionOpen, O as readDiscussionSessionEntry, P as reserveDiscussionBindingGeneration, S as slugifyDiscussionLabel, T as attachBindingToCurrentActiveSession, _ as discussionExternalRef, b as isDiscussionSessionKey, c as isClickClackDiscussionChannelRevokedAsync, d as prepareClickClackDiscussionChannelRevocation, f as discussionAccounts, g as discussionCredentialFingerprint, h as resolveDiscussionBindingAccount, j as getPendingDiscussionOpen, k as clearDiscussionBindingGeneration, l as markClickClackDiscussionChannelIdentityRevoked, m as normalizedServerBaseUrl, o as clearClickClackDiscussionChannelRevoked, p as discussionInfoForBinding, s as isClickClackDiscussionChannelRevoked, u as markClickClackDiscussionChannelRevoked, v as discussionSessionKey, x as resolveDiscussionLabel, y as fallbackDiscussionLabel } from "./channel-CaLQ1zSw.mjs";
3
- import { a as createClickClackClient, i as ClickClackHttpError, o as isClickClackChannelNameConflict, t as findClickClackWorkspace } from "./resolve-C2XmZanM.mjs";
1
+ import { h as resolveClickClackAccount, p as listClickClackAccountIds } from "./setup-surface-5wSYr6p2.mjs";
2
+ import { A as clearPendingDiscussionOpen, C as slugifyDiscussionLabel, D as getClickClackDiscussionBindingStore, E as bindingMatchesActiveSessionIncarnation, M as listPendingDiscussionOpens, N as recordPendingDiscussionOpen, O as readDiscussionSessionEntry, P as reserveDiscussionBindingGeneration, S as resolveDiscussionLabel, T as attachBindingToCurrentActiveSession, _ as discussionCredentialFingerprint, b as fallbackDiscussionLabel, c as isClickClackDiscussionChannelRevoked, d as markClickClackDiscussionChannelRevoked, f as prepareClickClackDiscussionChannelRevocation, g as resolveDiscussionBindingAccount, h as normalizedServerBaseUrl, j as getPendingDiscussionOpen, k as clearDiscussionBindingGeneration, l as isClickClackDiscussionChannelRevokedAsync, m as discussionInfoForBinding, o as prepareDiscussionSessionEntry, p as discussionAccounts, s as clearClickClackDiscussionChannelRevoked, u as markClickClackDiscussionChannelIdentityRevoked, v as discussionExternalRef, w as truncateDiscussionDisplayTitle, x as isDiscussionSessionKey, y as discussionSessionKey } from "./channel-ByAANbh8.mjs";
3
+ import { a as createClickClackClient, i as ClickClackHttpError, o as isClickClackChannelNameConflict, t as findClickClackWorkspace } from "./resolve-CRj6QjdF.mjs";
4
4
  import "../api.js";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { createAsyncLock } from "openclaw/plugin-sdk/async-lock-runtime";
8
+ import { resolveSessionAgentIdStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
8
9
  import { buildControlUiSessionPath, registerSessionDiscussionProvider } from "openclaw/plugin-sdk/session-discussion";
9
10
  import { createSessionVisibilityChecker } from "openclaw/plugin-sdk/session-visibility";
10
- import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
11
- import { resolveSessionAgentIdStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
12
11
  import { textResult } from "openclaw/plugin-sdk/tool-results";
12
+ import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
13
13
  // extensions/clickclack/src/discussions/binding-retention.ts
14
+ const MAX_RETAINED_DETACHED_DISCUSSION_BINDINGS = 1e3;
14
15
  var DetachedDiscussionBindingRetention = class {
15
16
  #runtime;
16
17
  #store;
17
- #maxRetained;
18
18
  constructor(options) {
19
19
  this.#runtime = options.runtime;
20
20
  this.#store = options.store;
21
- this.#maxRetained = options.maxRetained;
22
21
  }
23
22
  async mark(sessionKey, binding) {
24
23
  const current = await this.#store.getAsync(sessionKey);
@@ -26,15 +25,15 @@ var DetachedDiscussionBindingRetention = class {
26
25
  if (current.detachedAt === void 0) await this.#store.setIfCurrent(sessionKey, current, {
27
26
  ...current,
28
27
  detachedAt: Date.now()
29
- }, { assertCurrent: () => this.#assertDetached(sessionKey, current) });
30
- while (this.#store.detachedCount() > this.#maxRetained) if (!await this.#pruneOldest()) throw new Error("ClickClack detached discussion binding retention could not be reduced");
28
+ });
29
+ while (this.#store.detachedCount() > MAX_RETAINED_DETACHED_DISCUSSION_BINDINGS) if (!await this.#pruneOldest()) throw new Error("ClickClack detached discussion binding retention could not be reduced");
31
30
  }
32
31
  async clear(sessionKey, binding) {
33
32
  const current = await this.#store.getAsync(sessionKey);
34
33
  if (!current || !isDeepStrictEqual(current, binding)) return;
35
34
  if (current.detachedAt === void 0) return current;
36
35
  const { detachedAt: _detachedAt, ...retained } = current;
37
- return await this.#store.setIfCurrent(sessionKey, current, retained, { assertCurrent: () => this.#assertRoomCurrent(sessionKey, current) }) ? retained : void 0;
36
+ return await this.#store.setIfCurrent(sessionKey, current, retained) ? retained : void 0;
38
37
  }
39
38
  async ensureCapacity(sessionKey) {
40
39
  await this.#store.prepare();
@@ -45,29 +44,20 @@ var DetachedDiscussionBindingRetention = class {
45
44
  const oldest = await this.#store.oldestDetached();
46
45
  if (!oldest) return false;
47
46
  const current = oldest.binding;
48
- if (await readDiscussionSessionEntry(this.#runtime, oldest.sessionKey)) {
49
- await this.clear(oldest.sessionKey, current);
50
- continue;
47
+ const session = await prepareDiscussionSessionEntry(this.#runtime, oldest.sessionKey);
48
+ try {
49
+ if (session.entry) {
50
+ await this.clear(oldest.sessionKey, current);
51
+ continue;
52
+ }
53
+ const authority = { assertCurrent: session.source };
54
+ if (!await markClickClackDiscussionChannelRevoked(this.#runtime, oldest.sessionKey, current, authority)) continue;
55
+ if (await this.#store.deleteIfCurrent(oldest.sessionKey, current, authority)) return true;
56
+ } finally {
57
+ session.release();
51
58
  }
52
- const authority = { assertCurrent: () => this.#assertDetached(oldest.sessionKey, current) };
53
- if (!await markClickClackDiscussionChannelRevoked(this.#runtime, oldest.sessionKey, current, authority)) continue;
54
- if (await this.#store.deleteIfCurrent(oldest.sessionKey, current, authority)) return true;
55
59
  }
56
60
  }
57
- #sameRoom(left, right) {
58
- return left.serverBaseUrl === right.serverBaseUrl && left.channelId === right.channelId && left.externalRef === right.externalRef;
59
- }
60
- #assertRoomCurrent(sessionKey, expected) {
61
- const current = this.#store.get(sessionKey);
62
- if (!current || !this.#sameRoom(current, expected)) throw new Error("ClickClack discussion binding changed before retention committed");
63
- }
64
- #assertDetached(sessionKey, expected) {
65
- this.#assertRoomCurrent(sessionKey, expected);
66
- if (this.#runtime.agent.session.getSessionEntry({
67
- sessionKey,
68
- readConsistency: "latest"
69
- })) throw new Error("ClickClack discussion session returned before retention committed");
70
- }
71
61
  };
72
62
  // extensions/clickclack/src/discussions/control-session-url.ts
73
63
  function controlSessionUrl(baseUrl, sessionKey, fallbackAgentId, mainKey, displayName) {
@@ -86,19 +76,6 @@ function controlSessionUrl(baseUrl, sessionKey, fallbackAgentId, mainKey, displa
86
76
  url.hash = "";
87
77
  return url.toString();
88
78
  }
89
- // extensions/clickclack/src/discussions/history-format.ts
90
- function discussionRecordJson(value) {
91
- return JSON.stringify(value).replace(/[\u0085\u2028\u2029]/gu, (separator) => `\\u${separator.charCodeAt(0).toString(16).padStart(4, "0")}`);
92
- }
93
- /** Renders channel history as line-per-message records for the discussion tool. */
94
- function formatDiscussionHistory(history) {
95
- const text = history.messages.map((message) => {
96
- const author = message.author?.display_name || message.author?.handle || message.author_id || "Unknown";
97
- return `timestamp=${discussionRecordJson(message.created_at)} [Author ${discussionRecordJson(author)} id=${discussionRecordJson(message.author_id)}] text=${discussionRecordJson(message.body)}`;
98
- }).join("\n");
99
- const truncationNote = history.truncated ? "\n[History scan reached its safety bound; older active threads may be omitted.]" : "";
100
- return text ? `${text}${truncationNote}` : "";
101
- }
102
79
  // extensions/clickclack/src/discussions/installation.ts
103
80
  const INSTALLATION_NAMESPACE = "discussion-installation";
104
81
  const INSTALLATION_KEY = "current";
@@ -117,62 +94,55 @@ async function getClickClackDiscussionInstallationId(runtime) {
117
94
  if (!persisted) throw new Error("ClickClack discussion installation identity is unavailable; retry opening the discussion");
118
95
  return persisted;
119
96
  }
120
- // extensions/clickclack/src/discussions/reconcile-scheduler.ts
121
- const RECONCILE_DEBOUNCE_MS = 250;
122
- const RECONCILE_RETRY_MS = 1e3;
123
- const RECONCILE_RETRY_MAX_MS = 6e4;
124
- /**
125
- * Per-session debounced reconcile scheduling with failure backoff.
126
- * Contracts: bursts coalesce onto the earliest scheduled run (steady event
127
- * traffic can never postpone one); a failed run sets a not-before floor with
128
- * growing backoff that later events cannot undercut; events during an
129
- * in-flight run collapse into one follow-up scheduled after settlement; and
130
- * each service activation owns a separate scheduler scope and retry state.
131
- */
132
- var DiscussionReconcileScheduler = class {
133
- #hooks;
134
- #retryState = /* @__PURE__ */ new Map();
135
- #inFlight = /* @__PURE__ */ new Set();
136
- #followUps = /* @__PURE__ */ new Set();
137
- constructor(scheduler, hooks) {
138
- this.scheduler = scheduler;
139
- this.#hooks = hooks;
140
- }
141
- schedule(sessionKey, delayMs = RECONCILE_DEBOUNCE_MS) {
142
- if (this.scheduler.signal.aborted) return;
143
- if (this.#inFlight.has(sessionKey)) {
144
- this.#followUps.add(sessionKey);
145
- return;
146
- }
147
- const retry = this.#retryState.get(sessionKey);
148
- const fireAt = Math.max(this.scheduler.now() + delayMs, retry?.notBefore ?? 0);
149
- this.scheduler.schedule({
150
- id: `session:${sessionKey}`,
151
- atMs: fireAt,
152
- mode: "earliest",
153
- run: async () => {
154
- this.#inFlight.add(sessionKey);
155
- try {
156
- await this.#hooks.run(sessionKey);
157
- this.#retryState.delete(sessionKey);
158
- } catch (error) {
159
- if (this.scheduler.signal.aborted) return;
160
- const previous = this.#retryState.get(sessionKey);
161
- const nextRetryMs = Math.min(previous === void 0 ? RECONCILE_RETRY_MS : previous.delayMs * 2, RECONCILE_RETRY_MAX_MS);
162
- this.#retryState.set(sessionKey, {
163
- delayMs: nextRetryMs,
164
- notBefore: this.scheduler.now() + nextRetryMs
165
- });
166
- this.#hooks.warn(`discussion event reconcile failed for ${sessionKey}; retrying in ${nextRetryMs}ms: ${String(error)}`);
167
- this.#followUps.add(sessionKey);
168
- } finally {
169
- this.#inFlight.delete(sessionKey);
170
- if (!this.scheduler.signal.aborted && this.#followUps.delete(sessionKey)) this.schedule(sessionKey);
171
- }
172
- }
97
+ // extensions/clickclack/src/discussions/service-history.ts
98
+ function discussionRecordJson(value) {
99
+ return JSON.stringify(value).replace(/[\u0085\u2028\u2029]/gu, (separator) => `\\u${separator.charCodeAt(0).toString(16).padStart(4, "0")}`);
100
+ }
101
+ /** Renders channel history as line-per-message records for the discussion tool. */
102
+ function formatDiscussionHistory(history) {
103
+ const text = history.messages.map((message) => {
104
+ const author = message.author?.display_name || message.author?.handle || message.author_id || "Unknown";
105
+ return `timestamp=${discussionRecordJson(message.created_at)} [Author ${discussionRecordJson(author)} id=${discussionRecordJson(message.author_id)}] text=${discussionRecordJson(message.body)}`;
106
+ }).join("\n");
107
+ const truncationNote = history.truncated ? "\n[History scan reached its safety bound; older active threads may be omitted.]" : "";
108
+ return text ? `${text}${truncationNote}` : "";
109
+ }
110
+ async function readDiscussionHistory(params) {
111
+ const { runtime, store, sessionKey, binding, client, limit } = params;
112
+ const bindingFacts = await store.prepareRead(sessionKey);
113
+ let revocation;
114
+ let session;
115
+ try {
116
+ const channelRevocation = await prepareClickClackDiscussionChannelRevocation({
117
+ runtime,
118
+ ...binding
173
119
  });
120
+ revocation = channelRevocation;
121
+ const sessionEntry = await prepareDiscussionSessionEntry(runtime, sessionKey);
122
+ session = sessionEntry;
123
+ const canReadHistory = () => {
124
+ try {
125
+ sessionEntry.source();
126
+ const current = bindingFacts.read();
127
+ const config = runtime.config.current();
128
+ return current !== void 0 && current.externalRef === binding.externalRef && current.serverBaseUrl === binding.serverBaseUrl && current.channelId === binding.channelId && sessionEntry.entry?.sessionId === binding.sessionId && sessionEntry.entry.archivedAt === void 0 && resolveDiscussionBindingAccount(config, binding).state === "active" && !channelRevocation.isRevoked(current);
129
+ } catch {
130
+ return false;
131
+ }
132
+ };
133
+ if (!canReadHistory()) return { text: "No discussion is bound to this session." };
134
+ const history = await client.latestChannelMessages(binding.channelId, limit);
135
+ if (!canReadHistory()) return { text: "No discussion is bound to this session." };
136
+ return {
137
+ binding,
138
+ text: formatDiscussionHistory(history) || "The bound discussion has no messages yet."
139
+ };
140
+ } finally {
141
+ session?.release();
142
+ revocation?.release();
143
+ bindingFacts.release();
174
144
  }
175
- };
145
+ }
176
146
  // extensions/clickclack/src/discussions/service-open.ts
177
147
  const CHANNEL_NAME_MUTATION_ATTEMPTS = 4;
178
148
  function isDefinitiveNoCreateHttpError(error) {
@@ -236,13 +206,24 @@ async function renameDiscussionChannel(params) {
236
206
  }
237
207
  throw new Error("ClickClack discussion channel name retries were exhausted");
238
208
  }
239
- function assertManagedChannelContract(channel, expected) {
240
- const displayTitleMatches = !("display_title" in channel) || channel.display_title === expected.displayTitle;
241
- if (channel.external_managed !== true || (channel.external_ref ?? "") !== (expected.externalRef ?? "") || (channel.sidebar_section ?? "") !== (expected.section ?? "") || (channel.external_url ?? "") !== (expected.externalUrl ?? "") || !displayTitleMatches) throw new Error(`ClickClack server does not support the managed discussion channel contract for ${expected.sessionKey}`);
242
- }
243
209
  function assertManagedChannelListContract(channels) {
244
210
  if (channels.some((channel) => typeof channel.external_managed !== "boolean" || channel.external_ref !== void 0 && typeof channel.external_ref !== "string" || channel.external_url !== void 0 && typeof channel.external_url !== "string" || channel.sidebar_section !== void 0 && typeof channel.sidebar_section !== "string")) throw new Error("ClickClack server does not advertise the managed discussion contract");
245
211
  }
212
+ async function finalizePendingDiscussionBinding(runtime, sessionKey, binding) {
213
+ const pending = await getPendingDiscussionOpen(runtime, sessionKey);
214
+ if (pending?.externalRef === binding.externalRef) {
215
+ await clearClickClackDiscussionChannelRevoked({
216
+ runtime,
217
+ serverBaseUrl: binding.serverBaseUrl,
218
+ channelId: binding.channelId
219
+ });
220
+ await clearDiscussionBindingGeneration({
221
+ runtime,
222
+ sessionKey,
223
+ expectedGeneration: pending.generation
224
+ });
225
+ }
226
+ }
246
227
  async function openClickClackDiscussionBinding(params) {
247
228
  const { account, runtime, sessionKey, store } = params;
248
229
  const entry = await readDiscussionSessionEntry(runtime, sessionKey);
@@ -263,7 +244,13 @@ async function openClickClackDiscussionBinding(params) {
263
244
  });
264
245
  const unresolved = await getPendingDiscussionOpen(runtime, sessionKey);
265
246
  if (unresolved && (unresolved.accountId !== account.accountId || unresolved.credentialFingerprint !== credentialFingerprint || unresolved.serverBaseUrl !== serverBaseUrl || unresolved.workspaceId !== workspace.id)) {
266
- await params.reconcilePendingOpen(unresolved);
247
+ await reconcilePendingDiscussionOpen({
248
+ runtime,
249
+ store,
250
+ clientFactory: params.clientFactory,
251
+ pending: unresolved,
252
+ allowRetry: false
253
+ });
267
254
  if (await getPendingDiscussionOpen(runtime, sessionKey)) throw new Error("A previous ClickClack discussion open is still unresolved; restore its credential and retry");
268
255
  }
269
256
  const config = runtime.config.current();
@@ -272,16 +259,10 @@ async function openClickClackDiscussionBinding(params) {
272
259
  sessionKey
273
260
  });
274
261
  const fallback = fallbackDiscussionLabel(sessionKey, agentId);
275
- const describeChannel = (session) => {
276
- const label = resolveDiscussionLabel(session, sessionKey, agentId);
277
- return {
278
- label,
279
- displayTitle: label === fallback ? "" : truncateDiscussionDisplayTitle(label),
280
- section: session.category?.trim() || account.discussions.section,
281
- externalUrl: controlSessionUrl(account.discussions.controlUrlBase, sessionKey, account.agentId ?? agentId, config.session?.mainKey, label)
282
- };
283
- };
284
- const { label, displayTitle, section, externalUrl } = describeChannel(entry);
262
+ const label = resolveDiscussionLabel(entry, sessionKey, agentId);
263
+ const displayTitle = label === fallback ? "" : truncateDiscussionDisplayTitle(label);
264
+ const section = entry.category?.trim() || account.discussions.section;
265
+ const externalUrl = controlSessionUrl(account.discussions.controlUrlBase, sessionKey, account.agentId ?? agentId, config.session?.mainKey, label);
285
266
  const assertCurrentAuthority = () => {
286
267
  const currentAccounts = discussionAccounts(runtime.config.current());
287
268
  const currentAccount = currentAccounts.length === 1 ? currentAccounts[0] : void 0;
@@ -302,8 +283,7 @@ async function openClickClackDiscussionBinding(params) {
302
283
  sessionKey,
303
284
  accountId: account.accountId,
304
285
  credentialFingerprint,
305
- destinationIdentity,
306
- createGeneration: params.bindingGenerationFactory
286
+ destinationIdentity
307
287
  });
308
288
  const generationScope = {
309
289
  runtime,
@@ -387,13 +367,8 @@ async function openClickClackDiscussionBinding(params) {
387
367
  }
388
368
  if (!resolved || !managedFields) throw new Error("ClickClack discussion channel name retries were exhausted");
389
369
  try {
390
- assertManagedChannelContract(resolved, {
391
- sessionKey,
392
- externalRef,
393
- section,
394
- externalUrl,
395
- displayTitle
396
- });
370
+ const displayTitleMatches = !("display_title" in resolved) || resolved.display_title === displayTitle;
371
+ if (resolved.external_managed !== true || (resolved.external_ref ?? "") !== (externalRef ?? "") || (resolved.sidebar_section ?? "") !== (section ?? "") || (resolved.external_url ?? "") !== (externalUrl ?? "") || !displayTitleMatches) throw new Error(`ClickClack server does not support the managed discussion channel contract for ${sessionKey}`);
397
372
  if (adopted) assertChannelPatch(resolved, managedFields);
398
373
  } catch (error) {
399
374
  await clearPendingDiscussionOpen(generationScope);
@@ -412,30 +387,6 @@ async function openClickClackDiscussionBinding(params) {
412
387
  params.warn(`unattached discussion channel remains quarantined: ${channel.id}`);
413
388
  throw new Error("OpenClaw session became inactive while opening its ClickClack discussion");
414
389
  }
415
- const { label: currentLabel, displayTitle: currentDisplayTitle, section: currentSection, externalUrl: updatedExternalUrl } = describeChannel(currentEntry);
416
- const currentExternalUrl = updatedExternalUrl ?? "";
417
- let currentChannel = channel;
418
- if (currentEntry.sessionId !== entry.sessionId || currentLabel !== label || currentDisplayTitle !== displayTitle || currentSection !== section || currentExternalUrl !== (externalUrl ?? "")) try {
419
- currentChannel = await renameDiscussionChannel({
420
- client,
421
- workspaceId: workspace.id,
422
- channelId: channel.id,
423
- label: currentLabel,
424
- sessionKey,
425
- agentId,
426
- patch: {
427
- ...managedFields,
428
- external_url: currentExternalUrl,
429
- sidebar_section: currentSection,
430
- display_title: currentDisplayTitle
431
- },
432
- assertCurrentAuthority
433
- });
434
- } catch (error) {
435
- await clearPendingDiscussionOpen(generationScope);
436
- params.warn(`unattached discussion channel remains quarantined: ${channel.id}`);
437
- throw error;
438
- }
439
390
  const nextBinding = {
440
391
  accountId: account.accountId,
441
392
  agentId,
@@ -443,16 +394,16 @@ async function openClickClackDiscussionBinding(params) {
443
394
  serverBaseUrl,
444
395
  credentialFingerprint,
445
396
  externalRef,
446
- externalUrl: currentExternalUrl,
397
+ externalUrl: externalUrl ?? "",
447
398
  workspaceRef: account.discussions.workspace,
448
399
  workspaceId: workspace.id,
449
400
  channelId: channel.id,
450
401
  channelRouteId: channel.route_id,
451
402
  workspaceRouteId: workspace.route_id,
452
- section: currentSection,
403
+ section,
453
404
  archived: false,
454
- label: currentLabel,
455
- ...currentChannel.display_title !== void 0 ? { displayTitle: currentChannel.display_title } : {}
405
+ label,
406
+ ...channel.display_title !== void 0 ? { displayTitle: channel.display_title } : {}
456
407
  };
457
408
  try {
458
409
  nextBinding.sessionId = assertCurrentAuthority().sessionId;
@@ -468,33 +419,31 @@ async function openClickClackDiscussionBinding(params) {
468
419
  params.warn(`unbound discussion channel remains quarantined: ${channel.id}`);
469
420
  throw error;
470
421
  }
471
- await params.finalizePendingBinding(sessionKey, nextBinding);
422
+ await finalizePendingDiscussionBinding(runtime, sessionKey, nextBinding);
472
423
  return nextBinding;
473
424
  });
474
425
  }
426
+ /** Returns whether the service should retry inside its current session queue. */
475
427
  async function reconcilePendingDiscussionOpen(params) {
476
428
  const { pending } = params;
477
429
  const currentBinding = await params.store.getAsync(pending.sessionKey);
478
430
  if (currentBinding?.externalRef === pending.externalRef) {
479
- await params.finalizePendingBinding(pending.sessionKey, currentBinding);
480
- return;
431
+ await finalizePendingDiscussionBinding(params.runtime, pending.sessionKey, currentBinding);
432
+ return false;
481
433
  }
482
434
  const cfg = params.runtime.config.current();
483
435
  const account = listClickClackAccountIds(cfg).map((accountId) => resolveClickClackAccount({
484
436
  cfg,
485
437
  accountId
486
438
  })).find((candidate) => candidate.configured && normalizedServerBaseUrl(candidate) === pending.serverBaseUrl && discussionCredentialFingerprint(candidate.token) === pending.credentialFingerprint);
487
- if (!account) return;
439
+ if (!account) return false;
488
440
  const client = params.clientFactory(account);
489
441
  const entry = await readDiscussionSessionEntry(params.runtime, pending.sessionKey);
490
442
  const activeAccounts = discussionAccounts(cfg);
491
443
  const retryAccount = activeAccounts.length === 1 ? activeAccounts[0] : void 0;
492
444
  if (params.allowRetry !== false && entry?.sessionId && entry.archivedAt === void 0 && retryAccount && normalizedServerBaseUrl(retryAccount) === pending.serverBaseUrl && discussionCredentialFingerprint(retryAccount.token) === pending.credentialFingerprint) {
493
445
  const workspaces = await params.clientFactory(retryAccount).workspaces();
494
- if (findClickClackWorkspace(workspaces, retryAccount.discussions.workspace)?.id === pending.workspaceId) {
495
- await params.open(pending.sessionKey);
496
- return;
497
- }
446
+ if (findClickClackWorkspace(workspaces, retryAccount.discussions.workspace)?.id === pending.workspaceId) return true;
498
447
  }
499
448
  const channels = await client.channels(pending.workspaceId);
500
449
  assertManagedChannelListContract(channels);
@@ -511,47 +460,45 @@ async function reconcilePendingDiscussionOpen(params) {
511
460
  sessionKey: pending.sessionKey,
512
461
  expectedGeneration: pending.generation
513
462
  });
514
- return;
463
+ return false;
515
464
  }
516
465
  await clearDiscussionBindingGeneration({
517
466
  runtime: params.runtime,
518
467
  sessionKey: pending.sessionKey,
519
468
  expectedGeneration: pending.generation
520
469
  });
470
+ return false;
521
471
  }
522
472
  // extensions/clickclack/src/discussions/service.ts
523
473
  const RECONCILE_INTERVAL_MS = 6e4;
474
+ const RECONCILE_DEBOUNCE_MS = 250;
475
+ const RECONCILE_RETRY_MS = 1e3;
476
+ const RECONCILE_RETRY_MAX_MS = 6e4;
524
477
  var ClickClackDiscussionService = class {
525
478
  #runtime;
526
479
  #store;
527
480
  #clientFactory;
528
481
  #installationId;
529
- #bindingGenerationFactory;
530
482
  #detachedBindings;
531
483
  #sessionQueue = new KeyedAsyncQueue();
532
484
  #scheduler;
533
- #reconcileScheduler;
485
+ #scheduleReconcile;
534
486
  #withChannelMutationLock = createAsyncLock();
535
487
  #timer;
536
- #reconcileAllPromise;
537
488
  #unsubscribeSessionsChanged;
538
489
  #closed = false;
539
- #activation = 0;
540
490
  #cleanupPromise;
541
491
  #operations = /* @__PURE__ */ new Set();
542
- constructor(runtime, options = {}) {
492
+ constructor(runtime) {
543
493
  this.#runtime = runtime;
544
494
  this.#store = getClickClackDiscussionBindingStore(runtime);
545
- this.#clientFactory = options.clientFactory ?? ((account) => createClickClackClient({
495
+ this.#clientFactory = (account) => createClickClackClient({
546
496
  baseUrl: account.apiEndpoint,
547
497
  token: account.token
548
- }));
549
- this.#installationId = options.installationId;
550
- this.#bindingGenerationFactory = options.bindingGenerationFactory ?? randomUUID;
498
+ });
551
499
  this.#detachedBindings = new DetachedDiscussionBindingRetention({
552
500
  runtime,
553
- store: this.#store,
554
- maxRetained: options.maxRetainedDetachedBindings ?? 1e3
501
+ store: this.#store
555
502
  });
556
503
  this.provider = {
557
504
  id: "clickclack",
@@ -560,40 +507,78 @@ var ClickClackDiscussionService = class {
560
507
  };
561
508
  }
562
509
  async bindGatewayEvents(gatewayEvents, scheduler) {
563
- const activation = ++this.#activation;
564
510
  if (this.#cleanupPromise) await this.#cleanupPromise;
565
- if (activation !== this.#activation) return;
566
511
  if (this.#scheduler) await this.#scheduler.stop();
567
- if (activation !== this.#activation) return;
568
512
  this.#cleanupPromise = void 0;
569
513
  this.#unsubscribeSessionsChanged?.();
570
514
  this.#closed = false;
571
515
  this.#scheduler = scheduler.scope();
572
516
  this.#timer = void 0;
573
- this.#reconcileScheduler = new DiscussionReconcileScheduler(this.#scheduler, {
574
- run: (sessionKey) => this.reconcile(sessionKey),
575
- warn: (message) => this.#logger().warn(message)
576
- });
517
+ const activationScheduler = this.#scheduler;
518
+ /**
519
+ * Per-session debounced reconcile scheduling with failure backoff.
520
+ * Contracts: bursts coalesce onto the earliest scheduled run (steady event
521
+ * traffic can never postpone one); a failed run sets a not-before floor with
522
+ * growing backoff that later events cannot undercut; events during an
523
+ * in-flight run collapse into one follow-up scheduled after settlement; and
524
+ * each service activation owns a separate scheduler scope and retry state.
525
+ */
526
+ const retryState = /* @__PURE__ */ new Map();
527
+ const inFlight = /* @__PURE__ */ new Set();
528
+ const followUps = /* @__PURE__ */ new Set();
529
+ const scheduleReconcile = (sessionKey, delayMs = RECONCILE_DEBOUNCE_MS) => {
530
+ if (activationScheduler.signal.aborted) return;
531
+ if (inFlight.has(sessionKey)) {
532
+ followUps.add(sessionKey);
533
+ return;
534
+ }
535
+ const retry = retryState.get(sessionKey);
536
+ const fireAt = Math.max(activationScheduler.now() + delayMs, retry?.notBefore ?? 0);
537
+ activationScheduler.schedule({
538
+ id: `session:${sessionKey}`,
539
+ atMs: fireAt,
540
+ mode: "earliest",
541
+ run: async () => {
542
+ inFlight.add(sessionKey);
543
+ try {
544
+ await this.reconcile(sessionKey);
545
+ retryState.delete(sessionKey);
546
+ } catch (error) {
547
+ if (activationScheduler.signal.aborted) return;
548
+ const previous = retryState.get(sessionKey);
549
+ const nextRetryMs = Math.min(previous === void 0 ? RECONCILE_RETRY_MS : previous.delayMs * 2, RECONCILE_RETRY_MAX_MS);
550
+ retryState.set(sessionKey, {
551
+ delayMs: nextRetryMs,
552
+ notBefore: activationScheduler.now() + nextRetryMs
553
+ });
554
+ this.#logger().warn(`discussion event reconcile failed for ${sessionKey}; retrying in ${nextRetryMs}ms: ${String(error)}`);
555
+ followUps.add(sessionKey);
556
+ } finally {
557
+ inFlight.delete(sessionKey);
558
+ if (!activationScheduler.signal.aborted && followUps.delete(sessionKey)) scheduleReconcile(sessionKey);
559
+ }
560
+ }
561
+ });
562
+ };
563
+ this.#scheduleReconcile = scheduleReconcile;
577
564
  this.#unsubscribeSessionsChanged = gatewayEvents?.onSessionsChanged((event) => {
578
565
  this.#withOperation(async () => {
579
- if (await this.#store.getAsync(event.sessionKey) || await getPendingDiscussionOpen(this.#runtime, event.sessionKey)) {
580
- if (activation === this.#activation) this.#reconcileScheduler?.schedule(event.sessionKey);
581
- }
566
+ if (await this.#store.getAsync(event.sessionKey) || await getPendingDiscussionOpen(this.#runtime, event.sessionKey)) this.#scheduleReconcile?.(event.sessionKey);
582
567
  }).catch((error) => {
583
568
  this.#logger().warn(`discussion event admission failed: ${String(error)}`);
584
569
  });
585
570
  });
586
571
  await this.#withOperation(async () => {
587
- for (const sessionKey of await this.#listReconcileSessionKeys()) {
588
- if (activation !== this.#activation) return;
589
- this.#reconcileScheduler?.schedule(sessionKey, 0);
590
- }
572
+ for (const sessionKey of await this.#listReconcileSessionKeys()) this.#scheduleReconcile?.(sessionKey, 0);
591
573
  await this.#ensureTimer();
592
574
  });
593
575
  }
594
576
  hasEnabledAccount() {
595
577
  return discussionAccounts(this.#currentConfig()).length === 1;
596
578
  }
579
+ resolveBindingAccount(binding) {
580
+ return resolveDiscussionBindingAccount(this.#currentConfig(), binding);
581
+ }
597
582
  async info(sessionKey) {
598
583
  return await this.#withOperation(() => this.#sessionQueue.enqueue(sessionKey, async () => {
599
584
  await this.#store.prepare();
@@ -651,13 +636,10 @@ var ClickClackDiscussionService = class {
651
636
  account,
652
637
  clientFactory: this.#clientFactory,
653
638
  installationId: this.#installationId,
654
- bindingGenerationFactory: this.#bindingGenerationFactory,
655
639
  sessionKey,
656
640
  ensureTimer: () => this.#ensureTimer(),
657
- reconcilePendingOpen: (pending) => this.#reconcilePendingOpen(pending, { allowRetry: false }),
658
641
  withChannelMutationLock: (run) => this.#withChannelMutationLock(run),
659
642
  ensureBindingCapacity: (key) => this.#detachedBindings.ensureCapacity(key),
660
- finalizePendingBinding: (key, nextBinding) => this.#finalizePendingBinding(key, nextBinding),
661
643
  warn: (message) => this.#logger().warn(message)
662
644
  });
663
645
  } finally {
@@ -676,7 +658,14 @@ var ClickClackDiscussionService = class {
676
658
  const binding = await this.#store.getAsync(sessionKey);
677
659
  if (binding) await this.#reconcileBinding(sessionKey, binding);
678
660
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
679
- if (pending) await this.#reconcilePendingOpen(pending);
661
+ if (pending) {
662
+ if (await reconcilePendingDiscussionOpen({
663
+ runtime: this.#runtime,
664
+ store: this.#store,
665
+ clientFactory: this.#clientFactory,
666
+ pending
667
+ })) await this.#open(sessionKey);
668
+ }
680
669
  });
681
670
  } finally {
682
671
  await this.#ensureTimer();
@@ -684,21 +673,15 @@ var ClickClackDiscussionService = class {
684
673
  }
685
674
  async reconcileAll() {
686
675
  return await this.#withOperation(async () => {
687
- if (this.#reconcileAllPromise) return await this.#reconcileAllPromise;
688
- this.#reconcileAllPromise = (async () => {
689
- try {
690
- for (const sessionKey of await this.#listReconcileSessionKeys()) try {
691
- await this.#reconcile(sessionKey);
692
- } catch (error) {
693
- this.#logger().warn(`discussion reconcile failed for ${sessionKey}: ${String(error)}`);
694
- }
695
- } finally {
696
- await this.#ensureTimer();
676
+ try {
677
+ for (const sessionKey of await this.#listReconcileSessionKeys()) try {
678
+ await this.#reconcile(sessionKey);
679
+ } catch (error) {
680
+ this.#logger().warn(`discussion reconcile failed for ${sessionKey}: ${String(error)}`);
697
681
  }
698
- })().finally(() => {
699
- this.#reconcileAllPromise = void 0;
700
- });
701
- return await this.#reconcileAllPromise;
682
+ } finally {
683
+ await this.#ensureTimer();
684
+ }
702
685
  });
703
686
  }
704
687
  async readLatestMessages(sessionKey, limit) {
@@ -710,30 +693,27 @@ var ClickClackDiscussionService = class {
710
693
  if (resolved.state !== "active") return { text: "No discussion is bound to this session." };
711
694
  const attached = await this.#refreshSessionAttachment(sessionKey, binding);
712
695
  if (!attached) return { text: "No discussion is bound to this session." };
713
- if (!bindingMatchesActiveSessionIncarnation(this.#runtime, sessionKey, attached) || resolveDiscussionBindingAccount(this.#currentConfig(), attached).state !== "active" || isClickClackDiscussionChannelRevoked({
696
+ return await readDiscussionHistory({
714
697
  runtime: this.#runtime,
715
- serverBaseUrl: binding.serverBaseUrl,
716
- channelId: binding.channelId,
717
- binding: attached
718
- })) return { text: "No discussion is bound to this session." };
719
- return {
698
+ store: this.#store,
699
+ sessionKey,
720
700
  binding: attached,
721
- text: formatDiscussionHistory(await this.#clientFactory(resolved.account).latestChannelMessages(attached.channelId, limit)) || "The bound discussion has no messages yet."
722
- };
701
+ client: this.#clientFactory(resolved.account),
702
+ limit
703
+ });
723
704
  }));
724
705
  }
725
706
  cleanup() {
726
707
  this.#closed = true;
727
- this.#activation += 1;
728
708
  this.#unsubscribeSessionsChanged?.();
729
709
  this.#unsubscribeSessionsChanged = void 0;
730
- this.#reconcileScheduler = void 0;
710
+ this.#scheduleReconcile = void 0;
731
711
  this.#timer = void 0;
732
712
  this.#cleanupPromise ??= Promise.allSettled([this.#scheduler?.stop(), ...this.#operations]).then(() => void 0);
733
713
  return this.#cleanupPromise;
734
714
  }
735
715
  async #reconcileBinding(sessionKey, binding, resolvedAccount) {
736
- await this.#finalizePendingBinding(sessionKey, binding);
716
+ await finalizePendingDiscussionBinding(this.#runtime, sessionKey, binding);
737
717
  if (await isClickClackDiscussionChannelRevokedAsync({
738
718
  runtime: this.#runtime,
739
719
  serverBaseUrl: binding.serverBaseUrl,
@@ -750,7 +730,7 @@ var ClickClackDiscussionService = class {
750
730
  }
751
731
  const activeBinding = await this.#detachedBindings.clear(sessionKey, binding);
752
732
  if (!activeBinding) return;
753
- const resolved = resolvedAccount ? resolveDiscussionBindingAccount(this.#currentConfig(), activeBinding) : await this.#resolveBindingForUse(activeBinding);
733
+ const resolved = resolvedAccount ? this.resolveBindingAccount(activeBinding) : await this.#resolveBindingForUse(activeBinding);
754
734
  if (resolved.state === "retargeted") {
755
735
  await this.#revokeAndDeleteBinding(sessionKey, activeBinding);
756
736
  return;
@@ -782,7 +762,7 @@ var ClickClackDiscussionService = class {
782
762
  bindingForAttachment = freshBinding;
783
763
  observedSiblingTitleSupport = bindings.some(({ binding: candidate }) => candidate.displayTitle !== void 0 && candidate.serverBaseUrl === freshBinding.serverBaseUrl && candidate.accountId === freshBinding.accountId);
784
764
  }
785
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), bindingForAttachment);
765
+ const current = this.resolveBindingAccount(bindingForAttachment);
786
766
  if (current.state !== "active") return;
787
767
  const account = current.account;
788
768
  const attached = await this.#refreshSessionAttachment(sessionKey, bindingForAttachment);
@@ -801,41 +781,54 @@ var ClickClackDiscussionService = class {
801
781
  if (section !== currentBinding.section) patch.sidebar_section = section;
802
782
  if (externalUrl !== currentBinding.externalUrl) patch.external_url = externalUrl;
803
783
  if (Object.keys(patch).length === 0 && !labelChanged) return;
804
- const client = this.#clientFactory(account);
805
- const assertCurrentAuthority = () => {
806
- const bound = this.#store.get(sessionKey);
807
- if (!bound || bound.externalRef !== currentBinding.externalRef || bound.serverBaseUrl !== currentBinding.serverBaseUrl || bound.channelId !== currentBinding.channelId || !bindingMatchesActiveSessionIncarnation(this.#runtime, sessionKey, currentBinding) || resolveDiscussionBindingAccount(this.#currentConfig(), currentBinding).state !== "active" || isClickClackDiscussionChannelRevoked({
784
+ const bindingFacts = await this.#store.prepareRead(sessionKey);
785
+ let revocation;
786
+ let session;
787
+ try {
788
+ revocation = await prepareClickClackDiscussionChannelRevocation({
808
789
  runtime: this.#runtime,
809
790
  serverBaseUrl: currentBinding.serverBaseUrl,
791
+ channelId: currentBinding.channelId
792
+ });
793
+ const isRevoked = revocation.isRevoked;
794
+ session = await prepareDiscussionSessionEntry(this.#runtime, sessionKey);
795
+ const sessionAuthority = session;
796
+ const client = this.#clientFactory(account);
797
+ const assertCurrentAuthority = () => {
798
+ sessionAuthority.source();
799
+ const bound = bindingFacts.read();
800
+ if (!bound || bound.externalRef !== currentBinding.externalRef || bound.serverBaseUrl !== currentBinding.serverBaseUrl || bound.channelId !== currentBinding.channelId || sessionAuthority.entry?.sessionId !== currentBinding.sessionId || sessionAuthority.entry.archivedAt !== void 0 || this.resolveBindingAccount(currentBinding).state !== "active" || isRevoked(bound)) throw new Error("ClickClack discussion authority changed before channel update");
801
+ };
802
+ let updated;
803
+ if (labelChanged) updated = await this.#withChannelMutationLock(() => renameDiscussionChannel({
804
+ client,
805
+ workspaceId: currentBinding.workspaceId,
810
806
  channelId: currentBinding.channelId,
811
- binding: bound
812
- })) throw new Error("ClickClack discussion authority changed before channel update");
813
- };
814
- let updated;
815
- if (labelChanged) updated = await this.#withChannelMutationLock(() => renameDiscussionChannel({
816
- client,
817
- workspaceId: currentBinding.workspaceId,
818
- channelId: currentBinding.channelId,
819
- label,
820
- sessionKey,
821
- agentId: currentBinding.agentId,
822
- patch,
823
- assertCurrentAuthority
824
- }));
825
- else {
826
- assertCurrentAuthority();
827
- updated = await client.updateChannel(currentBinding.channelId, patch);
828
- assertChannelPatch(updated, patch);
807
+ label,
808
+ sessionKey,
809
+ agentId: currentBinding.agentId,
810
+ patch,
811
+ assertCurrentAuthority
812
+ }));
813
+ else {
814
+ assertCurrentAuthority();
815
+ updated = await client.updateChannel(currentBinding.channelId, patch);
816
+ assertChannelPatch(updated, patch);
817
+ }
818
+ const nextBinding = {
819
+ ...currentBinding,
820
+ externalUrl,
821
+ label,
822
+ section,
823
+ ...updated.display_title !== void 0 ? { displayTitle: updated.display_title } : {}
824
+ };
825
+ if (updated.display_title === void 0) delete nextBinding.displayTitle;
826
+ await this.#store.setIfCurrent(sessionKey, currentBinding, nextBinding);
827
+ } finally {
828
+ session?.release();
829
+ revocation?.release();
830
+ bindingFacts.release();
829
831
  }
830
- const nextBinding = {
831
- ...currentBinding,
832
- externalUrl,
833
- label,
834
- section,
835
- ...updated.display_title !== void 0 ? { displayTitle: updated.display_title } : {}
836
- };
837
- if (updated.display_title === void 0) delete nextBinding.displayTitle;
838
- await this.#store.setIfCurrent(sessionKey, currentBinding, nextBinding, { assertCurrent: assertCurrentAuthority });
839
832
  }
840
833
  async #refreshSessionAttachment(sessionKey, binding) {
841
834
  try {
@@ -850,17 +843,6 @@ var ClickClackDiscussionService = class {
850
843
  return;
851
844
  }
852
845
  }
853
- async #reconcilePendingOpen(pending, options = {}) {
854
- await reconcilePendingDiscussionOpen({
855
- runtime: this.#runtime,
856
- store: this.#store,
857
- clientFactory: this.#clientFactory,
858
- pending,
859
- ...options,
860
- finalizePendingBinding: (key, binding) => this.#finalizePendingBinding(key, binding),
861
- open: (key) => this.#open(key)
862
- });
863
- }
864
846
  async #releaseStaleBinding(sessionKey, binding) {
865
847
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
866
848
  if (pending?.externalRef === binding.externalRef) await clearDiscussionBindingGeneration({
@@ -874,27 +856,12 @@ var ClickClackDiscussionService = class {
874
856
  if (!await markClickClackDiscussionChannelRevoked(this.#runtime, sessionKey, binding)) return false;
875
857
  return await this.#store.deleteIfCurrent(sessionKey, binding);
876
858
  }
877
- async #finalizePendingBinding(sessionKey, binding) {
878
- const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
879
- if (pending?.externalRef === binding.externalRef) {
880
- await clearClickClackDiscussionChannelRevoked({
881
- runtime: this.#runtime,
882
- serverBaseUrl: binding.serverBaseUrl,
883
- channelId: binding.channelId
884
- });
885
- await clearDiscussionBindingGeneration({
886
- runtime: this.#runtime,
887
- sessionKey,
888
- expectedGeneration: pending.generation
889
- });
890
- }
891
- }
892
859
  async #resolveBindingForUse(binding) {
893
- const resolved = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
860
+ const resolved = this.resolveBindingAccount(binding);
894
861
  if (resolved.state !== "active") return resolved;
895
862
  const workspaces = await this.#clientFactory(resolved.account).workspaces();
896
863
  const workspace = findClickClackWorkspace(workspaces, resolved.account.discussions.workspace);
897
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
864
+ const current = this.resolveBindingAccount(binding);
898
865
  if (current.state !== "active") return current;
899
866
  return workspace?.id === binding.workspaceId ? current : { state: "retargeted" };
900
867
  }
@@ -939,7 +906,9 @@ var ClickClackDiscussionService = class {
939
906
  return operation;
940
907
  }
941
908
  };
942
- // extensions/clickclack/src/discussions/tool-policy.ts
909
+ // extensions/clickclack/src/discussions/register.ts
910
+ const DEFAULT_MESSAGE_LIMIT = 30;
911
+ const MAX_MESSAGE_LIMIT = 200;
943
912
  const TARGETED_SESSION_TOOLS = /* @__PURE__ */ new Set([
944
913
  "sessions_history",
945
914
  "sessions_send",
@@ -951,77 +920,74 @@ function blockedResult() {
951
920
  blockReason: `ClickClack discussion sessions may use ${[...TARGETED_SESSION_TOOLS].join(", ")} only with their attached main session.`
952
921
  };
953
922
  }
954
- function isClickClackDiscussionSessionTarget(params) {
955
- if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
956
- const { runtime, targetSessionKey } = params;
957
- let binding;
958
- try {
959
- const store = getClickClackDiscussionBindingStore(runtime);
960
- store.assertReadAvailable();
961
- binding = store.get(targetSessionKey);
962
- } catch {
923
+ function registerClickClackDiscussions(api) {
924
+ if (api.registrationMode === "tool-discovery") {
925
+ api.registerTool(() => null, { name: "discussion" });
963
926
  return;
964
927
  }
965
- return currentDiscussionTarget(params, binding, (current) => isClickClackDiscussionChannelRevoked({
966
- runtime,
967
- serverBaseUrl: current.serverBaseUrl,
968
- channelId: current.channelId,
969
- binding: current
970
- }));
971
- }
972
- function currentDiscussionTarget(params, binding, isRevoked) {
973
- const { runtime, targetSessionKey } = params;
974
- if (binding && discussionSessionKey({
975
- runtime,
976
- mainSessionKey: targetSessionKey,
977
- ...binding
978
- }) === params.requesterSessionKey && !isRevoked(binding) && bindingMatchesActiveSessionIncarnation(runtime, targetSessionKey, binding) && resolveDiscussionBindingAccount(runtime.config.current(), binding).state === "active") return {
979
- sessionKey: targetSessionKey,
980
- binding
981
- };
982
- }
983
- async function resolveClickClackDiscussionSessionTarget(params) {
984
- if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
985
- let facts;
986
- let revocation;
987
- try {
988
- facts = await getClickClackDiscussionBindingStore(params.runtime).prepareRead(params.targetSessionKey);
989
- const binding = facts.read();
990
- if (!binding) return;
991
- revocation = await prepareClickClackDiscussionChannelRevocation({
992
- runtime: params.runtime,
928
+ const runtime = api.runtime;
929
+ const service = new ClickClackDiscussionService(runtime);
930
+ function isClickClackDiscussionSessionTarget(params) {
931
+ if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
932
+ const { targetSessionKey } = params;
933
+ let binding;
934
+ try {
935
+ const store = getClickClackDiscussionBindingStore(runtime);
936
+ store.assertReadAvailable();
937
+ binding = store.get(targetSessionKey);
938
+ } catch {
939
+ return;
940
+ }
941
+ return currentDiscussionTarget(params, binding, (current) => isClickClackDiscussionChannelRevoked({
942
+ runtime,
943
+ serverBaseUrl: current.serverBaseUrl,
944
+ channelId: current.channelId,
945
+ binding: current
946
+ }), (current) => bindingMatchesActiveSessionIncarnation(runtime, targetSessionKey, current));
947
+ }
948
+ function currentDiscussionTarget(params, binding, isRevoked, isActiveSession) {
949
+ const { targetSessionKey } = params;
950
+ if (binding && discussionSessionKey({
951
+ runtime,
952
+ mainSessionKey: targetSessionKey,
993
953
  ...binding
994
- });
995
- return currentDiscussionTarget(params, facts.read(), revocation.isRevoked);
996
- } catch {
997
- return;
998
- } finally {
999
- revocation?.release();
1000
- facts?.release();
954
+ }) === params.requesterSessionKey && !isRevoked(binding) && isActiveSession(binding) && service.resolveBindingAccount(binding).state === "active") return {
955
+ sessionKey: targetSessionKey,
956
+ binding
957
+ };
1001
958
  }
1002
- }
1003
- /** Restricts a discussion side session's session tools to its attached main session. */
1004
- async function enforceClickClackDiscussionToolTarget(params) {
1005
- const callerSessionKey = params.context.sessionKey;
1006
- if (!callerSessionKey || !isDiscussionSessionKey(callerSessionKey)) return;
1007
- const { toolName } = params.event;
1008
- if (toolName !== "session_status" && !toolName.startsWith("sessions_")) return;
1009
- const usesAlternateSendTarget = toolName === "sessions_send" && (params.event.params.label !== void 0 || params.event.params.agentId !== void 0);
1010
- const mutatesStatus = toolName === "session_status" && params.event.params.model !== void 0;
1011
- const selectsHistoryIncarnation = toolName === "sessions_history" && params.event.params.sessionId !== void 0;
1012
- const targetSessionKey = params.event.params.sessionKey;
1013
- if (TARGETED_SESSION_TOOLS.has(toolName) && typeof targetSessionKey === "string" && !usesAlternateSendTarget && !mutatesStatus && !selectsHistoryIncarnation && await resolveClickClackDiscussionSessionTarget({
1014
- runtime: params.runtime,
1015
- requesterSessionKey: callerSessionKey,
1016
- targetSessionKey
1017
- })) return;
1018
- return blockedResult();
1019
- }
1020
- // extensions/clickclack/src/discussions/tool.ts
1021
- const DEFAULT_MESSAGE_LIMIT = 30;
1022
- const MAX_MESSAGE_LIMIT = 200;
1023
- function createClickClackDiscussionTool(params) {
1024
- return {
959
+ async function resolveClickClackDiscussionSessionTarget(params) {
960
+ if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
961
+ let facts;
962
+ let revocation;
963
+ let session;
964
+ try {
965
+ facts = await getClickClackDiscussionBindingStore(runtime).prepareRead(params.targetSessionKey);
966
+ const binding = facts.read();
967
+ if (!binding) return;
968
+ revocation = await prepareClickClackDiscussionChannelRevocation({
969
+ runtime,
970
+ ...binding
971
+ });
972
+ session = await prepareDiscussionSessionEntry(runtime, params.targetSessionKey);
973
+ session.source();
974
+ const entry = session.entry;
975
+ return currentDiscussionTarget(params, facts.read(), revocation.isRevoked, (current) => entry?.sessionId === current.sessionId && entry.archivedAt === void 0);
976
+ } catch {
977
+ return;
978
+ } finally {
979
+ session?.release();
980
+ revocation?.release();
981
+ facts?.release();
982
+ }
983
+ }
984
+ api.registerService({
985
+ id: "clickclack-discussion-session-events",
986
+ apiVersion: 2,
987
+ start: ({ gatewayEvents, scheduler }) => service.bindGatewayEvents(gatewayEvents, scheduler),
988
+ stop: () => service.cleanup()
989
+ });
990
+ api.registerTool(({ sessionKey }) => ({
1025
991
  name: "discussion",
1026
992
  label: "Discussion",
1027
993
  description: "Read the latest messages from the ClickClack discussion bound to this session.",
@@ -1036,50 +1002,40 @@ function createClickClackDiscussionTool(params) {
1036
1002
  additionalProperties: false
1037
1003
  },
1038
1004
  async execute(_toolCallId, input) {
1039
- if (!params.sessionKey) return textResult("No discussion is bound to this session.", { bound: false });
1005
+ if (!sessionKey) return textResult("No discussion is bound to this session.", { bound: false });
1040
1006
  const requested = typeof input === "object" && input !== null && "limit" in input ? Number(input.limit) : DEFAULT_MESSAGE_LIMIT;
1041
1007
  const limit = Number.isInteger(requested) ? Math.max(1, Math.min(MAX_MESSAGE_LIMIT, requested)) : DEFAULT_MESSAGE_LIMIT;
1042
- const result = await params.service.readLatestMessages(params.sessionKey, limit);
1008
+ const result = await service.readLatestMessages(sessionKey, limit);
1043
1009
  return textResult(result.text, {
1044
1010
  bound: Boolean(result.binding),
1045
1011
  limit,
1046
1012
  ...result.binding ? { channelId: result.binding.channelId } : {}
1047
1013
  });
1048
1014
  }
1049
- };
1050
- }
1051
- // extensions/clickclack/src/discussions/register.ts
1052
- function registerClickClackDiscussions(api) {
1053
- if (api.registrationMode === "tool-discovery") {
1054
- api.registerTool(() => null, { name: "discussion" });
1055
- return;
1056
- }
1057
- const service = new ClickClackDiscussionService(api.runtime);
1058
- api.registerService({
1059
- id: "clickclack-discussion-session-events",
1060
- apiVersion: 2,
1061
- start: ({ gatewayEvents, scheduler }) => service.bindGatewayEvents(gatewayEvents, scheduler),
1062
- stop: () => service.cleanup()
1063
- });
1064
- api.registerTool((context) => createClickClackDiscussionTool({
1065
- service,
1066
- sessionKey: context.sessionKey
1067
- }));
1068
- api.on("before_tool_call", (event, context) => enforceClickClackDiscussionToolTarget({
1069
- runtime: api.runtime,
1070
- event,
1071
- context
1072
1015
  }));
1016
+ api.on("before_tool_call", async (event, context) => {
1017
+ const callerSessionKey = context.sessionKey;
1018
+ if (!callerSessionKey || !isDiscussionSessionKey(callerSessionKey)) return;
1019
+ const { toolName } = event;
1020
+ if (toolName !== "session_status" && !toolName.startsWith("sessions_")) return;
1021
+ const usesAlternateSendTarget = toolName === "sessions_send" && (event.params.label !== void 0 || event.params.agentId !== void 0);
1022
+ const mutatesStatus = toolName === "session_status" && event.params.model !== void 0;
1023
+ const selectsHistoryIncarnation = toolName === "sessions_history" && event.params.sessionId !== void 0;
1024
+ const targetSessionKey = event.params.sessionKey;
1025
+ if (TARGETED_SESSION_TOOLS.has(toolName) && typeof targetSessionKey === "string" && !usesAlternateSendTarget && !mutatesStatus && !selectsHistoryIncarnation && await resolveClickClackDiscussionSessionTarget({
1026
+ requesterSessionKey: callerSessionKey,
1027
+ targetSessionKey
1028
+ })) return;
1029
+ return blockedResult();
1030
+ });
1073
1031
  const unregisterSessionAccess = createSessionVisibilityChecker.registerScopedAccessProvider(({ requesterSessionKey, targetSessionKey }) => {
1074
1032
  const target = isClickClackDiscussionSessionTarget({
1075
- runtime: api.runtime,
1076
1033
  requesterSessionKey,
1077
1034
  targetSessionKey
1078
1035
  });
1079
1036
  return target ? { expectedSessionId: target.binding.sessionId } : void 0;
1080
1037
  }, { async resolveAsync({ requesterSessionKey, targetSessionKey }) {
1081
1038
  const target = await resolveClickClackDiscussionSessionTarget({
1082
- runtime: api.runtime,
1083
1039
  requesterSessionKey,
1084
1040
  targetSessionKey
1085
1041
  });