@gorlitzer-labs/apiary 1.13.3

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +328 -0
  3. package/dist/agent/index.d.ts +689 -0
  4. package/dist/agent/index.js +34 -0
  5. package/dist/agent/index.js.map +1 -0
  6. package/dist/chunk-5V7QLCGB.js +184 -0
  7. package/dist/chunk-5V7QLCGB.js.map +1 -0
  8. package/dist/chunk-AYQJIAR5.js +152 -0
  9. package/dist/chunk-AYQJIAR5.js.map +1 -0
  10. package/dist/chunk-BZ4VDWC2.js +76 -0
  11. package/dist/chunk-BZ4VDWC2.js.map +1 -0
  12. package/dist/chunk-CFY6Z6Q6.js +95 -0
  13. package/dist/chunk-CFY6Z6Q6.js.map +1 -0
  14. package/dist/chunk-CZHO4DBN.js +1719 -0
  15. package/dist/chunk-CZHO4DBN.js.map +1 -0
  16. package/dist/chunk-D7DXZQWT.js +208 -0
  17. package/dist/chunk-D7DXZQWT.js.map +1 -0
  18. package/dist/chunk-ED6ROH6B.js +2021 -0
  19. package/dist/chunk-ED6ROH6B.js.map +1 -0
  20. package/dist/chunk-PEB6HEFT.js +606 -0
  21. package/dist/chunk-PEB6HEFT.js.map +1 -0
  22. package/dist/chunk-QL66XSDB.js +157 -0
  23. package/dist/chunk-QL66XSDB.js.map +1 -0
  24. package/dist/chunk-TPNFOQA7.js +288 -0
  25. package/dist/chunk-TPNFOQA7.js.map +1 -0
  26. package/dist/chunk-ZEFRNAX6.js +1771 -0
  27. package/dist/chunk-ZEFRNAX6.js.map +1 -0
  28. package/dist/cli/index.d.ts +1 -0
  29. package/dist/cli/index.js +2432 -0
  30. package/dist/cli/index.js.map +1 -0
  31. package/dist/index-Dp3QSGog.d.ts +837 -0
  32. package/dist/index.d.ts +2 -0
  33. package/dist/index.js +22 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/invites-OFXIQLLN.js +23 -0
  36. package/dist/invites-OFXIQLLN.js.map +1 -0
  37. package/dist/join-CQXEF65B.js +15 -0
  38. package/dist/join-CQXEF65B.js.map +1 -0
  39. package/dist/room-Z7KDRVYD.js +1099 -0
  40. package/dist/room-Z7KDRVYD.js.map +1 -0
  41. package/dist/run-DOADB4T7.js +90 -0
  42. package/dist/run-DOADB4T7.js.map +1 -0
  43. package/dist/update-JGE3WCQB.js +11 -0
  44. package/dist/update-JGE3WCQB.js.map +1 -0
  45. package/package.json +72 -0
