@openclaw/clickclack 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/.setup/{channel-BX2RqmGn.mjs → channel-D3WIuNxS.mjs} +398 -506
  2. package/dist/.setup/{resolve-B-W04sGX.mjs → resolve-BgFJI_p4.mjs} +28 -52
  3. package/dist/.setup/{rolldown-runtime-B4FMCO8f.mjs → rolldown-runtime-BBjsoOtd.mjs} +0 -1
  4. package/dist/.setup/{runtime-api-DIu-sNJs.mjs → runtime-api-CMReYU7v.mjs} +325 -371
  5. package/dist/.setup/secret-contract-api--45pFCg3.mjs +2 -0
  6. package/dist/.setup/{setup-claim-BJPvHiWS.mjs → setup-claim-Ca2nzQHc.mjs} +4 -9
  7. package/dist/.setup/{setup-plugin-api-BiMffAUC.mjs → setup-plugin-api-CFG0EYat.mjs} +1 -1
  8. package/dist/.setup/setup-plugin-api-Cg_ECaNj.mjs +1 -0
  9. package/dist/.setup/{setup-surface-fPdDl0l2.mjs → setup-surface-CSITttSD.mjs} +5 -5
  10. package/dist/.setup/{setup-verify-B5iJBDrk.mjs → setup-verify-DLfG0Fyt.mjs} +12 -24
  11. package/dist/.source-module-urls/aa673c321fe9be084b8926cbe5388ff5e2a41371389e19ca60a1983f2b634030.json +1 -0
  12. package/dist/api.js +3 -3
  13. package/dist/channel-plugin-api.js +1 -2
  14. package/dist/doctor-contract-api.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/runtime-api.js +4 -4
  17. package/dist/secret-contract-api.js +1 -2
  18. package/dist/setup-entry.js +2 -2
  19. package/dist/setup-plugin-api.js +1 -2
  20. package/node_modules/zod/package.json +1 -1
  21. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  22. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  23. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  24. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  25. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  26. package/node_modules/zod/src/v4/core/util.ts +13 -0
  27. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  28. package/node_modules/zod/v4/core/compile.cjs +8 -0
  29. package/node_modules/zod/v4/core/compile.js +8 -0
  30. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  31. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  32. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  33. package/node_modules/zod/v4/core/schemas.js +30 -0
  34. package/node_modules/zod/v4/core/util.cjs +15 -0
  35. package/node_modules/zod/v4/core/util.d.cts +2 -0
  36. package/node_modules/zod/v4/core/util.d.ts +2 -0
  37. package/node_modules/zod/v4/core/util.js +14 -0
  38. package/node_modules/zod/v4/core/versions.cjs +1 -1
  39. package/node_modules/zod/v4/core/versions.js +1 -1
  40. package/package.json +5 -7
  41. package/dist/.setup/secret-contract-api-CBcsgIYZ.mjs +0 -3
  42. package/dist/.setup/setup-plugin-api-bSnZClKM.mjs +0 -2
  43. package/node_modules/ws/LICENSE +0 -20
  44. package/node_modules/ws/README.md +0 -548
  45. package/node_modules/ws/browser.js +0 -8
  46. package/node_modules/ws/index.js +0 -22
  47. package/node_modules/ws/lib/buffer-util.js +0 -131
  48. package/node_modules/ws/lib/constants.js +0 -19
  49. package/node_modules/ws/lib/event-target.js +0 -292
  50. package/node_modules/ws/lib/extension.js +0 -203
  51. package/node_modules/ws/lib/limiter.js +0 -55
  52. package/node_modules/ws/lib/permessage-deflate.js +0 -530
  53. package/node_modules/ws/lib/receiver.js +0 -743
  54. package/node_modules/ws/lib/sender.js +0 -607
  55. package/node_modules/ws/lib/stream.js +0 -161
  56. package/node_modules/ws/lib/subprotocol.js +0 -62
  57. package/node_modules/ws/lib/validation.js +0 -152
  58. package/node_modules/ws/lib/websocket-server.js +0 -562
  59. package/node_modules/ws/lib/websocket.js +0 -1421
  60. package/node_modules/ws/package.json +0 -74
  61. package/node_modules/ws/wrapper.mjs +0 -21
