@jangmanj/pi-mcp-ext 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +93 -2
- package/package.json +52 -4
- package/src/client.ts +582 -0
- package/src/config.ts +135 -0
- package/src/events.ts +826 -0
- package/src/index.ts +1546 -0
- package/src/tasks.ts +110 -0
- package/src/transport-http.ts +144 -0
- package/src/transport-stdio.ts +644 -0
- package/src/types.ts +574 -0
package/src/events.ts
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SEP-3415 events engine (spec §5.1, §5.3, §5.4): events/list discovery, poll and push
|
|
3
|
+
* delivery, cursor persistence, per-subscription dedup, and batched turn wakes.
|
|
4
|
+
* Depends only on EngineHost/ServerClient from types.ts.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { writeFileSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateHead } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import {
|
|
12
|
+
CUSTOM_CURSORS,
|
|
13
|
+
CUSTOM_SUBSCRIPTIONS,
|
|
14
|
+
ErrorCode,
|
|
15
|
+
MESSAGE_EVENT,
|
|
16
|
+
} from "./types.ts";
|
|
17
|
+
import type {
|
|
18
|
+
CursorEntry,
|
|
19
|
+
DeliveryMode,
|
|
20
|
+
EngineHost,
|
|
21
|
+
EventDelivery,
|
|
22
|
+
EventDescriptor,
|
|
23
|
+
EventOccurrence,
|
|
24
|
+
EventsEngineApi,
|
|
25
|
+
JSONRPCNotification,
|
|
26
|
+
JsonObject,
|
|
27
|
+
ListEventsResult,
|
|
28
|
+
OpenStreamHandle,
|
|
29
|
+
PollEventsParams,
|
|
30
|
+
PollEventsResult,
|
|
31
|
+
ServerClient,
|
|
32
|
+
SubscribeRequest,
|
|
33
|
+
SubscriptionEntry,
|
|
34
|
+
SubscriptionRecord,
|
|
35
|
+
} from "./types.ts";
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------------------------
|
|
38
|
+
// Pure helpers (exported)
|
|
39
|
+
// ---------------------------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
/** JSON with object keys sorted recursively, so equal argument objects map to one string. */
|
|
42
|
+
export function canonicalJson(v: unknown): string {
|
|
43
|
+
if (v === null || typeof v !== "object") return JSON.stringify(v) ?? "null";
|
|
44
|
+
if (Array.isArray(v)) return `[${v.map(item => (item === undefined ? "null" : canonicalJson(item))).join(",")}]`;
|
|
45
|
+
const entries = Object.entries(v as Record<string, unknown>)
|
|
46
|
+
.filter(([, value]) => value !== undefined)
|
|
47
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
48
|
+
return `{${entries.map(([k, value]) => `${JSON.stringify(k)}:${canonicalJson(value)}`).join(",")}}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function subKeyOf(server: string, name: string, args?: Record<string, unknown>): string {
|
|
52
|
+
return `${server}\0${name}\0${canonicalJson(args ?? {})}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function escapeAttr(value: string): string {
|
|
56
|
+
return value
|
|
57
|
+
.replace(/&/g, "&")
|
|
58
|
+
.replace(/</g, "<")
|
|
59
|
+
.replace(/>/g, ">")
|
|
60
|
+
.replace(/"/g, """)
|
|
61
|
+
.replace(/'/g, "'");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Frame deliveries as untrusted external data: one `<mcp_event ...>` tag per occurrence with a
|
|
66
|
+
* JSON body (head-truncated; the full payload goes to a temp file when truncated), preceded by a
|
|
67
|
+
* gap marker for truncated deliveries.
|
|
68
|
+
*/
|
|
69
|
+
export function formatEventDeliveries(batch: EventDelivery[]): string {
|
|
70
|
+
const parts: string[] = [];
|
|
71
|
+
for (const delivery of batch) {
|
|
72
|
+
if (delivery.truncated) {
|
|
73
|
+
parts.push(
|
|
74
|
+
`<mcp_event_gap server="${escapeAttr(delivery.server)}" name="${escapeAttr(delivery.name)}" truncated="true">` +
|
|
75
|
+
`gap: events before this point may have been missed (truncated)</mcp_event_gap>`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
for (const occ of delivery.occurrences) {
|
|
79
|
+
const full = JSON.stringify(occ.data ?? {}, null, 2);
|
|
80
|
+
const truncated = truncateHead(full, { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES });
|
|
81
|
+
let body = truncated.content;
|
|
82
|
+
if (truncated.truncated) {
|
|
83
|
+
try {
|
|
84
|
+
const file = join(tmpdir(), `pi-mcp-event-${Date.now()}-${Math.random().toString(36).slice(2, 10)}.json`);
|
|
85
|
+
writeFileSync(file, full);
|
|
86
|
+
body += `\n[truncated: full payload written to ${file}]`;
|
|
87
|
+
} catch {
|
|
88
|
+
body += `\n[truncated]`;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
parts.push(
|
|
92
|
+
`<mcp_event server="${escapeAttr(delivery.server)}" name="${escapeAttr(occ.name ?? delivery.name)}" ` +
|
|
93
|
+
`event_id="${escapeAttr(occ.eventId)}" timestamp="${escapeAttr(occ.timestamp)}" truncated="${delivery.truncated ? "true" : "false"}">\n` +
|
|
94
|
+
`${body}\n</mcp_event>`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return parts.join("\n");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------------------------------------
|
|
102
|
+
// Engine
|
|
103
|
+
// ---------------------------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
interface Sub {
|
|
106
|
+
record: SubscriptionRecord;
|
|
107
|
+
cursor: string | null;
|
|
108
|
+
mode?: "push" | "poll";
|
|
109
|
+
descriptorDelivery: DeliveryMode[];
|
|
110
|
+
recentIds: string[];
|
|
111
|
+
recentSet: Set<string>;
|
|
112
|
+
started: boolean;
|
|
113
|
+
stopped: boolean;
|
|
114
|
+
startPromise?: Promise<void>;
|
|
115
|
+
generation: number;
|
|
116
|
+
stream?: OpenStreamHandle;
|
|
117
|
+
streamGen: number;
|
|
118
|
+
watchdogTimer?: ReturnType<typeof setTimeout>;
|
|
119
|
+
pollTimer?: ReturnType<typeof setTimeout>;
|
|
120
|
+
reconnectTimer?: ReturnType<typeof setTimeout>;
|
|
121
|
+
checkpointTimer?: ReturnType<typeof setTimeout>;
|
|
122
|
+
backoffMs: number;
|
|
123
|
+
dirtyCursor: boolean;
|
|
124
|
+
lastFlushAt: number;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function errorCodeOf(err: unknown): number | undefined {
|
|
128
|
+
const code = (err as { code?: unknown } | null)?.code;
|
|
129
|
+
return typeof code === "number" ? code : undefined;
|
|
130
|
+
}
|
|
131
|
+
function errorDataOf(err: unknown): Record<string, unknown> | undefined {
|
|
132
|
+
const data = (err as { data?: unknown } | null)?.data;
|
|
133
|
+
return typeof data === "object" && data !== null ? (data as Record<string, unknown>) : undefined;
|
|
134
|
+
}
|
|
135
|
+
function errorMessageOf(err: unknown): string {
|
|
136
|
+
return err instanceof Error ? err.message : String(err);
|
|
137
|
+
}
|
|
138
|
+
function timer(fn: () => void, ms: number): ReturnType<typeof setTimeout> {
|
|
139
|
+
const t = setTimeout(fn, Math.max(0, ms));
|
|
140
|
+
(t as { unref?: () => void }).unref?.();
|
|
141
|
+
return t;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function createEventsEngine(
|
|
145
|
+
host: EngineHost,
|
|
146
|
+
opts?: { pollFloorMs?: number; batchWindowMs?: number; watchdogMs?: number; checkpointMs?: number },
|
|
147
|
+
): EventsEngineApi {
|
|
148
|
+
const pollFloorMs = opts?.pollFloorMs ?? 1000;
|
|
149
|
+
const batchWindowMs = opts?.batchWindowMs ?? 75;
|
|
150
|
+
const watchdogMs = opts?.watchdogMs ?? 65000;
|
|
151
|
+
const checkpointMs = opts?.checkpointMs ?? 30000;
|
|
152
|
+
|
|
153
|
+
const subs = new Map<string, Sub>();
|
|
154
|
+
const descriptorCache = new Map<string, EventDescriptor[]>();
|
|
155
|
+
/** Newest non-null cursor per subKey, from restored entries. */
|
|
156
|
+
const persistedCursors = new Map<string, string>();
|
|
157
|
+
/** Newest recentEventIds per subKey, from restored entries. */
|
|
158
|
+
const persistedRecent = new Map<string, string[]>();
|
|
159
|
+
const listenDisposers = new Map<string, () => void>();
|
|
160
|
+
const wakeListeners = new Set<() => void>();
|
|
161
|
+
const pendingBatch = new Map<string, EventDelivery>();
|
|
162
|
+
let batchTimer: ReturnType<typeof setTimeout> | undefined;
|
|
163
|
+
let shutDown = false;
|
|
164
|
+
|
|
165
|
+
host.signal?.addEventListener?.("abort", () => void shutdown(), { once: true });
|
|
166
|
+
|
|
167
|
+
// ---- wakes / batching -------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
function emitWake(content: string, details: unknown): void {
|
|
170
|
+
host.wake(MESSAGE_EVENT, content, details);
|
|
171
|
+
for (const listener of [...wakeListeners]) {
|
|
172
|
+
try { listener(); } catch { /* listener faults are not delivery faults */ }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function flushBatch(): void {
|
|
177
|
+
batchTimer = undefined;
|
|
178
|
+
if (!pendingBatch.size) return;
|
|
179
|
+
const batch = [...pendingBatch.values()];
|
|
180
|
+
pendingBatch.clear();
|
|
181
|
+
emitWake(formatEventDeliveries(batch), { deliveries: batch });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function enqueueDelivery(sub: Sub, occurrences: EventOccurrence[], truncated: boolean): void {
|
|
185
|
+
const key = sub.record.subKey;
|
|
186
|
+
const existing = pendingBatch.get(key);
|
|
187
|
+
if (existing) {
|
|
188
|
+
existing.occurrences.push(...occurrences);
|
|
189
|
+
existing.truncated = existing.truncated || truncated;
|
|
190
|
+
} else {
|
|
191
|
+
pendingBatch.set(key, {
|
|
192
|
+
server: sub.record.server,
|
|
193
|
+
subKey: key,
|
|
194
|
+
name: sub.record.name,
|
|
195
|
+
truncated,
|
|
196
|
+
occurrences: [...occurrences],
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
batchTimer ??= timer(flushBatch, batchWindowMs);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function wakeNotice(sub: Sub, message: string): void {
|
|
203
|
+
emitWake(
|
|
204
|
+
`<mcp_event_notice server="${escapeAttr(sub.record.server)}" name="${escapeAttr(sub.record.name)}">${message}</mcp_event_notice>`,
|
|
205
|
+
{ deliveries: [], notice: message, server: sub.record.server, name: sub.record.name, subKey: sub.record.subKey },
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// ---- cursor persistence -----------------------------------------------------
|
|
210
|
+
|
|
211
|
+
function persistCursor(sub: Sub): void {
|
|
212
|
+
const entry: CursorEntry = {
|
|
213
|
+
server: sub.record.server,
|
|
214
|
+
subKey: sub.record.subKey,
|
|
215
|
+
cursor: sub.cursor,
|
|
216
|
+
recentEventIds: sub.recentIds.slice(-128),
|
|
217
|
+
updatedAt: new Date().toISOString(),
|
|
218
|
+
};
|
|
219
|
+
host.appendEntry(CUSTOM_CURSORS, entry);
|
|
220
|
+
sub.dirtyCursor = false;
|
|
221
|
+
sub.lastFlushAt = Date.now();
|
|
222
|
+
if (sub.checkpointTimer) { clearTimeout(sub.checkpointTimer); sub.checkpointTimer = undefined; }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Quiet-period advance: update memory now, flush at most once per checkpointMs. */
|
|
226
|
+
function markCursorQuiet(sub: Sub): void {
|
|
227
|
+
sub.dirtyCursor = true;
|
|
228
|
+
const elapsed = Date.now() - sub.lastFlushAt;
|
|
229
|
+
if (sub.lastFlushAt !== 0 && elapsed >= checkpointMs) { persistCursor(sub); return; }
|
|
230
|
+
if (!sub.checkpointTimer) {
|
|
231
|
+
const wait = sub.lastFlushAt === 0 ? 0 : checkpointMs - elapsed;
|
|
232
|
+
sub.checkpointTimer = timer(() => {
|
|
233
|
+
sub.checkpointTimer = undefined;
|
|
234
|
+
if (sub.dirtyCursor && !shutDown) persistCursor(sub);
|
|
235
|
+
}, wait);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function setCursor(sub: Sub, cursor: string | null | undefined): boolean {
|
|
240
|
+
const next = typeof cursor === "string" ? cursor : null;
|
|
241
|
+
const changed = next !== sub.cursor;
|
|
242
|
+
sub.cursor = next;
|
|
243
|
+
return changed;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ---- dedup / occurrence intake ----------------------------------------------
|
|
247
|
+
|
|
248
|
+
/** Filter duplicates (FIFO of 1024 per subKey) and advance the cursor per occurrence. */
|
|
249
|
+
function acceptOccurrences(sub: Sub, occurrences: EventOccurrence[], advancePerEvent: boolean): EventOccurrence[] {
|
|
250
|
+
const accepted: EventOccurrence[] = [];
|
|
251
|
+
for (const occ of occurrences) {
|
|
252
|
+
if (advancePerEvent) setCursor(sub, occ.cursor);
|
|
253
|
+
if (occ.eventId != null && sub.recentSet.has(occ.eventId)) continue;
|
|
254
|
+
if (occ.eventId != null) {
|
|
255
|
+
sub.recentSet.add(occ.eventId);
|
|
256
|
+
sub.recentIds.push(occ.eventId);
|
|
257
|
+
while (sub.recentIds.length > 1024) {
|
|
258
|
+
const evicted = sub.recentIds.shift();
|
|
259
|
+
if (evicted !== undefined) sub.recentSet.delete(evicted);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
accepted.push(occ);
|
|
263
|
+
}
|
|
264
|
+
return accepted;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---- events/list --------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
function ensureListen(server: string, client: ServerClient): void {
|
|
270
|
+
if (listenDisposers.has(server)) return;
|
|
271
|
+
if (!client.state?.eventsListChanged) return;
|
|
272
|
+
client.setListenInterest("events", { eventsListChanged: true });
|
|
273
|
+
const dispose = client.onListenNotification((msg: JSONRPCNotification) => {
|
|
274
|
+
if (msg.method === "notifications/events/list_changed") {
|
|
275
|
+
descriptorCache.delete(server);
|
|
276
|
+
void list(server).catch(err => host.log("warn", `events/list refresh for ${server} failed: ${errorMessageOf(err)}`));
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
listenDisposers.set(server, dispose);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
async function list(server: string): Promise<EventDescriptor[]> {
|
|
283
|
+
const client = host.getClient(server);
|
|
284
|
+
if (!client) throw new Error(`Unknown or not-ready MCP server: ${server}`);
|
|
285
|
+
ensureListen(server, client);
|
|
286
|
+
const events: EventDescriptor[] = [];
|
|
287
|
+
const seenCursors = new Set<string>();
|
|
288
|
+
let cursor: string | undefined;
|
|
289
|
+
for (let page = 0; page < 32; page++) {
|
|
290
|
+
const result = await client.request<ListEventsResult>("events/list", cursor ? { cursor } : {});
|
|
291
|
+
events.push(...(result.events ?? []));
|
|
292
|
+
const next = result.nextCursor;
|
|
293
|
+
if (!next || seenCursors.has(next)) break;
|
|
294
|
+
seenCursors.add(next);
|
|
295
|
+
cursor = next;
|
|
296
|
+
}
|
|
297
|
+
descriptorCache.set(server, events);
|
|
298
|
+
return events;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function selectMode(sub: Sub, descriptor: EventDescriptor): "push" | "poll" {
|
|
302
|
+
const available = (descriptor.delivery ?? []).filter(m => m === "push" || m === "poll");
|
|
303
|
+
if (!available.length) {
|
|
304
|
+
throw new Error(
|
|
305
|
+
`UnsupportedDeliveryMode: event "${descriptor.name}" on server "${sub.record.server}" only supports ` +
|
|
306
|
+
`${JSON.stringify(descriptor.delivery ?? [])}; this client supports "push" and "poll" (webhook is not supported)`,
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
if (sub.record.delivery === "poll" && available.includes("poll")) return "poll";
|
|
310
|
+
return available.includes("push") ? "push" : "poll";
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ---- poll ---------------------------------------------------------------------
|
|
314
|
+
|
|
315
|
+
function pollParams(sub: Sub): JsonObject {
|
|
316
|
+
const params: JsonObject = { name: sub.record.name, cursor: sub.cursor, maxEvents: 100 };
|
|
317
|
+
if (sub.record.arguments !== undefined) params.arguments = sub.record.arguments;
|
|
318
|
+
if (sub.record.maxAgeMs !== undefined) params.maxAgeMs = sub.record.maxAgeMs;
|
|
319
|
+
return params;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function schedulePoll(sub: Sub, delayMs: number): void {
|
|
323
|
+
if (shutDown || sub.stopped) return;
|
|
324
|
+
if (sub.pollTimer) clearTimeout(sub.pollTimer);
|
|
325
|
+
const gen = sub.generation;
|
|
326
|
+
sub.pollTimer = timer(() => {
|
|
327
|
+
sub.pollTimer = undefined;
|
|
328
|
+
void pollCycle(sub, gen).catch(err => host.log("warn", `events/poll loop for ${sub.record.name} failed: ${errorMessageOf(err)}`));
|
|
329
|
+
}, delayMs);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function livePoll(sub: Sub, gen: number): boolean {
|
|
333
|
+
return !shutDown && !sub.stopped && sub.generation === gen && subs.get(sub.record.subKey) === sub && sub.mode === "poll";
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** One drain cycle; returns the last result (used by the push catch-up handoff). */
|
|
337
|
+
async function drainPoll(sub: Sub, client: ServerClient, gen: number): Promise<PollEventsResult | undefined> {
|
|
338
|
+
let last: PollEventsResult | undefined;
|
|
339
|
+
for (let page = 0; page < 50; page++) {
|
|
340
|
+
const result = await client.request<PollEventsResult>("events/poll", pollParams(sub));
|
|
341
|
+
last = result;
|
|
342
|
+
const accepted = acceptOccurrences(sub, result.events ?? [], true);
|
|
343
|
+
const cursorChanged = setCursor(sub, result.cursor);
|
|
344
|
+
const truncated = result.truncated === true;
|
|
345
|
+
if (accepted.length || truncated) {
|
|
346
|
+
enqueueDelivery(sub, accepted, truncated);
|
|
347
|
+
persistCursor(sub);
|
|
348
|
+
} else if (cursorChanged) {
|
|
349
|
+
markCursorQuiet(sub);
|
|
350
|
+
}
|
|
351
|
+
if (!result.hasMore) return result;
|
|
352
|
+
if (shutDown || sub.stopped || sub.generation !== gen) return result;
|
|
353
|
+
}
|
|
354
|
+
return last; // 50 pages drained; caller yields before continuing
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function pollCycle(sub: Sub, gen: number): Promise<void> {
|
|
358
|
+
if (!livePoll(sub, gen)) return;
|
|
359
|
+
const client = host.getClient(sub.record.server);
|
|
360
|
+
if (!client) { schedulePoll(sub, Math.max(5000, pollFloorMs)); return; }
|
|
361
|
+
try {
|
|
362
|
+
const last = await drainPoll(sub, client, gen);
|
|
363
|
+
if (!livePoll(sub, gen)) return;
|
|
364
|
+
sub.backoffMs = 250;
|
|
365
|
+
if (last?.hasMore) schedulePoll(sub, 0);
|
|
366
|
+
else schedulePoll(sub, Math.max(last?.nextPollMs ?? 5000, pollFloorMs));
|
|
367
|
+
} catch (err) {
|
|
368
|
+
if (!livePoll(sub, gen)) return;
|
|
369
|
+
if (handleTerminalRpcError(sub, err)) return;
|
|
370
|
+
host.log("warn", `events/poll for ${sub.record.server}/${sub.record.name} failed: ${errorMessageOf(err)}`);
|
|
371
|
+
sub.backoffMs = Math.min(sub.backoffMs ? sub.backoffMs * 2 : 250, 30000);
|
|
372
|
+
schedulePoll(sub, Math.max(sub.backoffMs, pollFloorMs));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ---- push ---------------------------------------------------------------------
|
|
377
|
+
|
|
378
|
+
function clearWatchdog(sub: Sub): void {
|
|
379
|
+
if (sub.watchdogTimer) { clearTimeout(sub.watchdogTimer); sub.watchdogTimer = undefined; }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function armWatchdog(sub: Sub, streamGen: number): void {
|
|
383
|
+
clearWatchdog(sub);
|
|
384
|
+
sub.watchdogTimer = timer(() => {
|
|
385
|
+
sub.watchdogTimer = undefined;
|
|
386
|
+
if (shutDown || sub.stopped || sub.streamGen !== streamGen) return;
|
|
387
|
+
const handle = sub.stream;
|
|
388
|
+
sub.stream = undefined;
|
|
389
|
+
sub.streamGen++; // invalidate the cancelled stream's done handler
|
|
390
|
+
host.log("warn", `events/stream watchdog expired for ${sub.record.server}/${sub.record.name}; reconnecting`);
|
|
391
|
+
void (async () => {
|
|
392
|
+
try { await handle?.cancel("watchdog"); } catch { /* already gone */ }
|
|
393
|
+
if (!shutDown && !sub.stopped && subs.get(sub.record.subKey) === sub) {
|
|
394
|
+
await openPush(sub).catch(err => host.log("warn", `events/stream reconnect failed: ${errorMessageOf(err)}`));
|
|
395
|
+
}
|
|
396
|
+
})();
|
|
397
|
+
}, watchdogMs);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function scheduleReconnect(sub: Sub): void {
|
|
401
|
+
if (shutDown || sub.stopped || sub.reconnectTimer) return;
|
|
402
|
+
sub.backoffMs = Math.min(sub.backoffMs ? sub.backoffMs * 2 : 250, 30000);
|
|
403
|
+
const gen = sub.generation;
|
|
404
|
+
sub.reconnectTimer = timer(() => {
|
|
405
|
+
sub.reconnectTimer = undefined;
|
|
406
|
+
if (shutDown || sub.stopped || sub.generation !== gen) return;
|
|
407
|
+
void openPush(sub).catch(err => host.log("warn", `events/stream reconnect failed: ${errorMessageOf(err)}`));
|
|
408
|
+
}, sub.backoffMs);
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Terminal RPC failures shared by poll and push. Returns true when handled as a stop. */
|
|
412
|
+
function handleTerminalRpcError(sub: Sub, err: unknown): boolean {
|
|
413
|
+
const code = errorCodeOf(err);
|
|
414
|
+
if (code === ErrorCode.Forbidden) { terminateSub(sub, code, errorMessageOf(err)); return true; }
|
|
415
|
+
if (code === ErrorCode.NotFound) { terminateSub(sub, code, errorMessageOf(err)); return true; }
|
|
416
|
+
if (code === ErrorCode.Unsupported && errorDataOf(err)?.reason === "schema_changed") {
|
|
417
|
+
terminateSub(sub, code, errorMessageOf(err));
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function terminateSub(sub: Sub, code: number, message: string): void {
|
|
424
|
+
sub.stopped = true;
|
|
425
|
+
sub.started = false;
|
|
426
|
+
sub.streamGen++;
|
|
427
|
+
clearWatchdog(sub);
|
|
428
|
+
if (sub.pollTimer) { clearTimeout(sub.pollTimer); sub.pollTimer = undefined; }
|
|
429
|
+
if (sub.reconnectTimer) { clearTimeout(sub.reconnectTimer); sub.reconnectTimer = undefined; }
|
|
430
|
+
const handle = sub.stream;
|
|
431
|
+
sub.stream = undefined;
|
|
432
|
+
if (handle) void handle.cancel("terminated").catch(() => {});
|
|
433
|
+
persistCursor(sub); // termination flush
|
|
434
|
+
if (code === ErrorCode.NotFound || code === ErrorCode.Unsupported) {
|
|
435
|
+
descriptorCache.delete(sub.record.server);
|
|
436
|
+
void list(sub.record.server).catch(e => host.log("warn", `events/list refresh failed: ${errorMessageOf(e)}`));
|
|
437
|
+
wakeNotice(sub, `event subscription ended: the event descriptor changed or was removed (${code}: ${message})`);
|
|
438
|
+
} else if (code === ErrorCode.Forbidden) {
|
|
439
|
+
wakeNotice(sub, `event subscription terminated: access was revoked (${code}: ${message}); not reconnecting`);
|
|
440
|
+
} else {
|
|
441
|
+
wakeNotice(sub, `event subscription terminated (${code}: ${message})`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function fallbackToPoll(sub: Sub, reason: string): void {
|
|
446
|
+
if (!sub.descriptorDelivery.includes("poll")) {
|
|
447
|
+
host.log("warn", `events/stream unsupported for ${sub.record.server}/${sub.record.name} and poll is not available: ${reason}`);
|
|
448
|
+
scheduleReconnect(sub);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
host.log("info", `events/stream unsupported for ${sub.record.server}/${sub.record.name}; falling back to poll`);
|
|
452
|
+
sub.mode = "poll";
|
|
453
|
+
sub.streamGen++;
|
|
454
|
+
clearWatchdog(sub);
|
|
455
|
+
sub.stream = undefined;
|
|
456
|
+
void pollCycle(sub, sub.generation).catch(err => host.log("warn", `events/poll fallback failed: ${errorMessageOf(err)}`));
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function handleStreamNotification(sub: Sub, streamGen: number, msg: JSONRPCNotification): void {
|
|
460
|
+
if (shutDown || sub.stopped || sub.streamGen !== streamGen) return;
|
|
461
|
+
armWatchdog(sub, streamGen); // any stream notification (incl. $/sse-comment) proves liveness
|
|
462
|
+
const params = (msg.params ?? {}) as Record<string, unknown>;
|
|
463
|
+
switch (msg.method) {
|
|
464
|
+
case "notifications/events/active": {
|
|
465
|
+
const changed = setCursor(sub, params.cursor as string | null | undefined);
|
|
466
|
+
const truncated = params.truncated === true;
|
|
467
|
+
if (truncated) {
|
|
468
|
+
enqueueDelivery(sub, [], true);
|
|
469
|
+
persistCursor(sub);
|
|
470
|
+
} else if (changed) {
|
|
471
|
+
persistCursor(sub); // activation persists the fresh cursor
|
|
472
|
+
}
|
|
473
|
+
break;
|
|
474
|
+
}
|
|
475
|
+
case "notifications/events/event": {
|
|
476
|
+
const occ = params as unknown as EventOccurrence;
|
|
477
|
+
const before = sub.cursor;
|
|
478
|
+
const accepted = acceptOccurrences(sub, [occ], true);
|
|
479
|
+
if (accepted.length) {
|
|
480
|
+
enqueueDelivery(sub, accepted, false);
|
|
481
|
+
persistCursor(sub);
|
|
482
|
+
} else if (sub.cursor !== before) {
|
|
483
|
+
markCursorQuiet(sub);
|
|
484
|
+
}
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
case "notifications/events/heartbeat": {
|
|
488
|
+
if (setCursor(sub, params.cursor as string | null | undefined)) markCursorQuiet(sub);
|
|
489
|
+
break;
|
|
490
|
+
}
|
|
491
|
+
case "notifications/events/error": {
|
|
492
|
+
const error = params.error as { code?: number; message?: string } | undefined;
|
|
493
|
+
host.log("warn", `events/stream error for ${sub.record.server}/${sub.record.name}: ${error?.message ?? "unknown"} (${error?.code ?? "?"})`);
|
|
494
|
+
break; // keep the stream open
|
|
495
|
+
}
|
|
496
|
+
case "notifications/events/terminated": {
|
|
497
|
+
const error = (params.error ?? {}) as { code?: number; message?: string; data?: Record<string, unknown> };
|
|
498
|
+
const code = typeof error.code === "number" ? error.code : ErrorCode.InternalError;
|
|
499
|
+
const message = error.message ?? "terminated";
|
|
500
|
+
if (code === ErrorCode.Unsupported && error.data?.reason !== "schema_changed" && sub.descriptorDelivery.includes("poll")) {
|
|
501
|
+
persistCursor(sub);
|
|
502
|
+
fallbackToPoll(sub, message);
|
|
503
|
+
} else {
|
|
504
|
+
terminateSub(sub, code, message);
|
|
505
|
+
}
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
default:
|
|
509
|
+
break; // e.g. $/sse-comment: watchdog already reset
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function openPush(sub: Sub): Promise<void> {
|
|
514
|
+
if (shutDown || sub.stopped) return;
|
|
515
|
+
const client = host.getClient(sub.record.server);
|
|
516
|
+
if (!client) { sub.started = false; return; }
|
|
517
|
+
const gen = sub.generation;
|
|
518
|
+
|
|
519
|
+
// Catch-up handoff: with both modes and a stored cursor, drain via poll before streaming.
|
|
520
|
+
if (sub.descriptorDelivery.includes("poll") && sub.descriptorDelivery.includes("push") && sub.cursor !== null) {
|
|
521
|
+
try {
|
|
522
|
+
let last = await drainPoll(sub, client, gen);
|
|
523
|
+
while (last?.hasMore && !shutDown && !sub.stopped && sub.generation === gen) {
|
|
524
|
+
last = await drainPoll(sub, client, gen);
|
|
525
|
+
}
|
|
526
|
+
} catch (err) {
|
|
527
|
+
if (handleTerminalRpcError(sub, err)) return;
|
|
528
|
+
host.log("warn", `events/poll catch-up for ${sub.record.server}/${sub.record.name} failed: ${errorMessageOf(err)}`);
|
|
529
|
+
scheduleReconnect(sub);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
if (shutDown || sub.stopped || sub.generation !== gen) return;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const streamGen = ++sub.streamGen;
|
|
536
|
+
const params: JsonObject = { name: sub.record.name, cursor: sub.cursor };
|
|
537
|
+
if (sub.record.arguments !== undefined) params.arguments = sub.record.arguments;
|
|
538
|
+
if (sub.record.maxAgeMs !== undefined) params.maxAgeMs = sub.record.maxAgeMs;
|
|
539
|
+
|
|
540
|
+
let handle: OpenStreamHandle;
|
|
541
|
+
try {
|
|
542
|
+
handle = await client.openStream("events/stream", params, msg => handleStreamNotification(sub, streamGen, msg));
|
|
543
|
+
} catch (err) {
|
|
544
|
+
if (shutDown || sub.stopped || sub.generation !== gen) return;
|
|
545
|
+
if (errorCodeOf(err) === ErrorCode.Unsupported && errorDataOf(err)?.reason !== "schema_changed") {
|
|
546
|
+
fallbackToPoll(sub, errorMessageOf(err));
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
if (handleTerminalRpcError(sub, err)) return;
|
|
550
|
+
host.log("warn", `events/stream open failed for ${sub.record.server}/${sub.record.name}: ${errorMessageOf(err)}`);
|
|
551
|
+
scheduleReconnect(sub);
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
if (shutDown || sub.stopped || sub.generation !== gen || sub.streamGen !== streamGen) {
|
|
555
|
+
void handle.cancel("superseded").catch(() => {});
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
sub.stream = handle;
|
|
559
|
+
sub.backoffMs = 250;
|
|
560
|
+
armWatchdog(sub, streamGen);
|
|
561
|
+
void handle.done.then(
|
|
562
|
+
() => {
|
|
563
|
+
if (sub.streamGen !== streamGen || sub.stopped || shutDown) return;
|
|
564
|
+
sub.stream = undefined;
|
|
565
|
+
clearWatchdog(sub);
|
|
566
|
+
persistCursor(sub); // stream close flush
|
|
567
|
+
scheduleReconnect(sub); // ended without terminated: reconnect with backoff
|
|
568
|
+
},
|
|
569
|
+
(err: unknown) => {
|
|
570
|
+
if (sub.streamGen !== streamGen || sub.stopped || shutDown) return;
|
|
571
|
+
sub.stream = undefined;
|
|
572
|
+
clearWatchdog(sub);
|
|
573
|
+
if (errorCodeOf(err) === ErrorCode.Unsupported && errorDataOf(err)?.reason !== "schema_changed") {
|
|
574
|
+
fallbackToPoll(sub, errorMessageOf(err));
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if (handleTerminalRpcError(sub, err)) return;
|
|
578
|
+
host.log("warn", `events/stream for ${sub.record.server}/${sub.record.name} failed: ${errorMessageOf(err)}`);
|
|
579
|
+
persistCursor(sub);
|
|
580
|
+
scheduleReconnect(sub);
|
|
581
|
+
},
|
|
582
|
+
);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// ---- subscription lifecycle ---------------------------------------------------
|
|
586
|
+
|
|
587
|
+
function newSub(record: SubscriptionRecord, cursor: string | null): Sub {
|
|
588
|
+
const recentIds = (persistedRecent.get(record.subKey) ?? []).slice(-1024);
|
|
589
|
+
return {
|
|
590
|
+
record,
|
|
591
|
+
cursor,
|
|
592
|
+
descriptorDelivery: [],
|
|
593
|
+
recentIds,
|
|
594
|
+
recentSet: new Set(recentIds),
|
|
595
|
+
started: false,
|
|
596
|
+
stopped: false,
|
|
597
|
+
generation: 0,
|
|
598
|
+
streamGen: 0,
|
|
599
|
+
backoffMs: 250,
|
|
600
|
+
dirtyCursor: false,
|
|
601
|
+
lastFlushAt: 0,
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function isActive(sub: Sub): boolean {
|
|
606
|
+
return sub.started && !sub.stopped && !shutDown;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
async function startSub(sub: Sub): Promise<void> {
|
|
610
|
+
if (shutDown || sub.stopped || sub.started) return sub.startPromise ?? Promise.resolve();
|
|
611
|
+
if (sub.startPromise) return sub.startPromise;
|
|
612
|
+
const client = host.getClient(sub.record.server);
|
|
613
|
+
if (!client) return; // recorded; serverReady starts it later
|
|
614
|
+
sub.startPromise = (async () => {
|
|
615
|
+
try {
|
|
616
|
+
ensureListen(sub.record.server, client);
|
|
617
|
+
const descriptors = descriptorCache.get(sub.record.server) ?? (await list(sub.record.server));
|
|
618
|
+
const descriptor = descriptors.find(d => d.name === sub.record.name);
|
|
619
|
+
if (!descriptor) {
|
|
620
|
+
host.log("warn", `event "${sub.record.name}" not found in events/list for ${sub.record.server}; subscription not started`);
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
sub.descriptorDelivery = descriptor.delivery ?? [];
|
|
624
|
+
sub.mode = selectMode(sub, descriptor); // throws UnsupportedDeliveryMode for webhook-only
|
|
625
|
+
sub.started = true;
|
|
626
|
+
if (sub.mode === "poll") await pollCycle(sub, sub.generation);
|
|
627
|
+
else await openPush(sub);
|
|
628
|
+
} finally {
|
|
629
|
+
sub.startPromise = undefined;
|
|
630
|
+
}
|
|
631
|
+
})();
|
|
632
|
+
return sub.startPromise;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
async function stopSub(sub: Sub): Promise<void> {
|
|
636
|
+
sub.stopped = true;
|
|
637
|
+
sub.started = false;
|
|
638
|
+
sub.generation++;
|
|
639
|
+
sub.streamGen++;
|
|
640
|
+
clearWatchdog(sub);
|
|
641
|
+
if (sub.pollTimer) { clearTimeout(sub.pollTimer); sub.pollTimer = undefined; }
|
|
642
|
+
if (sub.reconnectTimer) { clearTimeout(sub.reconnectTimer); sub.reconnectTimer = undefined; }
|
|
643
|
+
if (sub.checkpointTimer) { clearTimeout(sub.checkpointTimer); sub.checkpointTimer = undefined; }
|
|
644
|
+
if (sub.dirtyCursor) persistCursor(sub);
|
|
645
|
+
const handle = sub.stream;
|
|
646
|
+
sub.stream = undefined;
|
|
647
|
+
if (handle) { try { await handle.cancel("stopped"); } catch { /* already gone */ } }
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// ---- public API -----------------------------------------------------------------
|
|
651
|
+
|
|
652
|
+
function restore(branch: readonly unknown[], allEntries: readonly unknown[]): void {
|
|
653
|
+
const asCustom = (e: unknown): { customType?: string; data?: unknown } | undefined =>
|
|
654
|
+
typeof e === "object" && e !== null ? (e as { customType?: string; data?: unknown }) : undefined;
|
|
655
|
+
|
|
656
|
+
// Newest non-null cursor + newest recentEventIds per subKey across all entries.
|
|
657
|
+
for (const raw of allEntries) {
|
|
658
|
+
const entry = asCustom(raw);
|
|
659
|
+
if (!entry) continue;
|
|
660
|
+
if (entry.customType === CUSTOM_CURSORS) {
|
|
661
|
+
const data = entry.data as CursorEntry | undefined;
|
|
662
|
+
if (!data?.subKey) continue;
|
|
663
|
+
if (typeof data.cursor === "string") persistedCursors.set(data.subKey, data.cursor);
|
|
664
|
+
if (Array.isArray(data.recentEventIds)) persistedRecent.set(data.subKey, [...data.recentEventIds]);
|
|
665
|
+
} else if (entry.customType === CUSTOM_SUBSCRIPTIONS) {
|
|
666
|
+
const data = entry.data as SubscriptionEntry | undefined;
|
|
667
|
+
if (data?.op === "upsert" && typeof data.cursor === "string") {
|
|
668
|
+
persistedCursors.set(data.subscription.subKey, data.cursor);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// Active subscription set from the branch.
|
|
674
|
+
const active = new Map<string, SubscriptionRecord>();
|
|
675
|
+
for (const raw of branch) {
|
|
676
|
+
const entry = asCustom(raw);
|
|
677
|
+
if (entry?.customType !== CUSTOM_SUBSCRIPTIONS) continue;
|
|
678
|
+
const data = entry.data as SubscriptionEntry | undefined;
|
|
679
|
+
if (data?.op === "upsert") active.set(data.subscription.subKey, data.subscription);
|
|
680
|
+
else if (data?.op === "remove") active.delete(data.subKey);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
for (const sub of [...subs.values()]) {
|
|
684
|
+
if (!active.has(sub.record.subKey)) {
|
|
685
|
+
subs.delete(sub.record.subKey);
|
|
686
|
+
void stopSub(sub);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
for (const record of active.values()) {
|
|
690
|
+
if (!subs.has(record.subKey)) {
|
|
691
|
+
subs.set(record.subKey, newSub(record, persistedCursors.get(record.subKey) ?? null));
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
for (const sub of subs.values()) {
|
|
695
|
+
void startSub(sub).catch(err => host.log("warn", `starting subscription ${sub.record.name} failed: ${errorMessageOf(err)}`));
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function serverReady(server: string): void {
|
|
700
|
+
const client = host.getClient(server);
|
|
701
|
+
if (client) ensureListen(server, client);
|
|
702
|
+
for (const sub of subs.values()) {
|
|
703
|
+
if (sub.record.server === server && !sub.stopped) {
|
|
704
|
+
void startSub(sub).catch(err => host.log("warn", `starting subscription ${sub.record.name} failed: ${errorMessageOf(err)}`));
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
async function subscribe(req: SubscribeRequest): Promise<SubscriptionRecord> {
|
|
710
|
+
const args = req.arguments as Record<string, unknown> | undefined;
|
|
711
|
+
const subKey = subKeyOf(req.server, req.name, args);
|
|
712
|
+
const existing = subs.get(subKey);
|
|
713
|
+
// Idempotent: an already-active subscription is not reopened (declarative subscriptions rely on this).
|
|
714
|
+
if (existing && isActive(existing) && req.cursor === undefined) return existing.record;
|
|
715
|
+
if (existing && existing.startPromise && req.cursor === undefined) {
|
|
716
|
+
await existing.startPromise.catch(() => {});
|
|
717
|
+
if (isActive(existing)) return existing.record;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const client = host.getClient(req.server);
|
|
721
|
+
if (client) {
|
|
722
|
+
// Validate against the descriptor before recording anything.
|
|
723
|
+
const descriptors = await list(req.server);
|
|
724
|
+
const descriptor = descriptors.find(d => d.name === req.name);
|
|
725
|
+
if (!descriptor) throw new Error(`Unknown event "${req.name}" on server "${req.server}" (not in events/list)`);
|
|
726
|
+
const probe: Sub = existing ?? newSub(
|
|
727
|
+
{ subKey, server: req.server, name: req.name, delivery: req.delivery ?? "auto", holdSettle: false },
|
|
728
|
+
null,
|
|
729
|
+
);
|
|
730
|
+
const wanted: SubscriptionRecord = {
|
|
731
|
+
subKey,
|
|
732
|
+
server: req.server,
|
|
733
|
+
name: req.name,
|
|
734
|
+
...(req.arguments !== undefined ? { arguments: req.arguments } : {}),
|
|
735
|
+
delivery: req.delivery ?? "auto",
|
|
736
|
+
...(req.maxAgeMs !== undefined ? { maxAgeMs: req.maxAgeMs } : {}),
|
|
737
|
+
holdSettle: req.holdSettle ?? false,
|
|
738
|
+
};
|
|
739
|
+
probe.record = wanted;
|
|
740
|
+
selectMode(probe, descriptor); // throws UnsupportedDeliveryMode for webhook-only
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const record: SubscriptionRecord = {
|
|
744
|
+
subKey,
|
|
745
|
+
server: req.server,
|
|
746
|
+
name: req.name,
|
|
747
|
+
...(req.arguments !== undefined ? { arguments: req.arguments } : {}),
|
|
748
|
+
delivery: req.delivery ?? "auto",
|
|
749
|
+
...(req.maxAgeMs !== undefined ? { maxAgeMs: req.maxAgeMs } : {}),
|
|
750
|
+
holdSettle: req.holdSettle ?? false,
|
|
751
|
+
};
|
|
752
|
+
const initialCursor = req.cursor !== undefined ? req.cursor : (persistedCursors.get(subKey) ?? existing?.cursor ?? null);
|
|
753
|
+
|
|
754
|
+
let sub: Sub;
|
|
755
|
+
if (existing) {
|
|
756
|
+
await stopSub(existing);
|
|
757
|
+
existing.stopped = false;
|
|
758
|
+
existing.record = record;
|
|
759
|
+
existing.cursor = initialCursor;
|
|
760
|
+
sub = existing;
|
|
761
|
+
} else {
|
|
762
|
+
sub = newSub(record, initialCursor);
|
|
763
|
+
subs.set(subKey, sub);
|
|
764
|
+
}
|
|
765
|
+
const entry: SubscriptionEntry = { op: "upsert", subscription: record, cursor: initialCursor };
|
|
766
|
+
host.appendEntry(CUSTOM_SUBSCRIPTIONS, entry);
|
|
767
|
+
await startSub(sub);
|
|
768
|
+
return record;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async function unsubscribe(server: string, name: string, args?: JsonObject): Promise<boolean> {
|
|
772
|
+
const subKey = subKeyOf(server, name, args as Record<string, unknown> | undefined);
|
|
773
|
+
const sub = subs.get(subKey);
|
|
774
|
+
if (!sub) return false;
|
|
775
|
+
subs.delete(subKey);
|
|
776
|
+
await stopSub(sub);
|
|
777
|
+
const entry: SubscriptionEntry = { op: "remove", subKey, server };
|
|
778
|
+
host.appendEntry(CUSTOM_SUBSCRIPTIONS, entry);
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
async function poll(server: string, params: PollEventsParams): Promise<PollEventsResult> {
|
|
783
|
+
const client = host.getClient(server);
|
|
784
|
+
if (!client) throw new Error(`Unknown or not-ready MCP server: ${server}`);
|
|
785
|
+
ensureListen(server, client);
|
|
786
|
+
const wire: JsonObject = { name: params.name, cursor: params.cursor ?? null };
|
|
787
|
+
if (params.arguments !== undefined) wire.arguments = params.arguments;
|
|
788
|
+
if (params.maxAgeMs !== undefined) wire.maxAgeMs = params.maxAgeMs;
|
|
789
|
+
if (params.maxEvents !== undefined) wire.maxEvents = params.maxEvents;
|
|
790
|
+
const result = await client.request<PollEventsResult>("events/poll", wire);
|
|
791
|
+
return { ...result, cursor: result.cursor ?? null };
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
async function shutdown(): Promise<void> {
|
|
795
|
+
if (shutDown) return;
|
|
796
|
+
shutDown = true;
|
|
797
|
+
if (batchTimer) { clearTimeout(batchTimer); batchTimer = undefined; }
|
|
798
|
+
flushBatch();
|
|
799
|
+
for (const dispose of listenDisposers.values()) { try { dispose(); } catch { /* ignore */ } }
|
|
800
|
+
listenDisposers.clear();
|
|
801
|
+
await Promise.all([...subs.values()].map(sub => stopSub(sub))); // stopSub flushes dirty cursors
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
return {
|
|
805
|
+
restore,
|
|
806
|
+
serverReady,
|
|
807
|
+
list,
|
|
808
|
+
subscribe,
|
|
809
|
+
unsubscribe,
|
|
810
|
+
subscriptions: () =>
|
|
811
|
+
[...subs.values()].map(sub => ({
|
|
812
|
+
...sub.record,
|
|
813
|
+
cursor: sub.cursor,
|
|
814
|
+
active: isActive(sub),
|
|
815
|
+
...(sub.mode ? { mode: sub.mode } : {}),
|
|
816
|
+
})),
|
|
817
|
+
poll,
|
|
818
|
+
holdsSettle: () => [...subs.values()].some(sub => sub.record.holdSettle && isActive(sub)),
|
|
819
|
+
activeStreams: () => [...subs.values()].filter(sub => sub.stream !== undefined).length,
|
|
820
|
+
onWake: (listener: () => void) => {
|
|
821
|
+
wakeListeners.add(listener);
|
|
822
|
+
return () => { wakeListeners.delete(listener); };
|
|
823
|
+
},
|
|
824
|
+
shutdown,
|
|
825
|
+
};
|
|
826
|
+
}
|