@@ -0,0 +1,689 @@
1
+ import { P as Participant, M as Message, a as PaginatedResult, E as EventCategory, R as RoomEvent, A as Attachment, b as Room, C as Channel, c as ParticipantType, d as AuthorityLevel } from '../index-Dp3QSGog.js';
2
+ import 'zod';
3
+
4
+ /**
5
+ * Uniform interface for reading/writing room data.
6
+ *
7
+ * Implemented by:
8
+ * - `LocalRoomDataSource` — wraps a Room + Channel for in-process access
9
+ * - `RemoteRoomDataSource` — wraps HTTP calls to a stoop server (Phase 5)
10
+ */
11
+ interface RoomDataSource {
12
+ readonly roomId: string;
13
+ /** The agent's own participant ID in this room. Used for whisper filtering. */
14
+ readonly selfId: string;
15
+ listParticipants(): Participant[];
16
+ getMessage(id: string): Promise<Message | null>;
17
+ searchMessages(query: string, limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
18
+ getMessages(limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
19
+ getEvents(category?: EventCategory | null, limit?: number, cursor?: string | null): Promise<PaginatedResult<RoomEvent>>;
20
+ sendMessage(content: string, replyToId?: string, image?: {
21
+ url: string;
22
+ mimeType: string;
23
+ sizeBytes: number;
24
+ } | null, attachments?: Attachment[], recipients?: string[]): Promise<Message>;
25
+ emitEvent?(event: RoomEvent): Promise<void>;
26
+ }
27
+ /**
28
+ * LocalRoomDataSource — wraps a Room + Channel for in-process access.
29
+ *
30
+ * Used by app-path consumers (ClaudeSession, LangGraphSession) and the
31
+ * CLI server's EventProcessor. Transparent — all calls delegate directly
32
+ * to the Room and Channel.
33
+ */
34
+ declare class LocalRoomDataSource implements RoomDataSource {
35
+ private _room;
36
+ private _channel;
37
+ constructor(_room: Room, _channel: Channel);
38
+ get roomId(): string;
39
+ get selfId(): string;
40
+ /** Direct access to the underlying Room (for backward compat / internal use). */
41
+ get room(): Room;
42
+ /** Direct access to the underlying Channel (for backward compat / internal use). */
43
+ get channel(): Channel;
44
+ listParticipants(): Participant[];
45
+ getMessage(id: string): Promise<Message | null>;
46
+ searchMessages(query: string, limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
47
+ getMessages(limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
48
+ getEvents(category?: EventCategory | null, limit?: number, cursor?: string | null): Promise<PaginatedResult<RoomEvent>>;
49
+ sendMessage(content: string, replyToId?: string, image?: {
50
+ url: string;
51
+ mimeType: string;
52
+ sizeBytes: number;
53
+ } | null, attachments?: Attachment[], recipients?: string[]): Promise<Message>;
54
+ emitEvent(event: RoomEvent): Promise<void>;
55
+ }
56
+
57
+ /**
58
+ * Shared interfaces for apiary agent infrastructure.
59
+ *
60
+ * Two layers:
61
+ *
62
+ * EventProcessor ──deliver()──► Consumer (tmux, HTTP API, etc.)
63
+ *
64
+ * EventProcessor owns the event loop, engagement, formatting.
65
+ * Consumers own LLM delivery, MCP servers, compaction, stats.
66
+ */
67
+
68
+ /**
69
+ * A structured content item delivered to the consumer.
70
+ *
71
+ * Text parts carry formatted event text; image parts carry the URL of an
72
+ * attached image so vision-capable consumers can see it natively.
73
+ */
74
+ type ContentPart = {
75
+ type: "text";
76
+ text: string;
77
+ } | {
78
+ type: "image";
79
+ url: string;
80
+ };
81
+ /**
82
+ * A resolved room connection: the data source, the room's display name,
83
+ * and optional direct room/channel references for backward compatibility.
84
+ *
85
+ * Tool handlers and EventProcessor use `dataSource` for all data access.
86
+ * Direct `room`/`channel` access is kept for app-path consumers that need it.
87
+ */
88
+ interface RoomConnection {
89
+ dataSource: RoomDataSource;
90
+ /** Present for local (app-path) rooms; absent for remote rooms. */
91
+ room?: Room;
92
+ /** Present for local (app-path) rooms; absent for remote rooms. */
93
+ channel?: Channel;
94
+ name: string;
95
+ }
96
+ /**
97
+ * Maps room names (and identifiers) to their live connections.
98
+ *
99
+ * Implemented by `EventProcessor`. Tool handlers and sessions receive a
100
+ * `RoomResolver` so they can look up rooms by the names the LLM uses.
101
+ */
102
+ interface RoomResolver {
103
+ /** Resolve a room by display name, identifier slug, or room ID. Returns null if unknown. */
104
+ resolve(roomName: string): RoomConnection | null;
105
+ /** List all currently connected rooms with metadata. */
106
+ listAll(): Array<{
107
+ name: string;
108
+ roomId: string;
109
+ identifier?: string;
110
+ mode: string;
111
+ participantCount: number;
112
+ lastMessage?: string;
113
+ }>;
114
+ }
115
+ /** Callbacks that bridge the session to the EventProcessor. */
116
+ interface ProcessorBridge {
117
+ isEventSeen?: (eventId: string) => boolean;
118
+ markEventsSeen?: (eventIds: string[]) => void;
119
+ assignRef?: (messageId: string) => string;
120
+ resolveRef?: (ref: string) => string | undefined;
121
+ onContextCompacted?: () => void;
122
+ onToolUse?: (toolName: string, status: "started" | "completed") => void;
123
+ }
124
+ /** Subset of ProcessorBridge used by tool handlers and MCP server. */
125
+ type ToolHandlerOptions = Pick<ProcessorBridge, "isEventSeen" | "markEventsSeen" | "assignRef" | "resolveRef">;
126
+
127
+ /** Event formatting and mode descriptions for apiary agents. */
128
+
129
+ /** Short 4-char ref for a message ID, used in transcripts. */
130
+ declare function messageRef(messageId: string): string;
131
+ /** Format a participant as a labeled name: "[human] Alice" or "[agent] Quinn". */
132
+ declare function participantLabel(p: Participant | null, fallback?: string): string;
133
+ /** Convert ContentPart[] back to a plain string (for trace logs and stats). */
134
+ declare function contentPartsToString(parts: ContentPart[]): string;
135
+ /**
136
+ * Format a typed event as ContentPart[] for the LLM session.
137
+ * Returns null for events that shouldn't be sent to the LLM (noise).
138
+ *
139
+ * Compact one-liner format:
140
+ * Messages: [14:23:01] #3847 [lobby] Alice: hey everyone
141
+ * Replies: [14:23:01] #9102 [lobby] Alice (→ #3847 Bob): good point
142
+ * Mentions: [14:23:01] #5521 [lobby] ⚡ Alice: @bot what do you think?
143
+ * Joined: [14:23:01] [lobby] + Alice joined
144
+ * Left: [14:23:15] [lobby] - Bob left
145
+ * Reactions: [14:23:20] [lobby] Alice reacted ❤️ to #3847
146
+ */
147
+ declare function formatEvent(event: RoomEvent, resolveParticipant: (id: string) => Participant | null, replyContext?: {
148
+ senderName: string;
149
+ content: string;
150
+ } | null, roomLabel?: string, reactionTarget?: {
151
+ senderName: string;
152
+ content: string;
153
+ isSelf: boolean;
154
+ } | null, assignRef?: (messageId: string) => string): ContentPart[] | null;
155
+
156
+ /**
157
+ * Engagement — controls which room events trigger LLM evaluation.
158
+ *
159
+ * # Overview
160
+ *
161
+ * Every event that reaches an agent is classified into one of three dispositions:
162
+ * - "trigger" — evaluate now (start an LLM call)
163
+ * - "content" — buffer as context; deliver to LLM on the next trigger
164
+ * - "drop" — ignore entirely (not delivered to LLM)
165
+ *
166
+ * The `EngagementStrategy` interface defines this contract. Implement it to
167
+ * customize when your agent responds. The built-in `StoopsEngagement` provides
168
+ * a 7-mode system; `classifyEvent()` is a standalone convenience function
169
+ * using the same logic.
170
+ *
171
+ * # Built-in modes (StoopsEngagement / classifyEvent)
172
+ *
173
+ * Active modes (agent evaluates on matching messages):
174
+ * - "everyone" — all messages trigger evaluation
175
+ * - "people" — only messages from human participants trigger evaluation
176
+ * - "agents" — only messages from other agents trigger evaluation
177
+ * - "fight" — all messages trigger (novelty roast mode)
178
+ *
179
+ * Standby modes (agent only wakes on @mentions):
180
+ * - "standby-everyone" — any @mention wakes the agent
181
+ * - "standby-people" — only @mentions from humans wake the agent
182
+ * - "standby-agents" — only @mentions from other agents wake the agent
183
+ *
184
+ * # Classification rules (in order)
185
+ *
186
+ * 1. Internal events (bookkeeping: edits, deletes, status changes, agent
187
+ * activity) → always drop
188
+ * 2. Self-sent events → drop (the agent ignores its own activity).
189
+ * Exception: mentions are not self-dropped — a standby agent should wake
190
+ * if it is @mentioned, even if the mention event's participant_id is itself.
191
+ * 3. Standby modes: only @mentions directed at the agent from a matching
192
+ * sender → trigger; everything else → drop.
193
+ * 4. Active modes, @mention → drop (the MessageSent event already carries the
194
+ * @mention text; delivering both would be redundant).
195
+ * 5. Active modes, message from matching sender → trigger
196
+ * 6. Active modes, message from non-matching sender → content (buffered context)
197
+ * 7. Active modes, ambient event (join/leave/reaction) → content
198
+ */
199
+
200
+ /**
201
+ * The outcome of classifying an event for a given agent.
202
+ *
203
+ * - "trigger" — run an LLM evaluation now
204
+ * - "content" — buffer as context; include with the next evaluation
205
+ * - "drop" — discard; never shown to the LLM
206
+ */
207
+ type EventDisposition = "trigger" | "content" | "drop";
208
+ /**
209
+ * Engagement strategy — decides which events trigger LLM evaluation.
210
+ *
211
+ * Implement this to customize when your agent responds. The runtime calls
212
+ * `classify()` for every incoming event and acts on the returned disposition.
213
+ *
214
+ * @example
215
+ * // Respond to everything:
216
+ * class AlwaysEngage implements EngagementStrategy {
217
+ * classify(event, roomId, selfId) {
218
+ * if (event.participant_id === selfId) return "drop";
219
+ * return "trigger";
220
+ * }
221
+ * }
222
+ */
223
+ interface EngagementStrategy {
224
+ /**
225
+ * Classify a room event for this agent.
226
+ *
227
+ * @param event — the room event to classify
228
+ * @param roomId — the room the event came from
229
+ * @param selfId — the agent's own participant ID (to drop self-events)
230
+ * @param senderType — "human" or "agent" for the event's sender
231
+ * @param senderId — participant ID of the sender. For `Mentioned` events,
232
+ * pass `event.message.sender_id` (who wrote the mention),
233
+ * not `event.participant_id` (who was mentioned).
234
+ */
235
+ classify(event: RoomEvent, roomId: string, selfId: string, senderType: ParticipantType, senderId: string): EventDisposition;
236
+ /**
237
+ * Return the current engagement mode for a room.
238
+ *
239
+ * Optional — strategies that don't use named modes may omit this.
240
+ * The runtime falls back to `"everyone"` when absent.
241
+ */
242
+ getMode?(roomId: string): EngagementMode;
243
+ /**
244
+ * Update the engagement mode for a room.
245
+ *
246
+ * Optional — called by the runtime when a room connects with an initial mode
247
+ * or when the user changes the mode at runtime. Strategies that don't use
248
+ * named modes may omit this; the call will be silently ignored.
249
+ */
250
+ setMode?(roomId: string, mode: EngagementMode): void;
251
+ /**
252
+ * Called when a room is disconnected from the runtime.
253
+ *
254
+ * Optional — use this for cleanup, e.g. removing per-room state that is
255
+ * no longer needed. Strategies with no per-room state may omit this.
256
+ */
257
+ onRoomDisconnected?(roomId: string): void;
258
+ }
259
+ type EngagementMode = "people" | "agents" | "everyone" | "fight" | "standby-people" | "standby-agents" | "standby-everyone";
260
+ /**
261
+ * StoopsEngagement — the built-in engagement strategy.
262
+ *
263
+ * Implements the 7-mode system: 4 active modes (everyone/people/agents/fight)
264
+ * and 3 standby modes that only wake on @mentions. Maintains per-room mode
265
+ * state internally.
266
+ *
267
+ * @example
268
+ * const engagement = new StoopsEngagement("people");
269
+ * engagement.setMode("room-1", "agents");
270
+ * engagement.classify(event, "room-1", selfId, "human", senderId);
271
+ */
272
+ declare class StoopsEngagement implements EngagementStrategy {
273
+ private _modes;
274
+ private _defaultMode;
275
+ constructor(defaultMode: EngagementMode);
276
+ /** Get the engagement mode for a room. Falls back to the default mode. */
277
+ getMode(roomId: string): EngagementMode;
278
+ /** Set the engagement mode for a room. */
279
+ setMode(roomId: string, mode: EngagementMode): void;
280
+ /** Called when a room is disconnected. Removes the room's mode so it doesn't linger. */
281
+ onRoomDisconnected(roomId: string): void;
282
+ classify(event: RoomEvent, roomId: string, selfId: string, senderType: ParticipantType, senderId: string): EventDisposition;
283
+ }
284
+ /**
285
+ * Classify a room event for an agent with the given engagement mode.
286
+ *
287
+ * Pure function — no state, no side effects, no SDK dependency.
288
+ * Uses the same classification logic as `StoopsEngagement` but takes all
289
+ * parameters explicitly. Useful for one-off classification or testing.
290
+ *
291
+ * @param event — the event to classify
292
+ * @param mode — the agent's current engagement mode for this room
293
+ * @param selfId — the agent's own participant ID (to drop self-events)
294
+ * @param senderType — type of the participant who caused the event
295
+ * @param senderId — participant ID of the sender.
296
+ * For `Mentioned` events, pass `event.message.sender_id`
297
+ * (who wrote the mention), not `event.participant_id`
298
+ * (who was mentioned).
299
+ */
300
+ declare function classifyEvent(event: RoomEvent, mode: EngagementMode, selfId: string, senderType: ParticipantType, senderId: string): EventDisposition;
301
+
302
+ /** EventMultiplexer — merges N channel async streams into one labeled stream. */
303
+
304
+ interface LabeledEvent {
305
+ roomId: string;
306
+ roomName: string;
307
+ event: RoomEvent;
308
+ }
309
+ /**
310
+ * Merges events from multiple channels into a single async iterable stream.
311
+ * Each event is labeled with its source room's ID and name.
312
+ *
313
+ * Channels can be added/removed while the multiplexer is running.
314
+ */
315
+ declare class EventMultiplexer {
316
+ private _queue;
317
+ private _waiters;
318
+ private _channels;
319
+ private _closed;
320
+ private _closeResolve;
321
+ addChannel(roomId: string, roomName: string, channel: Channel): void;
322
+ removeChannel(roomId: string): void;
323
+ close(): void;
324
+ private _listenLoop;
325
+ private _push;
326
+ [Symbol.asyncIterator](): AsyncIterator<LabeledEvent>;
327
+ }
328
+
329
+ /**
330
+ * EventProcessor — core event loop for apiary agents.
331
+ *
332
+ * Owns: engagement classification, content buffering, event formatting,
333
+ * ref map, room connections, mode management. Does NOT own: LLM sessions,
334
+ * MCP servers, compaction hooks, stats tracking.
335
+ *
336
+ * Delivery is pluggable — pass a `deliver` callback to `run()`.
337
+ * The callback receives formatted ContentPart[] and does whatever the
338
+ * consumer needs (Claude SDK query, LangGraph injection, tmux send-keys).
339
+ */
340
+
341
+ interface EventProcessorOptions {
342
+ /** Engagement mode when no per-room override is set. */
343
+ defaultMode?: EngagementMode;
344
+ /** Custom engagement strategy. Defaults to StoopsEngagement. */
345
+ engagement?: EngagementStrategy;
346
+ /** The agent's own stable identifier slug (e.g. "my-agent"). */
347
+ selfIdentifier?: string;
348
+ /** Called when engagement mode changes for a room. */
349
+ onModeChange?: (roomId: string, roomName: string, mode: EngagementMode) => void;
350
+ /** Called before each delivery. Return false to skip. */
351
+ preQuery?: () => Promise<boolean>;
352
+ }
353
+ /**
354
+ * What an agent runtime observed on its CLI's screen, as reported to the room.
355
+ *
356
+ * Deliberately coarser than each bridge's internal TUI states: the room only
357
+ * needs to distinguish "getting on with it" from "stuck until a human acts",
358
+ * because those look identical from the outside and only one of them resolves
359
+ * by waiting.
360
+ */
361
+ type AgentActivityState = "idle" | "working" | "blocked";
362
+ declare class EventProcessor implements RoomResolver {
363
+ private _participantId;
364
+ private _participantName;
365
+ private _options;
366
+ private _engagement;
367
+ private _deliver;
368
+ private _multiplexer;
369
+ private _registry;
370
+ private _buffer;
371
+ private _tracker;
372
+ private _processing;
373
+ private _eventQueue;
374
+ private _stopped;
375
+ private _currentContextRoomId;
376
+ private _log;
377
+ private _refMap;
378
+ private _injectBuffer;
379
+ /** Per-room participant IDs (for multi-server CLI agents where each server assigns a different ID). */
380
+ private _roomSelfIds;
381
+ constructor(participantId: string, participantName: string, options?: EventProcessorOptions);
382
+ get participantId(): string;
383
+ set participantId(id: string);
384
+ get participantName(): string;
385
+ get currentContextRoomId(): string | null;
386
+ /** Set a room-specific participant ID (for multi-server CLI agents). */
387
+ setRoomParticipantId(roomId: string, participantId: string): void;
388
+ /** Get the effective selfId for a room — room-specific if set, otherwise the global one. */
389
+ getSelfIdForRoom(roomId: string): string;
390
+ assignRef(messageId: string): string;
391
+ resolveRef(ref: string): string | undefined;
392
+ isEventSeen(eventId: string): boolean;
393
+ markEventsSeen(eventIds: string[]): void;
394
+ drainInjectBuffer(): ContentPart[][] | null;
395
+ /**
396
+ * Called by the consumer when context was compacted.
397
+ * Clears seen-event cache and ref map so catch_up returns full history.
398
+ */
399
+ onContextCompacted(): void;
400
+ /**
401
+ * Called by the consumer when a tool call starts or completes.
402
+ * Routes ToolUseEvent to the room that triggered the current evaluation.
403
+ */
404
+ emitToolUse(toolName: string, status: "started" | "completed"): void;
405
+ resolve(roomName: string): RoomConnection | null;
406
+ listAll(): Array<{
407
+ name: string;
408
+ roomId: string;
409
+ identifier?: string;
410
+ mode: string;
411
+ participantCount: number;
412
+ lastMessage?: string;
413
+ }>;
414
+ /**
415
+ * Push a live status label ("Sautéed for 12s", "Compacting…", null=idle)
416
+ * to every connected REMOTE room (i.e. CLI-path agents talking to an
417
+ * apiary HTTP server). Local app-path connections are skipped — they don't
418
+ * have a /activity HTTP endpoint to hit.
419
+ *
420
+ * Called from the CLI runtime's tmux poll loop. Best-effort: failures are
421
+ * swallowed so a flaky network never crashes the agent.
422
+ */
423
+ broadcastActivity(label: string | null, state?: AgentActivityState): Promise<void>;
424
+ /**
425
+ * Push token usage + last-turn context size to every connected REMOTE
426
+ * room so the room TUI can show per-agent context size and roll up a
427
+ * room total. Mirrors broadcastActivity — same best-effort semantics.
428
+ */
429
+ broadcastMetrics(metrics: {
430
+ input_tokens: number;
431
+ output_tokens: number;
432
+ cache_read_tokens: number;
433
+ cache_create_tokens: number;
434
+ last_ctx_tokens: number;
435
+ model: string;
436
+ }): Promise<void>;
437
+ connectRoom(room: Room, roomName: string, mode?: EngagementMode, identifier?: string): Promise<void>;
438
+ /**
439
+ * Connect a remote room via a RoomDataSource (no local Room/Channel).
440
+ *
441
+ * Used by the client-side agent runtime to register rooms that are
442
+ * accessed over HTTP. Events come from an external source (SSE multiplexer)
443
+ * passed to run(), not from the internal EventMultiplexer.
444
+ */
445
+ connectRemoteRoom(dataSource: RoomDataSource, roomName: string, mode?: EngagementMode, identifier?: string): void;
446
+ /** Disconnect a remote room (by room ID). */
447
+ disconnectRemoteRoom(roomId: string): void;
448
+ disconnectRoom(roomId: string): Promise<void>;
449
+ getModeForRoom(roomId: string): EngagementMode;
450
+ setModeForRoom(roomId: string, mode: EngagementMode, notifyAgent?: boolean): void;
451
+ getLog(): RoomEvent[];
452
+ /**
453
+ * Start the event loop.
454
+ *
455
+ * @param deliver — callback that receives formatted content and delivers
456
+ * it to the agent. This is the consumer's responsibility. The function
457
+ * should block until delivery is complete (e.g., LLM evaluation finished).
458
+ * @param eventSource — optional external event source (e.g. SseMultiplexer).
459
+ * If provided, events are consumed from this instead of the internal
460
+ * EventMultiplexer. Used by the client-side agent runtime.
461
+ * @param initialParts — optional content to deliver before entering the
462
+ * event loop. Used by the runtime to deliver auto-join confirmation.
463
+ */
464
+ run(deliver: (parts: ContentPart[]) => Promise<void>, eventSource?: AsyncIterable<LabeledEvent>, initialParts?: ContentPart[]): Promise<void>;
465
+ stop(): Promise<void>;
466
+ buildFullCatchUp(): Promise<ContentPart[]>;
467
+ private _buildFullCatchUp;
468
+ private _handleLabeledEvent;
469
+ private _processTrigger;
470
+ private _resolveParticipantForRoom;
471
+ private _resolveReplyContext;
472
+ private _resolveReactionTarget;
473
+ private _formatForLLM;
474
+ private _processRaw;
475
+ }
476
+
477
+ /** What the caller is waiting for. */
478
+ type WaitTarget = "idle" | "blocked" | "working" | "change";
479
+
480
+ /**
481
+ * Runtime MCP server — local MCP proxy for the client-side agent runtime.
482
+ *
483
+ * Claude Code / OpenCode connects to this local server. Tool calls are routed
484
+ * to the right apiary server via the RoomResolver (which maps room names to
485
+ * RemoteRoomDataSource instances).
486
+ *
487
+ * Tools:
488
+ * Always present:
489
+ * apiary__catch_up(room?) — with room: room catch-up. Without: list rooms + pending invites.
490
+ * apiary__search_by_text(room, query, count?, cursor?)
491
+ * apiary__search_by_message(room, ref, direction?, count?)
492
+ * apiary__send_message(room, content, reply_to?)
493
+ * apiary__set_mode(room, mode)
494
+ * apiary__join_room(url, alias?)
495
+ * apiary__leave_room(room)
496
+ *
497
+ * With --admin flag:
498
+ * apiary__admin__set_mode_for(room, participant, mode)
499
+ * apiary__admin__kick(room, participant)
500
+ */
501
+
502
+ interface JoinRoomResult {
503
+ success: boolean;
504
+ error?: string;
505
+ roomName?: string;
506
+ agentName?: string;
507
+ authority?: string;
508
+ mode?: string;
509
+ personName?: string;
510
+ participants?: Array<{
511
+ name: string;
512
+ authority: string;
513
+ }>;
514
+ recentLines?: string[];
515
+ /** Room rules — surfaced in the join response so the agent sees them on entry. */
516
+ rules?: string[];
517
+ }
518
+ interface RuntimeMcpServerOptions {
519
+ resolver: RoomResolver;
520
+ toolOptions: ToolHandlerOptions;
521
+ /**
522
+ * Server-granted authority for this agent's session. Drives which admin /
523
+ * product_owner tools are exposed. When undefined or "member"/"guest", only
524
+ * non-privileged tools are registered. Updated after each `join_room`
525
+ * because the agent's tier can vary per room.
526
+ */
527
+ authority?: AuthorityLevel;
528
+ /** Called when the agent requests joining a new room mid-session. */
529
+ onJoinRoom?: (url: string, alias?: string, name?: string) => Promise<JoinRoomResult>;
530
+ /** Called when the agent requests leaving a room. */
531
+ onLeaveRoom?: (room: string) => Promise<{
532
+ success: boolean;
533
+ error?: string;
534
+ }>;
535
+ /** Called when the agent changes its own mode. */
536
+ onSetMode?: (room: string, mode: string) => Promise<{
537
+ success: boolean;
538
+ error?: string;
539
+ }>;
540
+ /** Called when the agent pings a participant for a status check. */
541
+ onPing?: (room: string, participant: string) => Promise<{
542
+ success: boolean;
543
+ error?: string;
544
+ }>;
545
+ onWaitForAgent?: (room: string, participant: string, until?: WaitTarget, timeoutSec?: number) => Promise<{
546
+ success: boolean;
547
+ message?: string;
548
+ error?: string;
549
+ }>;
550
+ /** Called for admin set-mode-for. */
551
+ onAdminSetModeFor?: (room: string, participant: string, mode: string) => Promise<{
552
+ success: boolean;
553
+ error?: string;
554
+ }>;
555
+ /** Called for admin kick. */
556
+ onAdminKick?: (room: string, participant: string) => Promise<{
557
+ success: boolean;
558
+ error?: string;
559
+ }>;
560
+ /** Called for admin mute (demote to guest). */
561
+ onAdminMute?: (room: string, participant: string) => Promise<{
562
+ success: boolean;
563
+ error?: string;
564
+ }>;
565
+ /** Called for admin unmute (restore to member). */
566
+ onAdminUnmute?: (room: string, participant: string) => Promise<{
567
+ success: boolean;
568
+ error?: string;
569
+ }>;
570
+ /** Called for admin promote (elevate to product_owner). */
571
+ onAdminPromote?: (room: string, participant: string) => Promise<{
572
+ success: boolean;
573
+ error?: string;
574
+ }>;
575
+ /** Called for admin demote (drop product_owner back to member). */
576
+ onAdminDemote?: (room: string, participant: string) => Promise<{
577
+ success: boolean;
578
+ error?: string;
579
+ }>;
580
+ }
581
+ interface RuntimeMcpServer {
582
+ url: string;
583
+ stop: () => Promise<void>;
584
+ }
585
+ /**
586
+ * Create a runtime MCP server on a random localhost port (HTTP transport).
587
+ * Returns the URL for --mcp-config and a stop function.
588
+ */
589
+ declare function createRuntimeMcpServer(opts: RuntimeMcpServerOptions): Promise<RuntimeMcpServer>;
590
+
591
+ /**
592
+ * RefMap — bidirectional map between short decimal refs and full message UUIDs.
593
+ *
594
+ * Why 4 digits: a ref like #3847 tokenizes to 1–2 tokens in most LLMs, while a
595
+ * raw UUID (a1b2c3d4-e5f6-...) burns 8–12 tokens for no benefit. Since refs
596
+ * appear on every message in transcripts and tool output, the savings compound.
597
+ *
598
+ * 10,000 unique refs per cycle is far more than an LLM context window can hold
599
+ * (a 200k-token window fits ~2000 messages at most). The map is cleared on every
600
+ * context compaction, so overflow is essentially impossible in practice. If it
601
+ * does happen, the fallback to a UUID-derived hash still works — just less tidy.
602
+ *
603
+ * Uses a linear congruential generator (n * 6337 mod 10000) to produce
604
+ * non-sequential refs — gcd(6337, 10000) = 1 guarantees a full cycle through
605
+ * all 10,000 values before any collision.
606
+ *
607
+ * @example
608
+ * const refs = new RefMap();
609
+ * const ref = refs.assign("msg-uuid-abc"); // "3847"
610
+ * refs.assign("msg-uuid-abc"); // "3847" (idempotent)
611
+ * refs.resolve("3847"); // "msg-uuid-abc"
612
+ * refs.clear(); // reset on compaction
613
+ */
614
+ declare class RefMap {
615
+ private _counter;
616
+ private _refToId;
617
+ private _idToRef;
618
+ /** Assign a short ref to a message ID. Returns existing ref if already assigned. */
619
+ assign(messageId: string): string;
620
+ /** Resolve a ref back to the full message UUID. Returns undefined if unknown. */
621
+ resolve(ref: string): string | undefined;
622
+ /** Clear all mappings and reset the counter. Called on context compaction. */
623
+ clear(): void;
624
+ }
625
+
626
+ declare class RemoteRoomDataSource implements RoomDataSource {
627
+ private _serverUrl;
628
+ private _sessionToken;
629
+ private _roomId;
630
+ private _participants;
631
+ private _selfId;
632
+ private _selfName;
633
+ constructor(_serverUrl: string, _sessionToken: string, _roomId: string);
634
+ /** Set own identity for populating outgoing message stubs. */
635
+ setSelf(id: string, name: string): void;
636
+ get roomId(): string;
637
+ get selfId(): string;
638
+ get serverUrl(): string;
639
+ get sessionToken(): string;
640
+ /** Set the initial participant list (from join response). */
641
+ setParticipants(participants: Participant[]): void;
642
+ /** Add a participant (on ParticipantJoined event). */
643
+ addParticipant(participant: Participant): void;
644
+ /** Remove a participant (on ParticipantLeft event). */
645
+ removeParticipant(participantId: string): void;
646
+ listParticipants(): Participant[];
647
+ getMessage(id: string): Promise<Message | null>;
648
+ searchMessages(query: string, limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
649
+ getMessages(limit?: number, cursor?: string | null): Promise<PaginatedResult<Message>>;
650
+ getEvents(category?: EventCategory | null, limit?: number, cursor?: string | null): Promise<PaginatedResult<RoomEvent>>;
651
+ sendMessage(content: string, replyToId?: string, image?: {
652
+ url: string;
653
+ mimeType: string;
654
+ sizeBytes: number;
655
+ } | null, attachments?: Attachment[], recipients?: string[]): Promise<Message>;
656
+ emitEvent(event: RoomEvent): Promise<void>;
657
+ }
658
+
659
+ /**
660
+ * SseMultiplexer — merges N SSE connections into one labeled event stream.
661
+ *
662
+ * Each connection is an HTTP fetch to a stoop server's /events endpoint.
663
+ * Events are parsed from the SSE `data:` lines and wrapped as LabeledEvents
664
+ * (same shape as EventMultiplexer output so EventProcessor can consume either).
665
+ *
666
+ * Connections can be added/removed while the multiplexer is running.
667
+ * Each connection has its own AbortController for independent lifecycle.
668
+ */
669
+
670
+ declare class SseMultiplexer {
671
+ private _queue;
672
+ private _waiters;
673
+ private _connections;
674
+ private _closed;
675
+ /**
676
+ * Add an SSE connection to a stoop server.
677
+ * Starts streaming events immediately.
678
+ */
679
+ addConnection(serverUrl: string, sessionToken: string, roomName: string, roomId: string): void;
680
+ /** Remove a connection by room ID. */
681
+ removeConnection(roomId: string): void;
682
+ /** Close all connections and signal the iterator to finish. */
683
+ close(): void;
684
+ private _sseLoop;
685
+ private _push;
686
+ [Symbol.asyncIterator](): AsyncIterator<LabeledEvent>;
687
+ }
688
+
689
+ export { type ContentPart, type EngagementMode, type EngagementStrategy, type EventDisposition, EventMultiplexer, EventProcessor, type EventProcessorOptions, type LabeledEvent, LocalRoomDataSource, type ProcessorBridge, RefMap, RemoteRoomDataSource, type RoomConnection, type RoomDataSource, type RoomResolver, type RuntimeMcpServer, type RuntimeMcpServerOptions, SseMultiplexer, StoopsEngagement, type ToolHandlerOptions, classifyEvent, contentPartsToString, createRuntimeMcpServer, formatEvent, messageRef, participantLabel };