@openclaw/clickclack 2026.10.10-beta.5 → 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 (61) hide show
  1. package/dist/.setup/{channel-DRcZ_twH.mjs → channel-ByAANbh8.mjs} +382 -543
  2. package/dist/.setup/{resolve-Br3ylpSz.mjs → resolve-CRj6QjdF.mjs} +29 -46
  3. package/dist/.setup/{rolldown-runtime-B4FMCO8f.mjs → rolldown-runtime-782esTHO.mjs} +1 -3
  4. package/dist/.setup/{runtime-api-BrlvVAQJ.mjs → runtime-api-BsRK-sfA.mjs} +329 -383
  5. package/dist/.setup/{secret-contract-CF7TKtkU.mjs → secret-contract-Dj8nibUr.mjs} +1 -2
  6. package/dist/.setup/{secret-contract-api--45pFCg3.mjs → secret-contract-api-DS3Vv0Gu.mjs} +1 -1
  7. package/dist/.setup/{setup-claim-BPuQuMKW.mjs → setup-claim-BAKxfObl.mjs} +5 -11
  8. package/dist/.setup/{setup-plugin-api-Ccxm2ydn.mjs → setup-plugin-api-BTqE973B.mjs} +2 -3
  9. package/dist/.setup/setup-plugin-api-CfuhJJvK.mjs +1 -0
  10. package/dist/.setup/{setup-surface-BJ3jioqA.mjs → setup-surface-5wSYr6p2.mjs} +11 -17
  11. package/dist/.setup/{setup-verify-DGsYtVh9.mjs → setup-verify-IayKkFWq.mjs} +13 -26
  12. package/dist/.source-module-urls/aa673c321fe9be084b8926cbe5388ff5e2a41371389e19ca60a1983f2b634030.json +1 -1
  13. package/dist/api.js +3 -3
  14. package/dist/channel-plugin-api.js +1 -1
  15. package/dist/doctor-contract-api.js +6 -11
  16. package/dist/index.js +2 -3
  17. package/dist/runtime-api.js +4 -4
  18. package/dist/secret-contract-api.js +1 -1
  19. package/dist/setup-entry.js +3 -4
  20. package/dist/setup-plugin-api.js +1 -1
  21. package/node_modules/zod/package.json +1 -1
  22. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  23. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  24. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  25. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  26. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  27. package/node_modules/zod/src/v4/core/util.ts +13 -0
  28. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  29. package/node_modules/zod/v4/core/compile.cjs +8 -0
  30. package/node_modules/zod/v4/core/compile.js +8 -0
  31. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  32. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  33. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  34. package/node_modules/zod/v4/core/schemas.js +30 -0
  35. package/node_modules/zod/v4/core/util.cjs +15 -0
  36. package/node_modules/zod/v4/core/util.d.cts +2 -0
  37. package/node_modules/zod/v4/core/util.d.ts +2 -0
  38. package/node_modules/zod/v4/core/util.js +14 -0
  39. package/node_modules/zod/v4/core/versions.cjs +1 -1
  40. package/node_modules/zod/v4/core/versions.js +1 -1
  41. package/package.json +5 -7
  42. package/dist/.setup/setup-plugin-api-0RMVREuM.mjs +0 -1
  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,24 +1,23 @@