@@ -1,24 +1,23 @@
1
- import { h as resolveClickClackAccount, p as listClickClackAccountIds } from "./setup-surface-fPdDl0l2.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-BX2RqmGn.mjs";
3
- import { a as createClickClackClient, i as ClickClackHttpError, o as isClickClackChannelNameConflict, t as findClickClackWorkspace } from "./resolve-B-W04sGX.mjs";
1
+ import { h as resolveClickClackAccount, p as listClickClackAccountIds } from "./setup-surface-CSITttSD.mjs";
2
+ import { A as clearDiscussionBindingGeneration, C as resolveDiscussionLabel, D as bindingMatchesActiveSessionIncarnation, E as attachBindingToCurrentActiveSession, F as reserveDiscussionBindingGeneration, M as getPendingDiscussionOpen, N as listPendingDiscussionOpens, O as getClickClackDiscussionBindingStore, P as recordPendingDiscussionOpen, S as isDiscussionSessionKey, T as truncateDiscussionDisplayTitle, _ as resolveDiscussionBindingAccount, b as discussionSessionKey, c as clearClickClackDiscussionChannelRevoked, d as markClickClackDiscussionChannelIdentityRevoked, f as markClickClackDiscussionChannelRevoked, g as normalizedServerBaseUrl, h as discussionInfoForBinding, j as clearPendingDiscussionOpen, k as readDiscussionSessionEntry, l as isClickClackDiscussionChannelRevoked, m as discussionAccounts, o as prepareDiscussionSessionEntry, p as prepareClickClackDiscussionChannelRevocation, s as adoptLegacyMarkers, u as isClickClackDiscussionChannelRevokedAsync, v as discussionCredentialFingerprint, w as slugifyDiscussionLabel, x as fallbackDiscussionLabel, y as discussionExternalRef } from "./channel-D3WIuNxS.mjs";
3
+ import { a as createClickClackClient, i as ClickClackHttpError, o as isClickClackChannelNameConflict, t as findClickClackWorkspace } from "./resolve-BgFJI_p4.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
  //#region 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
  //#endregion
73
63
  //#region extensions/clickclack/src/discussions/control-session-url.ts
@@ -88,20 +78,6 @@ function controlSessionUrl(baseUrl, sessionKey, fallbackAgentId, mainKey, displa
88
78
  return url.toString();
89
79
  }
90
80
  //#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
81
  //#region extensions/clickclack/src/discussions/installation.ts
106
82
  const INSTALLATION_NAMESPACE = "discussion-installation";
107
83
  const INSTALLATION_KEY = "current";
@@ -121,62 +97,55 @@ async function getClickClackDiscussionInstallationId(runtime) {
121
97
  return persisted;
122
98
  }
123
99
  //#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
- }
100
+ //#region extensions/clickclack/src/discussions/service-history.ts
101
+ function discussionRecordJson(value) {
102
+ return JSON.stringify(value).replace(/[\u0085\u2028\u2029]/gu, (separator) => `\\u${separator.charCodeAt(0).toString(16).padStart(4, "0")}`);
103
+ }
104
+ /** Renders channel history as line-per-message records for the discussion tool. */
105
+ function formatDiscussionHistory(history) {
106
+ const text = history.messages.map((message) => {
107
+ const author = message.author?.display_name || message.author?.handle || message.author_id || "Unknown";
108
+ return `timestamp=${discussionRecordJson(message.created_at)} [Author ${discussionRecordJson(author)} id=${discussionRecordJson(message.author_id)}] text=${discussionRecordJson(message.body)}`;
109
+ }).join("\n");
110
+ const truncationNote = history.truncated ? "\n[History scan reached its safety bound; older active threads may be omitted.]" : "";
111
+ return text ? `${text}${truncationNote}` : "";
112
+ }
113
+ async function readDiscussionHistory(params) {
114
+ const { runtime, store, sessionKey, binding, client, limit } = params;
115
+ const bindingFacts = await store.prepareRead(sessionKey);
116
+ let revocation;
117
+ let session;
118
+ try {
119
+ const channelRevocation = await prepareClickClackDiscussionChannelRevocation({
120
+ runtime,
121
+ ...binding
177
122
  });
123
+ revocation = channelRevocation;
124
+ const sessionEntry = await prepareDiscussionSessionEntry(runtime, sessionKey);
125
+ session = sessionEntry;
126
+ const canReadHistory = () => {
127
+ try {
128
+ sessionEntry.source();
129
+ const current = bindingFacts.read();
130
+ const config = runtime.config.current();
131
+ 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);
132
+ } catch {
133
+ return false;
134
+ }
135
+ };
136
+ if (!canReadHistory()) return { text: "No discussion is bound to this session." };
137
+ const history = await client.latestChannelMessages(binding.channelId, limit);
138
+ if (!canReadHistory()) return { text: "No discussion is bound to this session." };
139
+ return {
140
+ binding,
141
+ text: formatDiscussionHistory(history) || "The bound discussion has no messages yet."
142
+ };
143
+ } finally {
144
+ session?.release();
145
+ revocation?.release();
146
+ bindingFacts.release();
178
147
  }
179
- };
148
+ }
180
149
  //#endregion
181
150
  //#region extensions/clickclack/src/discussions/service-open.ts
182
151
  const CHANNEL_NAME_MUTATION_ATTEMPTS = 4;
@@ -241,13 +210,24 @@ async function renameDiscussionChannel(params) {
241
210
  }
242
211
  throw new Error("ClickClack discussion channel name retries were exhausted");
243
212
  }
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
213
  function assertManagedChannelListContract(channels) {
249
214
  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
215
  }
