@abraca/mcp 2.90.0 → 2.91.0

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.
package/src/server.ts DELETED
@@ -1,1393 +0,0 @@
1
- /**
2
- * AbracadabraMCPServer — manages connection lifecycle, provider cache, and cleanup.
3
- *
4
- * Space-aware: on connect, discovers Spaces (top-level docs with kind="space")
5
- * by listing children of the server root. The first Space becomes the active
6
- * one; use switchSpace(docId) to change.
7
- */
8
-
9
- import type { DocumentMeta, ServerInfo } from "@abraca/dabra";
10
- import {
11
- AbracadabraClient,
12
- AbracadabraProvider,
13
- foldRecords,
14
- isEncryptedContent,
15
- Kind,
16
- loadOrCreateKeyFile,
17
- loginOrRegisterWithKey,
18
- makeChallengeSigner,
19
- openSyncedProvider,
20
- pickEntrySpace,
21
- recordFromYAny,
22
- SERVER_ROOT_ID,
23
- WebSocketStatus,
24
- } from "@abraca/dabra";
25
- import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
26
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
27
- import * as Y from "yjs";
28
- import { containsMention, stripMention } from "./mentions.ts";
29
- import { waitForSync } from "./utils.ts";
30
-
31
- /**
32
- * Controls when the agent reacts to incoming chat:
33
- * - `all` — respond to every message in every visible channel (legacy)
34
- * - `mention` — group chats require `@<alias>`; DMs always respond
35
- * - `task` — ignore chat entirely; only respond to ai:task awareness events
36
- * - `mention+task` — group chats require mention OR ai:task; DMs always respond (default)
37
- */
38
- export type TriggerMode = "all" | "mention" | "task" | "mention+task";
39
-
40
- export interface MCPServerConfig {
41
- url: string;
42
- agentName?: string;
43
- agentColor?: string;
44
- inviteCode?: string;
45
- keyFile?: string;
46
- triggerMode?: TriggerMode;
47
- /** Aliases matched in `@<alias>` tokens. Defaults to `[agentName]`. */
48
- mentionAliases?: string[];
49
- }
50
-
51
- interface SpaceConnection {
52
- doc: Y.Doc;
53
- provider: AbracadabraProvider;
54
- docId: string;
55
- }
56
-
57
- interface CachedProvider {
58
- provider: AbracadabraProvider;
59
- lastAccessed: number;
60
- }
61
-
62
- const IDLE_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
63
-
64
- export class AbracadabraMCPServer {
65
- readonly config: MCPServerConfig;
66
- readonly client: AbracadabraClient;
67
- private _serverInfo: ServerInfo | null = null;
68
- private _rootDocId: string | null = null;
69
- private _spaces: DocumentMeta[] = [];
70
- private _activeConnection: SpaceConnection | null = null;
71
- private _spaceConnections = new Map<string, SpaceConnection>();
72
- private childCache = new Map<string, CachedProvider>();
73
- private evictionTimer: ReturnType<typeof setInterval> | null = null;
74
- private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
75
- private _mcpServerRef: McpServer | null = null;
76
- private _serverRef: Server | null = null;
77
- private _handledTaskIds = new Set<string>();
78
- private _userId: string | null = null;
79
- private _statusClearTimer: ReturnType<typeof setTimeout> | null = null;
80
- private _typingInterval: ReturnType<typeof setInterval> | null = null;
81
- private _lastChatChannel: string | null = null;
82
- // Channel of the CURRENTLY-ACTIVE chat/task turn (null when no turn is in
83
- // flight). Status updates from the hook-bridge (general Claude Code tool
84
- // activity) default their `statusContext` to THIS, not `_lastChatChannel`.
85
- // Using the (sticky) `_lastChatChannel` made unrelated session activity
86
- // leak the "thinking" incantation into the last chat the agent ever touched,
87
- // even when it never received that conversation's message.
88
- private _activeTurnChannel: string | null = null;
89
- private _signFn: ((challenge: string) => Promise<string>) | null = null;
90
- /** Rolling buffer of the last N tool calls in the current turn, surfaced via awareness. */
91
- private _toolHistory: Array<{
92
- tool: string;
93
- target?: string;
94
- ts: number;
95
- channel: string | null;
96
- /** Expandable detail (diff / code / command / text) for the dashboard. */
97
- detail?: unknown;
98
- }> = [];
99
- private static readonly TOOL_HISTORY_MAX = 20;
100
-
101
- // ── Inbox-driven dispatch ──────────────────────────────────────────────────
102
- // The server fans DMs + @mentions out as entries on this agent's per-user
103
- // `kind="inbox"` doc (server is the only writer). That is the *only*
104
- // recipient-correct signal for a DM the agent isn't subscribed to — the
105
- // `messages:new_message` stateless broadcast only reaches subscribers of the
106
- // channel/DM doc, and the agent never subscribes to DM docs. So we observe
107
- // the inbox's `entries` Y.Array and dispatch from there.
108
- /** De-dupes concurrent connection heals across parallel tool calls. */
109
- private _reconnecting: Promise<void> | null = null;
110
- private _inboxStarted = false;
111
- private _inboxDocId: string | null = null;
112
- private _inboxDoc: Y.Doc | null = null;
113
- private _inboxProvider: AbracadabraProvider | null = null;
114
- private _inboxDisposers: Array<() => void> = [];
115
- private _inboxInitialized = false;
116
- private _seenInboxIds = new Set<string>();
117
- /** Shared message-id dedupe so the inbox path and `_handleStatelessChat`
118
- * (subscribed-doc broadcast) never dispatch the same message twice. */
119
- private _dispatchedMessageIds = new Set<string>();
120
- private static readonly DEDUPE_MAX = 1000;
121
-
122
- constructor(config: MCPServerConfig) {
123
- this.config = config;
124
- this.client = new AbracadabraClient({
125
- url: config.url,
126
- persistAuth: false,
127
- });
128
- }
129
-
130
- get agentName(): string {
131
- return this.config.agentName || "AI Assistant";
132
- }
133
-
134
- get agentColor(): string {
135
- return this.config.agentColor || "hsl(270, 80%, 60%)";
136
- }
137
-
138
- get triggerMode(): TriggerMode {
139
- return this.config.triggerMode ?? "mention+task";
140
- }
141
-
142
- get mentionAliases(): string[] {
143
- const explicit = this.config.mentionAliases?.filter(
144
- (a) => a.trim().length > 0,
145
- );
146
- if (explicit && explicit.length > 0) return explicit;
147
- return [this.agentName];
148
- }
149
-
150
- get serverInfo(): ServerInfo | null {
151
- return this._serverInfo;
152
- }
153
-
154
- get rootDocId(): string | null {
155
- return this._rootDocId;
156
- }
157
-
158
- /**
159
- * Spaces visible to the caller — direct children of the server root with
160
- * `kind === "space"`. Populated by {@link connect}.
161
- */
162
- get spaces(): DocumentMeta[] {
163
- return this._spaces;
164
- }
165
-
166
- /**
167
- * Re-fetch the server's top-level `kind="space"` docs and refresh the
168
- * cached `_spaces` snapshot. {@link connect} only takes the snapshot once,
169
- * so a space created/seeded after connect (or removed) would otherwise stay
170
- * invisible to `list_spaces` until a full reconnect. Tools that surface the
171
- * space list should call this first so they reflect server truth.
172
- */
173
- async refreshSpaces(): Promise<DocumentMeta[]> {
174
- if (!this.client) return this._spaces;
175
- try {
176
- const { spaces } = pickEntrySpace(await this.client.listChildren());
177
- this._spaces = spaces;
178
- } catch {
179
- // Network/transient failure — keep the last-known snapshot rather
180
- // than blanking the list.
181
- }
182
- return this._spaces;
183
- }
184
-
185
- get rootDocument(): Y.Doc | null {
186
- return this._activeConnection?.doc ?? null;
187
- }
188
-
189
- get rootYProvider(): AbracadabraProvider | null {
190
- return this._activeConnection?.provider ?? null;
191
- }
192
-
193
- get userId(): string | null {
194
- return this._userId;
195
- }
196
-
197
- /** Start the server: authenticate with Ed25519 key, discover spaces/root doc, connect provider. */
198
- async connect(): Promise<void> {
199
- // Step 1: Load or generate the Ed25519 key file
200
- const keypair = await loadOrCreateKeyFile(this.config.keyFile, {
201
- defaultFileName: "agent.key",
202
- onCreate: ({ path, publicKeyB64 }) => {
203
- console.error(
204
- `[abracadabra-mcp] Generated new agent keypair at ${path}`,
205
- );
206
- console.error(`[abracadabra-mcp] Public key: ${publicKeyB64}`);
207
- },
208
- });
209
- this._userId = keypair.publicKeyB64;
210
- this._signFn = makeChallengeSigner(keypair);
211
-
212
- // Step 2: Authenticate via challenge-response (register on first run)
213
- await loginOrRegisterWithKey(this.client, keypair, {
214
- displayName: this.agentName,
215
- deviceName: "MCP Agent",
216
- inviteCode: this.config.inviteCode,
217
- onRegister: () =>
218
- console.error(
219
- "[abracadabra-mcp] Key not registered, creating new account...",
220
- ),
221
- });
222
- console.error(
223
- `[abracadabra-mcp] Authenticated as ${this.agentName} (pubkey=${keypair.publicKeyB64})`,
224
- );
225
-
226
- // Step 3: Discover server info
227
- this._serverInfo = await this.client.serverInfo();
228
-
229
- // Step 4: Discover Spaces — top-level docs (children of the server root)
230
- // tagged with kind="space". The first Space is the default landing doc;
231
- // any other top-level doc serves as a fallback if no Spaces exist.
232
- const { entry: first, spaces } = pickEntrySpace(
233
- await this.client.listChildren(),
234
- );
235
- this._spaces = spaces;
236
- const initialDocId = first?.id ?? null;
237
- if (first) {
238
- console.error(
239
- `[abracadabra-mcp] Active space: ${first.label ?? first.id} (${first.id})`,
240
- );
241
- }
242
-
243
- if (!initialDocId) {
244
- throw new Error(
245
- `No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}. Create a Space first.`,
246
- );
247
- }
248
-
249
- this._rootDocId = initialDocId;
250
- console.error(`[abracadabra-mcp] Active space doc: ${initialDocId}`);
251
-
252
- // Step 5: Connect to initial space
253
- await this._connectToSpace(initialDocId);
254
- console.error("[abracadabra-mcp] Space doc synced");
255
-
256
- // Step 6: Start eviction timer
257
- this.evictionTimer = setInterval(() => this.evictIdle(), 60_000);
258
-
259
- // Step 7: Connection heartbeat. An idle MCP (no tool calls for a while)
260
- // would otherwise let an expired JWT drop the socket with nothing to heal
261
- // it — silently killing chat/awareness + inbox dispatch. `ensureConnected`
262
- // is a no-op while healthy (just refreshes a near-expiry token) and
263
- // reconnects on the SAME docs (space + inbox) if dead, so observers survive.
264
- this.heartbeatTimer = setInterval(() => {
265
- void this.ensureConnected();
266
- }, 30_000);
267
- }
268
-
269
- /** Connect to a space's root doc and cache it. Sets it as the active connection. */
270
- private async _connectToSpace(docId: string): Promise<SpaceConnection> {
271
- const existing = this._spaceConnections.get(docId);
272
- if (existing) {
273
- this._activeConnection = existing;
274
- this._rootDocId = docId;
275
- return existing;
276
- }
277
-
278
- // Re-authenticate if JWT has expired (prevents WS auth failures)
279
- if (!this.client.isTokenValid() && this._signFn && this._userId) {
280
- console.error("[abracadabra-mcp] JWT expired, re-authenticating...");
281
- await this.client.loginWithKey(this._userId, this._signFn);
282
- console.error("[abracadabra-mcp] Re-authenticated successfully");
283
- }
284
-
285
- const { doc, provider } = await openSyncedProvider({
286
- client: this.client,
287
- docId,
288
- });
289
-
290
- provider.awareness.setLocalStateField("user", {
291
- name: this.agentName,
292
- color: this.agentColor,
293
- publicKey: this._userId,
294
- isAgent: true,
295
- });
296
- // Ensure no stale status from a previous session
297
- provider.awareness.setLocalStateField("status", null);
298
- provider.awareness.setLocalStateField("activeToolCall", null);
299
- provider.awareness.setLocalStateField("statusContext", null);
300
- provider.awareness.setLocalStateField("turnId", null);
301
- provider.awareness.setLocalStateField("toolHistory", []);
302
-
303
- const conn: SpaceConnection = { doc, provider, docId };
304
- this._spaceConnections.set(docId, conn);
305
- this._activeConnection = conn;
306
- this._rootDocId = docId;
307
-
308
- // Re-attach awareness + stateless listeners if messaging is active (handles space switches)
309
- if (this._mcpServerRef) {
310
- this._observeRootAwareness(provider);
311
- provider.on("stateless", ({ payload }: { payload: string }) => {
312
- this._handleStatelessChat(payload);
313
- });
314
- }
315
-
316
- return conn;
317
- }
318
-
319
- /**
320
- * Switch the active space to the given doc ID.
321
- * Clears the child provider cache (children belong to the previous space).
322
- */
323
- async switchSpace(docId: string): Promise<void> {
324
- for (const [, cached] of this.childCache) {
325
- cached.provider.destroy();
326
- }
327
- this.childCache.clear();
328
- await this._connectToSpace(docId);
329
- console.error(`[abracadabra-mcp] Switched active space to ${docId}`);
330
- }
331
-
332
- /**
333
- * Make the space that OWNS `targetId` the active connection before a tree
334
- * read/write, so the op targets the right space's `doc-tree` map.
335
- *
336
- * Without this, every tree tool used `getTreeMap()` (the single active
337
- * space) and treated `rootId`/`parentId` as a mere filter — so reading a
338
- * non-active space returned stale/empty trees, and *writing* to one
339
- * silently orphaned the entry into the active space's map (a real
340
- * data-loss path: docs built "in Ideas" while Development was active
341
- * landed in Development under a non-node parent and never reached Ideas).
342
- *
343
- * Resolution order:
344
- * - falsy or already the active root → no-op.
345
- * - a known Space id → connect/activate it (cheap; `_spaceConnections`
346
- * caches the provider so re-activation is free).
347
- * - present in the active space's tree → no-op (a normal child doc).
348
- * - present in an already-connected *other* space's tree → activate that.
349
- * - otherwise unresolved → returns `false`; callers decide (reads report
350
- * not-found/empty, writes refuse rather than orphan).
351
- *
352
- * Switching uses {@link _connectToSpace} (not {@link switchSpace}) so the
353
- * child-content provider cache survives — content docs are keyed by global
354
- * guid, independent of which space is active.
355
- */
356
- /**
357
- * Heal the active connection before a tool op so a dropped/idle WebSocket or
358
- * an expired JWT doesn't surface as a 15s sync timeout ("MCP not responding").
359
- * Refreshes the token, lets the SDK's own auto-reconnect finish if it's mid-
360
- * flight, and rebuilds the space connection from scratch if the socket is
361
- * truly dead. De-duped so parallel tool calls heal once. Best-effort: never
362
- * throws — a failed heal falls through to the normal (possibly erroring) op.
363
- */
364
- /** Whether a provider's shared WebSocket is currently connected. Isolated in
365
- * its own scope so repeated checks don't trip TS control-flow narrowing on
366
- * the live `connectionStatus` getter. */
367
- private _wsConnected(provider: AbracadabraProvider): boolean {
368
- return provider.connectionStatus === WebSocketStatus.Connected;
369
- }
370
-
371
- async ensureConnected(): Promise<void> {
372
- if (this._reconnecting) return this._reconnecting;
373
- this._reconnecting = (async () => {
374
- try {
375
- // 1) Refresh the JWT proactively so any reconnect re-authenticates
376
- // with a fresh token (a stale one is rejected, which stops the WS
377
- // retry loop). The provider's `token` callback reads `client.token`,
378
- // so refreshing it here is enough for the forced reconnect below.
379
- if (!this.client.isTokenValid() && this._signFn && this._userId) {
380
- try {
381
- await this.client.loginWithKey(this._userId, this._signFn);
382
- } catch (e) {
383
- console.error("[abracadabra-mcp] Re-auth during heal failed:", e);
384
- }
385
- }
386
-
387
- // 2) Heal the active space provider (root doc tree + chat/awareness).
388
- const conn = this._activeConnection;
389
- if (conn) await this._healProvider(conn.provider, "space");
390
-
391
- // 3) Heal the dedicated inbox provider. It rides its OWN socket, so the
392
- // space-provider heal above doesn't cover it — a drop + expired JWT
393
- // could otherwise permanently stop its retry and silently kill DM /
394
- // mention dispatch. Same failure mode, same same-doc fix.
395
- if (this._inboxProvider) {
396
- await this._healProvider(this._inboxProvider, "inbox");
397
- }
398
- } finally {
399
- this._reconnecting = null;
400
- }
401
- })();
402
- return this._reconnecting;
403
- }
404
-
405
- /**
406
- * Bring one provider's socket back to a synced state WITHOUT swapping its
407
- * Y.Doc. First let the SDK's own auto-reconnect finish if it's mid-flight;
408
- * if the socket is still dead, force a reconnect on the same doc. Because the
409
- * document is never replaced, every observer attached to it (root awareness,
410
- * tree reads, the inbox `entries` array, the stateless chat listener) keeps
411
- * firing — no re-attach needed. Best-effort: logs but never throws.
412
- */
413
- private async _healProvider(
414
- provider: AbracadabraProvider,
415
- label: string,
416
- ): Promise<void> {
417
- if (this._wsConnected(provider)) return;
418
-
419
- // Give the SDK's own reconnect a bounded window before forcing one.
420
- try {
421
- await waitForSync(provider, 6000);
422
- } catch {
423
- /* fell through to forced reconnect */
424
- }
425
- // connectionStatus is a live getter — re-check via the helper (fresh
426
- // scope) since the WS may have come back during the wait.
427
- if (this._wsConnected(provider)) return;
428
-
429
- console.error(
430
- `[abracadabra-mcp] ${label} socket dead — forcing reconnect on the same doc…`,
431
- );
432
- provider.reconnect();
433
- try {
434
- await waitForSync(provider, 10000);
435
- console.error(`[abracadabra-mcp] ${label} reconnected + re-synced`);
436
- } catch (e) {
437
- console.error(
438
- `[abracadabra-mcp] ${label} reconnect did not re-sync in time:`,
439
- e,
440
- );
441
- }
442
- }
443
-
444
- async ensureSpaceActive(
445
- targetId: string | null | undefined,
446
- ): Promise<boolean> {
447
- await this.ensureConnected();
448
- if (!targetId || targetId === this._rootDocId) return true;
449
-
450
- // A top-level Space id — activate it directly (handles the common
451
- // `list_spaces` → operate-on-space-id flow that triggered the bug).
452
- if (this._spaces.some((s) => s.id === targetId)) {
453
- await this._connectToSpace(targetId);
454
- return true;
455
- }
456
-
457
- // A normal doc already in the active space's tree — nothing to do.
458
- if (this.getTreeMap()?.has(targetId)) return true;
459
-
460
- // A doc in another space we've already connected to — activate it.
461
- for (const [spaceId, conn] of this._spaceConnections) {
462
- if (spaceId === this._rootDocId) continue;
463
- if (conn.doc.getMap("doc-tree").has(targetId)) {
464
- await this._connectToSpace(spaceId);
465
- return true;
466
- }
467
- }
468
-
469
- // Unresolved: not a space, not in any connected tree. Caller guards.
470
- return false;
471
- }
472
-
473
- /** Get the root doc-tree Y.Map of the active space. */
474
- getTreeMap(): Y.Map<any> | null {
475
- return this._activeConnection?.doc.getMap("doc-tree") ?? null;
476
- }
477
-
478
- /**
479
- * Resolve a doc's `{label, type}` from the active space's tree map. Used to
480
- * enrich chat-dispatch notifications so Claude knows what kind of doc the
481
- * chat is attached to (e.g. checklist vs. kanban) without burning tool
482
- * calls to discover it. Returns null when the doc isn't in this tree.
483
- */
484
- getDocSummary(docId: string): { label?: string; type?: string } | null {
485
- const tree = this.getTreeMap();
486
- if (!tree) return null;
487
- const raw = tree.get(docId);
488
- if (!raw) return null;
489
- // Entries may be Y.Map or plain JS objects depending on how they were
490
- // written. Normalize both.
491
- const entry = typeof raw?.toJSON === "function" ? raw.toJSON() : raw;
492
- return {
493
- label: typeof entry?.label === "string" ? entry.label : undefined,
494
- type: typeof entry?.type === "string" ? entry.type : undefined,
495
- };
496
- }
497
-
498
- /** Get the root doc-trash Y.Map of the active space. */
499
- getTrashMap(): Y.Map<any> | null {
500
- return this._activeConnection?.doc.getMap("doc-trash") ?? null;
501
- }
502
-
503
- /** Get plugin names enabled in the active space via space-plugins Y.Map. */
504
- getEnabledPluginNames(): string[] {
505
- const doc = this._activeConnection?.doc;
506
- if (!doc) return [];
507
- const pluginsMap = doc.getMap("space-plugins");
508
- const names: string[] = [];
509
- pluginsMap.forEach((value: any, key: string) => {
510
- const entry = value?.toJSON ? value.toJSON() : value;
511
- if (entry?.enabled) names.push(key);
512
- });
513
- return names;
514
- }
515
-
516
- /**
517
- * Get or create a child provider for a given document ID.
518
- * Caches providers and waits for sync before returning.
519
- */
520
- async getChildProvider(docId: string): Promise<AbracadabraProvider> {
521
- // Heal a dropped socket / stale JWT first; this may rebuild the active
522
- // provider (and clear the child cache), so run it before the cache check.
523
- await this.ensureConnected();
524
-
525
- const cached = this.childCache.get(docId);
526
- if (cached && cached.provider.connectionStatus !== WebSocketStatus.Disconnected) {
527
- cached.lastAccessed = Date.now();
528
- return cached.provider;
529
- }
530
- if (cached) {
531
- // Cached provider rode a socket that's since dropped — discard and reload
532
- // so we never hand back a dead provider that times out on every op.
533
- try {
534
- cached.provider.destroy();
535
- } catch {
536
- /* already gone */
537
- }
538
- this.childCache.delete(docId);
539
- }
540
-
541
- const activeProvider = this._activeConnection?.provider;
542
- if (!activeProvider) {
543
- throw new Error("Not connected. Call connect() first.");
544
- }
545
-
546
- // Re-authenticate if JWT has expired (prevents child WS auth failures)
547
- if (!this.client.isTokenValid() && this._signFn && this._userId) {
548
- console.error("[abracadabra-mcp] JWT expired, re-authenticating...");
549
- await this.client.loginWithKey(this._userId, this._signFn);
550
- console.error("[abracadabra-mcp] Re-authenticated successfully");
551
- }
552
-
553
- const childProvider = await activeProvider.loadChild(docId);
554
- await waitForSync(childProvider);
555
-
556
- childProvider.awareness.setLocalStateField("user", {
557
- name: this.agentName,
558
- color: this.agentColor,
559
- publicKey: this._userId,
560
- isAgent: true,
561
- });
562
-
563
- this.childCache.set(docId, {
564
- provider: childProvider,
565
- lastAccessed: Date.now(),
566
- });
567
-
568
- return childProvider;
569
- }
570
-
571
- /** Update root awareness to reflect the currently focused document. */
572
- setFocusedDoc(docId: string): void {
573
- this.rootYProvider?.awareness.setLocalStateField("docId", docId);
574
- }
575
-
576
- /**
577
- * Set a TipTap-compatible collapsed cursor (anchor === head) on a child doc's awareness.
578
- * Only call after getChildProvider has cached the provider.
579
- * @param index Character index in xmlFragment ('default'). Clamped to [0, length].
580
- */
581
- setDocCursor(docId: string, index: number): void {
582
- const cached = this.childCache.get(docId);
583
- if (!cached) return;
584
-
585
- const fragment = cached.provider.document.getXmlFragment("default");
586
- const clampedIndex = Math.max(0, Math.min(index, fragment.length));
587
- const relPos = Y.createRelativePositionFromTypeIndex(
588
- fragment,
589
- clampedIndex,
590
- );
591
- const relPosJson = Y.relativePositionToJSON(relPos);
592
-
593
- cached.provider.awareness.setLocalStateField("anchor", relPosJson);
594
- cached.provider.awareness.setLocalStateField("head", relPosJson);
595
- }
596
-
597
- /** Evict child providers that have been idle for too long. */
598
- private evictIdle(): void {
599
- const now = Date.now();
600
- for (const [docId, cached] of this.childCache) {
601
- if (now - cached.lastAccessed > IDLE_TIMEOUT_MS) {
602
- // Clear cursor before destroying so TipTap removes the caret overlay
603
- cached.provider.awareness.setLocalStateField("anchor", null);
604
- cached.provider.awareness.setLocalStateField("head", null);
605
- cached.provider.destroy();
606
- this.childCache.delete(docId);
607
- console.error(`[abracadabra-mcp] Evicted idle provider: ${docId}`);
608
- }
609
- }
610
- }
611
-
612
- /** Wire up real-time channel notifications via awareness observation and stateless chat. */
613
- startChannelNotifications(mcpServer: McpServer): void {
614
- this._mcpServerRef = mcpServer;
615
- this._serverRef = mcpServer.server;
616
- const provider = this._activeConnection?.provider;
617
- if (provider) {
618
- this._observeRootAwareness(provider);
619
- provider.on("stateless", ({ payload }: { payload: string }) => {
620
- this._handleStatelessChat(payload);
621
- });
622
- console.error("[abracadabra-mcp] Stateless chat listener attached");
623
- void this._startInboxNotifications();
624
- }
625
- }
626
-
627
- /**
628
- * Bootstrap inbox observation. Sends `messages:inbox_fetch` over the active
629
- * provider; the server's `messages:inbox_history` reply carries the
630
- * `inbox_doc_id`. We then open a dedicated provider on that doc and observe
631
- * its `entries` Y.Array for live DM/mention dispatch. Mirrors the
632
- * dashboard's `useNotifications` pattern.
633
- */
634
- private async _startInboxNotifications(): Promise<void> {
635
- if (this._inboxStarted) return;
636
- const provider = this._activeConnection?.provider;
637
- if (!provider) return;
638
- this._inboxStarted = true;
639
-
640
- provider.on("stateless", ({ payload }: { payload: string }) => {
641
- if (!payload.includes('"messages:inbox_history"')) return;
642
- try {
643
- const data = JSON.parse(payload);
644
- if (data?.type !== "messages:inbox_history") return;
645
- const inboxDocId =
646
- typeof data.inbox_doc_id === "string" ? data.inbox_doc_id : null;
647
- if (inboxDocId) void this._ensureInboxObserver(inboxDocId);
648
- } catch {
649
- /* ignore malformed */
650
- }
651
- });
652
-
653
- // Elicit the inbox_history (and thus inbox_doc_id). unread_only:false so a
654
- // fresh agent learns its inbox doc even with no unread entries.
655
- provider.sendStateless(
656
- JSON.stringify({
657
- type: "messages:inbox_fetch",
658
- limit: 50,
659
- unread_only: false,
660
- }),
661
- );
662
- console.error(
663
- "[abracadabra-mcp] Inbox bootstrap sent (messages:inbox_fetch)",
664
- );
665
- }
666
-
667
- /**
668
- * Open a dedicated provider on the agent's inbox doc and observe its
669
- * `entries` Y.Array. The server is the only writer; we only read.
670
- */
671
- private async _ensureInboxObserver(inboxDocId: string): Promise<void> {
672
- if (this._inboxDocId) return; // already observing
673
- this._inboxDocId = inboxDocId;
674
-
675
- // Re-authenticate if the JWT expired (mirrors _connectToSpace).
676
- if (!this.client.isTokenValid() && this._signFn && this._userId) {
677
- await this.client.loginWithKey(this._userId, this._signFn);
678
- }
679
-
680
- const doc = new Y.Doc({ guid: inboxDocId });
681
- const provider = new AbracadabraProvider({
682
- name: inboxDocId,
683
- document: doc,
684
- client: this.client,
685
- disableOfflineStore: true,
686
- subdocLoading: "lazy",
687
- });
688
- this._inboxDoc = doc;
689
- this._inboxProvider = provider;
690
-
691
- try {
692
- await waitForSync(provider);
693
- } catch (err: any) {
694
- console.error(
695
- `[abracadabra-mcp] Inbox sync failed: ${err?.message ?? err}`,
696
- );
697
- return;
698
- }
699
-
700
- const entriesArr = doc.getArray("entries");
701
- const readMap = doc.getMap("read");
702
- const onChange = () => {
703
- void this._pumpInbox(entriesArr, readMap);
704
- };
705
- entriesArr.observe(onChange);
706
- readMap.observe(onChange);
707
- this._inboxDisposers.push(() => entriesArr.unobserve(onChange));
708
- this._inboxDisposers.push(() => readMap.unobserve(onChange));
709
-
710
- await this._pumpInbox(entriesArr, readMap);
711
- console.error(`[abracadabra-mcp] Inbox observer attached (${inboxDocId})`);
712
- }
713
-
714
- /**
715
- * Diff the inbox `entries` array against what we've already seen. On the
716
- * first pump we only record a baseline (don't replay history). New entries
717
- * are classified by their authoritative `kind` and dispatched.
718
- */
719
- private async _pumpInbox(
720
- entriesArr: Y.Array<any>,
721
- readMap: Y.Map<any>,
722
- ): Promise<void> {
723
- const raw = entriesArr.toArray() as any[];
724
- const entries = raw.map((e) =>
725
- typeof e?.toJSON === "function" ? e.toJSON() : e,
726
- );
727
-
728
- if (!this._inboxInitialized) {
729
- for (const e of entries) if (e?.id) this._seenInboxIds.add(e.id);
730
- this._inboxInitialized = true;
731
- console.error(
732
- `[abracadabra-mcp] Inbox baseline: ${this._seenInboxIds.size} existing entries (not replayed)`,
733
- );
734
- return;
735
- }
736
-
737
- for (const e of entries) {
738
- const id: string | undefined = e?.id;
739
- if (!id || this._seenInboxIds.has(id)) continue;
740
- this._seenInboxIds.add(id);
741
- console.error(
742
- `[abracadabra-mcp] inbox NEW entry: kind=${e?.kind} channel=${e?.channel_doc_id} sender=${e?.sender_name ?? e?.sender_id} read=${!!readMap.get(id)}`,
743
- );
744
- if (readMap.get(id)) continue; // already read elsewhere
745
- try {
746
- await this._dispatchInboxEntry(e);
747
- } catch (err: any) {
748
- console.error(
749
- `[abracadabra-mcp] Inbox dispatch failed for ${id}: ${err?.message ?? err}`,
750
- );
751
- }
752
- }
753
- this._trimSet(this._seenInboxIds);
754
- }
755
-
756
- /** Classify + dispatch one inbox entry as a channel notification. */
757
- private async _dispatchInboxEntry(entry: any): Promise<void> {
758
- if (!this._serverRef) return;
759
- const kind = typeof entry?.kind === "string" ? entry.kind : "";
760
- const channelDocId =
761
- typeof entry?.channel_doc_id === "string" ? entry.channel_doc_id : "";
762
- const messageId =
763
- typeof entry?.message_id === "string" ? entry.message_id : null;
764
- const senderId =
765
- typeof entry?.sender_id === "string" ? entry.sender_id : "";
766
- if (!channelDocId) return;
767
- if (senderId && senderId === this._userId) return; // own message (defensive)
768
-
769
- // Authoritative trigger gate — `kind` comes from the server, no guessing.
770
- // dm → always dispatch (DMs trigger regardless of mode)
771
- // mention/reply → dispatch unless mode === 'task' (chat-ignoring)
772
- // system/other → skip
773
- const mode = this.triggerMode;
774
- if (kind === "mention" || kind === "reply") {
775
- if (mode === "task") return;
776
- } else if (kind !== "dm") {
777
- return;
778
- }
779
-
780
- // Cross-path dedupe: a mention on a doc the agent is also subscribed to
781
- // arrives via both the inbox and `_handleStatelessChat`. First one wins.
782
- if (messageId && this._rememberDispatched(messageId)) return;
783
-
784
- const content = await this._resolveInboxContent(
785
- channelDocId,
786
- messageId,
787
- entry?.preview,
788
- );
789
-
790
- this._lastChatChannel = channelDocId;
791
- this._beginTurn(channelDocId);
792
- this.setAutoStatus("thinking");
793
-
794
- const attachedDoc = this.getDocSummary(channelDocId);
795
- const attachedHint =
796
- attachedDoc &&
797
- attachedDoc.type &&
798
- attachedDoc.type !== "channel" &&
799
- attachedDoc.type !== "dm"
800
- ? ` The chat is attached to the document channel_doc_id="${channelDocId}" (label: ${JSON.stringify(attachedDoc.label ?? "")}, type: "${attachedDoc.type}"). If the user refers to "this <doc-kind>" or talks about the document the chat is attached to, they mean THIS doc — operate on it directly via its id without searching.`
801
- : "";
802
-
803
- await this._serverRef.notification({
804
- method: "notifications/claude/channel",
805
- params: {
806
- content,
807
- instructions: `You MUST use send_chat_message with channel_doc_id="${channelDocId}" for ALL responses — both progress updates and final answers. The user CANNOT see plain text output; they only see messages sent via send_chat_message. When doing multi-step work, send brief status updates via send_chat_message (e.g. "Looking into that..." or "Found it, writing up results...") so the user knows you're working. Never output plain text as a substitute for send_chat_message.${attachedHint}`,
808
- meta: {
809
- source: "abracadabra",
810
- type: kind === "dm" ? "dm_message" : "chat_message",
811
- channel_doc_id: channelDocId,
812
- sender: entry?.sender_name ?? "Unknown",
813
- sender_id: senderId,
814
- doc_id: channelDocId,
815
- ...(attachedDoc
816
- ? {
817
- attached_doc: {
818
- id: channelDocId,
819
- label: attachedDoc.label,
820
- type: attachedDoc.type,
821
- },
822
- }
823
- : {}),
824
- },
825
- },
826
- });
827
- console.error(
828
- `[abracadabra-mcp] Dispatched ${kind} on ${channelDocId} from ${entry?.sender_name ?? (senderId || "unknown")}`,
829
- );
830
-
831
- // Mark the inbox entry read so it doesn't re-pump on reconnect.
832
- this._activeConnection?.provider?.sendStateless(
833
- JSON.stringify({
834
- type: "messages:inbox_mark_read",
835
- id: entry.id,
836
- }),
837
- );
838
- }
839
-
840
- /**
841
- * Resolve full message content. The inbox `preview` is truncated to ≤200
842
- * bytes (and null for E2E), so for fidelity we read the actual record from
843
- * the channel/DM doc's active period — same shape the dashboard reads.
844
- * Falls back to the preview, then a short notice.
845
- */
846
- private async _resolveInboxContent(
847
- channelDocId: string,
848
- messageId: string | null,
849
- preview: unknown,
850
- ): Promise<string> {
851
- const previewStr =
852
- typeof preview === "string" && preview.length > 0 ? preview : null;
853
- const root = this._activeConnection?.provider;
854
- if (root && messageId) {
855
- try {
856
- const wrapper = await root.loadChild(channelDocId);
857
- if (!wrapper.synced) await waitForSync(wrapper);
858
- const periods = wrapper.document.getArray("periods");
859
- const len = periods.length;
860
- // Scan the last two periods (resilient to a rollover between send + read).
861
- for (let i = len - 1; i >= 0 && i >= len - 2; i--) {
862
- const p: any = periods.get(i);
863
- const periodId: string | undefined = p?.id ?? p?.get?.("id");
864
- if (!periodId) continue;
865
- const period = await root.loadChild(periodId);
866
- if (!period.synced) await waitForSync(period);
867
- const records = (
868
- period.document.getArray("messages").toArray() as unknown[]
869
- )
870
- .map((v) => recordFromYAny(v))
871
- .filter(
872
- (r): r is NonNullable<ReturnType<typeof recordFromYAny>> =>
873
- r !== null,
874
- );
875
- const folded = foldRecords(records);
876
- const hit = folded.find((f) => f.id === messageId);
877
- if (hit) {
878
- if (isEncryptedContent(hit.content)) {
879
- return (
880
- previewStr ??
881
- "[encrypted message — this agent is not provisioned to read this channel]"
882
- );
883
- }
884
- return hit.content;
885
- }
886
- }
887
- } catch (err: any) {
888
- console.error(
889
- `[abracadabra-mcp] content read failed for ${channelDocId}/${messageId}: ${err?.message ?? err}`,
890
- );
891
- }
892
- }
893
- return previewStr ?? "[message content unavailable]";
894
- }
895
-
896
- /** Check-and-mark: true if already dispatched, else records it and returns false. */
897
- private _rememberDispatched(messageId: string): boolean {
898
- if (this._dispatchedMessageIds.has(messageId)) return true;
899
- this._dispatchedMessageIds.add(messageId);
900
- this._trimSet(this._dispatchedMessageIds);
901
- return false;
902
- }
903
-
904
- /** Check-only: true if this id was already dispatched (does NOT record it). */
905
- private _wasDispatched(messageId: string): boolean {
906
- return this._dispatchedMessageIds.has(messageId);
907
- }
908
-
909
- private _trimSet(s: Set<string>): void {
910
- if (s.size <= AbracadabraMCPServer.DEDUPE_MAX) return;
911
- const excess = s.size - AbracadabraMCPServer.DEDUPE_MAX;
912
- let i = 0;
913
- for (const v of s) {
914
- if (i++ >= excess) break;
915
- s.delete(v);
916
- }
917
- }
918
-
919
- /** Attach awareness observer to detect `ai:task` fields from human users. */
920
- private _observeRootAwareness(provider: AbracadabraProvider): void {
921
- const selfId = provider.awareness.clientID;
922
- provider.awareness.on("change", () => {
923
- // Strict `mention` mode ignores ai:task awareness; every other mode honors it.
924
- if (this.triggerMode === "mention") return;
925
-
926
- const states = provider.awareness.getStates();
927
- for (const [clientId, state] of states) {
928
- if (clientId === selfId) continue;
929
- const task = (state as Record<string, any>)["ai:task"];
930
- if (!task || typeof task !== "object") continue;
931
- const { id, text } = task as { id?: string; text?: string };
932
- if (!id || !text) continue;
933
- if (this._handledTaskIds.has(id)) continue;
934
- this._handledTaskIds.add(id);
935
-
936
- // Extract sender name from awareness state
937
- const user = (state as Record<string, any>)["user"];
938
- const senderName =
939
- user && typeof user === "object" && typeof user.name === "string"
940
- ? user.name
941
- : "Unknown";
942
-
943
- console.error(
944
- `[abracadabra-mcp] Handling ai:task id=${id} from ${senderName}: ${text.slice(0, 80)}`,
945
- );
946
- this._beginTurn();
947
- this.setAutoStatus("thinking");
948
- this._dispatchAiTask({
949
- id,
950
- text,
951
- docId: (state as Record<string, any>)["docId"],
952
- senderName,
953
- });
954
- }
955
- });
956
- console.error("[abracadabra-mcp] Root awareness observation started");
957
- }
958
-
959
- /** Dispatch an ai:task as a channel notification. */
960
- private async _dispatchAiTask(task: {
961
- id: string;
962
- text: string;
963
- docId?: string;
964
- senderName: string;
965
- }): Promise<void> {
966
- if (!this._serverRef) return;
967
- try {
968
- await this._serverRef.notification({
969
- method: "notifications/claude/channel",
970
- params: {
971
- content: task.text,
972
- instructions: `You MUST use the reply tool with doc_id="${task.docId ?? ""}" and task_id="${task.id}" for your final response. The user CANNOT see plain text output; they only see replies sent via MCP tools. For progress updates during multi-step work, use send_chat_message with channel="group:${task.docId ?? ""}" (e.g. "Looking into that..." or "Found it, writing up results..."). Never output plain text as a substitute for MCP tools.`,
973
- meta: {
974
- source: "abracadabra",
975
- type: "ai_task",
976
- task_id: task.id,
977
- sender: task.senderName,
978
- doc_id: task.docId ?? "",
979
- },
980
- },
981
- });
982
- console.error(
983
- `[abracadabra-mcp] Channel notification sent for ai:task id=${task.id}`,
984
- );
985
- } catch (error: any) {
986
- console.error(
987
- `[abracadabra-mcp] Channel notification failed: ${error.message}`,
988
- );
989
- }
990
- }
991
-
992
- /**
993
- * Clear an ai:task from awareness to signal completion.
994
- * Scans all awareness states for the given task ID and removes it.
995
- */
996
- clearAiTask(taskId: string): void {
997
- const provider = this._activeConnection?.provider;
998
- if (!provider) return;
999
- const selfId = provider.awareness.clientID;
1000
- const states = provider.awareness.getStates();
1001
- for (const [clientId, state] of states) {
1002
- if (clientId === selfId) continue;
1003
- const task = (state as Record<string, any>)["ai:task"];
1004
- if (task && typeof task === "object" && (task as any).id === taskId) {
1005
- // We can't clear another client's awareness directly, but we can
1006
- // signal completion by setting our own awareness field
1007
- provider.awareness.setLocalStateField("ai:task:done", taskId);
1008
- break;
1009
- }
1010
- }
1011
- }
1012
-
1013
- /** Handle incoming `messages:new_message` broadcasts and dispatch as channel notifications. */
1014
- private async _handleStatelessChat(payload: string): Promise<void> {
1015
- if (!this._serverRef) return;
1016
- if (!payload.includes('"messages:new_message"')) return;
1017
-
1018
- try {
1019
- const env = JSON.parse(payload);
1020
- if (env.type !== "messages:new_message") return;
1021
- const data = env.record;
1022
- if (!data) return;
1023
- // Only react to actual messages — skip edit/tombstone records.
1024
- if (data.record_kind && data.record_kind !== "message") return;
1025
- // Skip own messages
1026
- if (data.sender_id && data.sender_id === this._userId) return;
1027
-
1028
- const channelDocId = data.channel_doc_id as string | undefined;
1029
- if (!channelDocId) return;
1030
-
1031
- // Cross-path dedupe (CHECK ONLY here — do NOT mark yet). If the inbox
1032
- // already dispatched this id, skip. We must not *mark* the id before
1033
- // the trigger gate below: a non-mention group message that this path
1034
- // skips would otherwise poison the dedupe set and block the inbox
1035
- // observer from dispatching a legitimate @mention/DM for the same id.
1036
- if (data.id && this._wasDispatched(data.id)) return;
1037
-
1038
- // This path only ever sees docs the agent is *subscribed* to (the active
1039
- // space root + lazily-loaded children) — i.e. group/channel/space chat,
1040
- // never a DM doc (the agent never subscribes to those). DM correctness
1041
- // lives entirely in the inbox observer, so group trigger semantics are
1042
- // correct here.
1043
- const isGroup = true;
1044
-
1045
- // ── Trigger mode gate ─────────────────────────────────────────────
1046
- const mode = this.triggerMode;
1047
- const content = typeof data.content === "string" ? data.content : "";
1048
- let dispatchContent = content;
1049
-
1050
- if (isGroup) {
1051
- if (mode === "task") {
1052
- return;
1053
- }
1054
- if (mode === "mention" || mode === "mention+task") {
1055
- const aliases = this.mentionAliases;
1056
- // Authoritative signal: the server-stored `mentions` array carries
1057
- // the resolved pubkeys the sender @-mentioned. If our pubkey is in
1058
- // it, we're mentioned — regardless of how the @text was written.
1059
- // Fall back to text matching for older clients that don't send it.
1060
- const mentionedByPubkey =
1061
- Array.isArray(data.mentions) &&
1062
- !!this._userId &&
1063
- data.mentions.includes(this._userId);
1064
- const mentionedByText = containsMention(content, aliases);
1065
- if (!mentionedByPubkey && !mentionedByText) {
1066
- console.error(
1067
- `[abracadabra-mcp] skipped ${channelDocId} — not mentioned (mentions=${JSON.stringify(data.mentions ?? [])}, aliases=${aliases.join("|")})`,
1068
- );
1069
- return;
1070
- }
1071
- dispatchContent = stripMention(content, aliases) || content;
1072
- }
1073
- // mode === 'all' falls through unchanged
1074
- }
1075
- // ──────────────────────────────────────────────────────────────────
1076
-
1077
- // Auto-mark this message position read.
1078
- const rootProvider = this._activeConnection?.provider;
1079
- if (rootProvider && data.id && data.period_id) {
1080
- rootProvider.sendStateless(
1081
- JSON.stringify({
1082
- type: "messages:mark_read",
1083
- channel_doc_id: channelDocId,
1084
- period_id: data.period_id,
1085
- message_id: data.id,
1086
- ts: Date.now(),
1087
- }),
1088
- );
1089
- }
1090
- this._lastChatChannel = channelDocId;
1091
-
1092
- // Mark dispatched only now that the gate passed — this is the message
1093
- // we're actually handling, so the inbox path should skip its twin.
1094
- if (data.id) this._rememberDispatched(data.id);
1095
-
1096
- this._beginTurn(channelDocId);
1097
- this.setAutoStatus("thinking");
1098
-
1099
- const attachedDoc = this.getDocSummary(channelDocId);
1100
- const attachedHint =
1101
- attachedDoc &&
1102
- attachedDoc.type &&
1103
- attachedDoc.type !== "channel" &&
1104
- attachedDoc.type !== "dm"
1105
- ? ` The chat is attached to the document channel_doc_id="${channelDocId}" (label: ${JSON.stringify(attachedDoc.label ?? "")}, type: "${attachedDoc.type}"). If the user refers to "this <doc-kind>" or talks about the document the chat is attached to, they mean THIS doc — operate on it directly via its id without searching.`
1106
- : "";
1107
-
1108
- await this._serverRef.notification({
1109
- method: "notifications/claude/channel",
1110
- params: {
1111
- content: dispatchContent,
1112
- instructions: `You MUST use send_chat_message with channel_doc_id="${channelDocId}" for ALL responses — both progress updates and final answers. The user CANNOT see plain text output; they only see messages sent via send_chat_message. When doing multi-step work, send brief status updates via send_chat_message (e.g. "Looking into that..." or "Found it, writing up results...") so the user knows you're working. Never output plain text as a substitute for send_chat_message.${attachedHint}`,
1113
- meta: {
1114
- source: "abracadabra",
1115
- type: "chat_message",
1116
- channel_doc_id: channelDocId,
1117
- sender: data.sender_name ?? "Unknown",
1118
- sender_id: data.sender_id ?? "",
1119
- doc_id: channelDocId,
1120
- ...(attachedDoc
1121
- ? {
1122
- attached_doc: {
1123
- id: channelDocId,
1124
- label: attachedDoc.label,
1125
- type: attachedDoc.type,
1126
- },
1127
- }
1128
- : {}),
1129
- },
1130
- },
1131
- });
1132
- console.error(
1133
- `[abracadabra-mcp] Chat message from ${data.sender_name ?? "unknown"} on ${channelDocId}`,
1134
- );
1135
- } catch {
1136
- // Ignore non-chat or malformed payloads
1137
- }
1138
- }
1139
-
1140
- /**
1141
- * Set the agent's status in root awareness with auto-clear after idle.
1142
- * @param statusContext — scopes the status to a specific channel/context so the
1143
- * dashboard only shows it in the relevant chat. Defaults to `_lastChatChannel`.
1144
- */
1145
- setAutoStatus(
1146
- status: string | null,
1147
- docId?: string,
1148
- statusContext?: string | null,
1149
- ): void {
1150
- const provider = this._activeConnection?.provider;
1151
- if (!provider) return;
1152
-
1153
- if (this._statusClearTimer) {
1154
- clearTimeout(this._statusClearTimer);
1155
- this._statusClearTimer = null;
1156
- }
1157
-
1158
- provider.awareness.setLocalStateField("status", status);
1159
- if (docId !== undefined) {
1160
- provider.awareness.setLocalStateField("docId", docId);
1161
- }
1162
-
1163
- // Scope status to the channel of the ACTIVE turn (null when none), so the
1164
- // dashboard only shows the incantation/typing in the chat the agent is
1165
- // actually engaged with. Defaulting to the sticky `_lastChatChannel` is
1166
- // what leaked unrelated session activity into an idle chat.
1167
- const context = status
1168
- ? statusContext !== undefined
1169
- ? statusContext
1170
- : this._activeTurnChannel
1171
- : null;
1172
- provider.awareness.setLocalStateField("statusContext", context ?? null);
1173
-
1174
- // When clearing status this is the authoritative end-of-turn signal:
1175
- // drop the tool pill and the turn id so the incantation + typing dots
1176
- // collapse. We deliberately do NOT wipe `toolHistory` here — the dashboard
1177
- // merges that array into its persistent inline tool-call log, and wiping
1178
- // it in the same awareness flush as the final message would race the
1179
- // client and lose the whole turn's activity. toolHistory is reset only at
1180
- // the start of the next turn (`_beginTurn`).
1181
- if (!status) {
1182
- this._stopTypingInterval();
1183
- this._activeTurnChannel = null;
1184
- provider.awareness.setLocalStateField("activeToolCall", null);
1185
- provider.awareness.setLocalStateField("turnId", null);
1186
- }
1187
-
1188
- // Auto-clear status after 10s of no updates. Short enough that a real
1189
- // idle is noticed quickly; long enough that normal inter-tool gaps
1190
- // (PostToolUse → next PreToolUse) don't flicker. Same rule: leave
1191
- // toolHistory in place for the persistent client log.
1192
- if (status) {
1193
- this._statusClearTimer = setTimeout(() => {
1194
- provider.awareness.setLocalStateField("status", null);
1195
- provider.awareness.setLocalStateField("activeToolCall", null);
1196
- provider.awareness.setLocalStateField("statusContext", null);
1197
- provider.awareness.setLocalStateField("turnId", null);
1198
- this._activeTurnChannel = null;
1199
- this._stopTypingInterval();
1200
- }, 10_000);
1201
- }
1202
- }
1203
-
1204
- /**
1205
- * Start a new agent turn. Mints a fresh UUID and writes it to awareness so
1206
- * the dashboard can gate the incantation on "there is an active turn",
1207
- * decoupled from the (racier) status field. Called from chat arrival and
1208
- * ai:task dispatch right before `setAutoStatus('thinking')`.
1209
- *
1210
- * Also starts a heartbeat typing indicator so the dashboard renders typing
1211
- * dots whenever no tool pill is active during the turn — this replaces the
1212
- * "dead air" gap users see between thinking and the final reply.
1213
- */
1214
- private _beginTurn(channel?: string): void {
1215
- const provider = this._activeConnection?.provider;
1216
- if (!provider) return;
1217
- this._toolHistory = [];
1218
- // Remember which channel (if any) this turn belongs to, so hook-bridge
1219
- // status updates scope to it — and ONLY it — for the turn's duration.
1220
- this._activeTurnChannel = channel ?? null;
1221
- provider.awareness.setLocalStateField("toolHistory", []);
1222
- provider.awareness.setLocalStateField("turnId", crypto.randomUUID());
1223
- // Only chat turns get a typing heartbeat — pass the channel explicitly.
1224
- // ai:task turns (document replies, no chat channel) call _beginTurn()
1225
- // with no arg and must NOT spray typing frames at a stale channel.
1226
- if (channel) this._startTypingInterval(channel);
1227
- }
1228
-
1229
- /**
1230
- * Enter the "writing" phase: the agent has finished reasoning and is about
1231
- * to send a chat message. The dashboard maps `status === 'writing'` to
1232
- * typing dots (not the incantation phrase). Keeps the turn alive (turnId
1233
- * stays set) and emits a typing frame immediately so the dots appear at
1234
- * once; the heartbeat keeps them alive until `setAutoStatus(null)`.
1235
- */
1236
- setWritingStatus(channel: string): void {
1237
- this._lastChatChannel = channel;
1238
- this.setAutoStatus("writing", undefined, channel);
1239
- this._startTypingInterval(channel);
1240
- }
1241
-
1242
- /** Re-send typing indicator every 2s so dashboard keeps showing it (expires at 3s). */
1243
- private _startTypingInterval(channel: string): void {
1244
- this._stopTypingInterval();
1245
- // Fire one immediately so the indicator appears without waiting 2s.
1246
- this.sendTypingIndicator(channel);
1247
- this._typingInterval = setInterval(() => {
1248
- this.sendTypingIndicator(channel);
1249
- }, 2000);
1250
- }
1251
-
1252
- private _stopTypingInterval(): void {
1253
- if (this._typingInterval) {
1254
- clearInterval(this._typingInterval);
1255
- this._typingInterval = null;
1256
- }
1257
- // Do NOT clear _lastChatChannel here — subsequent turns need it as the
1258
- // default channel context. _lastChatChannel is rewritten on every chat
1259
- // arrival anyway, so leaving it set across turns is correct.
1260
- }
1261
-
1262
- /**
1263
- * Broadcast which tool the agent is currently executing.
1264
- *
1265
- * Renders as a ChatTool pill on the dashboard. On non-null calls, the tool
1266
- * is also appended to `toolHistory` (capped at TOOL_HISTORY_MAX) and written
1267
- * to awareness so the dashboard's inline trace can show the turn's recent
1268
- * activity. Tools do NOT clear (`setActiveToolCall(null)`) on completion —
1269
- * the pill stays until the next tool replaces it or `setAutoStatus(null)`
1270
- * flushes the turn. This keeps pills visible long enough to see.
1271
- */
1272
- setActiveToolCall(
1273
- toolCall: { name: string; target?: string; detail?: unknown } | null,
1274
- ): void {
1275
- const provider = this._activeConnection?.provider;
1276
- if (!provider) return;
1277
- provider.awareness.setLocalStateField("activeToolCall", toolCall);
1278
- if (toolCall) {
1279
- this._toolHistory.push({
1280
- tool: toolCall.name,
1281
- target: toolCall.target,
1282
- ts: Date.now(),
1283
- channel: this._lastChatChannel,
1284
- detail: toolCall.detail,
1285
- });
1286
- if (this._toolHistory.length > AbracadabraMCPServer.TOOL_HISTORY_MAX) {
1287
- this._toolHistory.splice(
1288
- 0,
1289
- this._toolHistory.length - AbracadabraMCPServer.TOOL_HISTORY_MAX,
1290
- );
1291
- }
1292
- provider.awareness.setLocalStateField("toolHistory", [
1293
- ...this._toolHistory,
1294
- ]);
1295
- }
1296
- }
1297
-
1298
- /**
1299
- * Attach expandable `detail` (arguments + result summary) to the most recent
1300
- * tool-history entry for `toolName`, then re-broadcast `toolHistory`.
1301
- *
1302
- * Called by the central tool wrapper in index.ts *after* a tool resolves, so
1303
- * the dashboard's tool cards can expand to show what the tool was called with
1304
- * and what it returned — the same affordance built-in Claude tools (bash /
1305
- * read / edit) already get via the hook-bridge. Tools that never emitted a
1306
- * pill (no `setActiveToolCall`) have no entry to attach to, so this no-ops.
1307
- */
1308
- recordToolDetail(toolName: string, detail: unknown): void {
1309
- const provider = this._activeConnection?.provider;
1310
- if (!provider) return;
1311
- // The matching pill was pushed at the start of this tool's handler, so the
1312
- // last detail-less entry for this name is this invocation's entry.
1313
- for (let i = this._toolHistory.length - 1; i >= 0; i--) {
1314
- const h = this._toolHistory[i];
1315
- if (h.tool === toolName && h.detail == null) {
1316
- h.detail = detail;
1317
- provider.awareness.setLocalStateField("toolHistory", [
1318
- ...this._toolHistory,
1319
- ]);
1320
- return;
1321
- }
1322
- }
1323
- }
1324
-
1325
- /**
1326
- * Send a typing indicator to a chat channel. Pass the channel doc id
1327
- * (or for legacy callers, a `group:<docId>` string — we strip the prefix).
1328
- */
1329
- sendTypingIndicator(channel: string): void {
1330
- const rootProvider = this._activeConnection?.provider;
1331
- if (!rootProvider) return;
1332
- const channelDocId = channel.startsWith("group:")
1333
- ? channel.slice(6)
1334
- : channel.startsWith("dm:")
1335
- ? channel
1336
- : channel;
1337
- rootProvider.sendStateless(
1338
- JSON.stringify({
1339
- type: "messages:typing",
1340
- channel_doc_id: channelDocId,
1341
- }),
1342
- );
1343
- }
1344
-
1345
- /** Graceful shutdown. */
1346
- async destroy(): Promise<void> {
1347
- this._stopTypingInterval();
1348
- if (this._statusClearTimer) {
1349
- clearTimeout(this._statusClearTimer);
1350
- this._statusClearTimer = null;
1351
- }
1352
- if (this.evictionTimer) {
1353
- clearInterval(this.evictionTimer);
1354
- this.evictionTimer = null;
1355
- }
1356
- if (this.heartbeatTimer) {
1357
- clearInterval(this.heartbeatTimer);
1358
- this.heartbeatTimer = null;
1359
- }
1360
-
1361
- for (const dispose of this._inboxDisposers) {
1362
- try {
1363
- dispose();
1364
- } catch {
1365
- /* ignore */
1366
- }
1367
- }
1368
- this._inboxDisposers = [];
1369
- this._inboxProvider?.destroy();
1370
- this._inboxProvider = null;
1371
- this._inboxDoc = null;
1372
-
1373
- for (const [, cached] of this.childCache) {
1374
- cached.provider.destroy();
1375
- }
1376
- this.childCache.clear();
1377
-
1378
- // Clear awareness fields before destroying so other clients don't see stale state
1379
- for (const [, conn] of this._spaceConnections) {
1380
- conn.provider.awareness.setLocalStateField("status", null);
1381
- conn.provider.awareness.setLocalStateField("activeToolCall", null);
1382
- conn.provider.awareness.setLocalStateField("statusContext", null);
1383
- conn.provider.awareness.setLocalStateField("turnId", null);
1384
- conn.provider.awareness.setLocalStateField("toolHistory", []);
1385
- conn.provider.destroy();
1386
- }
1387
- this._toolHistory = [];
1388
- this._spaceConnections.clear();
1389
- this._activeConnection = null;
1390
-
1391
- console.error("[abracadabra-mcp] Shutdown complete");
1392
- }
1393
- }