1
- import { h as resolveClickClackAccount, p as listClickClackAccountIds } from "./setup-surface-BJ3jioqA.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-DRcZ_twH.mjs";
3
- import { a as createClickClackClient, i as ClickClackHttpError, o as isClickClackChannelNameConflict, t as findClickClackWorkspace } from "./resolve-Br3ylpSz.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";
13
- //#region extensions/clickclack/src/discussions/binding-retention.ts
12
+ import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
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,32 +44,22 @@ 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
- //#endregion
73
- //#region extensions/clickclack/src/discussions/control-session-url.ts
62
+ // extensions/clickclack/src/discussions/control-session-url.ts
74
63
  function controlSessionUrl(baseUrl, sessionKey, fallbackAgentId, mainKey, displayName) {
75
64
  if (!baseUrl) return;
76
65
  const url = new URL(baseUrl);
@@ -87,22 +76,7 @@ function controlSessionUrl(baseUrl, sessionKey, fallbackAgentId, mainKey, displa
87
76
  url.hash = "";
88
77
  return url.toString();
89
78
  }
90
- //#endregion
91
- //#region extensions/clickclack/src/discussions/history-format.ts
92
- function discussionRecordJson(value) {
93
- return JSON.stringify(value).replace(/[\u0085\u2028\u2029]/gu, (separator) => `\\u${separator.charCodeAt(0).toString(16).padStart(4, "0")}`);
94
- }
95
- /** Renders channel history as line-per-message records for the discussion tool. */
96
- function formatDiscussionHistory(history) {
97
- const text = history.messages.map((message) => {
98
- const author = message.author?.display_name || message.author?.handle || message.author_id || "Unknown";
99
- return `timestamp=${discussionRecordJson(message.created_at)} [Author ${discussionRecordJson(author)} id=${discussionRecordJson(message.author_id)}] text=${discussionRecordJson(message.body)}`;
100
- }).join("\n");
101
- const truncationNote = history.truncated ? "\n[History scan reached its safety bound; older active threads may be omitted.]" : "";
102
- return text ? `${text}${truncationNote}` : "";
103
- }
104
- //#endregion
105
- //#region extensions/clickclack/src/discussions/installation.ts
79
+ // extensions/clickclack/src/discussions/installation.ts
106
80
  const INSTALLATION_NAMESPACE = "discussion-installation";
107
81
  const INSTALLATION_KEY = "current";
108
82
  /** Returns the durable installation namespace used in server-visible ownership refs. */
@@ -120,65 +94,56 @@ async function getClickClackDiscussionInstallationId(runtime) {
120
94
  if (!persisted) throw new Error("ClickClack discussion installation identity is unavailable; retry opening the discussion");
121
95
  return persisted;
122
96
  }
123
- //#endregion
124
- //#region extensions/clickclack/src/discussions/reconcile-scheduler.ts
125
- const RECONCILE_DEBOUNCE_MS = 250;
126
- const RECONCILE_RETRY_MS = 1e3;
127
- const RECONCILE_RETRY_MAX_MS = 6e4;
128
- /**
129
- * Per-session debounced reconcile scheduling with failure backoff.
130
- * Contracts: bursts coalesce onto the earliest scheduled run (steady event
131
- * traffic can never postpone one); a failed run sets a not-before floor with
132
- * growing backoff that later events cannot undercut; events during an
133
- * in-flight run collapse into one follow-up scheduled after settlement; and
134
- * each service activation owns a separate scheduler scope and retry state.
135
- */
136
- var DiscussionReconcileScheduler = class {
137
- #hooks;
138
- #retryState = /* @__PURE__ */ new Map();
139
- #inFlight = /* @__PURE__ */ new Set();
140
- #followUps = /* @__PURE__ */ new Set();
141
- constructor(scheduler, hooks) {
142
- this.scheduler = scheduler;
143
- this.#hooks = hooks;
144
- }
145
- schedule(sessionKey, delayMs = RECONCILE_DEBOUNCE_MS) {
146
- if (this.scheduler.signal.aborted) return;
147
- if (this.#inFlight.has(sessionKey)) {
148
- this.#followUps.add(sessionKey);
149
- return;
150
- }
151
- const retry = this.#retryState.get(sessionKey);
152
- const fireAt = Math.max(this.scheduler.now() + delayMs, retry?.notBefore ?? 0);
153
- this.scheduler.schedule({
154
- id: `session:${sessionKey}`,
155
- atMs: fireAt,
156
- mode: "earliest",
157
- run: async () => {
158
- this.#inFlight.add(sessionKey);
159
- try {
160
- await this.#hooks.run(sessionKey);
161
- this.#retryState.delete(sessionKey);
162
- } catch (error) {
163
- if (this.scheduler.signal.aborted) return;
164
- const previous = this.#retryState.get(sessionKey);
165
- const nextRetryMs = Math.min(previous === void 0 ? RECONCILE_RETRY_MS : previous.delayMs * 2, RECONCILE_RETRY_MAX_MS);
166
- this.#retryState.set(sessionKey, {
167
- delayMs: nextRetryMs,
168
- notBefore: this.scheduler.now() + nextRetryMs
169
- });
170
- this.#hooks.warn(`discussion event reconcile failed for ${sessionKey}; retrying in ${nextRetryMs}ms: ${String(error)}`);
171
- this.#followUps.add(sessionKey);
172
- } finally {
173
- this.#inFlight.delete(sessionKey);
174
- if (!this.scheduler.signal.aborted && this.#followUps.delete(sessionKey)) this.schedule(sessionKey);
175
- }
176
- }
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
177
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();
178
144
  }
179
- };
180
- //#endregion
181
- //#region extensions/clickclack/src/discussions/service-open.ts
145
+ }
146
+ // extensions/clickclack/src/discussions/service-open.ts
182
147
  const CHANNEL_NAME_MUTATION_ATTEMPTS = 4;
183
148
  function isDefinitiveNoCreateHttpError(error) {
184
149
  if (!(error instanceof ClickClackHttpError) || error.status < 400 || error.status >= 500) return false;
@@ -241,13 +206,24 @@ async function renameDiscussionChannel(params) {
241
206
  }
242
207
  throw new Error("ClickClack discussion channel name retries were exhausted");
243
208
  }
244
- function assertManagedChannelContract(channel, expected) {
245
- const displayTitleMatches = !("display_title" in channel) || channel.display_title === expected.displayTitle;
246
- 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}`);
247
- }
248
209
  function assertManagedChannelListContract(channels) {
249
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");
250
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
+ }
251
227
  async function openClickClackDiscussionBinding(params) {
252
228
  const { account, runtime, sessionKey, store } = params;
253
229
  const entry = await readDiscussionSessionEntry(runtime, sessionKey);
@@ -268,7 +244,13 @@ async function openClickClackDiscussionBinding(params) {
268
244
  });
269
245
  const unresolved = await getPendingDiscussionOpen(runtime, sessionKey);
270
246
  if (unresolved && (unresolved.accountId !== account.accountId || unresolved.credentialFingerprint !== credentialFingerprint || unresolved.serverBaseUrl !== serverBaseUrl || unresolved.workspaceId !== workspace.id)) {
271
- await params.reconcilePendingOpen(unresolved);
247
+ await reconcilePendingDiscussionOpen({
248
+ runtime,
249
+ store,
250
+ clientFactory: params.clientFactory,
251
+ pending: unresolved,
252
+ allowRetry: false
253
+ });
272
254
  if (await getPendingDiscussionOpen(runtime, sessionKey)) throw new Error("A previous ClickClack discussion open is still unresolved; restore its credential and retry");
273
255
  }
274
256
  const config = runtime.config.current();
@@ -277,16 +259,10 @@ async function openClickClackDiscussionBinding(params) {
277
259
  sessionKey
278
260
  });
279
261
  const fallback = fallbackDiscussionLabel(sessionKey, agentId);
280
- const describeChannel = (session) => {
281
- const label = resolveDiscussionLabel(session, sessionKey, agentId);
282
- return {
283
- label,
284
- displayTitle: label === fallback ? "" : truncateDiscussionDisplayTitle(label),
285
- section: session.category?.trim() || account.discussions.section,
286
- externalUrl: controlSessionUrl(account.discussions.controlUrlBase, sessionKey, account.agentId ?? agentId, config.session?.mainKey, label)
287
- };
288
- };
289
- 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);
290
266
  const assertCurrentAuthority = () => {
291
267
  const currentAccounts = discussionAccounts(runtime.config.current());
292
268
  const currentAccount = currentAccounts.length === 1 ? currentAccounts[0] : void 0;
@@ -307,8 +283,7 @@ async function openClickClackDiscussionBinding(params) {
307
283
  sessionKey,
308
284
  accountId: account.accountId,
309
285
  credentialFingerprint,
310
- destinationIdentity,
311
- createGeneration: params.bindingGenerationFactory
286
+ destinationIdentity
312
287
  });
313
288
  const generationScope = {
314
289
  runtime,
@@ -392,13 +367,8 @@ async function openClickClackDiscussionBinding(params) {
392
367
  }
393
368
  if (!resolved || !managedFields) throw new Error("ClickClack discussion channel name retries were exhausted");
394
369
  try {
395
- assertManagedChannelContract(resolved, {
396
- sessionKey,
397
- externalRef,
398
- section,
399
- externalUrl,
400
- displayTitle
401
- });
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}`);
402
372
  if (adopted) assertChannelPatch(resolved, managedFields);