216
+ async function finalizePendingDiscussionBinding(runtime, sessionKey, binding) {
217
+ const pending = await getPendingDiscussionOpen(runtime, sessionKey);
218
+ if (pending?.externalRef === binding.externalRef) {
219
+ await clearClickClackDiscussionChannelRevoked({
220
+ runtime,
221
+ serverBaseUrl: binding.serverBaseUrl,
222
+ channelId: binding.channelId
223
+ });
224
+ await clearDiscussionBindingGeneration({
225
+ runtime,
226
+ sessionKey,
227
+ expectedGeneration: pending.generation
228
+ });
229
+ }
230
+ }
251
231
  async function openClickClackDiscussionBinding(params) {
252
232
  const { account, runtime, sessionKey, store } = params;
253
233
  const entry = await readDiscussionSessionEntry(runtime, sessionKey);
@@ -268,7 +248,13 @@ async function openClickClackDiscussionBinding(params) {
268
248
  });
269
249
  const unresolved = await getPendingDiscussionOpen(runtime, sessionKey);
270
250
  if (unresolved && (unresolved.accountId !== account.accountId || unresolved.credentialFingerprint !== credentialFingerprint || unresolved.serverBaseUrl !== serverBaseUrl || unresolved.workspaceId !== workspace.id)) {
271
- await params.reconcilePendingOpen(unresolved);
251
+ await reconcilePendingDiscussionOpen({
252
+ runtime,
253
+ store,
254
+ clientFactory: params.clientFactory,
255
+ pending: unresolved,
256
+ allowRetry: false
257
+ });
272
258
  if (await getPendingDiscussionOpen(runtime, sessionKey)) throw new Error("A previous ClickClack discussion open is still unresolved; restore its credential and retry");
273
259
  }
274
260
  const config = runtime.config.current();
@@ -277,16 +263,10 @@ async function openClickClackDiscussionBinding(params) {
277
263
  sessionKey
278
264
  });
279
265
  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);
266
+ const label = resolveDiscussionLabel(entry, sessionKey, agentId);
267
+ const displayTitle = label === fallback ? "" : truncateDiscussionDisplayTitle(label);
268
+ const section = entry.category?.trim() || account.discussions.section;
269
+ const externalUrl = controlSessionUrl(account.discussions.controlUrlBase, sessionKey, account.agentId ?? agentId, config.session?.mainKey, label);
290
270
  const assertCurrentAuthority = () => {
291
271
  const currentAccounts = discussionAccounts(runtime.config.current());
292
272
  const currentAccount = currentAccounts.length === 1 ? currentAccounts[0] : void 0;
@@ -307,8 +287,7 @@ async function openClickClackDiscussionBinding(params) {
307
287
  sessionKey,
308
288
  accountId: account.accountId,
309
289
  credentialFingerprint,
310
- destinationIdentity,
311
- createGeneration: params.bindingGenerationFactory
290
+ destinationIdentity
312
291
  });
313
292
  const generationScope = {
314
293
  runtime,
@@ -392,13 +371,8 @@ async function openClickClackDiscussionBinding(params) {
392
371
  }
393
372
  if (!resolved || !managedFields) throw new Error("ClickClack discussion channel name retries were exhausted");
394
373
  try {
395
- assertManagedChannelContract(resolved, {
396
- sessionKey,
397
- externalRef,
398
- section,
399
- externalUrl,
400
- displayTitle
401
- });
374
+ const displayTitleMatches = !("display_title" in resolved) || resolved.display_title === displayTitle;
375
+ 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
376
  if (adopted) assertChannelPatch(resolved, managedFields);
403
377
  } catch (error) {
404
378
  await clearPendingDiscussionOpen(generationScope);
@@ -417,30 +391,6 @@ async function openClickClackDiscussionBinding(params) {
417
391
  params.warn(`unattached discussion channel remains quarantined: ${channel.id}`);
418
392
  throw new Error("OpenClaw session became inactive while opening its ClickClack discussion");
419
393
  }
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
394
  const nextBinding = {
445
395
  accountId: account.accountId,
446
396
  agentId,
@@ -448,16 +398,16 @@ async function openClickClackDiscussionBinding(params) {
448
398
  serverBaseUrl,
449
399
  credentialFingerprint,
450
400
  externalRef,
451
- externalUrl: currentExternalUrl,
401
+ externalUrl: externalUrl ?? "",
452
402
  workspaceRef: account.discussions.workspace,
453
403
  workspaceId: workspace.id,
454
404
  channelId: channel.id,
455
405
  channelRouteId: channel.route_id,
456
406
  workspaceRouteId: workspace.route_id,
457
- section: currentSection,
407
+ section,
458
408
  archived: false,
459
- label: currentLabel,
460
- ...currentChannel.display_title !== void 0 ? { displayTitle: currentChannel.display_title } : {}
409
+ label,
410
+ ...channel.display_title !== void 0 ? { displayTitle: channel.display_title } : {}
461
411
  };
462
412
  try {
463
413
  nextBinding.sessionId = assertCurrentAuthority().sessionId;
@@ -473,33 +423,31 @@ async function openClickClackDiscussionBinding(params) {
473
423
  params.warn(`unbound discussion channel remains quarantined: ${channel.id}`);
474
424
  throw error;
475
425
  }
476
- await params.finalizePendingBinding(sessionKey, nextBinding);
426
+ await finalizePendingDiscussionBinding(runtime, sessionKey, nextBinding);
477
427
  return nextBinding;
478
428
  });
479
429
  }
430
+ /** Returns whether the service should retry inside its current session queue. */
480
431
  async function reconcilePendingDiscussionOpen(params) {
481
432
  const { pending } = params;
482
433
  const currentBinding = await params.store.getAsync(pending.sessionKey);
483
434
  if (currentBinding?.externalRef === pending.externalRef) {
484
- await params.finalizePendingBinding(pending.sessionKey, currentBinding);
485
- return;
435
+ await finalizePendingDiscussionBinding(params.runtime, pending.sessionKey, currentBinding);
436
+ return false;
486
437
  }
487
438
  const cfg = params.runtime.config.current();
488
439
  const account = listClickClackAccountIds(cfg).map((accountId) => resolveClickClackAccount({
489
440
  cfg,
490
441
  accountId
491
442
  })).find((candidate) => candidate.configured && normalizedServerBaseUrl(candidate) === pending.serverBaseUrl && discussionCredentialFingerprint(candidate.token) === pending.credentialFingerprint);
492
- if (!account) return;
443
+ if (!account) return false;
493
444
  const client = params.clientFactory(account);
494
445
  const entry = await readDiscussionSessionEntry(params.runtime, pending.sessionKey);
495
446
  const activeAccounts = discussionAccounts(cfg);
496
447
  const retryAccount = activeAccounts.length === 1 ? activeAccounts[0] : void 0;
497
448
  if (params.allowRetry !== false && entry?.sessionId && entry.archivedAt === void 0 && retryAccount && normalizedServerBaseUrl(retryAccount) === pending.serverBaseUrl && discussionCredentialFingerprint(retryAccount.token) === pending.credentialFingerprint) {
498
449
  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
- }
450
+ if (findClickClackWorkspace(workspaces, retryAccount.discussions.workspace)?.id === pending.workspaceId) return true;
503
451
  }
504
452
  const channels = await client.channels(pending.workspaceId);
505
453
  assertManagedChannelListContract(channels);
@@ -516,48 +464,46 @@ async function reconcilePendingDiscussionOpen(params) {
516
464
  sessionKey: pending.sessionKey,
517
465
  expectedGeneration: pending.generation
518
466
  });
