@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +107 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
@@ -0,0 +1,293 @@
1
+ /** Independent Session snapshots and passive event subscriptions. */
2
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
3
+ if (value !== null && value !== void 0) {
4
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
5
+ var dispose, inner;
6
+ if (async) {
7
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
8
+ dispose = value[Symbol.asyncDispose];
9
+ }
10
+ if (dispose === void 0) {
11
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
12
+ dispose = value[Symbol.dispose];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
16
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
17
+ env.stack.push({ value: value, dispose: dispose, async: async });
18
+ }
19
+ else if (async) {
20
+ env.stack.push({ async: true });
21
+ }
22
+ return value;
23
+ };
24
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
25
+ return function (env) {
26
+ function fail(e) {
27
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
28
+ env.hasError = true;
29
+ }
30
+ var r, s = 0;
31
+ function next() {
32
+ while (r = env.stack.pop()) {
33
+ try {
34
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
35
+ if (r.dispose) {
36
+ var result = r.dispose.call(r.value);
37
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
38
+ }
39
+ else s |= 1;
40
+ }
41
+ catch (e) {
42
+ fail(e);
43
+ }
44
+ }
45
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
46
+ if (env.hasError) throw env.error;
47
+ }
48
+ return next();
49
+ };
50
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ });
54
+ import { SessionLogOffset, SessionSeq, isAppendSurfaceEvent } from '@unieai/rabi-session';
55
+ import { RemoteError, remoteErrorOf } from '@unieai/rabi-typert-protocol';
56
+ import { DEFAULT_MAX_MESSAGES, paginate, pageRecords, entryFor, addressId, validateHistoryWindow, validateAddress, rejectNotFound, } from "../history.js";
57
+ import { EventListener, ProjectionListener } from "./listener.js";
58
+ import { SessionAssistantStreamsListener } from "./assistant-stream.js";
59
+ /** Session snapshots do not share lifetime with passive subscriptions. */
60
+ export class HistoryController {
61
+ ctx;
62
+ /** Reconnect state for this controller's assistant subscriptions. */
63
+ streamsListener;
64
+ /** @param ctx - Host context carrying Session reads and projections. */
65
+ constructor(ctx) {
66
+ this.ctx = ctx;
67
+ this.streamsListener = new SessionAssistantStreamsListener(this.ctx);
68
+ }
69
+ /**
70
+ * Read a passive page of Session events at an exact cut.
71
+ * @param request - Session identity and optional cut and page window.
72
+ * @param signal - read cancellation.
73
+ * @returns a page at the supplied cut, or the observed log end when omitted.
74
+ */
75
+ async events(request, signal) {
76
+ const spec = resolveHistoryRequest(request);
77
+ try {
78
+ return await this.usingObservation({ sessionId: addressId(request.address), projection: request.address.kind === 'subagent' }, signal, (observation) => {
79
+ validateObservationAddress(request.address, observation);
80
+ return history(observation, spec);
81
+ });
82
+ }
83
+ catch (error) {
84
+ if (remoteErrorOf(error)?.code === 'session/not-found')
85
+ rejectNotFound(request.address);
86
+ throw error;
87
+ }
88
+ }
89
+ /**
90
+ * Subscribe to Session events without reading or activating the Session.
91
+ * @param request - Session address to subscribe.
92
+ * @param signal - stream cancellation.
93
+ * @returns subscription readiness followed by event frames; readiness does not establish existence.
94
+ */
95
+ async *observeEvent(request, signal) {
96
+ const env_1 = { stack: [], error: void 0, hasError: false };
97
+ try {
98
+ const listener = __addDisposableResource(env_1, new EventListener(this.ctx, addressId(request.address), signal), false);
99
+ yield { type: 'ready' };
100
+ yield* listener.events();
101
+ }
102
+ catch (e_1) {
103
+ env_1.error = e_1;
104
+ env_1.hasError = true;
105
+ }
106
+ finally {
107
+ __disposeResources(env_1);
108
+ }
109
+ }
110
+ /**
111
+ * Read exact projections or migration cache hints without activating the Session.
112
+ * @param request - Session identity whose exact projection baseline is required.
113
+ * @param signal - read cancellation.
114
+ * @returns exact sequenced values, migration cache hints, or null when absent.
115
+ */
116
+ async projections(request, signal) {
117
+ const { sessionId } = request;
118
+ if (sessionId.length === 0) {
119
+ throw new RemoteError('gateway/bad-request', 'sessionId must not be empty', {});
120
+ }
121
+ try {
122
+ signal.throwIfAborted();
123
+ const live = this.ctx.sessions.get(sessionId);
124
+ if (live !== undefined) {
125
+ const snapshot = this.ctx.sessionProjections.snapshot(live);
126
+ return { kind: 'sequenced', asOfSeq: snapshot.asOfSeq, values: snapshot.values };
127
+ }
128
+ else {
129
+ const stored = await this.ctx.get('sessionPersistence')?.stat(sessionId, { signal });
130
+ signal.throwIfAborted();
131
+ if (stored?.formatStatus === 'migration-required') {
132
+ const cached = this.ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header);
133
+ return { kind: 'migration-required', values: { ...cached?.values } };
134
+ }
135
+ return await this.usingObservation({ sessionId: request.sessionId, projection: true }, signal, observation => ({
136
+ kind: 'sequenced',
137
+ ...projections(observation),
138
+ }));
139
+ }
140
+ }
141
+ catch (error) {
142
+ const code = typeof error === 'object' && error !== null && 'code' in error ? error.code : undefined;
143
+ if (code === 'SESSION_QUERY_SESSION_NOT_FOUND' || code === 'session/not-found') {
144
+ return null;
145
+ }
146
+ if (signal.aborted || code === 'SESSION_QUERY_ABORTED') {
147
+ throw new RemoteError('gateway/cancelled', 'Session projection read was cancelled', {}, { cause: error });
148
+ }
149
+ if (remoteErrorOf(error) !== undefined)
150
+ throw error;
151
+ throw new RemoteError('gateway/internal', 'Session projection read failed', {}, { cause: error });
152
+ }
153
+ }
154
+ /**
155
+ * Subscribe to projection changes without reading a baseline.
156
+ * @param request - Session identity to subscribe without reading a baseline.
157
+ * @param signal - stream cancellation.
158
+ * @returns readiness followed by one change frame per committed event, listing every key it changed.
159
+ */
160
+ async *observeProjections(request, signal) {
161
+ const env_2 = { stack: [], error: void 0, hasError: false };
162
+ try {
163
+ const listener = __addDisposableResource(env_2, new ProjectionListener(this.ctx, request.sessionId, signal), false);
164
+ yield { type: 'ready' };
165
+ yield* listener.changes();
166
+ }
167
+ catch (e_2) {
168
+ env_2.error = e_2;
169
+ env_2.hasError = true;
170
+ }
171
+ finally {
172
+ __disposeResources(env_2);
173
+ }
174
+ }
175
+ /**
176
+ * Read bounded committed assistant messages through a stopping cursor.
177
+ * @param sessionId - Session whose committed assistant messages are requested.
178
+ * @param afterSeq - exclusive lower bound.
179
+ * @param throughSeq - inclusive stopping-state cursor.
180
+ * @param maxMessages - positive assistant record limit.
181
+ * @param signal - caller cancellation, independent of a completed wait deadline.
182
+ * @returns newest-first assistant messages and whether further matching records were omitted.
183
+ */
184
+ async assistantOutput(sessionId, afterSeq, throughSeq, maxMessages, signal) {
185
+ return this.usingObservation({ sessionId, projection: false }, signal, (observation) => {
186
+ if (throughSeq > observation.cursor) {
187
+ throw new RemoteError('gateway/internal', 'Session history no longer covers the wait cursor', {});
188
+ }
189
+ const records = [];
190
+ const events = observation.events;
191
+ for (let index = throughSeq; index > afterSeq; index--) {
192
+ const event = events[index];
193
+ if (event.type !== 'assistant/message' || !isAppendSurfaceEvent(event))
194
+ continue;
195
+ if (records.length === maxMessages)
196
+ return { records, truncated: true };
197
+ records.push(entryFor(event));
198
+ }
199
+ return { records, truncated: false };
200
+ });
201
+ }
202
+ async usingObservation({ sessionId, projection }, signal, callback) {
203
+ const env_3 = { stack: [], error: void 0, hasError: false };
204
+ try {
205
+ let observation;
206
+ try {
207
+ observation = await this.ctx.sessionQuery.observeSession(sessionId, { signal, projectionMode: projection ? 'all' : 'none' });
208
+ }
209
+ catch (error) {
210
+ const code = error?.code;
211
+ if (code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
212
+ throw new RemoteError('session/not-found', `session "${sessionId}" not found`, { sessionId });
213
+ }
214
+ if (code === 'SESSION_QUERY_ABORTED') {
215
+ // Keep the query's own message: cancellation detail was visible before this mapping.
216
+ throw new RemoteError('gateway/cancelled', error instanceof Error ? error.message : 'Session read was cancelled', {}, { cause: error });
217
+ }
218
+ throw error;
219
+ }
220
+ try {
221
+ signal.throwIfAborted();
222
+ }
223
+ catch (error) {
224
+ observation[Symbol.dispose]();
225
+ throw error;
226
+ }
227
+ if (callback === undefined)
228
+ return observation;
229
+ const ownedObservation = __addDisposableResource(env_3, observation, false);
230
+ return await callback(ownedObservation);
231
+ }
232
+ catch (e_3) {
233
+ env_3.error = e_3;
234
+ env_3.hasError = true;
235
+ }
236
+ finally {
237
+ __disposeResources(env_3);
238
+ }
239
+ }
240
+ }
241
+ /**
242
+ * Validate an Address against the exact read used by a Controller.
243
+ * @param address - caller-supplied Session address.
244
+ * @param observation - borrowed read; subagent addresses require projections.
245
+ */
246
+ export function validateObservationAddress(address, observation) {
247
+ if (observation.header.cwd === undefined)
248
+ rejectNotFound(address);
249
+ validateAddress(address, observation.header, observation.inheritedEventCount, observation.projections);
250
+ }
251
+ /**
252
+ * Convert a borrowed observation to one page without acquiring or retaining it.
253
+ * @param observation - exact read cut owned by the caller.
254
+ * @param request - validated page window and optional inclusive cut.
255
+ * @returns a chronological page at the requested cut.
256
+ */
257
+ export function history(observation, request) {
258
+ const cursor = request.throughSeq === undefined ? observation.cursor
259
+ : request.throughSeq === -1 ? -1 : SessionSeq(request.throughSeq);
260
+ if (cursor > observation.cursor) {
261
+ throw new RemoteError('gateway/bad-request', `session history cut ${String(cursor)} exceeds ${String(observation.cursor)}`, {});
262
+ }
263
+ const page = paginate(observation.events, request.beforeSeq === undefined ? undefined : SessionLogOffset(request.beforeSeq), request.maxMessages, cursor, request.turnWindow);
264
+ return { cursor, records: pageRecords(page.events), hasMore: page.hasMore };
265
+ }
266
+ /**
267
+ * Convert the projection baseline without acquiring or retaining its observation.
268
+ * @param observation - projected read cut owned by the caller.
269
+ * @returns the exact baseline; missing projection support fails explicitly.
270
+ */
271
+ export function projections(observation) {
272
+ const snapshot = observation.projections;
273
+ if (snapshot === undefined)
274
+ throw new RemoteError('session/projections-unavailable', 'Session projections are unavailable', {});
275
+ return { asOfSeq: snapshot.asOfSeq, values: snapshot.values };
276
+ }
277
+ /**
278
+ * Validate and resolve the history page window.
279
+ * @param request - external history window.
280
+ * @returns the validated request with an explicit message budget.
281
+ */
282
+ export function resolveHistoryRequest(request) {
283
+ if (request.throughSeq !== undefined
284
+ && (!Number.isSafeInteger(request.throughSeq) || request.throughSeq < -1 || Object.is(request.throughSeq, -0))) {
285
+ throw new RemoteError('gateway/bad-request', 'throughSeq must be an integer greater than or equal to -1', {});
286
+ }
287
+ if (request.beforeSeq !== undefined
288
+ && (!Number.isSafeInteger(request.beforeSeq) || request.beforeSeq < 0 || Object.is(request.beforeSeq, -0))) {
289
+ throw new RemoteError('gateway/bad-request', 'beforeSeq must be a non-negative safe integer', {});
290
+ }
291
+ validateHistoryWindow(request);
292
+ return { ...request, maxMessages: request.maxMessages ?? DEFAULT_MAX_MESSAGES };
293
+ }
@@ -0,0 +1,105 @@
1
+ /** Passive per-Session streams; subscriptions never acquire Session observations. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import type { Session, SessionEvent, SessionId } from '@unieai/rabi-session';
4
+ import type { SessionProjectionChange, SessionEventEntry } from '../types.ts';
5
+ /** Raw history notifications buffered before an opening cut is known. */
6
+ export type EventItem = {
7
+ readonly type: 'event';
8
+ readonly session: Session;
9
+ readonly event: SessionEvent;
10
+ } | {
11
+ readonly type: 'created';
12
+ readonly session: Session;
13
+ readonly end: number;
14
+ };
15
+ /** A single subscription buffers before either consumption mode starts. */
16
+ export declare class EventListener implements Disposable {
17
+ private readonly buffer;
18
+ private readonly disposes;
19
+ private firstReceivedSeq;
20
+ private nextExpectedSeq;
21
+ /**
22
+ * @param ctx - context owning the event registrations.
23
+ * @param sessionId - Session whose notifications are emitted.
24
+ * @param signal - cancellation that wakes consumers.
25
+ * @param queue - optional caller-owned buffer; only an internally created buffer is disposed here.
26
+ */
27
+ constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal, queue?: Pick<ListenerBuffer<SessionEventEntry>, 'createInput' | 'capture'>);
28
+ /** Consume notifications without reading history.
29
+ * @returns event frames from the first received event, without loading a baseline. */
30
+ events(): AsyncIterable<SessionEventEntry>;
31
+ /** Set the inclusive opening cut for buffered history notifications.
32
+ * @param cursor - snapshot cut set before consuming the queue. */
33
+ setCursor(cursor: number): void;
34
+ private transform;
35
+ private iterate;
36
+ private recordFirst;
37
+ [Symbol.dispose](): void;
38
+ }
39
+ /**
40
+ * Select the uncovered events represented by one notification.
41
+ * @param item - one buffered notification.
42
+ * @param next - next required seq, or undefined before the first event.
43
+ * @returns uncovered events and the next required seq without acquiring an observation.
44
+ */
45
+ export declare function eventItem(item: EventItem, next?: number): {
46
+ events: readonly SessionEvent[];
47
+ next: number | undefined;
48
+ };
49
+ /** Projection changes of one Session, one change per committed event that changed a projection. */
50
+ export declare class ProjectionListener implements Disposable {
51
+ private readonly buffer;
52
+ /**
53
+ * @param ctx - context owning projection notifications.
54
+ * @param sessionId - Session whose notifications are emitted.
55
+ * @param signal - cancellation that removes registrations and wakes consumers.
56
+ */
57
+ constructor(ctx: Context, sessionId: SessionId, signal: AbortSignal);
58
+ /** Consume per-event projection changes.
59
+ * @returns validated change frames, one per committed event; projection seqs need not be contiguous. */
60
+ changes(): AsyncIterable<SessionProjectionChange>;
61
+ [Symbol.dispose](): void;
62
+ }
63
+ /** Owns buffering, callback failure and registration cleanup for one consumer. */
64
+ export declare class ListenerBuffer<T> implements Disposable {
65
+ private readonly values;
66
+ private readonly transformIds;
67
+ private readonly transforms;
68
+ private readonly cleanup;
69
+ private wake;
70
+ private closed;
71
+ private failure;
72
+ private consumed;
73
+ constructor(ctx: Context, signal: AbortSignal);
74
+ /**
75
+ * Register cleanup, or run it immediately when already closed.
76
+ * @param dispose - synchronous cleanup.
77
+ */
78
+ own(dispose: () => void): void;
79
+ /**
80
+ * Contain producer failure and wake the consumer with that failure.
81
+ * @param action - synchronous producer operation.
82
+ */
83
+ capture(action: () => void): void;
84
+ /**
85
+ * Register a dequeue transform and obtain its write-only input.
86
+ * @param transform - conversion bound once and evaluated when each input is dequeued.
87
+ * @returns a write-only input sharing this buffer's storage and lifetime.
88
+ * @throws when this buffer is already closed.
89
+ */
90
+ createInput<Input>(transform: (item: Input) => Iterable<T>): {
91
+ append(item: Input): void;
92
+ prepend(item: Input): void;
93
+ };
94
+ /**
95
+ * Consume queued values once, releasing the buffer when iteration ends.
96
+ * @returns transformed output values.
97
+ */
98
+ items(): AsyncIterable<T>;
99
+ private throwIfFailed;
100
+ /** @returns whether disposal ended this buffer while a transform was yielding. */
101
+ private isClosed;
102
+ private notify;
103
+ [Symbol.dispose](): void;
104
+ }
105
+ //# sourceMappingURL=listener.d.ts.map
@@ -0,0 +1,296 @@
1
+ /** Passive per-Session streams; subscriptions never acquire Session observations. */
2
+ import { Deque } from '@unieai/rabi-deque';
3
+ import { SessionLogOffset } from '@unieai/rabi-session';
4
+ import { RemoteError } from '@unieai/rabi-typert-protocol';
5
+ import { entryFor } from "../history.js";
6
+ /** A single subscription buffers before either consumption mode starts. */
7
+ export class EventListener {
8
+ buffer;
9
+ disposes = [];
10
+ firstReceivedSeq;
11
+ nextExpectedSeq;
12
+ /**
13
+ * @param ctx - context owning the event registrations.
14
+ * @param sessionId - Session whose notifications are emitted.
15
+ * @param signal - cancellation that wakes consumers.
16
+ * @param queue - optional caller-owned buffer; only an internally created buffer is disposed here.
17
+ */
18
+ constructor(ctx, sessionId, signal, queue) {
19
+ signal.throwIfAborted();
20
+ const buffer = queue ?? new ListenerBuffer(ctx, signal);
21
+ this.buffer = queue === undefined ? buffer : undefined;
22
+ const input = buffer.createInput(item => this.transform(item));
23
+ const target = sessionId;
24
+ try {
25
+ this.disposes.push(ctx.on('session/event', (session, event) => {
26
+ if (session.id !== target)
27
+ return;
28
+ buffer.capture(() => {
29
+ this.recordFirst(event.seq);
30
+ input.append({ type: 'event', session, event });
31
+ });
32
+ }, { global: true }));
33
+ this.disposes.push(ctx.on('session/created', (session) => {
34
+ if (session.id !== target)
35
+ return;
36
+ buffer.capture(() => {
37
+ if (session.firstLiveSeq < session.seq)
38
+ this.recordFirst(session.firstLiveSeq);
39
+ input.prepend({ type: 'created', session, end: session.seq });
40
+ });
41
+ }, { global: true }));
42
+ this.buffer?.own(() => { this[Symbol.dispose](); });
43
+ }
44
+ catch (error) {
45
+ this[Symbol.dispose]();
46
+ throw error;
47
+ }
48
+ }
49
+ /** Consume notifications without reading history.
50
+ * @returns event frames from the first received event, without loading a baseline. */
51
+ events() {
52
+ return this.iterate();
53
+ }
54
+ /** Set the inclusive opening cut for buffered history notifications.
55
+ * @param cursor - snapshot cut set before consuming the queue. */
56
+ setCursor(cursor) {
57
+ this.nextExpectedSeq = cursor + 1;
58
+ }
59
+ *transform(item) {
60
+ if (this.disposes.length === 0)
61
+ return;
62
+ this.nextExpectedSeq ??= this.firstReceivedSeq;
63
+ const result = eventItem(item, this.nextExpectedSeq);
64
+ this.nextExpectedSeq = result.next;
65
+ for (const event of result.events) {
66
+ if (this.disposes.length === 0)
67
+ return;
68
+ yield entryFor(event);
69
+ }
70
+ }
71
+ async *iterate() {
72
+ if (this.buffer === undefined)
73
+ throw new Error('Consume the externally owned history buffer directly');
74
+ try {
75
+ yield* this.buffer.items();
76
+ }
77
+ finally {
78
+ this[Symbol.dispose]();
79
+ }
80
+ }
81
+ recordFirst(seq) {
82
+ this.firstReceivedSeq = this.firstReceivedSeq === undefined ? seq : Math.min(this.firstReceivedSeq, seq);
83
+ }
84
+ [Symbol.dispose]() {
85
+ for (const dispose of this.disposes.splice(0).reverse())
86
+ dispose();
87
+ this.buffer?.[Symbol.dispose]();
88
+ }
89
+ }
90
+ /**
91
+ * Select the uncovered events represented by one notification.
92
+ * @param item - one buffered notification.
93
+ * @param next - next required seq, or undefined before the first event.
94
+ * @returns uncovered events and the next required seq without acquiring an observation.
95
+ */
96
+ export function eventItem(item, next) {
97
+ if (item.type === 'event') {
98
+ if (next !== undefined && item.event.seq < next)
99
+ return { events: [], next };
100
+ if (next !== undefined && item.event.seq !== next) {
101
+ throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {});
102
+ }
103
+ return { events: [item.event], next: item.event.seq + 1 };
104
+ }
105
+ const start = next ?? item.session.firstLiveSeq;
106
+ if (start >= item.end)
107
+ return { events: [], next };
108
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session-created history adaptation.
109
+ const events = item.session.snapshotEvents(SessionLogOffset(start), SessionLogOffset(item.end));
110
+ for (const event of events) {
111
+ if (next !== undefined && event.seq !== next) {
112
+ throw new RemoteError('gateway/internal', `session event stream skipped seq ${String(next)}`, {});
113
+ }
114
+ next = event.seq + 1;
115
+ }
116
+ return { events, next };
117
+ }
118
+ /** Projection changes of one Session, one change per committed event that changed a projection. */
119
+ export class ProjectionListener {
120
+ buffer;
121
+ /**
122
+ * @param ctx - context owning projection notifications.
123
+ * @param sessionId - Session whose notifications are emitted.
124
+ * @param signal - cancellation that removes registrations and wakes consumers.
125
+ */
126
+ constructor(ctx, sessionId, signal) {
127
+ this.buffer = new ListenerBuffer(ctx, signal);
128
+ const input = this.buffer.createInput(item => [item]);
129
+ const target = sessionId;
130
+ try {
131
+ this.buffer.own(ctx.sessionProjections.onEventChanged((session, changes, seq) => {
132
+ if (session.id !== target)
133
+ return;
134
+ this.buffer.capture(() => {
135
+ // Every projection definition validates its value before change publication.
136
+ const change = { type: 'projection', seq, changes: changes };
137
+ input.append({ session, change });
138
+ });
139
+ }));
140
+ }
141
+ catch (error) {
142
+ this.buffer[Symbol.dispose]();
143
+ throw error;
144
+ }
145
+ }
146
+ /** Consume per-event projection changes.
147
+ * @returns validated change frames, one per committed event; projection seqs need not be contiguous. */
148
+ async *changes() {
149
+ try {
150
+ for await (const { change } of this.buffer.items()) {
151
+ yield change;
152
+ }
153
+ }
154
+ finally {
155
+ this[Symbol.dispose]();
156
+ }
157
+ }
158
+ [Symbol.dispose]() {
159
+ this.buffer[Symbol.dispose]();
160
+ }
161
+ }
162
+ /** Owns buffering, callback failure and registration cleanup for one consumer. */
163
+ export class ListenerBuffer {
164
+ values = new Deque();
165
+ transformIds = new Deque();
166
+ transforms = [];
167
+ cleanup = [];
168
+ wake;
169
+ closed = false;
170
+ failure;
171
+ consumed = false;
172
+ constructor(ctx, signal) {
173
+ signal.throwIfAborted();
174
+ const close = () => { this[Symbol.dispose](); };
175
+ signal.addEventListener('abort', close, { once: true });
176
+ this.own(() => { signal.removeEventListener('abort', close); });
177
+ try {
178
+ const dispose = ctx.effect(() => close, 'session-controller.listener-buffer');
179
+ this.own(() => { void dispose(); });
180
+ }
181
+ catch (error) {
182
+ this[Symbol.dispose]();
183
+ throw error;
184
+ }
185
+ }
186
+ /**
187
+ * Register cleanup, or run it immediately when already closed.
188
+ * @param dispose - synchronous cleanup.
189
+ */
190
+ own(dispose) {
191
+ if (this.closed)
192
+ dispose();
193
+ else
194
+ this.cleanup.push(dispose);
195
+ }
196
+ /**
197
+ * Contain producer failure and wake the consumer with that failure.
198
+ * @param action - synchronous producer operation.
199
+ */
200
+ capture(action) {
201
+ if (this.closed)
202
+ return;
203
+ try {
204
+ action();
205
+ }
206
+ catch (error) {
207
+ this.failure = { error };
208
+ this[Symbol.dispose]();
209
+ }
210
+ }
211
+ /**
212
+ * Register a dequeue transform and obtain its write-only input.
213
+ * @param transform - conversion bound once and evaluated when each input is dequeued.
214
+ * @returns a write-only input sharing this buffer's storage and lifetime.
215
+ * @throws when this buffer is already closed.
216
+ */
217
+ createInput(transform) {
218
+ if (this.closed)
219
+ throw new Error('Cannot register a transform on a closed listener buffer');
220
+ const transformId = this.transforms.length;
221
+ // Only this typed input can enqueue values with its private transform id.
222
+ this.transforms.push(value => transform(value));
223
+ return {
224
+ append: (item) => {
225
+ if (this.closed)
226
+ return;
227
+ this.values.pushBack(item);
228
+ this.transformIds.pushBack(transformId);
229
+ this.notify();
230
+ },
231
+ prepend: (item) => {
232
+ if (this.closed)
233
+ return;
234
+ this.values.pushFront(item);
235
+ this.transformIds.pushFront(transformId);
236
+ this.notify();
237
+ },
238
+ };
239
+ }
240
+ /**
241
+ * Consume queued values once, releasing the buffer when iteration ends.
242
+ * @returns transformed output values.
243
+ */
244
+ async *items() {
245
+ if (this.consumed)
246
+ throw new RemoteError('gateway/internal', 'Session listener already has a consumer', {});
247
+ this.consumed = true;
248
+ try {
249
+ for (;;) {
250
+ if (this.failure !== undefined)
251
+ throw this.failure.error;
252
+ if (this.closed)
253
+ return;
254
+ if (this.transformIds.size === 0) {
255
+ await new Promise((resolve) => { this.wake = resolve; });
256
+ continue;
257
+ }
258
+ const transformId = this.transformIds.popFront();
259
+ const value = this.values.popFront();
260
+ for (const item of this.transforms[transformId](value)) {
261
+ this.throwIfFailed();
262
+ if (this.isClosed())
263
+ return;
264
+ yield item;
265
+ }
266
+ }
267
+ }
268
+ finally {
269
+ this[Symbol.dispose]();
270
+ }
271
+ }
272
+ throwIfFailed() {
273
+ if (this.failure !== undefined)
274
+ throw this.failure.error;
275
+ }
276
+ /** @returns whether disposal ended this buffer while a transform was yielding. */
277
+ isClosed() {
278
+ return this.closed;
279
+ }
280
+ notify() {
281
+ const wake = this.wake;
282
+ this.wake = undefined;
283
+ wake?.();
284
+ }
285
+ [Symbol.dispose]() {
286
+ if (this.closed)
287
+ return;
288
+ this.closed = true;
289
+ this.values.clear();
290
+ this.transformIds.clear();
291
+ this.transforms.length = 0;
292
+ this.notify();
293
+ for (const dispose of this.cleanup.splice(0).reverse())
294
+ dispose();
295
+ }
296
+ }