403
373
  } catch (error) {
404
374
  await clearPendingDiscussionOpen(generationScope);
@@ -417,30 +387,6 @@ async function openClickClackDiscussionBinding(params) {
417
387
  params.warn(`unattached discussion channel remains quarantined: ${channel.id}`);
418
388
  throw new Error("OpenClaw session became inactive while opening its ClickClack discussion");
419
389
  }
420
- const { label: currentLabel, displayTitle: currentDisplayTitle, section: currentSection, externalUrl: updatedExternalUrl } = describeChannel(currentEntry);
421
- const currentExternalUrl = updatedExternalUrl ?? "";
422
- let currentChannel = channel;
423
- if (currentEntry.sessionId !== entry.sessionId || currentLabel !== label || currentDisplayTitle !== displayTitle || currentSection !== section || currentExternalUrl !== (externalUrl ?? "")) try {
424
- currentChannel = await renameDiscussionChannel({
425
- client,
426
- workspaceId: workspace.id,
427
- channelId: channel.id,
428
- label: currentLabel,
429
- sessionKey,
430
- agentId,
431
- patch: {
432
- ...managedFields,
433
- external_url: currentExternalUrl,
434
- sidebar_section: currentSection,
435
- display_title: currentDisplayTitle
436
- },
437
- assertCurrentAuthority
438
- });
439
- } catch (error) {
440
- await clearPendingDiscussionOpen(generationScope);
441
- params.warn(`unattached discussion channel remains quarantined: ${channel.id}`);
442
- throw error;
443
- }
444
390
  const nextBinding = {
445
391
  accountId: account.accountId,
446
392
  agentId,
@@ -448,16 +394,16 @@ async function openClickClackDiscussionBinding(params) {
448
394
  serverBaseUrl,
449
395
  credentialFingerprint,
450
396
  externalRef,
451
- externalUrl: currentExternalUrl,
397
+ externalUrl: externalUrl ?? "",
452
398
  workspaceRef: account.discussions.workspace,
453
399
  workspaceId: workspace.id,
454
400
  channelId: channel.id,
455
401
  channelRouteId: channel.route_id,
456
402
  workspaceRouteId: workspace.route_id,
457
- section: currentSection,
403
+ section,
458
404
  archived: false,
459
- label: currentLabel,
460
- ...currentChannel.display_title !== void 0 ? { displayTitle: currentChannel.display_title } : {}
405
+ label,
406
+ ...channel.display_title !== void 0 ? { displayTitle: channel.display_title } : {}
461
407
  };
462
408
  try {
463
409
  nextBinding.sessionId = assertCurrentAuthority().sessionId;
@@ -473,33 +419,31 @@ async function openClickClackDiscussionBinding(params) {
473
419
  params.warn(`unbound discussion channel remains quarantined: ${channel.id}`);
474
420
  throw error;
475
421
  }
476
- await params.finalizePendingBinding(sessionKey, nextBinding);
422
+ await finalizePendingDiscussionBinding(runtime, sessionKey, nextBinding);
477
423
  return nextBinding;
478
424
  });
479
425
  }