519
- return;
467
+ return false;
520
468
  }
521
469
  await clearDiscussionBindingGeneration({
522
470
  runtime: params.runtime,
523
471
  sessionKey: pending.sessionKey,
524
472
  expectedGeneration: pending.generation
525
473
  });
474
+ return false;
526
475
  }
527
476
  //#endregion
528
477
  //#region extensions/clickclack/src/discussions/service.ts
529
478
  const RECONCILE_INTERVAL_MS = 6e4;
479
+ const RECONCILE_DEBOUNCE_MS = 250;
480
+ const RECONCILE_RETRY_MS = 1e3;
481
+ const RECONCILE_RETRY_MAX_MS = 6e4;
530
482
  var ClickClackDiscussionService = class {
531
483
  #runtime;
532
484
  #store;
533
485
  #clientFactory;
534
486
  #installationId;
535
- #bindingGenerationFactory;
536
487
  #detachedBindings;
537
488
  #sessionQueue = new KeyedAsyncQueue();
538
489
  #scheduler;
539
- #reconcileScheduler;
490
+ #scheduleReconcile;
540
491
  #withChannelMutationLock = createAsyncLock();
541
492
  #timer;
542
- #reconcileAllPromise;
543
493
  #unsubscribeSessionsChanged;
544
494
  #closed = false;
545
- #activation = 0;
546
495
  #cleanupPromise;
547
496
  #operations = /* @__PURE__ */ new Set();
548
- constructor(runtime, options = {}) {
497
+ constructor(runtime) {
549
498
  this.#runtime = runtime;
550
499
  this.#store = getClickClackDiscussionBindingStore(runtime);
551
- this.#clientFactory = options.clientFactory ?? ((account) => createClickClackClient({
500
+ this.#clientFactory = (account) => createClickClackClient({
552
501
  baseUrl: account.apiEndpoint,
553
502
  token: account.token
554
- }));
555
- this.#installationId = options.installationId;
556
- this.#bindingGenerationFactory = options.bindingGenerationFactory ?? randomUUID;
503
+ });
557
504
  this.#detachedBindings = new DetachedDiscussionBindingRetention({
558
505
  runtime,
559
- store: this.#store,
560
- maxRetained: options.maxRetainedDetachedBindings ?? 1e3
506
+ store: this.#store
561
507
  });
562
508
  this.provider = {
563
509
  id: "clickclack",
@@ -566,40 +512,78 @@ var ClickClackDiscussionService = class {
566
512
  };
567
513
  }
