holon-sh 0.0.1-dev.7 → 0.0.1-dev.9

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 (52) hide show
  1. package/README.md +96 -67
  2. package/dist/context.d.ts +55 -0
  3. package/dist/context.d.ts.map +1 -0
  4. package/dist/context.js +9 -0
  5. package/dist/context.js.map +1 -0
  6. package/dist/ext/events.d.ts +268 -0
  7. package/dist/ext/events.d.ts.map +1 -0
  8. package/dist/ext/events.js +619 -0
  9. package/dist/ext/events.js.map +1 -0
  10. package/dist/ext/files.client.d.ts +50 -0
  11. package/dist/ext/files.client.d.ts.map +1 -0
  12. package/dist/ext/files.client.js +359 -0
  13. package/dist/ext/files.client.js.map +1 -0
  14. package/dist/ext/files.d.ts +21 -0
  15. package/dist/ext/files.d.ts.map +1 -0
  16. package/dist/ext/files.js +3 -0
  17. package/dist/ext/files.js.map +1 -0
  18. package/dist/ext/platform.browser.d.ts +4 -0
  19. package/dist/ext/platform.browser.d.ts.map +1 -0
  20. package/dist/ext/platform.browser.js +15 -0
  21. package/dist/ext/platform.browser.js.map +1 -0
  22. package/dist/ext/platform.node.d.ts +4 -0
  23. package/dist/ext/platform.node.d.ts.map +1 -0
  24. package/dist/ext/platform.node.js +45 -0
  25. package/dist/ext/platform.node.js.map +1 -0
  26. package/dist/ext/webhooks.d.ts +18 -0
  27. package/dist/ext/webhooks.d.ts.map +1 -0
  28. package/dist/ext/webhooks.js +527 -0
  29. package/dist/ext/webhooks.js.map +1 -0
  30. package/dist/protocol.d.ts +134 -0
  31. package/dist/protocol.d.ts.map +1 -0
  32. package/dist/protocol.js +32 -0
  33. package/dist/protocol.js.map +1 -0
  34. package/dist/runtime.d.ts +72 -0
  35. package/dist/runtime.d.ts.map +1 -0
  36. package/dist/runtime.js +453 -0
  37. package/dist/runtime.js.map +1 -0
  38. package/package.json +56 -19
  39. package/{context.d.ts → src/context.ts} +11 -1
  40. package/src/ext/events.ts +812 -0
  41. package/src/ext/files.client.ts +329 -0
  42. package/src/ext/files.ts +16 -0
  43. package/src/ext/platform.browser.ts +15 -0
  44. package/src/ext/platform.node.ts +43 -0
  45. package/src/ext/webhooks.ts +512 -0
  46. package/src/protocol.ts +119 -0
  47. package/src/runtime.ts +467 -0
  48. package/context.mjs +0 -6
  49. package/protocol.d.ts +0 -51
  50. package/runtime.d.ts +0 -47
  51. package/runtime.mjs +0 -207
  52. package/validate.mjs +0 -12