426
+ /** Returns whether the service should retry inside its current session queue. */
480
427
  async function reconcilePendingDiscussionOpen(params) {
481
428
  const { pending } = params;
482
429
  const currentBinding = await params.store.getAsync(pending.sessionKey);
483
430
  if (currentBinding?.externalRef === pending.externalRef) {
484
- await params.finalizePendingBinding(pending.sessionKey, currentBinding);
485
- return;
431
+ await finalizePendingDiscussionBinding(params.runtime, pending.sessionKey, currentBinding);
432
+ return false;
486
433
  }
487
434
  const cfg = params.runtime.config.current();
488
435
  const account = listClickClackAccountIds(cfg).map((accountId) => resolveClickClackAccount({
489
436
  cfg,
490
437
  accountId
491
438
  })).find((candidate) => candidate.configured && normalizedServerBaseUrl(candidate) === pending.serverBaseUrl && discussionCredentialFingerprint(candidate.token) === pending.credentialFingerprint);
492
- if (!account) return;
439
+ if (!account) return false;
493
440
  const client = params.clientFactory(account);
494
441
  const entry = await readDiscussionSessionEntry(params.runtime, pending.sessionKey);
495
442
  const activeAccounts = discussionAccounts(cfg);
496
443
  const retryAccount = activeAccounts.length === 1 ? activeAccounts[0] : void 0;
497
444
  if (params.allowRetry !== false && entry?.sessionId && entry.archivedAt === void 0 && retryAccount && normalizedServerBaseUrl(retryAccount) === pending.serverBaseUrl && discussionCredentialFingerprint(retryAccount.token) === pending.credentialFingerprint) {
498
445
  const workspaces = await params.clientFactory(retryAccount).workspaces();
499
- if (findClickClackWorkspace(workspaces, retryAccount.discussions.workspace)?.id === pending.workspaceId) {
500
- await params.open(pending.sessionKey);
501
- return;
502
- }
446
+ if (findClickClackWorkspace(workspaces, retryAccount.discussions.workspace)?.id === pending.workspaceId) return true;
503
447
  }
504
448
  const channels = await client.channels(pending.workspaceId);
505
449
  assertManagedChannelListContract(channels);
@@ -516,48 +460,45 @@ async function reconcilePendingDiscussionOpen(params) {
516
460
  sessionKey: pending.sessionKey,
517
461
  expectedGeneration: pending.generation
518
462
  });
519
- return;
463
+ return false;
520
464
  }
521
465
  await clearDiscussionBindingGeneration({
522
466
  runtime: params.runtime,
523
467
  sessionKey: pending.sessionKey,
524
468
  expectedGeneration: pending.generation
525
469
  });
470
+ return false;
526
471
  }
527
- //#endregion
528
- //#region extensions/clickclack/src/discussions/service.ts
472
+ // extensions/clickclack/src/discussions/service.ts
529
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;
530
477
  var ClickClackDiscussionService = class {
531
478
  #runtime;
532
479
  #store;
533
480
  #clientFactory;
534
481
  #installationId;
535
- #bindingGenerationFactory;
536
482
  #detachedBindings;
537
483
  #sessionQueue = new KeyedAsyncQueue();
538
484
  #scheduler;
539
- #reconcileScheduler;
485
+ #scheduleReconcile;
540
486
  #withChannelMutationLock = createAsyncLock();
541
487
  #timer;
542
- #reconcileAllPromise;
543
488
  #unsubscribeSessionsChanged;
544
489
  #closed = false;
545
- #activation = 0;
546
490
  #cleanupPromise;
547
491
  #operations = /* @__PURE__ */ new Set();
548
- constructor(runtime, options = {}) {
492
+ constructor(runtime) {
549
493
  this.#runtime = runtime;
550
494
  this.#store = getClickClackDiscussionBindingStore(runtime);
551
- this.#clientFactory = options.clientFactory ?? ((account) => createClickClackClient({
495
+ this.#clientFactory = (account) => createClickClackClient({
552
496
  baseUrl: account.apiEndpoint,
553
497
  token: account.token
554
- }));
555
- this.#installationId = options.installationId;
556
- this.#bindingGenerationFactory = options.bindingGenerationFactory ?? randomUUID;
498
+ });
557
499
  this.#detachedBindings = new DetachedDiscussionBindingRetention({
558
500
  runtime,
559
- store: this.#store,
560
- maxRetained: options.maxRetainedDetachedBindings ?? 1e3
501
+ store: this.#store
561
502
  });