568
514
  async bindGatewayEvents(gatewayEvents, scheduler) {
569
- const activation = ++this.#activation;
570
515
  if (this.#cleanupPromise) await this.#cleanupPromise;
571
- if (activation !== this.#activation) return;
572
516
  if (this.#scheduler) await this.#scheduler.stop();
573
- if (activation !== this.#activation) return;
574
517
  this.#cleanupPromise = void 0;
575
518
  this.#unsubscribeSessionsChanged?.();
576
519
  this.#closed = false;
577
520
  this.#scheduler = scheduler.scope();
578
521
  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
- });
522
+ const activationScheduler = this.#scheduler;
523
+ /**
524
+ * Per-session debounced reconcile scheduling with failure backoff.
525
+ * Contracts: bursts coalesce onto the earliest scheduled run (steady event
526
+ * traffic can never postpone one); a failed run sets a not-before floor with
527
+ * growing backoff that later events cannot undercut; events during an
528
+ * in-flight run collapse into one follow-up scheduled after settlement; and
529
+ * each service activation owns a separate scheduler scope and retry state.
530
+ */
531
+ const retryState = /* @__PURE__ */ new Map();
532
+ const inFlight = /* @__PURE__ */ new Set();
533
+ const followUps = /* @__PURE__ */ new Set();
534
+ const scheduleReconcile = (sessionKey, delayMs = RECONCILE_DEBOUNCE_MS) => {
535
+ if (activationScheduler.signal.aborted) return;
536
+ if (inFlight.has(sessionKey)) {
537
+ followUps.add(sessionKey);
538
+ return;
539
+ }
540
+ const retry = retryState.get(sessionKey);
541
+ const fireAt = Math.max(activationScheduler.now() + delayMs, retry?.notBefore ?? 0);
542
+ activationScheduler.schedule({
543
+ id: `session:${sessionKey}`,
544
+ atMs: fireAt,
545
+ mode: "earliest",
546
+ run: async () => {
547
+ inFlight.add(sessionKey);
548
+ try {
549
+ await this.reconcile(sessionKey);
550
+ retryState.delete(sessionKey);
551
+ } catch (error) {
552
+ if (activationScheduler.signal.aborted) return;
553
+ const previous = retryState.get(sessionKey);
554
+ const nextRetryMs = Math.min(previous === void 0 ? RECONCILE_RETRY_MS : previous.delayMs * 2, RECONCILE_RETRY_MAX_MS);
555
+ retryState.set(sessionKey, {
556
+ delayMs: nextRetryMs,
557
+ notBefore: activationScheduler.now() + nextRetryMs
558
+ });
559
+ this.#logger().warn(`discussion event reconcile failed for ${sessionKey}; retrying in ${nextRetryMs}ms: ${String(error)}`);
560
+ followUps.add(sessionKey);
561
+ } finally {
562
+ inFlight.delete(sessionKey);
563
+ if (!activationScheduler.signal.aborted && followUps.delete(sessionKey)) scheduleReconcile(sessionKey);
564
+ }
565
+ }
566
+ });
567
+ };
568
+ this.#scheduleReconcile = scheduleReconcile;
583
569
  this.#unsubscribeSessionsChanged = gatewayEvents?.onSessionsChanged((event) => {
584
570
  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
- }
571
+ if (await this.#store.getAsync(event.sessionKey) || await getPendingDiscussionOpen(this.#runtime, event.sessionKey)) this.#scheduleReconcile?.(event.sessionKey);
588
572
  }).catch((error) => {
589
573
  this.#logger().warn(`discussion event admission failed: ${String(error)}`);
590
574
  });
591
575
  });
592
576
  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
- }
577
+ for (const sessionKey of await this.#listReconcileSessionKeys()) this.#scheduleReconcile?.(sessionKey, 0);
597
578
  await this.#ensureTimer();
598
579
  });
599
580
  }
600
581
  hasEnabledAccount() {
601
582
  return discussionAccounts(this.#currentConfig()).length === 1;
602
583
  }
584
+ resolveBindingAccount(binding) {
585
+ return resolveDiscussionBindingAccount(this.#currentConfig(), binding);
586
+ }
603
587
  async info(sessionKey) {
604
588
  return await this.#withOperation(() => this.#sessionQueue.enqueue(sessionKey, async () => {
605
589
  await this.#store.prepare();
@@ -657,13 +641,10 @@ var ClickClackDiscussionService = class {
657
641
  account,
658
642
  clientFactory: this.#clientFactory,
659
643
  installationId: this.#installationId,
660
- bindingGenerationFactory: this.#bindingGenerationFactory,
661
644
  sessionKey,
662
645
  ensureTimer: () => this.#ensureTimer(),
663
- reconcilePendingOpen: (pending) => this.#reconcilePendingOpen(pending, { allowRetry: false }),
664
646
  withChannelMutationLock: (run) => this.#withChannelMutationLock(run),
665
647
  ensureBindingCapacity: (key) => this.#detachedBindings.ensureCapacity(key),
666
- finalizePendingBinding: (key, nextBinding) => this.#finalizePendingBinding(key, nextBinding),
667
648
  warn: (message) => this.#logger().warn(message)
668
649
  });
669
650
  } finally {
@@ -682,7 +663,14 @@ var ClickClackDiscussionService = class {
682
663
  const binding = await this.#store.getAsync(sessionKey);
683
664
  if (binding) await this.#reconcileBinding(sessionKey, binding);
684
665
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
685
- if (pending) await this.#reconcilePendingOpen(pending);
666
+ if (pending) {
667
+ if (await reconcilePendingDiscussionOpen({
668
+ runtime: this.#runtime,
669
+ store: this.#store,
670
+ clientFactory: this.#clientFactory,
671
+ pending
672
+ })) await this.#open(sessionKey);
673
+ }
686
674
  });
687
675
  } finally {
688
676
  await this.#ensureTimer();
@@ -690,21 +678,15 @@ var ClickClackDiscussionService = class {
690
678
  }
691
679
  async reconcileAll() {
692
680
  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();
681
+ try {
682
+ for (const sessionKey of await this.#listReconcileSessionKeys()) try {
683
+ await this.#reconcile(sessionKey);
684
+ } catch (error) {
685
+ this.#logger().warn(`discussion reconcile failed for ${sessionKey}: ${String(error)}`);
703
686
  }
704
- })().finally(() => {
705
- this.#reconcileAllPromise = void 0;
706
- });
707
- return await this.#reconcileAllPromise;
687
+ } finally {
688
+ await this.#ensureTimer();
689
+ }
708
690
  });