@@ -0,0 +1,619 @@
1
+ // The server side of MCP Events, as the Triggers & Events Working Group's design sketch defines it:
2
+ // https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md
3
+ // The draft is experimental, so this lives under ext and may change with it.
4
+ // It serves the poll and push delivery modes, and webhook delivery when given a webhookTtl, from a module of its own
5
+ // that reaches the event types through the internals below. Names follow the sketch, and types are the MCP SDK's own
6
+ // wherever it has them.
7
+ import { ProtocolError, ProtocolErrorCode, SUBSCRIPTION_ID_META_KEY } from "@modelcontextprotocol/server";
8
+ import { webhooks } from "./webhooks.js";
9
+ /** The identifier a server declares the Events extension under, in capabilities.extensions. */
10
+ export const EVENTS_EXTENSION = "io.modelcontextprotocol/events";
11
+ /** Reaches what a delivery mode needs of the events it serves. Not for applications. */
12
+ export const INTERNALS = Symbol.for("holon-sh.events.internals");
13
+ const INVALID_PARAMS = ProtocolErrorCode.InvalidParams;
14
+ const INTERNAL_ERROR = ProtocolErrorCode.InternalError;
15
+ // The sketch's general-purpose codes, provisional until the specification allocates them.
16
+ const NOT_FOUND = -32023;
17
+ const FORBIDDEN = -32024;
18
+ const RESOURCE_EXHAUSTED = -32025;
19
+ const UNSUPPORTED = -32026;
20
+ // Requests are checked here, against each event type's own schema.
21
+ const params = { "~standard": { version: 1, vendor: "holon-sh", validate: (value) => ({ value: value ?? {} }) } };
22
+ const refusal = ({ code, message, data }) => new ProtocolError(code, message, data);
23
+ const removed = { code: NOT_FOUND, message: "NotFound", data: { kind: "event" } };
24
+ const forbidden = { code: FORBIDDEN, message: "Forbidden" };
25
+ // What a client is told of a failure: its code when it is a JSON-RPC one, and its message.
26
+ const described = (error) => ({
27
+ code: Number.isInteger(error?.code) ? error.code : INTERNAL_ERROR,
28
+ message: error?.message || "InternalError",
29
+ ...(error?.data !== undefined && { data: error.data }),
30
+ });
31
+ // Arguments are the same subscription whatever order their keys came in.
32
+ const canonical = (value) => Array.isArray(value) ? value.map(canonical)
33
+ : value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]))
34
+ : value;
35
+ // Who asked, as Holon admitted them: the user, the client acting for them, the agent when one acts for the user, and
36
+ // what the token allows. A caller without a subject has no identity: nobody can tell it from another such caller.
37
+ const caller = (context) => {
38
+ const authInfo = context?.authInfo;
39
+ const { iss = null, sub, act = null } = authInfo?.extra ?? {};
40
+ if (!authInfo || typeof sub !== "string")
41
+ return null;
42
+ return JSON.stringify(canonical([iss, sub, authInfo.clientId ?? null, act, [...authInfo.scopes ?? []].sort()]));
43
+ };
44
+ const hex = (bytes) => [...bytes].map(byte => byte.toString(16).padStart(2, "0")).join("");
45
+ // A subscription's id is the same for the same caller, event type and arguments, so it survives reconnects and poll
46
+ // leases, as a webhook subscription's does. It is made with the global crypto, which needs no node:crypto at load.
47
+ const identify = async (who, name, args) => {
48
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify([who, name, canonical(args)])));
49
+ return `sub_${hex(new Uint8Array(digest, 0, 16))}`;
50
+ };
51
+ // A caller without an identity gets an id of its own for each stream.
52
+ const unique = () => `sub_${hex(crypto.getRandomValues(new Uint8Array(16)))}`;
53
+ // A teardown that fails has nobody to tell, and must not take the process down.
54
+ const settle = (run) => { Promise.resolve().then(run).catch(() => { }); };
55
+ const integer = (value, minimum) => value === undefined || Number.isInteger(value) && value >= minimum;
56
+ // What each type without a check function keeps of what it emits, for polls and reconnecting streams: the sketch's
57
+ // emit buffer.
58
+ const KEPT_EVENTS = 10_000;
59
+ const KEPT_AGE = 10 * 60_000;
60
+ // How long a poll is told to wait before the next, and how often a stream asks a check function.
61
+ const INTERVAL = 1000;
62
+ // How often a stream hears from the server when nothing happens, as the sketch recommends.
63
+ const HEARTBEAT = 30_000;
64
+ // How long a poll subscription lasts after its last poll: the sketch's poll subscription TTL.
65
+ const POLL_SUBSCRIPTION_TTL = 60_000;
66
+ // How many subscriptions may be held at once, by every delivery mode, and by one caller. Callers without an identity
67
+ // cannot be told apart, so they count together as one caller.
68
+ const MAX_SUBSCRIPTIONS = 10_000;
69
+ const MAX_SUBSCRIPTIONS_PER_CALLER = 1000;
70
+ // How many event types events/list returns at a time.
71
+ const PAGE_SIZE = 100;
72
+ /**
73
+ * Event types a process emits and the MCP servers it creates serve, in the poll and push delivery modes of MCP Events,
74
+ * the draft extension of the Triggers & Events Working Group. Each type keeps the last ten thousand events it emits,
75
+ * for ten minutes, for polls and for streams that reconnect: those cursors last as long as the process, and after a
76
+ * restart a client is told that events were skipped. A type with a check function uses its source's cursors instead,
77
+ * which outlive the process. A type is asked again, and a poll told to come back, every second. A stream hears from
78
+ * the server every thirty seconds.
79
+ */
80
+ export function createEvents({ webhookTtl, webhook } = {}) {
81
+ const modes = webhookTtl === undefined ? [] : [webhooks({ ...webhook, ttl: webhookTtl, heartbeat: HEARTBEAT })];
82
+ const offered = ["poll", "push", ...modes.map(mode => mode.name)];
83
+ // Cursors are positions in this process's memory. One from another process names nothing here. The name is made
84
+ // without node:crypto, which is not there when a server is evaluated for its contract.
85
+ const epoch = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
86
+ const types = new Map();
87
+ let declared = 0;
88
+ let subscribed = 0;
89
+ const callers = new Map();
90
+ const position = (type, sequence = type.sequence) => `${epoch}.${sequence}`;
91
+ // An event emitted to one subscription that it could not be given is owed to it as a gap, on its next poll or
92
+ // stream. The ids owed one are as many as the events a type keeps.
93
+ const owe = (type, id) => {
94
+ type.owed.delete(id);
95
+ type.owed.set(id, true);
96
+ if (type.owed.size > KEPT_EVENTS)
97
+ type.owed.delete(type.owed.keys().next().value);
98
+ };
99
+ // What a subscription is owed after a cursor from the events emitted: the ones for it, in order, where delivery
100
+ // starts, and where it now stands. A null cursor starts from now, and so does one from another process. One past
101
+ // the events still kept starts from the oldest kept, and says that events were skipped.
102
+ const since = (state, subscription, cursor, maxAgeMs, limit = Infinity) => {
103
+ const type = state;
104
+ const now = { events: [], start: position(type), cursor: position(type), hasMore: false };
105
+ if (cursor == null)
106
+ return { ...now, truncated: false };
107
+ const [process, text] = cursor.split(".");
108
+ const sequence = Number(text);
109
+ if (process !== epoch || !Number.isInteger(sequence) || sequence > type.sequence)
110
+ return { ...now, truncated: true };
111
+ const floor = maxAgeMs === undefined ? -Infinity : Date.now() - maxAgeMs;
112
+ const later = type.kept.filter(kept => kept.sequence > sequence);
113
+ const recent = later.filter(kept => kept.at >= floor);
114
+ const truncated = sequence < type.dropped || recent.length < later.length;
115
+ const events = [];
116
+ const failures = [];
117
+ let reached = recent.length ? recent[0].sequence - 1 : type.sequence;
118
+ const start = position(type, reached);
119
+ for (const kept of recent) {
120
+ if (events.length === limit)
121
+ return { events, failures, start, cursor: position(type, reached), truncated, hasMore: true };
122
+ reached = kept.sequence;
123
+ const event = shape(type, kept, subscription, error => failures.push(error));
124
+ if (event)
125
+ events.push(event);
126
+ }
127
+ return { events, failures, start, cursor: position(type), truncated, hasMore: false };
128
+ };
129
+ // What a subscription is owed after a cursor from the type's check function. The cursor is the author's own. Each
130
+ // event is placed at its own cursor when it has one, so a batch can be cut short; otherwise at the cursor before
131
+ // the batch, which is safe to resume from. After a gap, delivery starts from the position the check reached.
132
+ const checked = async (type, { arguments: args, context }, cursor, maxAgeMs, limit = Infinity) => {
133
+ const result = await type.check(cursor ?? null, args, context);
134
+ const next = result?.cursor ?? null;
135
+ // A null cursor asks for the current position and nothing before it, except of a source that has no positions:
136
+ // each check of that is asked with null, and answers with what is new.
137
+ if (cursor == null && next !== null)
138
+ return { events: [], start: next, cursor: next, truncated: false, hasMore: false };
139
+ const items = result?.events ?? [];
140
+ const floor = maxAgeMs === undefined || cursor == null ? -Infinity : Date.now() - maxAgeMs;
141
+ let truncated = next !== null && Boolean(result.truncated);
142
+ const events = [];
143
+ const failures = [];
144
+ let reached = cursor ?? null;
145
+ let cuttable = false;
146
+ const answer = (end, hasMore) => ({ events, failures, start: truncated || !events.length ? end : cursor ?? null, cursor: end, truncated, hasMore });
147
+ for (const [index, item] of items.entries()) {
148
+ if (events.length === limit && cuttable)
149
+ return answer(reached, true);
150
+ const after = index === items.length - 1 ? next : item.cursor ?? reached;
151
+ const { eventId = crypto.randomUUID(), timestamp = new Date().toISOString(), data, _meta } = item;
152
+ if (Date.parse(timestamp) < floor)
153
+ truncated = next !== null;
154
+ else if (serialisable(type, eventId, { data, _meta }, error => failures.push(error)))
155
+ events.push({ eventId, name: type.name, timestamp, data, ...(_meta && { _meta }), cursor: after });
156
+ reached = after;
157
+ cuttable = item.cursor != null;
158
+ }
159
+ return answer(next, Boolean(result.hasMore));
160
+ };
161
+ // What a subscription is owed after a cursor, whichever way its type learns of events.
162
+ const read = (type, subscription, cursor, { maxAgeMs, maxEvents } = {}) => type.check ? checked(type, subscription, cursor, maxAgeMs, maxEvents) : since(type, subscription, cursor, maxAgeMs, maxEvents);
163
+ // The occurrence a subscription receives, or nothing when it is not for it. An event emitted to one subscription
164
+ // is for that one alone, and its arguments are not asked.
165
+ // An event that cannot be shaped for a subscription, because `match` or `transform` throws or what `transform`
166
+ // returns cannot be sent as JSON, is skipped for that subscription alone, so its cursor moves past it. It is
167
+ // logged, and `failed` hears of it so a stream can say so once.
168
+ const shape = (state, { sequence, target, occurrence }, { id, untargetable, arguments: args, context }, failed) => {
169
+ const type = state;
170
+ let data;
171
+ try {
172
+ if (target !== undefined ? untargetable || target !== id : type.match && !type.match(occurrence.data, args, context))
173
+ return undefined;
174
+ data = type.transform ? type.transform(occurrence.data, args, context) : occurrence.data;
175
+ if (type.transform)
176
+ JSON.stringify(data);
177
+ }
178
+ catch (error) {
179
+ skipped(type, occurrence.eventId, error, failed);
180
+ return undefined;
181
+ }
182
+ return { ...occurrence, data, ...(sequence !== undefined && { cursor: position(type, sequence) }) };
183
+ };
184
+ const skipped = (type, eventId, error, failed) => {
185
+ console.error(`holon-sh/ext/events: event ${eventId} of ${type.name} was skipped for a subscription:`, error);
186
+ failed?.({ code: INTERNAL_ERROR, message: `Event ${eventId} could not be delivered and was skipped`, data: { eventId, reason: String(error?.message ?? error) } });
187
+ };
188
+ // What a check function found is skipped in the same way when it cannot be sent as JSON.
189
+ const serialisable = (type, eventId, value, failed) => {
190
+ try {
191
+ JSON.stringify(value);
192
+ return true;
193
+ }
194
+ catch (error) {
195
+ skipped(type, eventId, error, failed);
196
+ return false;
197
+ }
198
+ };
199
+ // The event type and arguments a request names, checked as the sketch's errors require, in its order: the type,
200
+ // the delivery mode, the request's own fields, the arguments, and then whether the caller may subscribe. A caller
201
+ // refused loses what it holds of that subscription at once.
202
+ const subscription = async ({ name, arguments: args = {}, cursor, maxAgeMs, maxEvents }, context, delivery) => {
203
+ const type = types.get(name);
204
+ if (!type)
205
+ throw refusal(removed);
206
+ if (delivery && !type.delivery.includes(delivery))
207
+ throw refusal({ code: UNSUPPORTED, message: "Unsupported", data: { feature: "deliveryMode", value: delivery } });
208
+ if (cursor != null && typeof cursor !== "string")
209
+ throw new ProtocolError(INVALID_PARAMS, "cursor must be a string or null");
210
+ if (!integer(maxAgeMs, 0))
211
+ throw new ProtocolError(INVALID_PARAMS, "maxAgeMs must be a non-negative integer");
212
+ if (!integer(maxEvents, 1))
213
+ throw new ProtocolError(INVALID_PARAMS, "maxEvents must be a positive integer");
214
+ const checked = await type.inputSchema["~standard"].validate(args);
215
+ if (checked.issues)
216
+ throw new ProtocolError(INVALID_PARAMS, `Invalid arguments for ${name}: ${checked.issues.map(issue => issue.message).join("; ")}`);
217
+ const who = caller(context);
218
+ // Polls share a lease per caller and arguments, and callers without an identity share one per arguments.
219
+ const lease = await identify(who, type.name, checked.value);
220
+ if (type.authorize && !(await type.authorize(checked.value, context))) {
221
+ endSubscription(type, lease, forbidden);
222
+ // This refusal is the answer the poll lease would have given, so the next poll begins afresh.
223
+ leases.delete(lease);
224
+ throw refusal(forbidden);
225
+ }
226
+ return { type, subscription: { id: who === null ? unique() : lease, lease, arguments: checked.value, context } };
227
+ };
228
+ const endSubscription = (type, id, error) => {
229
+ for (const held of [...type.subscriptions.get(id)?.held ?? []])
230
+ held.end(error);
231
+ };
232
+ // Begins holding a subscription, by a stream, a poll lease or another delivery mode: counted against the limits
233
+ // first, so a refused one provisions nothing. The type's onSubscribe is called when the first hold of an id
234
+ // begins, and its onUnsubscribe when the last ends, so two streams of one subscription set it up once. `end` is how
235
+ // the delivery mode is told the app terminated it; `close` is how the mode says its hold is over.
236
+ const open = async (state, { id, delivery, arguments: args, context }, end) => {
237
+ const type = state;
238
+ if (types.get(type.name) !== type)
239
+ throw refusal(removed);
240
+ // Callers without an identity cannot be told apart, so they count together as one.
241
+ const who = caller(context) ?? "anonymous";
242
+ if (subscribed >= MAX_SUBSCRIPTIONS)
243
+ throw refusal({ code: RESOURCE_EXHAUSTED, message: "ResourceExhausted", data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS } });
244
+ if ((callers.get(who) ?? 0) >= MAX_SUBSCRIPTIONS_PER_CALLER)
245
+ throw refusal({ code: RESOURCE_EXHAUSTED, message: "ResourceExhausted", data: { limit: "subscriptionsPerCaller", max: MAX_SUBSCRIPTIONS_PER_CALLER } });
246
+ subscribed++;
247
+ callers.set(who, (callers.get(who) ?? 0) + 1);
248
+ let entry = type.subscriptions.get(id);
249
+ if (!entry) {
250
+ const subscription = { subscriptionId: id, name: type.name, delivery, arguments: args, context };
251
+ const ready = Promise.resolve().then(() => type.onSubscribe?.(subscription)).then(() => subscription);
252
+ ready.catch(() => { });
253
+ entry = { held: new Set(), ready };
254
+ type.subscriptions.set(id, entry);
255
+ }
256
+ const current = entry;
257
+ let closed = false;
258
+ const held = { id, name: type.name, delivery, arguments: args, context, end, close() {
259
+ if (closed)
260
+ return;
261
+ closed = true;
262
+ subscribed--;
263
+ const count = callers.get(who) ?? 1;
264
+ if (count === 1)
265
+ callers.delete(who);
266
+ else
267
+ callers.set(who, count - 1);
268
+ current.held.delete(held);
269
+ if (current.held.size)
270
+ return;
271
+ if (type.subscriptions.get(id) === current)
272
+ type.subscriptions.delete(id);
273
+ // Only a subscription that was set up is told it ended.
274
+ current.ready.then(subscription => { if (type.onUnsubscribe)
275
+ settle(() => type.onUnsubscribe(subscription)); }, () => { });
276
+ } };
277
+ current.held.add(held);
278
+ try {
279
+ await current.ready;
280
+ }
281
+ catch (error) {
282
+ held.close();
283
+ throw error;
284
+ }
285
+ // The type was removed while the subscription was being set up.
286
+ if (types.get(type.name) !== type) {
287
+ held.close();
288
+ throw refusal(removed);
289
+ }
290
+ return held;
291
+ };
292
+ // Poll subscriptions are leased: the first poll of a subscription begins one, each poll renews it, and it ends
293
+ // when polls stop for a minute, many of the intervals the poll was told to wait.
294
+ const leases = new Map();
295
+ const lease = async (type, { lease: key, ...subscribed }) => {
296
+ // A lease shared by callers without an identity is nobody's in particular, so nothing is emitted to it alone.
297
+ const shared = key !== subscribed.id;
298
+ let lent = leases.get(key);
299
+ if (lent && (lent.ended || lent.type !== type)) {
300
+ leases.delete(key);
301
+ clearTimeout(lent.timer);
302
+ lent.release?.();
303
+ // The poll after one the app ended is answered with why, and the one after it begins afresh.
304
+ if (lent.ended && lent.type === type)
305
+ throw refusal(lent.ended);
306
+ lent = undefined;
307
+ }
308
+ if (!lent) {
309
+ const fresh = { type };
310
+ lent = fresh;
311
+ leases.set(key, fresh);
312
+ fresh.opening = open(type, { ...subscribed, id: key, delivery: "poll" }, error => {
313
+ fresh.ended = error;
314
+ fresh.release?.();
315
+ });
316
+ fresh.opening.then(held => {
317
+ if (shared)
318
+ held.untargetable = true;
319
+ fresh.release = () => held.close();
320
+ if (fresh.ended)
321
+ held.close();
322
+ }, () => { if (leases.get(key) === fresh)
323
+ leases.delete(key); });
324
+ }
325
+ const current = lent;
326
+ const held = await current.opening;
327
+ // Ended while it was being set up.
328
+ if (current.ended) {
329
+ leases.delete(key);
330
+ throw refusal(current.ended);
331
+ }
332
+ clearTimeout(current.timer);
333
+ current.timer = setTimeout(() => {
334
+ if (leases.get(key) === current)
335
+ leases.delete(key);
336
+ held.close();
337
+ }, POLL_SUBSCRIPTION_TTL);
338
+ current.timer.unref?.();
339
+ return held;
340
+ };
341
+ // What a delivery mode works with: `subscription` checks a request, names its event type and the subscription's
342
+ // id, `open` begins holding a subscription, `read` gives a subscription what it is owed after a cursor (`since` and
343
+ // `shape` for emitted events alone), `position` is a type's cursor, a type's `sinks` hear what is emitted, and its
344
+ // `subscriptions` are the ones held by every mode, by id.
345
+ const internals = { types, subscription, open, read, since, shape, position };
346
+ return {
347
+ [INTERNALS]: internals,
348
+ /**
349
+ * Declares an event type and returns the function that emits it. `match` decides which subscriptions receive an
350
+ * event from their arguments, and `transform` shapes its data for each. `check` returns what happened after a
351
+ * cursor, for event types whose source keeps its own history.
352
+ */
353
+ event(name, { description, inputSchema, payloadSchema, _meta, match, transform, check, delivery = offered.filter(mode => !check || mode !== "webhook"), authorize, onSubscribe, onUnsubscribe }) {
354
+ if (types.has(name))
355
+ throw new Error(`Event ${name} is already declared.`);
356
+ const unknown = delivery.filter(mode => !offered.includes(mode));
357
+ if (unknown.length || !delivery.length)
358
+ throw new Error(`Event ${name} is delivered by ${delivery.join(", ") || "nothing"}, but only ${offered.join(", ")} are served.`);
359
+ // Webhook delivery sends what is emitted, and does not ask a check function.
360
+ if (check && delivery.includes("webhook"))
361
+ throw new Error(`Event ${name} has a check function, which webhook delivery does not read.`);
362
+ const type = {
363
+ name, order: ++declared, description, inputSchema, payloadSchema, _meta, match, transform, check: check, interval: INTERVAL, delivery, authorize, onSubscribe, onUnsubscribe,
364
+ sequence: 0, dropped: 0, kept: [], sinks: new Set(), subscriptions: new Map(), owed: new Map(),
365
+ };
366
+ types.set(name, type);
367
+ return {
368
+ emit(data, { eventId = crypto.randomUUID(), timestamp = new Date().toISOString(), subscriptionId: target } = {}) {
369
+ const occurrence = { eventId, name, timestamp, data };
370
+ // Data that cannot be sent as JSON is refused here, before anything is kept or sent.
371
+ JSON.stringify(occurrence);
372
+ // A type with a check function is asked for what polls are owed, so what it emits is pushed and not kept.
373
+ if (type.check) {
374
+ // An event for one subscription that has no stream to take it is lost.
375
+ if (target !== undefined && ![...type.subscriptions.get(target)?.held ?? []].some(held => held.delivery !== "poll"))
376
+ owe(type, target);
377
+ for (const sink of type.sinks)
378
+ sink({ target, occurrence });
379
+ return;
380
+ }
381
+ // An event for one subscription is kept like any other, so the subscription has it when it comes back.
382
+ const kept = { sequence: ++type.sequence, at: Date.now(), target, occurrence };
383
+ type.kept.push(kept);
384
+ while (type.kept.length > KEPT_EVENTS || type.kept[0].at < kept.at - KEPT_AGE)
385
+ type.dropped = type.kept.shift().sequence;
386
+ for (const sink of type.sinks)
387
+ sink(kept);
388
+ },
389
+ cursor() {
390
+ if (type.check)
391
+ throw new Error(`Event ${name} has a check function, whose cursor is its source's own.`);
392
+ return position(type);
393
+ },
394
+ terminate(id, error = forbidden) {
395
+ if (id !== undefined)
396
+ return endSubscription(type, id, error);
397
+ for (const each of [...type.subscriptions.keys()])
398
+ endSubscription(type, each, error);
399
+ },
400
+ remove() {
401
+ if (types.get(name) !== type)
402
+ return;
403
+ types.delete(name);
404
+ for (const each of [...type.subscriptions.keys()])
405
+ endSubscription(type, each, removed);
406
+ },
407
+ };
408
+ },
409
+ /** Serves the declared event types on an MCP server: events/list, events/poll and events/stream. */
410
+ serve(mcp) {
411
+ const underlying = "server" in mcp ? mcp.server : mcp;
412
+ // The custom methods are registered through the parts of the server this module uses.
413
+ const server = underlying;
414
+ // The sketch declares capabilities.events. The MCP SDK's client drops top-level capabilities it does not know,
415
+ // so the extension is declared under capabilities.extensions too, where SDK clients read it.
416
+ // Clients are never told the event types changed: over Holon's stateless HTTP, the notification reaches none.
417
+ server.registerCapabilities({ events: { listChanged: false }, extensions: { [EVENTS_EXTENSION]: { listChanged: false } } });
418
+ const json = (schema) => schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
419
+ server.setRequestHandler("events/list", { params }, request => {
420
+ const all = [...types.values()];
421
+ let start = 0;
422
+ if (request.cursor != null) {
423
+ const after = Number(request.cursor);
424
+ if (typeof request.cursor !== "string" || !Number.isInteger(after))
425
+ throw new ProtocolError(INVALID_PARAMS, "Invalid cursor for events/list");
426
+ start = all.findIndex(type => type.order > after);
427
+ if (start < 0)
428
+ start = all.length;
429
+ }
430
+ const page = all.slice(start, start + PAGE_SIZE);
431
+ return {
432
+ events: page.map(type => ({
433
+ name: type.name,
434
+ ...(type.description && { description: type.description }),
435
+ delivery: type.delivery,
436
+ inputSchema: json(type.inputSchema),
437
+ payloadSchema: json(type.payloadSchema),
438
+ ...(type._meta && { _meta: type._meta }),
439
+ })),
440
+ ...(start + PAGE_SIZE < all.length && { nextCursor: String(page.at(-1).order) }),
441
+ };
442
+ });
443
+ for (const mode of modes)
444
+ mode.serve(underlying, internals);
445
+ server.setRequestHandler("events/poll", { params }, async (request, ctx) => {
446
+ const { type, subscription: subscribed } = await subscription(request, ctx.http, "poll");
447
+ const held = await lease(type, subscribed);
448
+ // Each poll is answered for its own caller, with the lease's id.
449
+ const { events, start, failures, truncated, ...rest } = await read(type, { ...subscribed, id: held.id, untargetable: held.untargetable }, request.cursor, request);
450
+ const lost = !held.untargetable && type.owed.delete(held.id);
451
+ // A poll carries its cursor once, for the whole response.
452
+ return { events: events.map(({ cursor, ...event }) => event), ...rest, truncated: truncated || lost, nextPollMs: type.interval };
453
+ });
454
+ server.setRequestHandler("events/stream", { params }, async (request, ctx) => {
455
+ const { type: state, subscription: subscribed } = await subscription(request, ctx.http, "push");
456
+ const type = state;
457
+ const { signal } = ctx.mcpReq;
458
+ const meta = { [SUBSCRIPTION_ID_META_KEY]: ctx.mcpReq.id };
459
+ let done = false;
460
+ let ending;
461
+ let wake = () => { };
462
+ const finish = () => {
463
+ done = true;
464
+ wake();
465
+ };
466
+ const held = await open(type, { ...subscribed, delivery: "push" }, error => {
467
+ ending = error;
468
+ finish();
469
+ });
470
+ // A client that left while the subscription was being set up is not waited for.
471
+ if (signal.aborted) {
472
+ held.close();
473
+ return { _meta: {} };
474
+ }
475
+ // Ended while it was being set up: no stream is opened, and the request is refused.
476
+ if (ending) {
477
+ held.close();
478
+ throw refusal(ending);
479
+ }
480
+ signal.addEventListener("abort", finish, { once: true });
481
+ // A stream that cannot be written to is over.
482
+ const notify = async (method, body) => {
483
+ if (signal.aborted)
484
+ return;
485
+ try {
486
+ await ctx.mcpReq.notify({ method: `notifications/events/${method}`, params: { ...body, _meta: meta } });
487
+ }
488
+ catch {
489
+ finish();
490
+ }
491
+ };
492
+ // The stream follows its cursor: emitted events wake it, and a type with a check function is asked again
493
+ // every interval. What it is owed waits in the buffer or the source, not here, so a slow client is not owed
494
+ // more memory than one batch; when what it is owed is no longer kept, it is told of the gap.
495
+ let cursor = request.cursor ?? null;
496
+ let behind = true;
497
+ // What a type with a check function emitted and the stream has yet to send. The check function finds it
498
+ // too, so when too much waits the oldest is let go.
499
+ const pushed = [];
500
+ const sink = (kept) => {
501
+ if (type.check) {
502
+ pushed.push(kept);
503
+ if (pushed.length > KEPT_EVENTS)
504
+ pushed.shift();
505
+ }
506
+ else
507
+ behind = true;
508
+ wake();
509
+ };
510
+ type.sinks.add(sink);
511
+ let beat;
512
+ let beating = false;
513
+ const heartbeats = () => setInterval(async () => {
514
+ if (beating)
515
+ return;
516
+ beating = true;
517
+ try {
518
+ // Access is checked again while the subscription lasts, and one that is lost ends it.
519
+ if (type.authorize && !(await type.authorize(subscribed.arguments, subscribed.context)))
520
+ return endSubscription(type, held.id, forbidden);
521
+ await notify("heartbeat", { cursor });
522
+ }
523
+ catch (error) {
524
+ await notify("error", { error: described(error) });
525
+ }
526
+ finally {
527
+ beating = false;
528
+ }
529
+ }, HEARTBEAT);
530
+ let first = true;
531
+ try {
532
+ let due = 0;
533
+ while (!done) {
534
+ if (type.check ? Date.now() >= due : behind) {
535
+ behind = false;
536
+ let result;
537
+ try {
538
+ result = await read(type, held, cursor, { ...(first && request.maxAgeMs !== undefined && { maxAgeMs: request.maxAgeMs }) });
539
+ }
540
+ catch (error) {
541
+ // Without a first answer there is no stream to tell, and the request fails.
542
+ if (first)
543
+ throw error;
544
+ await notify("error", { error: described(error) });
545
+ }
546
+ due = Date.now() + type.interval;
547
+ if (result) {
548
+ // A check function's gap is told after the events that follow it, at the position after them, since
549
+ // the position before them is not known and the client's cursor must not go back. The stream is
550
+ // confirmed before anything else is said on it.
551
+ const after = type.check && result.truncated && !first;
552
+ const truncated = result.truncated || first && type.owed.delete(held.id);
553
+ if (first || truncated && !after)
554
+ await notify("active", { cursor: type.check && result.truncated ? cursor : result.start, truncated });
555
+ if (first)
556
+ beat = heartbeats();
557
+ first = false;
558
+ for (const error of result.failures ?? [])
559
+ await notify("error", { error });
560
+ for (const event of result.events) {
561
+ if (done)
562
+ break;
563
+ await notify("event", event);
564
+ cursor = event.cursor ?? null;
565
+ }
566
+ if (done)
567
+ break;
568
+ cursor = result.cursor;
569
+ if (after)
570
+ await notify("active", { cursor, truncated: true });
571
+ if (result.hasMore) {
572
+ due = 0;
573
+ behind = true;
574
+ }
575
+ }
576
+ }
577
+ // What a type with a check function emits is sent at once, at the cursor the stream has reached.
578
+ while (pushed.length && !done) {
579
+ let failure;
580
+ const event = shape(type, pushed.shift(), held, error => { failure = error; });
581
+ if (failure)
582
+ await notify("error", { error: failure });
583
+ if (event)
584
+ await notify("event", { ...event, cursor });
585
+ }
586
+ if (done)
587
+ break;
588
+ let timer;
589
+ await new Promise(resolve => {
590
+ wake = resolve;
591
+ if (done || pushed.length || (!type.check && behind))
592
+ resolve();
593
+ else if (type.check)
594
+ timer = setTimeout(resolve, Math.max(0, due - Date.now()));
595
+ });
596
+ clearTimeout(timer);
597
+ wake = () => { };
598
+ }
599
+ if (ending) {
600
+ if (first)
601
+ throw refusal(ending);
602
+ await notify("terminated", { error: ending });
603
+ }
604
+ }
605
+ finally {
606
+ clearInterval(beat);
607
+ type.sinks.delete(sink);
608
+ // What was emitted to this subscription alone and not sent is owed to it as a gap when it comes back.
609
+ if (held.id === subscribed.lease && pushed.some(kept => kept.target === held.id))
610
+ owe(type, held.id);
611
+ held.close();
612
+ }
613
+ // The final frame, sent when the server ends the stream; when the client did, nobody is listening.
614
+ return { _meta: {} };
615
+ });
616
+ },
617
+ };
618
+ }
619
+ //# sourceMappingURL=events.js.map