562
503
  this.provider = {
563
504
  id: "clickclack",
@@ -566,40 +507,78 @@ var ClickClackDiscussionService = class {
566
507
  };
567
508
  }
568
509
  async bindGatewayEvents(gatewayEvents, scheduler) {
569
- const activation = ++this.#activation;
570
510
  if (this.#cleanupPromise) await this.#cleanupPromise;
571
- if (activation !== this.#activation) return;
572
511
  if (this.#scheduler) await this.#scheduler.stop();
573
- if (activation !== this.#activation) return;
574
512
  this.#cleanupPromise = void 0;
575
513
  this.#unsubscribeSessionsChanged?.();
576
514
  this.#closed = false;
577
515
  this.#scheduler = scheduler.scope();
578
516
  this.#timer = void 0;
579
- this.#reconcileScheduler = new DiscussionReconcileScheduler(this.#scheduler, {
580
- run: (sessionKey) => this.reconcile(sessionKey),
581
- warn: (message) => this.#logger().warn(message)
582
- });
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;
583
564
  this.#unsubscribeSessionsChanged = gatewayEvents?.onSessionsChanged((event) => {
584
565
  this.#withOperation(async () => {
585
- if (await this.#store.getAsync(event.sessionKey) || await getPendingDiscussionOpen(this.#runtime, event.sessionKey)) {
586
- if (activation === this.#activation) this.#reconcileScheduler?.schedule(event.sessionKey);
587
- }
566
+ if (await this.#store.getAsync(event.sessionKey) || await getPendingDiscussionOpen(this.#runtime, event.sessionKey)) this.#scheduleReconcile?.(event.sessionKey);
588
567
  }).catch((error) => {
589
568
  this.#logger().warn(`discussion event admission failed: ${String(error)}`);
590
569
  });
591
570
  });
592
571
  await this.#withOperation(async () => {
593
- for (const sessionKey of await this.#listReconcileSessionKeys()) {
594
- if (activation !== this.#activation) return;
595
- this.#reconcileScheduler?.schedule(sessionKey, 0);
596
- }
572
+ for (const sessionKey of await this.#listReconcileSessionKeys()) this.#scheduleReconcile?.(sessionKey, 0);
597
573
  await this.#ensureTimer();
598
574
  });
599
575
  }
600
576
  hasEnabledAccount() {
601
577
  return discussionAccounts(this.#currentConfig()).length === 1;
602
578
  }
579
+ resolveBindingAccount(binding) {
580
+ return resolveDiscussionBindingAccount(this.#currentConfig(), binding);
581
+ }
603
582
  async info(sessionKey) {
604
583
  return await this.#withOperation(() => this.#sessionQueue.enqueue(sessionKey, async () => {
605
584
  await this.#store.prepare();
@@ -657,13 +636,10 @@ var ClickClackDiscussionService = class {
657
636
  account,
658
637
  clientFactory: this.#clientFactory,
659
638
  installationId: this.#installationId,
660
- bindingGenerationFactory: this.#bindingGenerationFactory,
661
639
  sessionKey,
662
640
  ensureTimer: () => this.#ensureTimer(),
663
- reconcilePendingOpen: (pending) => this.#reconcilePendingOpen(pending, { allowRetry: false }),
664
641
  withChannelMutationLock: (run) => this.#withChannelMutationLock(run),
665
642
  ensureBindingCapacity: (key) => this.#detachedBindings.ensureCapacity(key),
666
- finalizePendingBinding: (key, nextBinding) => this.#finalizePendingBinding(key, nextBinding),
667
643
  warn: (message) => this.#logger().warn(message)
668
644
  });
669
645
  } finally {
@@ -682,7 +658,14 @@ var ClickClackDiscussionService = class {
682
658
  const binding = await this.#store.getAsync(sessionKey);
683
659
  if (binding) await this.#reconcileBinding(sessionKey, binding);
684
660
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
685
- 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
+ }
686
669
  });