709
691
  }
710
692
  async readLatestMessages(sessionKey, limit) {
@@ -716,30 +698,27 @@ var ClickClackDiscussionService = class {
716
698
  if (resolved.state !== "active") return { text: "No discussion is bound to this session." };
717
699
  const attached = await this.#refreshSessionAttachment(sessionKey, binding);
718
700
  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({
701
+ return await readDiscussionHistory({
720
702
  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 {
703
+ store: this.#store,
704
+ sessionKey,
726
705
  binding: attached,
727
- text: formatDiscussionHistory(await this.#clientFactory(resolved.account).latestChannelMessages(attached.channelId, limit)) || "The bound discussion has no messages yet."
728
- };
706
+ client: this.#clientFactory(resolved.account),
707
+ limit
708
+ });
729
709
  }));
730
710
  }
731
711
  cleanup() {
732
712
  this.#closed = true;
733
- this.#activation += 1;
734
713
  this.#unsubscribeSessionsChanged?.();
735
714
  this.#unsubscribeSessionsChanged = void 0;
736
- this.#reconcileScheduler = void 0;
715
+ this.#scheduleReconcile = void 0;
737
716
  this.#timer = void 0;
738
717
  this.#cleanupPromise ??= Promise.allSettled([this.#scheduler?.stop(), ...this.#operations]).then(() => void 0);
739
718
  return this.#cleanupPromise;
740
719
  }
741
720
  async #reconcileBinding(sessionKey, binding, resolvedAccount) {
742
- await this.#finalizePendingBinding(sessionKey, binding);
721
+ await finalizePendingDiscussionBinding(this.#runtime, sessionKey, binding);
743
722
  if (await isClickClackDiscussionChannelRevokedAsync({
744
723
  runtime: this.#runtime,
745
724
  serverBaseUrl: binding.serverBaseUrl,
@@ -756,7 +735,7 @@ var ClickClackDiscussionService = class {
756
735
  }
757
736
  const activeBinding = await this.#detachedBindings.clear(sessionKey, binding);
758
737
  if (!activeBinding) return;
759
- const resolved = resolvedAccount ? resolveDiscussionBindingAccount(this.#currentConfig(), activeBinding) : await this.#resolveBindingForUse(activeBinding);
738
+ const resolved = resolvedAccount ? this.resolveBindingAccount(activeBinding) : await this.#resolveBindingForUse(activeBinding);
760
739
  if (resolved.state === "retargeted") {
761
740
  await this.#revokeAndDeleteBinding(sessionKey, activeBinding);
762
741
  return;
@@ -788,7 +767,7 @@ var ClickClackDiscussionService = class {
788
767
  bindingForAttachment = freshBinding;
789
768
  observedSiblingTitleSupport = bindings.some(({ binding: candidate }) => candidate.displayTitle !== void 0 && candidate.serverBaseUrl === freshBinding.serverBaseUrl && candidate.accountId === freshBinding.accountId);
790
769
  }
791
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), bindingForAttachment);
770
+ const current = this.resolveBindingAccount(bindingForAttachment);
792
771
  if (current.state !== "active") return;
793
772
  const account = current.account;
794
773
  const attached = await this.#refreshSessionAttachment(sessionKey, bindingForAttachment);
@@ -807,41 +786,54 @@ var ClickClackDiscussionService = class {
807
786
  if (section !== currentBinding.section) patch.sidebar_section = section;
808
787
  if (externalUrl !== currentBinding.externalUrl) patch.external_url = externalUrl;
809
788
  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({
789
+ const bindingFacts = await this.#store.prepareRead(sessionKey);
790
+ let revocation;
791
+ let session;
792
+ try {
793
+ revocation = await prepareClickClackDiscussionChannelRevocation({
814
794
  runtime: this.#runtime,
815
795
  serverBaseUrl: currentBinding.serverBaseUrl,
796
+ channelId: currentBinding.channelId
797
+ });
798
+ const isRevoked = revocation.isRevoked;
799
+ session = await prepareDiscussionSessionEntry(this.#runtime, sessionKey);
800
+ const sessionAuthority = session;
801
+ const client = this.#clientFactory(account);
802
+ const assertCurrentAuthority = () => {
803
+ sessionAuthority.source();
804
+ const bound = bindingFacts.read();
805
+ 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");
806
+ };
807
+ let updated;
808
+ if (labelChanged) updated = await this.#withChannelMutationLock(() => renameDiscussionChannel({
809
+ client,
810
+ workspaceId: currentBinding.workspaceId,
816
811
  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);
812
+ label,
813
+ sessionKey,
814
+ agentId: currentBinding.agentId,
815
+ patch,
816
+ assertCurrentAuthority
817
+ }));
818
+ else {
819
+ assertCurrentAuthority();
820
+ updated = await client.updateChannel(currentBinding.channelId, patch);
821
+ assertChannelPatch(updated, patch);
822
+ }
823
+ const nextBinding = {
824
+ ...currentBinding,
825
+ externalUrl,
826
+ label,
827
+ section,
828
+ ...updated.display_title !== void 0 ? { displayTitle: updated.display_title } : {}
829
+ };
830
+ if (updated.display_title === void 0) delete nextBinding.displayTitle;
831
+ await this.#store.setIfCurrent(sessionKey, currentBinding, nextBinding);
832
+ } finally {
833
+ session?.release();
834
+ revocation?.release();
835
+ bindingFacts.release();
835
836
  }
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
837
  }
846
838
  async #refreshSessionAttachment(sessionKey, binding) {
847
839
  try {
@@ -856,17 +848,6 @@ var ClickClackDiscussionService = class {
856
848
  return;
857
849
  }
858
850
  }
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
851
  async #releaseStaleBinding(sessionKey, binding) {
871
852
  const pending = await getPendingDiscussionOpen(this.#runtime, sessionKey);
872
853
  if (pending?.externalRef === binding.externalRef) await clearDiscussionBindingGeneration({
@@ -880,27 +861,12 @@ var ClickClackDiscussionService = class {
880
861
  if (!await markClickClackDiscussionChannelRevoked(this.#runtime, sessionKey, binding)) return false;
881
862
  return await this.#store.deleteIfCurrent(sessionKey, binding);
882
863
  }
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
864
  async #resolveBindingForUse(binding) {
899
- const resolved = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
865
+ const resolved = this.resolveBindingAccount(binding);
900
866
  if (resolved.state !== "active") return resolved;
901
867
  const workspaces = await this.#clientFactory(resolved.account).workspaces();
902
868
  const workspace = findClickClackWorkspace(workspaces, resolved.account.discussions.workspace);
903
- const current = resolveDiscussionBindingAccount(this.#currentConfig(), binding);
869
+ const current = this.resolveBindingAccount(binding);
904
870
  if (current.state !== "active") return current;
905
871
  return workspace?.id === binding.workspaceId ? current : { state: "retargeted" };
906
872
  }
@@ -946,7 +912,9 @@ var ClickClackDiscussionService = class {
946
912
  }
947
913
  };
948
914
  //#endregion
949
- //#region extensions/clickclack/src/discussions/tool-policy.ts
915
+ //#region extensions/clickclack/src/discussions/register.ts
916
+ const DEFAULT_MESSAGE_LIMIT = 30;
917
+ const MAX_MESSAGE_LIMIT = 200;
950
918
  const TARGETED_SESSION_TOOLS = /* @__PURE__ */ new Set([
951
919
  "sessions_history",
952
920
  "sessions_send",
@@ -958,78 +926,75 @@ function blockedResult() {
958
926
  blockReason: `ClickClack discussion sessions may use ${[...TARGETED_SESSION_TOOLS].join(", ")} only with their attached main session.`
959
927
  };
960
928
  }
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 {
929
+ function registerClickClackDiscussions(api) {
930
+ if (api.registrationMode === "tool-discovery") {
931
+ api.registerTool(() => null, { name: "discussion" });
970
932
  return;
971
933
  }
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,
934
+ const runtime = api.runtime;
935
+ adoptLegacyMarkers(runtime);
936
+ const service = new ClickClackDiscussionService(runtime);
937
+ function isClickClackDiscussionSessionTarget(params) {
938
+ if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
939
+ const { targetSessionKey } = params;
940
+ let binding;
941
+ try {
942
+ const store = getClickClackDiscussionBindingStore(runtime);
943
+ store.assertReadAvailable();
944
+ binding = store.get(targetSessionKey);
945
+ } catch {
946
+ return;
947
+ }
948
+ return currentDiscussionTarget(params, binding, (current) => isClickClackDiscussionChannelRevoked({
949
+ runtime,
950
+ serverBaseUrl: current.serverBaseUrl,
951
+ channelId: current.channelId,
952
+ binding: current
953
+ }), (current) => bindingMatchesActiveSessionIncarnation(runtime, targetSessionKey, current));
954
+ }
955
+ function currentDiscussionTarget(params, binding, isRevoked, isActiveSession) {
956
+ const { targetSessionKey } = params;
957
+ if (binding && discussionSessionKey({
958
+ runtime,
959
+ mainSessionKey: targetSessionKey,
1000
960
  ...binding
1001
- });
1002
- return currentDiscussionTarget(params, facts.read(), revocation.isRevoked);
1003
- } catch {
1004
- return;
1005
- } finally {
1006
- revocation?.release();
1007
- facts?.release();
961
+ }) === params.requesterSessionKey && !isRevoked(binding) && isActiveSession(binding) && service.resolveBindingAccount(binding).state === "active") return {
962
+ sessionKey: targetSessionKey,
963
+ binding
964
+ };
1008
965
  }
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 {
966
+ async function resolveClickClackDiscussionSessionTarget(params) {
967
+ if (!isDiscussionSessionKey(params.requesterSessionKey)) return;
968
+ let facts;
969
+ let revocation;
970
+ let session;
971
+ try {
972
+ facts = await getClickClackDiscussionBindingStore(runtime).prepareRead(params.targetSessionKey);
973
+ const binding = facts.read();
974
+ if (!binding) return;
975
+ revocation = await prepareClickClackDiscussionChannelRevocation({
976
+ runtime,
977
+ ...binding
978
+ });
979
+ session = await prepareDiscussionSessionEntry(runtime, params.targetSessionKey);
980
+ session.source();
981
+ const entry = session.entry;
982
+ return currentDiscussionTarget(params, facts.read(), revocation.isRevoked, (current) => entry?.sessionId === current.sessionId && entry.archivedAt === void 0);
983
+ } catch {
984
+ return;
985
+ } finally {
986
+ session?.release();
987
+ revocation?.release();
988
+ facts?.release();
989
+ }
990
+ }
991
+ api.registerService({
992
+ id: "clickclack-discussion-session-events",
993
+ apiVersion: 2,
994
+ start: ({ gatewayEvents, scheduler }) => service.bindGatewayEvents(gatewayEvents, scheduler),
995
+ stop: () => service.cleanup()
996
+ });
997
+ api.registerTool(({ sessionKey }) => ({
1033
998
  name: "discussion",
1034
999
  label: "Discussion",
1035
1000
  description: "Read the latest messages from the ClickClack discussion bound to this session.",
@@ -1044,51 +1009,40 @@ function createClickClackDiscussionTool(params) {
1044
1009
  additionalProperties: false
1045
1010
  },
1046
1011
  async execute(_toolCallId, input) {
1047
- if (!params.sessionKey) return textResult("No discussion is bound to this session.", { bound: false });
1012
+ if (!sessionKey) return textResult("No discussion is bound to this session.", { bound: false });
1048
1013
  const requested = typeof input === "object" && input !== null && "limit" in input ? Number(input.limit) : DEFAULT_MESSAGE_LIMIT;
1049
1014
  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);
1015
+ const result = await service.readLatestMessages(sessionKey, limit);
1051
1016
  return textResult(result.text, {
1052
1017
  bound: Boolean(result.binding),
1053
1018
  limit,
1054
1019
  ...result.binding ? { channelId: result.binding.channelId } : {}
1055
1020
  });
1056
1021
  }
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
1022
  }));
1023
+ api.on("before_tool_call", async (event, context) => {
1024
+ const callerSessionKey = context.sessionKey;
1025
+ if (!callerSessionKey || !isDiscussionSessionKey(callerSessionKey)) return;
1026
+ const { toolName } = event;
1027
+ if (toolName !== "session_status" && !toolName.startsWith("sessions_")) return;
1028
+ const usesAlternateSendTarget = toolName === "sessions_send" && (event.params.label !== void 0 || event.params.agentId !== void 0);
1029
+ const mutatesStatus = toolName === "session_status" && event.params.model !== void 0;
1030
+ const selectsHistoryIncarnation = toolName === "sessions_history" && event.params.sessionId !== void 0;
1031
+ const targetSessionKey = event.params.sessionKey;
1032
+ if (TARGETED_SESSION_TOOLS.has(toolName) && typeof targetSessionKey === "string" && !usesAlternateSendTarget && !mutatesStatus && !selectsHistoryIncarnation && await resolveClickClackDiscussionSessionTarget({
1033
+ requesterSessionKey: callerSessionKey,
1034
+ targetSessionKey
1035
+ })) return;
1036
+ return blockedResult();
1037
+ });
1082
1038
  const unregisterSessionAccess = createSessionVisibilityChecker.registerScopedAccessProvider(({ requesterSessionKey, targetSessionKey }) => {
1083
1039
  const target = isClickClackDiscussionSessionTarget({
1084
- runtime: api.runtime,
1085
1040
  requesterSessionKey,
1086
1041
  targetSessionKey
1087
1042
  });
1088
1043
  return target ? { expectedSessionId: target.binding.sessionId } : void 0;
1089
1044
  }, { async resolveAsync({ requesterSessionKey, targetSessionKey }) {
1090
1045
  const target = await resolveClickClackDiscussionSessionTarget({
1091
- runtime: api.runtime,
1092
1046
  requesterSessionKey,
1093
1047
  targetSessionKey
1094
1048
  });