687
670
  } finally {
688
671
  await this.#ensureTimer();
@@ -690,21 +673,15 @@ var ClickClackDiscussionService = class {
690
673
  }
691
674
  async reconcileAll() {
692
675
  return await this.#withOperation(async () => {
693
- if (this.#reconcileAllPromise) return await this.#reconcileAllPromise;
694
- this.#reconcileAllPromise = (async () => {
695
- try {
696
- for (const sessionKey of await this.#listReconcileSessionKeys()) try {
697
- await this.#reconcile(sessionKey);
698
- } catch (error) {
699
- this.#logger().warn(`discussion reconcile failed for ${sessionKey}: ${String(error)}`);
700
- }
701
- } finally {
702
- 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)}`);
703
681
  }
704
- })().finally(() => {
705
- this.#reconcileAllPromise = void 0;
706
- });
707
- return await this.#reconcileAllPromise;
682
+ } finally {
683
+ await this.#ensureTimer();
684
+ }
708
685
  });
709
686
  }
710
687
  async readLatestMessages(sessionKey, limit) {
@@ -716,30 +693,27 @@ var ClickClackDiscussionService = class {
716
693
  if (resolved.state !== "active") return { text: "No discussion is bound to this session." };
717
694
  const attached = await this.#refreshSessionAttachment(sessionKey, binding);
718
695
  if (!attached) return { text: "No discussion is bound to this session." };
719
- if (!bindingMatchesActiveSessionIncarnation(this.#runtime, sessionKey, attached) || resolveDiscussionBindingAccount(this.#currentConfig(), attached).state !== "active" || isClickClackDiscussionChannelRevoked({
696
+ return await readDiscussionHistory({
720
697
  runtime: this.#runtime,
721
- serverBaseUrl: binding.serverBaseUrl,
722
- channelId: binding.channelId,
723
- binding: attached
724
- })) return { text: "No discussion is bound to this session." };
725
- return {
698
+ store: this.#store,
699
+ sessionKey,
726
700
  binding: attached,
727
- text: formatDiscussionHistory(await this.#clientFactory(resolved.account).latestChannelMessages(attached.channelId, limit)) || "The bound discussion has no messages yet."
728
- };
701
+ client: this.#clientFactory(resolved.account),
702
+ limit
703
+ });
729
704
  }));
730
705
  }
731
706
  cleanup() {
732
707
  this.#closed = true;
733
- this.#activation += 1;
734
708
  this.#unsubscribeSessionsChanged?.();
735
709
  this.#unsubscribeSessionsChanged = void 0;
736
- this.#reconcileScheduler = void 0;
710
+ this.#scheduleReconcile = void 0;
737
711
  this.#timer = void 0;
738
712
  this.#cleanupPromise ??= Promise.allSettled([this.#scheduler?.stop(), ...this.#operations]).then(() => void 0);
739
713
  return this.#cleanupPromise;
740
714
  }
741
715
  async #reconcileBinding(sessionKey, binding, resolvedAccount) {
742
- await this.#finalizePendingBinding(sessionKey, binding);
716
+ await finalizePendingDiscussionBinding(this.#runtime, sessionKey, binding);
743
717
  if (await isClickClackDiscussionChannelRevokedAsync({
744
718
  runtime: this.#runtime,
745
719
  serverBaseUrl: binding.serverBaseUrl,
@@ -756,7 +730,7 @@ var ClickClackDiscussionService = class {
756
730
  }
757
731
  const activeBinding = await this.#detachedBindings.clear(sessionKey, binding);
758
732
  if (!activeBinding) return;
759
- const resolved = resolvedAccount ? resolveDiscussionBindingAccount(this.#currentConfig(), activeBinding) : await this.#resolveBindingForUse(activeBinding);
733
+ const resolved = resolvedAccount ? this.resolveBindingAccount(activeBinding) : await this.#resolveBindingForUse(activeBinding);
760
734
  if (resolved.state === "retargeted") {
761
735
  await this.#revokeAndDeleteBinding(sessionKey, activeBinding);
762
736
  return;
@@ -788,7 +762,7 @@ var ClickClackDiscussionService = class {
788
762
  bindingForAttachment = freshBinding;
789
763
  observedSiblingTitleSupport = bindings.some(({ binding: candidate }) => candidate.displayTitle !== void 0 && candidate.serverBaseUrl === freshBinding.serverBaseUrl && candidate.accountId === freshBinding.accountId);
790
764
  }
791
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), bindingForAttachment);
765
+ const current = this.resolveBindingAccount(bindingForAttachment);
792
766
  if (current.state !== "active") return;
793
767
  const account = current.account;
794
768
  const attached = await this.#refreshSessionAttachment(sessionKey, bindingForAttachment);
@@ -807,41 +781,54 @@ var ClickClackDiscussionService = class {
807
781
  if (section !== currentBinding.section) patch.sidebar_section = section;
808
782
  if (externalUrl !== currentBinding.externalUrl) patch.external_url = externalUrl;
809
783
  if (Object.keys(patch).length === 0 && !labelChanged) return;
810
- const client = this.#clientFactory(account);
811
- const assertCurrentAuthority = () => {
812
- const bound = this.#store.get(sessionKey);
813
- 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({
814
789
  runtime: this.#runtime,
815
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,
816
806
  channelId: currentBinding.channelId,
817
- binding: bound
818
- })) throw new Error("ClickClack discussion authority changed before channel update");
819
- };
820
- let updated;
821
- if (labelChanged) updated = await this.#withChannelMutationLock(() => renameDiscussionChannel({
822
- client,
823
- workspaceId: currentBinding.workspaceId,
824
- channelId: currentBinding.channelId,
825
- label,
826
- sessionKey,
827
- agentId: currentBinding.agentId,
828
- patch,
829
- assertCurrentAuthority
830
- }));
831
- else {
832
- assertCurrentAuthority();
833
- updated = await client.updateChannel(currentBinding.channelId, patch);
834
- 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();
835
831
  }
836
- const nextBinding = {
837
- ...currentBinding,
838
- externalUrl,
839
- label,
840
- section,
841
- ...updated.display_title !== void 0 ? { displayTitle: updated.display_title } : {}
842
- };
843
- if (updated.display_title === void 0) delete nextBinding.displayTitle;
844
- await this.#store.setIfCurrent(sessionKey, currentBinding, nextBinding, { assertCurrent: assertCurrentAuthority });
845
832
  }
846
833
  async #refreshSessionAttachment(sessionKey, binding) {
847
834
  try {
@@ -856,17 +843,6 @@ var ClickClackDiscussionService = class {
856
843
  return;
857
844
  }
858
845
  }
859
- async #reconcilePendingOpen(pending, options = {}) {
860
- await reconcilePendingDiscussionOpen({
861
- runtime: this.#runtime,
862
- store: this.#store,
863
- clientFactory: this.#clientFactory,
864
- pending,
865
- ...options,
866
- finalizePendingBinding: (key, binding) => this.#finalizePendingBinding(key, binding),
867
- open: (key) => this.#open(key)
868
- });
869
- }
870
846
  async #releaseStaleBinding(sessionKey, binding) {
871
847
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
872
848
  if (pending?.externalRef === binding.externalRef) await clearDiscussionBindingGeneration({
@@ -880,27 +856,12 @@ var ClickClackDiscussionService = class {
880
856
  if (!await markClickClackDiscussionChannelRevoked(this.#runtime, sessionKey, binding)) return false;
881
857
  return await this.#store.deleteIfCurrent(sessionKey, binding);
882
858
  }
883
- async #finalizePendingBinding(sessionKey, binding) {
884
- const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
885
- if (pending?.externalRef === binding.externalRef) {
886
- await clearClickClackDiscussionChannelRevoked({
887
- runtime: this.#runtime,
888
- serverBaseUrl: binding.serverBaseUrl,
889
- channelId: binding.channelId
890
- });
891
- await clearDiscussionBindingGeneration({
892
- runtime: this.#runtime,
893
- sessionKey,
894
- expectedGeneration: pending.generation
895
- });
896
- }
897
- }
898
859
  async #resolveBindingForUse(binding) {
899
- const resolved = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
860
+ const resolved = this.resolveBindingAccount(binding);
900
861
  if (resolved.state !== "active") return resolved;
901
862
  const workspaces = await this.#clientFactory(resolved.account).workspaces();
902
863
  const workspace = findClickClackWorkspace(workspaces, resolved.account.discussions.workspace);
903
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
864
+ const current = this.resolveBindingAccount(binding);
904
865
  if (current.state !== "active") return current;
905
866
  return workspace?.id === binding.workspaceId ? current : { state: "retargeted" };
906
867
  }
@@ -945,8 +906,9 @@ var ClickClackDiscussionService = class {
945
906
  return operation;
946
907
  }
947
908
  };
948
- //#endregion
949
- //#region 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;
950
912
  const TARGETED_SESSION_TOOLS = /* @__PURE__ */ new Set([
951
913
  "sessions_history",
952
914
  "sessions_send",
@@ -958,78 +920,74 @@ function blockedResult() {
958
920
  blockReason: `ClickClack discussion sessions may use ${[...TARGETED_SESSION_TOOLS].join(", ")} only with their attached main session.`
959
921
  };
960
922
  }
961
- function isClickClackDiscussionSessionTarget(params) {
962
- if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
963
- const { runtime, targetSessionKey } = params;
964
- let binding;
965
- try {
966
- const store = getClickClackDiscussionBindingStore(runtime);
967
- store.assertReadAvailable();
968
- binding = store.get(targetSessionKey);
969
- } catch {
923
+ function registerClickClackDiscussions(api) {
924
+ if (api.registrationMode === "tool-discovery") {
925
+ api.registerTool(() => null, { name: "discussion" });
970
926
  return;
971
927
  }
972
- return currentDiscussionTarget(params, binding, (current) => isClickClackDiscussionChannelRevoked({
973
- runtime,
974
- serverBaseUrl: current.serverBaseUrl,
975
- channelId: current.channelId,
976
- binding: current
977
- }));
978
- }
979
- function currentDiscussionTarget(params, binding, isRevoked) {
980
- const { runtime, targetSessionKey } = params;
981
- if (binding && discussionSessionKey({
982
- runtime,
983
- mainSessionKey: targetSessionKey,
984
- ...binding
985
- }) === params.requesterSessionKey && !isRevoked(binding) && bindingMatchesActiveSessionIncarnation(runtime, targetSessionKey, binding) && resolveDiscussionBindingAccount(runtime.config.current(), binding).state === "active") return {
986
- sessionKey: targetSessionKey,
987
- binding
988
- };
989
- }
990
- async function resolveClickClackDiscussionSessionTarget(params) {
991
- if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
992
- let facts;
993
- let revocation;
994
- try {
995
- facts = await getClickClackDiscussionBindingStore(params.runtime).prepareRead(params.targetSessionKey);
996
- const binding = facts.read();
997
- if (!binding) return;
998
- revocation = await prepareClickClackDiscussionChannelRevocation({
999
- 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,
1000
953
  ...binding
1001
- });
1002
- return currentDiscussionTarget(params, facts.read(), revocation.isRevoked);
1003
- } catch {
1004
- return;
1005
- } finally {
1006
- revocation?.release();
1007
- facts?.release();
954
+ }) === params.requesterSessionKey && !isRevoked(binding) && isActiveSession(binding) && service.resolveBindingAccount(binding).state === "active") return {
955
+ sessionKey: targetSessionKey,
956
+ binding
957
+ };
1008
958
  }
1009
- }
1010
- /** Restricts a discussion side session's session tools to its attached main session. */
1011
- async function enforceClickClackDiscussionToolTarget(params) {
1012
- const callerSessionKey = params.context.sessionKey;
1013
- if (!callerSessionKey || !isDiscussionSessionKey(callerSessionKey)) return;
1014
- const { toolName } = params.event;
1015
- if (toolName !== "session_status" && !toolName.startsWith("sessions_")) return;
1016
- const usesAlternateSendTarget = toolName === "sessions_send" && (params.event.params.label !== void 0 || params.event.params.agentId !== void 0);
1017
- const mutatesStatus = toolName === "session_status" && params.event.params.model !== void 0;
1018
- const selectsHistoryIncarnation = toolName === "sessions_history" && params.event.params.sessionId !== void 0;
1019
- const targetSessionKey = params.event.params.sessionKey;
1020
- if (TARGETED_SESSION_TOOLS.has(toolName) && typeof targetSessionKey === "string" && !usesAlternateSendTarget && !mutatesStatus && !selectsHistoryIncarnation && await resolveClickClackDiscussionSessionTarget({
1021
- runtime: params.runtime,
1022
- requesterSessionKey: callerSessionKey,
1023
- targetSessionKey
1024
- })) return;
1025
- return blockedResult();
1026
- }
1027
- //#endregion
1028
- //#region extensions/clickclack/src/discussions/tool.ts
1029
- const DEFAULT_MESSAGE_LIMIT = 30;
1030
- const MAX_MESSAGE_LIMIT = 200;
1031
- function createClickClackDiscussionTool(params) {
1032
- 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 }) => ({
1033
991
  name: "discussion",
1034
992
  label: "Discussion",
1035
993
  description: "Read the latest messages from the ClickClack discussion bound to this session.",
@@ -1044,51 +1002,40 @@ function createClickClackDiscussionTool(params) {
1044
1002
  additionalProperties: false
1045
1003
  },
1046
1004
  async execute(_toolCallId, input) {
1047
- 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 });
1048
1006
  const requested = typeof input === "object" && input !== null && "limit" in input ? Number(input.limit) : DEFAULT_MESSAGE_LIMIT;
1049
1007
  const limit = Number.isInteger(requested) ? Math.max(1, Math.min(MAX_MESSAGE_LIMIT, requested)) : DEFAULT_MESSAGE_LIMIT;
1050
- const result = await params.service.readLatestMessages(params.sessionKey, limit);
1008
+ const result = await service.readLatestMessages(sessionKey, limit);
1051
1009
  return textResult(result.text, {
1052
1010
  bound: Boolean(result.binding),
1053
1011
  limit,
1054
1012
  ...result.binding ? { channelId: result.binding.channelId } : {}
1055
1013
  });
1056
1014
  }
1057
- };
1058
- }
1059
- //#endregion
1060
- //#region extensions/clickclack/src/discussions/register.ts
1061
- function registerClickClackDiscussions(api) {
1062
- if (api.registrationMode === "tool-discovery") {
1063
- api.registerTool(() => null, { name: "discussion" });
1064
- return;
1065
- }
1066
- const service = new ClickClackDiscussionService(api.runtime);
1067
- api.registerService({
1068
- id: "clickclack-discussion-session-events",
1069
- apiVersion: 2,
1070
- start: ({ gatewayEvents, scheduler }) => service.bindGatewayEvents(gatewayEvents, scheduler),
1071
- stop: () => service.cleanup()
1072
- });
1073
- api.registerTool((context) => createClickClackDiscussionTool({
1074
- service,
1075
- sessionKey: context.sessionKey
1076
- }));
1077
- api.on("before_tool_call", (event, context) => enforceClickClackDiscussionToolTarget({
1078
- runtime: api.runtime,
1079
- event,
1080
- context
1081
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
+ });
1082
1031
  const unregisterSessionAccess = createSessionVisibilityChecker.registerScopedAccessProvider(({ requesterSessionKey, targetSessionKey }) => {
1083
1032
  const target = isClickClackDiscussionSessionTarget({
1084
- runtime: api.runtime,
1085
1033
  requesterSessionKey,
1086
1034
  targetSessionKey
1087
1035
  });
1088
1036
  return target ? { expectedSessionId: target.binding.sessionId } : void 0;
1089
1037
  }, { async resolveAsync({ requesterSessionKey, targetSessionKey }) {
1090
1038
  const target = await resolveClickClackDiscussionSessionTarget({
1091
- runtime: api.runtime,
1092
1039
  requesterSessionKey,
1093
1040
  targetSessionKey
1094
1041
  });
@@ -1106,5 +1053,4 @@ function registerClickClackDiscussions(api) {
1106
1053
  }
1107
1054
  });
1108
1055
  }
1109
- //#endregion
1110
1056
  export { registerClickClackDiscussions as t };