@opengeni/events 0.2.8 → 0.3.1
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/dist/index.d.ts +82 -5
- package/dist/index.js +136 -21
- package/dist/index.js.map +1 -1
- package/package.json +14 -14
- package/src/coalesce.ts +20 -19
- package/src/index.ts +265 -27
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { SessionEvent } from '@opengeni/contracts';
|
|
2
|
-
import { Database, AppendEventInput } from '@opengeni/db';
|
|
1
|
+
import { SessionEvent, WorkspaceControlEvent } from '@opengeni/contracts';
|
|
2
|
+
import { appendSessionEvents, Database, AppendEventInput } from '@opengeni/db';
|
|
3
|
+
import { connect } from 'nats';
|
|
3
4
|
export { NatsConnection, connect, nkeys } from 'nats';
|
|
4
5
|
|
|
5
6
|
declare function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent[];
|
|
@@ -114,6 +115,8 @@ type EventLogger = {
|
|
|
114
115
|
};
|
|
115
116
|
type EventBusOptions = {
|
|
116
117
|
logger?: EventLogger;
|
|
118
|
+
/** Test/host transport seam; production defaults to the nats.js connector. */
|
|
119
|
+
connect?: typeof connect;
|
|
117
120
|
};
|
|
118
121
|
|
|
119
122
|
/**
|
|
@@ -138,6 +141,22 @@ interface RequestConnection {
|
|
|
138
141
|
timeout: number;
|
|
139
142
|
}): Promise<RequestReply>;
|
|
140
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* The raw subscribe/publish surface the selfhosted OP-STREAM transport consumes
|
|
146
|
+
* (structurally identical to `@opengeni/runtime`'s `NatsOpStreamConnection`):
|
|
147
|
+
* a plain subscription for the runner's fire-and-forget op frames
|
|
148
|
+
* (`agent.<ws>.<id>.op.<op_id>`) and a plain publish for the server's acks
|
|
149
|
+
* (`agent.<ws>.<id>.ack`). Same managed connection as everything else — a NATS
|
|
150
|
+
* connection natively supports all of it; there is NEVER a second connection.
|
|
151
|
+
*/
|
|
152
|
+
interface OpStreamConnection {
|
|
153
|
+
subscribe(subject: string): AsyncIterable<{
|
|
154
|
+
data: Uint8Array;
|
|
155
|
+
}> & {
|
|
156
|
+
unsubscribe(): void;
|
|
157
|
+
};
|
|
158
|
+
publish(subject: string, payload: Uint8Array): void;
|
|
159
|
+
}
|
|
141
160
|
/**
|
|
142
161
|
* A handler answering a request/reply on a subscribed subject: given the request
|
|
143
162
|
* bytes (+ the concrete subject the message landed on, for `agent.<ws>.<id>.rpc`
|
|
@@ -149,6 +168,10 @@ type RequestHandler = (request: Uint8Array, subject: string) => Promise<Uint8Arr
|
|
|
149
168
|
type EventBus = {
|
|
150
169
|
publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;
|
|
151
170
|
subscribe: (workspaceId: string, sessionId: string, onEvents: (events: SessionEvent[]) => void | Promise<void>) => Promise<() => void>;
|
|
171
|
+
/** Best-effort live invalidation; the event is already durable in Postgres. */
|
|
172
|
+
publishWorkspaceControl: (workspaceId: string, event: WorkspaceControlEvent) => Promise<void>;
|
|
173
|
+
/** One workspace subscription fans a control change to every open descendant view. */
|
|
174
|
+
subscribeWorkspaceControl: (workspaceId: string, onEvent: (event: WorkspaceControlEvent) => void | Promise<void>) => Promise<() => void>;
|
|
152
175
|
/**
|
|
153
176
|
* Issue a binary request/reply on a subject over the bus's NATS connection
|
|
154
177
|
* (the selfhosted control plane: `agent.<ws>.<id>.rpc`). A new usage of what was
|
|
@@ -182,6 +205,12 @@ type EventBus = {
|
|
|
182
205
|
* plane injects this so the transport never opens a second connection.
|
|
183
206
|
*/
|
|
184
207
|
getRequestConnection: () => RequestConnection;
|
|
208
|
+
/**
|
|
209
|
+
* The `OpStreamConnection` accessor the selfhosted op-stream transport
|
|
210
|
+
* consumes (`NatsOpStreamTransport`) — the same managed connection again.
|
|
211
|
+
* Optional so bus test doubles that never exercise op-stream stay valid.
|
|
212
|
+
*/
|
|
213
|
+
getOpStreamConnection?: () => OpStreamConnection;
|
|
185
214
|
isConnected?: () => boolean;
|
|
186
215
|
close: () => Promise<void>;
|
|
187
216
|
};
|
|
@@ -237,8 +266,56 @@ type NatsConnectAuth = {
|
|
|
237
266
|
declare function createResponderConnection(natsUrl: string, auth: NatsConnectAuth, subject: string, handler: RequestHandler, options?: {
|
|
238
267
|
name?: string;
|
|
239
268
|
logger?: EventLogger;
|
|
269
|
+
connect?: typeof connect;
|
|
240
270
|
}): Promise<ResponderConnection>;
|
|
241
|
-
|
|
242
|
-
|
|
271
|
+
/**
|
|
272
|
+
* Optional timing seam for {@link appendAndPublishEvents}: `onAppend` fires after
|
|
273
|
+
* the durable DB write, `onPublish` after the best-effort live fan-out (on both
|
|
274
|
+
* success AND failure of the publish, so a broker blip still records its latency).
|
|
275
|
+
* Kept as a plain callback so the events package takes no dependency on the
|
|
276
|
+
* observability package; the worker wires it to Prometheus histograms.
|
|
277
|
+
*/
|
|
278
|
+
type AppendPublishObserver = {
|
|
279
|
+
onAppend?: (info: {
|
|
280
|
+
durationSeconds: number;
|
|
281
|
+
count: number;
|
|
282
|
+
}) => void;
|
|
283
|
+
onPublish?: (info: {
|
|
284
|
+
durationSeconds: number;
|
|
285
|
+
count: number;
|
|
286
|
+
}) => void;
|
|
287
|
+
};
|
|
288
|
+
type AppendPublishOptions = AppendPublishObserver & {
|
|
289
|
+
/** Test/host persistence seam; production uses the database implementation. */
|
|
290
|
+
appendSessionEvents?: typeof appendSessionEvents;
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* Invoke a phase-timing callback with the elapsed seconds since `startedAt` and the
|
|
294
|
+
* event count, swallowing any throw so a metrics sink can never break the
|
|
295
|
+
* append/publish path. Exported for direct unit testing: the wider test suite
|
|
296
|
+
* installs a process-global `mock.module("@opengeni/events")` that stubs
|
|
297
|
+
* `appendAndPublishEvents` (spreading the real module for everything else), so the
|
|
298
|
+
* observer wiring can only be exercised through a helper that survives that mock.
|
|
299
|
+
*/
|
|
300
|
+
declare function observeSince(fn: ((info: {
|
|
301
|
+
durationSeconds: number;
|
|
302
|
+
count: number;
|
|
303
|
+
}) => void) | undefined, startedAt: number, count: number): void;
|
|
304
|
+
declare function appendAndPublishEvents(db: Database, bus: EventBus, workspaceId: string, sessionId: string, events: AppendEventInput[], options?: AppendPublishOptions): Promise<SessionEvent[]>;
|
|
305
|
+
/**
|
|
306
|
+
* Best-effort live fanout for events another DB helper already committed in
|
|
307
|
+
* the same transaction as related durable state. This must never append again.
|
|
308
|
+
*/
|
|
309
|
+
declare function publishDurableSessionEvents(bus: EventBus, workspaceId: string, sessionId: string, appended: SessionEvent[], observe?: AppendPublishObserver): Promise<void>;
|
|
310
|
+
/** Best-effort fanout for a workspace-control event already committed in PostgreSQL. */
|
|
311
|
+
declare function publishDurableWorkspaceControlEvent(bus: EventBus, workspaceId: string, event: WorkspaceControlEvent): Promise<void>;
|
|
312
|
+
declare function appendAndPublishTurnEventsFenced(db: Database, bus: EventBus, workspaceId: string, sessionId: string, turnId: string, executionGeneration: number, attemptId: string, events: AppendEventInput[]): Promise<{
|
|
313
|
+
events: SessionEvent[];
|
|
314
|
+
accepted: boolean;
|
|
315
|
+
}>;
|
|
316
|
+
declare function formatSse<T extends {
|
|
317
|
+
sequence: number;
|
|
318
|
+
type: string;
|
|
319
|
+
}>(event: T): string;
|
|
243
320
|
|
|
244
|
-
export { type DecodedAuthRequest, type EventBus, type EventBusOptions, type EventLogger, type MintAuthResponseInput, type MintUserJwtInput, type NatsConnectAuth, type NatsPermission, type NatsPermissions, type RequestConnection, type RequestHandler, type RequestReply, type ResponderConnection, appendAndPublishEvents, coalesceSessionEventDeltas, createNatsEventBus, createResponderConnection, decodeAuthRequest, formatSse, mintAuthResponse, mintUserJwt, workspaceAgentPermissions };
|
|
321
|
+
export { type AppendPublishObserver, type AppendPublishOptions, type DecodedAuthRequest, type EventBus, type EventBusOptions, type EventLogger, type MintAuthResponseInput, type MintUserJwtInput, type NatsConnectAuth, type NatsPermission, type NatsPermissions, type OpStreamConnection, type RequestConnection, type RequestHandler, type RequestReply, type ResponderConnection, appendAndPublishEvents, appendAndPublishTurnEventsFenced, coalesceSessionEventDeltas, createNatsEventBus, createResponderConnection, decodeAuthRequest, formatSse, mintAuthResponse, mintUserJwt, observeSince, publishDurableSessionEvents, publishDurableWorkspaceControlEvent, workspaceAgentPermissions };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import {
|
|
3
|
+
appendSessionEvents,
|
|
4
|
+
appendSessionEventsForTurnAttempt,
|
|
5
|
+
sessionSubject
|
|
6
|
+
} from "@opengeni/db";
|
|
7
|
+
import {
|
|
8
|
+
connect,
|
|
9
|
+
JSONCodec
|
|
10
|
+
} from "nats";
|
|
4
11
|
|
|
5
12
|
// src/coalesce.ts
|
|
6
13
|
var COALESCIBLE_DELTA_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -17,13 +24,17 @@ function coalesceSessionEventDeltas(events) {
|
|
|
17
24
|
}
|
|
18
25
|
coalesced.push({
|
|
19
26
|
...run.first,
|
|
20
|
-
payload: run.first.type === "sandbox.command.output.delta" ?
|
|
21
|
-
chunk
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
+
payload: run.first.type === "sandbox.command.output.delta" ? (
|
|
28
|
+
// Sandbox output keeps its CANONICAL field (`chunk` — the terminal and
|
|
29
|
+
// projection read it) plus the stream/commandId identity of the run.
|
|
30
|
+
{
|
|
31
|
+
chunk: run.text,
|
|
32
|
+
coalescedUntil: run.lastSequence,
|
|
33
|
+
...run.sandboxStream !== void 0 ? { stream: run.sandboxStream } : {},
|
|
34
|
+
...run.sandboxCommandId !== void 0 ? { commandId: run.sandboxCommandId } : {},
|
|
35
|
+
...run.sandboxName !== void 0 ? { name: run.sandboxName } : {}
|
|
36
|
+
}
|
|
37
|
+
) : {
|
|
27
38
|
text: run.text,
|
|
28
39
|
coalescedUntil: run.lastSequence
|
|
29
40
|
}
|
|
@@ -318,7 +329,7 @@ async function createNatsEventBus(natsUrl, auth, options = {}) {
|
|
|
318
329
|
connectOptions.user = auth.user;
|
|
319
330
|
connectOptions.pass = auth.pass;
|
|
320
331
|
}
|
|
321
|
-
const nc = await connect(withReconnectDefaults(connectOptions));
|
|
332
|
+
const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));
|
|
322
333
|
let connected = true;
|
|
323
334
|
logConnectionStatus(nc, "event-bus", options.logger, (type) => {
|
|
324
335
|
if (type === "disconnect" || type === "reconnecting" || type === "staleConnection" || type === "error") {
|
|
@@ -330,28 +341,66 @@ async function createNatsEventBus(natsUrl, auth, options = {}) {
|
|
|
330
341
|
const requestConnection = {
|
|
331
342
|
request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeout)
|
|
332
343
|
};
|
|
344
|
+
const opStreamConnection = {
|
|
345
|
+
subscribe: (subject) => nc.subscribe(subject),
|
|
346
|
+
publish: (subject, payload) => {
|
|
347
|
+
nc.publish(subject, payload);
|
|
348
|
+
}
|
|
349
|
+
};
|
|
333
350
|
return {
|
|
334
351
|
publish: async (workspaceId, sessionId, events) => {
|
|
335
352
|
if (events.length === 0) {
|
|
336
353
|
return;
|
|
337
354
|
}
|
|
338
355
|
try {
|
|
339
|
-
nc.publish(
|
|
356
|
+
nc.publish(
|
|
357
|
+
sessionSubject(workspaceId, sessionId),
|
|
358
|
+
codec.encode({ workspaceId, sessionId, events })
|
|
359
|
+
);
|
|
340
360
|
} catch (error) {
|
|
341
|
-
(options.logger?.warn ?? silentLogger.warn)(
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
361
|
+
(options.logger?.warn ?? silentLogger.warn)(
|
|
362
|
+
"NATS live publish dropped; events are durable in the DB and reconcile on stream replay",
|
|
363
|
+
{
|
|
364
|
+
workspaceId,
|
|
365
|
+
sessionId,
|
|
366
|
+
error: error instanceof Error ? error.message : String(error)
|
|
367
|
+
}
|
|
368
|
+
);
|
|
346
369
|
return;
|
|
347
370
|
}
|
|
348
371
|
await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);
|
|
349
372
|
},
|
|
350
373
|
subscribe: async (workspaceId, sessionId, onEvents) => subscribeSession(nc, workspaceId, sessionId, onEvents),
|
|
374
|
+
publishWorkspaceControl: async (workspaceId, event) => {
|
|
375
|
+
try {
|
|
376
|
+
nc.publish(workspaceControlSubject(workspaceId), codec.encode(event));
|
|
377
|
+
} catch (error) {
|
|
378
|
+
(options.logger?.warn ?? silentLogger.warn)(
|
|
379
|
+
"NATS workspace-control invalidation dropped; clients reconcile from Postgres",
|
|
380
|
+
{
|
|
381
|
+
workspaceId,
|
|
382
|
+
revision: event.revision,
|
|
383
|
+
error: error instanceof Error ? error.message : String(error)
|
|
384
|
+
}
|
|
385
|
+
);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);
|
|
389
|
+
},
|
|
390
|
+
subscribeWorkspaceControl: async (workspaceId, onEvent) => {
|
|
391
|
+
const sub = nc.subscribe(workspaceControlSubject(workspaceId));
|
|
392
|
+
void (async () => {
|
|
393
|
+
for await (const msg of sub) {
|
|
394
|
+
await onEvent(codec.decode(msg.data));
|
|
395
|
+
}
|
|
396
|
+
})();
|
|
397
|
+
return () => sub.unsubscribe();
|
|
398
|
+
},
|
|
351
399
|
request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),
|
|
352
400
|
subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler),
|
|
353
401
|
subscribeAgentEvents: (subject, handler) => subscribeAgentEvents(nc, subject, handler),
|
|
354
402
|
getRequestConnection: () => requestConnection,
|
|
403
|
+
getOpStreamConnection: () => opStreamConnection,
|
|
355
404
|
isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),
|
|
356
405
|
close: async () => {
|
|
357
406
|
await nc.drain();
|
|
@@ -369,8 +418,12 @@ async function createResponderConnection(natsUrl, auth, subject, handler, option
|
|
|
369
418
|
} else if (auth.kind === "token") {
|
|
370
419
|
connectOptions.token = auth.token;
|
|
371
420
|
}
|
|
372
|
-
const nc = await connect(withReconnectDefaults(connectOptions));
|
|
373
|
-
logConnectionStatus(
|
|
421
|
+
const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));
|
|
422
|
+
logConnectionStatus(
|
|
423
|
+
nc,
|
|
424
|
+
options.name ? `auth-callout:${options.name}` : "auth-callout",
|
|
425
|
+
options.logger
|
|
426
|
+
);
|
|
374
427
|
const sub = nc.subscribe(subject);
|
|
375
428
|
void (async () => {
|
|
376
429
|
for await (const msg of sub) {
|
|
@@ -391,8 +444,32 @@ async function createResponderConnection(natsUrl, auth, subject, handler, option
|
|
|
391
444
|
}
|
|
392
445
|
};
|
|
393
446
|
}
|
|
394
|
-
|
|
395
|
-
|
|
447
|
+
function observeSince(fn, startedAt, count) {
|
|
448
|
+
if (!fn) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
try {
|
|
452
|
+
fn({ durationSeconds: Math.max(0, (performance.now() - startedAt) / 1e3), count });
|
|
453
|
+
} catch {
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
async function appendAndPublishEvents(db, bus, workspaceId, sessionId, events, options = {}) {
|
|
457
|
+
const appendStartedAt = performance.now();
|
|
458
|
+
const appended = await (options.appendSessionEvents ?? appendSessionEvents)(
|
|
459
|
+
db,
|
|
460
|
+
workspaceId,
|
|
461
|
+
sessionId,
|
|
462
|
+
events
|
|
463
|
+
);
|
|
464
|
+
observeSince(options.onAppend, appendStartedAt, appended.length);
|
|
465
|
+
await publishDurableSessionEvents(bus, workspaceId, sessionId, appended, options);
|
|
466
|
+
return appended;
|
|
467
|
+
}
|
|
468
|
+
async function publishDurableSessionEvents(bus, workspaceId, sessionId, appended, observe) {
|
|
469
|
+
if (appended.length === 0) {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
const publishStartedAt = performance.now();
|
|
396
473
|
try {
|
|
397
474
|
await bus.publish(workspaceId, sessionId, appended);
|
|
398
475
|
} catch (error) {
|
|
@@ -401,7 +478,38 @@ async function appendAndPublishEvents(db, bus, workspaceId, sessionId, events) {
|
|
|
401
478
|
error
|
|
402
479
|
);
|
|
403
480
|
}
|
|
404
|
-
|
|
481
|
+
observeSince(observe?.onPublish, publishStartedAt, appended.length);
|
|
482
|
+
}
|
|
483
|
+
async function publishDurableWorkspaceControlEvent(bus, workspaceId, event) {
|
|
484
|
+
try {
|
|
485
|
+
await bus.publishWorkspaceControl(workspaceId, event);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
console.warn(
|
|
488
|
+
`[events] workspace-control live publish failed for ${workspaceId} at revision ${event.revision}; the event is durable and reconciles on stream replay`,
|
|
489
|
+
error
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
async function appendAndPublishTurnEventsFenced(db, bus, workspaceId, sessionId, turnId, executionGeneration, attemptId, events) {
|
|
494
|
+
const result = await appendSessionEventsForTurnAttempt(
|
|
495
|
+
db,
|
|
496
|
+
workspaceId,
|
|
497
|
+
sessionId,
|
|
498
|
+
turnId,
|
|
499
|
+
executionGeneration,
|
|
500
|
+
attemptId,
|
|
501
|
+
events
|
|
502
|
+
);
|
|
503
|
+
if (result.events.length === 0) return result;
|
|
504
|
+
try {
|
|
505
|
+
await bus.publish(workspaceId, sessionId, result.events);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
console.warn(
|
|
508
|
+
`[events] live fenced publish failed for ${workspaceId}/${sessionId}/${turnId}@${executionGeneration}/${attemptId}; ${result.events.length} event(s) are durable`,
|
|
509
|
+
error
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
return result;
|
|
405
513
|
}
|
|
406
514
|
function subscribeSession(nc, workspaceId, sessionId, onEvents) {
|
|
407
515
|
const sub = nc.subscribe(sessionSubject(workspaceId, sessionId));
|
|
@@ -461,8 +569,12 @@ function formatSse(event) {
|
|
|
461
569
|
""
|
|
462
570
|
].join("\n");
|
|
463
571
|
}
|
|
572
|
+
function workspaceControlSubject(workspaceId) {
|
|
573
|
+
return `workspaces.${workspaceId}.control`;
|
|
574
|
+
}
|
|
464
575
|
export {
|
|
465
576
|
appendAndPublishEvents,
|
|
577
|
+
appendAndPublishTurnEventsFenced,
|
|
466
578
|
coalesceSessionEventDeltas,
|
|
467
579
|
connect2 as connect,
|
|
468
580
|
createNatsEventBus,
|
|
@@ -472,6 +584,9 @@ export {
|
|
|
472
584
|
mintAuthResponse,
|
|
473
585
|
mintUserJwt,
|
|
474
586
|
nkeys2 as nkeys,
|
|
587
|
+
observeSince,
|
|
588
|
+
publishDurableSessionEvents,
|
|
589
|
+
publishDurableWorkspaceControlEvent,
|
|
475
590
|
workspaceAgentPermissions
|
|
476
591
|
};
|
|
477
592
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/coalesce.ts","../src/nats-jwt.ts"],"sourcesContent":["import type { SessionBusMessage, SessionEvent } from \"@opengeni/contracts\";\nimport { appendSessionEvents, sessionSubject, type AppendEventInput, type Database } from \"@opengeni/db\";\nimport { connect, JSONCodec, type ConnectionOptions, type Msg, type NatsConnection, type Subscription } from \"nats\";\n\nconst codec = JSONCodec<SessionBusMessage | SessionEvent>();\n\nexport type EventLogger = {\n debug?: (message: string, attributes?: Record<string, unknown>) => void;\n warn?: (message: string, attributes?: Record<string, unknown>) => void;\n};\n\nexport type EventBusOptions = {\n logger?: EventLogger;\n};\n\nconst silentLogger: Required<EventLogger> = {\n debug: () => {},\n warn: () => {},\n};\n\nexport { coalesceSessionEventDeltas } from \"./coalesce\";\n\n/**\n * Reconnect + keepalive defaults applied to EVERY long-lived NATS connection\n * this package opens (the event bus AND the standalone auth-callout responder).\n *\n * The production outage these guard against: an in-cluster NATS broker pod\n * restart. nats.js's stock policy gives up after ~10 attempts (~20s) and the\n * client goes permanently CONNECTION_CLOSED — which takes the whole control\n * plane down with it: every session-create publishes events to NATS, and the\n * API-hosted auth-callout responder dies so BYO agents get \"authorization\n * violation\". Recovery then required a MANUAL api+worker restart. With these\n * options the client retries forever and auto-recovers the moment the broker\n * returns. Factored into one source of truth so the call sites never drift.\n *\n * - `reconnect` + `maxReconnectAttempts: -1` — never give up (infinite retry).\n * - `reconnectTimeWait` (2s base) + `reconnectJitter`/`reconnectJitterTLS`\n * (up to 1s) — a fleet of api/worker pods doesn't thundering-herd the broker\n * on recovery.\n * - `waitOnFirstConnect` — a broker briefly unavailable at boot must not\n * hard-fail the process; the client keeps trying instead of throwing.\n * - `pingInterval`/`maxPingOut` — promptly detect a silently-dead socket so the\n * reconnect machinery actually engages instead of hanging on a zombie.\n */\nconst RECONNECT_OPTIONS = {\n reconnect: true,\n maxReconnectAttempts: -1,\n reconnectTimeWait: 2_000,\n reconnectJitter: 1_000,\n reconnectJitterTLS: 1_000,\n waitOnFirstConnect: true,\n pingInterval: 20_000,\n maxPingOut: 3,\n} satisfies ConnectionOptions;\n\n/**\n * The single source of truth for a long-lived connection's resilience: merge the\n * reconnect/keepalive defaults UNDER the caller's connection options (servers +\n * optional auth/name). Every long-lived `connect()` in this package goes through\n * here so the two call sites can never diverge.\n */\nfunction withReconnectDefaults(options: ConnectionOptions): ConnectionOptions {\n return { ...RECONNECT_OPTIONS, ...options };\n}\n\n/** How long a best-effort publish waits on `flush()` before giving up (see `publish`). */\nconst PUBLISH_FLUSH_TIMEOUT_MS = 2_000;\n\n/**\n * Await `nc.flush()` but never longer than `timeoutMs`. With infinite reconnect a\n * `flush()` issued while the broker is down does NOT reject — it pends until the\n * broker returns, which can be minutes. Racing it against a timer keeps a long\n * outage from stalling an in-flight turn; the published message stays buffered\n * and is delivered on reconnect regardless. A flush rejection (connection fully\n * CLOSED) is swallowed here so the timeout race never leaks an unhandled\n * rejection — the caller's publish path is what logs the drop.\n */\nasync function flushWithTimeout(nc: NatsConnection, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n });\n try {\n await Promise.race([nc.flush().catch(() => undefined), timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Drain a long-lived connection's status async-iterator to the log so a future\n * broker outage is OBSERVABLE (disconnect → reconnecting → reconnect → update).\n * Fire-and-forget for the connection's lifetime; the loop ends when the\n * connection closes. `label` distinguishes the event-bus connection from the\n * auth-callout responder in the logs.\n */\nfunction logConnectionStatus(\n nc: NatsConnection,\n label: string,\n logger: EventLogger = silentLogger,\n onStatus?: (type: string) => void,\n): void {\n void (async () => {\n try {\n for await (const status of nc.status()) {\n onStatus?.(status.type);\n const attributes = { label, status: status.type, data: status.data };\n if (isWarnNatsStatus(status.type)) {\n (logger.warn ?? silentLogger.warn)(\"NATS connection status\", attributes);\n } else {\n (logger.debug ?? silentLogger.debug)(\"NATS connection status\", attributes);\n }\n }\n } catch {\n // The status iterator simply ends when the connection closes; never let it\n // throw out of this background loop.\n }\n })();\n}\n\nfunction isWarnNatsStatus(type: string): boolean {\n return type === \"disconnect\" || type === \"error\" || type === \"staleConnection\";\n}\n\nexport {\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n workspaceAgentPermissions,\n type DecodedAuthRequest,\n type MintAuthResponseInput,\n type MintUserJwtInput,\n type NatsPermission,\n type NatsPermissions,\n} from \"./nats-jwt\";\n\n// Re-export the raw NATS primitives a consumer needs to open a direct connection or\n// generate nkeys (the auth-callout responder's standalone connection, the\n// agent-simulating integration tests). This keeps `nats` an internal dependency of\n// this leaf — callers in the bun workspace reach it through @opengeni/events rather\n// than depending on `nats` directly.\nexport { connect, nkeys, type NatsConnection } from \"nats\";\n\n/**\n * A raw request/reply reply — just the response bytes. Mirrors the subset of the\n * NATS `Msg` shape a binary request/reply caller needs (`NatsControlRpc` consumes\n * exactly this). Kept minimal so the events package does not leak the `nats` `Msg`\n * type into the agent-loop-free runtime leaf.\n */\nexport type RequestReply = { data: Uint8Array };\n\n/**\n * The minimal request/reply connection the selfhosted control plane consumes\n * (structurally identical to `@opengeni/runtime`'s `NatsRequestConnection`). The\n * API/worker hand this accessor to `NatsControlRpc` so the control transport rides\n * the SAME managed NATS connection the event bus already owns — a NATS connection\n * natively supports both pub/sub and request/reply, so there is NEVER a second\n * connection.\n */\nexport interface RequestConnection {\n request(subject: string, payload: Uint8Array, opts: { timeout: number }): Promise<RequestReply>;\n}\n\n/**\n * A handler answering a request/reply on a subscribed subject: given the request\n * bytes (+ the concrete subject the message landed on, for `agent.<ws>.<id>.rpc`\n * style wildcard routing), return the response bytes to reply with. A thrown error\n * leaves the request unanswered (the caller's request times out / sees no\n * responder), which the control plane maps to `agent_offline` / reconnecting.\n */\nexport type RequestHandler = (request: Uint8Array, subject: string) => Promise<Uint8Array> | Uint8Array;\n\nexport type EventBus = {\n publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;\n subscribe: (workspaceId: string, sessionId: string, onEvents: (events: SessionEvent[]) => void | Promise<void>) => Promise<() => void>;\n /**\n * Issue a binary request/reply on a subject over the bus's NATS connection\n * (the selfhosted control plane: `agent.<ws>.<id>.rpc`). A new usage of what was\n * a one-way bus — same connection, native NATS request/reply. Rejects on a\n * no-responder (NATS 503) or a request timeout; the caller (`NatsControlRpc`)\n * maps those to `agent_offline` / `agent_reconnecting`, never a NotFound.\n */\n request: (subject: string, payload: Uint8Array, opts: { timeoutMs: number }) => Promise<RequestReply>;\n /**\n * Subscribe-and-reply on a subject (the responder side — the enrolled agent, or\n * a test stand-in for it): for every request on `subject`, call `handler` and\n * `respond` with its bytes over the SAME connection. Returns an unsubscribe fn.\n * A subject may be a NATS wildcard (e.g. `agent.*.*.rpc`).\n */\n subscribeRequests: (subject: string, handler: RequestHandler) => () => void;\n /**\n * Subscribe to the agent EVENT plane (the one-way fire-and-forget heartbeats +\n * going-offline the agent PUBLISHES on `agent.<ws>.<id>.events`, NOT a\n * request/reply). The M10 metrics-ingestion consumer subscribes the wildcard\n * `agent.*.*.events` and gets each raw payload plus its concrete subject (so it\n * can extract `<ws>`/`<id>` for the per-enrollment upsert). Returns an\n * unsubscribe fn. Decoding the AgentEvent is the caller's concern (this leaf\n * does not depend on `@opengeni/agent-proto`).\n */\n subscribeAgentEvents: (\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n ) => () => void;\n /**\n * The `RequestConnection` accessor the selfhosted `NatsControlRpc` consumes —\n * the SAME managed connection (pub/sub + request/reply share it). The control\n * plane injects this so the transport never opens a second connection.\n */\n getRequestConnection: () => RequestConnection;\n isConnected?: () => boolean;\n close: () => Promise<void>;\n};\n\n/**\n * Connect the event bus + control-plane request/reply over ONE managed NATS\n * connection. `auth` is the PRIVILEGED control-plane login (M-AUTH): when the\n * server runs with auth_callout, the api/worker authenticates as a static account\n * user permitted to request `agent.*.rpc` + receive its inbox replies. When `auth`\n * is omitted the connection is anonymous (local dev / a NATS without auth_callout)\n * — the existing behavior, unchanged.\n */\nexport async function createNatsEventBus(\n natsUrl: string,\n auth?: { user: string; pass: string },\n options: EventBusOptions = {},\n): Promise<EventBus> {\n const connectOptions: ConnectionOptions = { servers: natsUrl };\n if (auth) {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n }\n const nc = await connect(withReconnectDefaults(connectOptions));\n let connected = true;\n logConnectionStatus(nc, \"event-bus\", options.logger, (type) => {\n if (type === \"disconnect\" || type === \"reconnecting\" || type === \"staleConnection\" || type === \"error\") {\n connected = false;\n } else if (type === \"connect\" || type === \"reconnect\") {\n connected = true;\n }\n });\n const requestConnection: RequestConnection = {\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeout),\n };\n return {\n publish: async (workspaceId, sessionId, events) => {\n if (events.length === 0) {\n return;\n }\n // Best-effort LIVE fan-out. These events are ALREADY durably appended to\n // the DB before we get here (they carry a DB-assigned `sequence`), and\n // every consumer reconciles from that durable log — the server SSE stream\n // replays + gap-backfills via `listSessionEvents`, and the SDK client\n // reconnects and replays from the durable events endpoint. So a publish\n // that fails during a broker blip only delays LIVE delivery (healed by the\n // next successful publish's gap-backfill, or a stream reconnect); it must\n // never throw the in-flight turn to death.\n try {\n nc.publish(sessionSubject(workspaceId, sessionId), codec.encode({ workspaceId, sessionId, events }));\n } catch (error) {\n // `publish()` throws synchronously only when the connection is fully\n // CLOSED (with infinite reconnect, effectively never outside shutdown).\n (options.logger?.warn ?? silentLogger.warn)(\"NATS live publish dropped; events are durable in the DB and reconcile on stream replay\", {\n workspaceId,\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);\n },\n subscribe: async (workspaceId, sessionId, onEvents) => subscribeSession(nc, workspaceId, sessionId, onEvents),\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),\n subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler),\n subscribeAgentEvents: (subject, handler) => subscribeAgentEvents(nc, subject, handler),\n getRequestConnection: () => requestConnection,\n isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),\n close: async () => {\n await nc.drain();\n },\n };\n}\n\n/**\n * A standalone NATS connection answering request/reply on ONE subject — the\n * transport primitive the auth-callout responder uses. It is DELIBERATELY a\n * SEPARATE connection from the event bus: the callout responder authenticates as\n * the callout account's `auth_users` user (a username/password or token in the\n * `AUTH` account), which is a DIFFERENT identity from the control-plane's\n * privileged account that the event bus + `NatsControlRpc` ride. One connection\n * per identity; never multiplex the two.\n *\n * `request`/`reply` here is the RAW NATS request/reply (`$SYS.REQ.USER.AUTH`): the\n * server publishes an authorization request with a reply inbox; the handler returns\n * the signed authorization-response bytes which we `respond` on that inbox.\n */\nexport interface ResponderConnection {\n /** Subscribe-and-reply on `subject`; returns an async close that drains. */\n close: () => Promise<void>;\n}\n\n/** Connection auth for a standalone NATS connection (the callout responder). */\nexport type NatsConnectAuth =\n | { kind: \"user-password\"; user: string; pass: string }\n | { kind: \"token\"; token: string }\n | { kind: \"anonymous\" };\n\n/**\n * Open a standalone NATS connection and subscribe `subject`, replying to every\n * request with `handler(requestBytes, subject)`. Used by the auth-callout\n * responder to serve `$SYS.REQ.USER.AUTH` as the callout auth user. Returns a\n * handle whose `close()` drains the connection. A handler that throws leaves the\n * request UNANSWERED — for auth-callout that means the server denies the\n * connection on its own timeout, which is the correct fail-closed behavior (a\n * responder bug must never accidentally grant access).\n */\nexport async function createResponderConnection(\n natsUrl: string,\n auth: NatsConnectAuth,\n subject: string,\n handler: RequestHandler,\n options: { name?: string; logger?: EventLogger } = {},\n): Promise<ResponderConnection> {\n const connectOptions: ConnectionOptions = { servers: natsUrl };\n if (options.name) {\n connectOptions.name = options.name;\n }\n if (auth.kind === \"user-password\") {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n } else if (auth.kind === \"token\") {\n connectOptions.token = auth.token;\n }\n const nc = await connect(withReconnectDefaults(connectOptions));\n logConnectionStatus(nc, options.name ? `auth-callout:${options.name}` : \"auth-callout\", options.logger);\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n if (!msg.reply) {\n continue;\n }\n try {\n const reply = await handler(msg.data, msg.subject);\n msg.respond(reply);\n } catch {\n // Leave UNANSWERED — fail-closed. The server denies the connect attempt\n // on its callout timeout; a responder error never grants access.\n }\n }\n })();\n return {\n close: async () => {\n sub.unsubscribe();\n await nc.drain();\n },\n };\n}\n\nexport async function appendAndPublishEvents(db: Database, bus: EventBus, workspaceId: string, sessionId: string, events: AppendEventInput[]): Promise<SessionEvent[]> {\n const appended = await appendSessionEvents(db, workspaceId, sessionId, events);\n // The DB append above is the durable system of record; the publish is only a\n // best-effort LIVE fan-out. Guard it so NO EventBus implementation can throw an\n // in-flight agent turn to death on a transient NATS disconnect — consumers\n // reconcile any missed live events from the durable log via the events/stream\n // endpoint (DB replay + gap-backfill). The managed `createNatsEventBus` bus\n // already swallows internally, so this catch is the belt-and-suspenders guard\n // for any other bus impl (and a fully CLOSED connection during shutdown).\n try {\n await bus.publish(workspaceId, sessionId, appended);\n } catch (error) {\n console.warn(\n `[events] live publish failed for ${workspaceId}/${sessionId}; ${appended.length} event(s) are durable and reconcile on stream replay`,\n error,\n );\n }\n return appended;\n}\n\nfunction subscribeSession(nc: NatsConnection, workspaceId: string, sessionId: string, onEvents: (events: SessionEvent[]) => void | Promise<void>): () => void {\n const sub: Subscription = nc.subscribe(sessionSubject(workspaceId, sessionId));\n void (async () => {\n for await (const msg of sub) {\n const decoded = codec.decode(msg.data) as SessionBusMessage | SessionEvent;\n const events = \"events\" in decoded ? decoded.events : [decoded];\n await onEvents(events);\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\n/**\n * A binary request/reply over the managed connection. Returns ONLY the reply\n * bytes (the `RequestReply` shape) — the request/reply error semantics (a\n * no-responder NATS 503, a request timeout) propagate as the rejected promise so\n * the caller owns the mapping. The reply is delivered via the connection's\n * built-in mux inbox; no extra subscription is created here.\n */\nasync function requestReply(nc: NatsConnection, subject: string, payload: Uint8Array, timeout: number): Promise<RequestReply> {\n const msg: Msg = await nc.request(subject, payload, { timeout });\n return { data: msg.data };\n}\n\n/**\n * Subscribe to `subject` and reply to every request with the handler's bytes,\n * over the SAME connection. The responder side of request/reply: each delivered\n * `Msg` carries a `reply` inbox; `msg.respond(bytes)` publishes the answer there.\n * A handler that throws (or a message with no `reply` subject) is left unanswered\n * — the requester then sees a timeout, never a malformed reply.\n */\nfunction subscribeRequests(nc: NatsConnection, subject: string, handler: RequestHandler): () => void {\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n // A request always carries a reply inbox; a plain publish to this subject\n // (no reply) is ignored — request/reply is the only contract here.\n if (!msg.reply) {\n continue;\n }\n try {\n const reply = await handler(msg.data, msg.subject);\n msg.respond(reply);\n } catch {\n // Leave the request unanswered: the requester's request times out, which\n // the selfhosted control plane reads as a transient blip (reconnecting),\n // never a malformed reply. The responder stays subscribed for the next op.\n }\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\n/**\n * Subscribe to the one-way agent event plane: deliver each published payload (the\n * agent's `AgentEvent` heartbeat / going-offline, NOT a request/reply) to the\n * handler with its concrete subject. A plain `nc.subscribe` (no reply); a handler\n * that throws is swallowed so one bad event never tears down the subscription\n * (ingestion is best-effort — a metrics gap is never fatal).\n */\nfunction subscribeAgentEvents(\n nc: NatsConnection,\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n): () => void {\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n try {\n await handler(msg.data, msg.subject);\n } catch {\n // Swallow: best-effort ingestion. The subscription stays live for the\n // next event.\n }\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\nexport function formatSse(event: SessionEvent): string {\n return [\n `id: ${event.sequence}`,\n `event: ${event.type}`,\n `data: ${JSON.stringify(event)}`,\n \"\",\n \"\",\n ].join(\"\\n\");\n}\n","import type { SessionEvent } from \"@opengeni/contracts\";\n\nconst COALESCIBLE_DELTA_TYPES = new Set([\n \"agent.message.delta\",\n \"agent.reasoning.delta\",\n \"sandbox.command.output.delta\",\n]);\n\ntype DeltaRun = {\n first: SessionEvent;\n lastSequence: number;\n text: string;\n sandboxName: string | undefined;\n sandboxStream: string | undefined;\n sandboxCommandId: string | undefined;\n};\n\nexport function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent[] {\n const coalesced: SessionEvent[] = [];\n let run: DeltaRun | null = null;\n\n const flush = () => {\n if (!run) {\n return;\n }\n coalesced.push({\n ...run.first,\n payload: run.first.type === \"sandbox.command.output.delta\"\n // Sandbox output keeps its CANONICAL field (`chunk` — the terminal and\n // projection read it) plus the stream/commandId identity of the run.\n ? {\n chunk: run.text,\n coalescedUntil: run.lastSequence,\n ...(run.sandboxStream !== undefined ? { stream: run.sandboxStream } : {}),\n ...(run.sandboxCommandId !== undefined ? { commandId: run.sandboxCommandId } : {}),\n ...(run.sandboxName !== undefined ? { name: run.sandboxName } : {}),\n }\n : {\n text: run.text,\n coalescedUntil: run.lastSequence,\n },\n });\n run = null;\n };\n\n for (const event of events) {\n if (!isCoalescibleDelta(event)) {\n flush();\n coalesced.push(event);\n continue;\n }\n\n const isSandbox = event.type === \"sandbox.command.output.delta\";\n const sandboxName = isSandbox ? sandboxDeltaName(event.payload) : undefined;\n const sandboxStream = isSandbox ? sandboxDeltaString(event.payload, \"stream\") : undefined;\n const sandboxCommandId = isSandbox ? sandboxDeltaString(event.payload, \"commandId\") : undefined;\n if (\n run\n && sameDeltaRun(run.first, event, run.sandboxName, sandboxName)\n && run.sandboxStream === sandboxStream\n && run.sandboxCommandId === sandboxCommandId\n ) {\n run.text += deltaText(event);\n run.lastSequence = event.sequence;\n continue;\n }\n\n flush();\n run = {\n first: event,\n lastSequence: event.sequence,\n text: deltaText(event),\n sandboxName,\n sandboxStream,\n sandboxCommandId,\n };\n }\n\n flush();\n return coalesced;\n}\n\nfunction isCoalescibleDelta(event: SessionEvent): boolean {\n return COALESCIBLE_DELTA_TYPES.has(event.type);\n}\n\nfunction sameDeltaRun(\n first: SessionEvent,\n next: SessionEvent,\n firstSandboxName: string | undefined,\n nextSandboxName: string | undefined,\n): boolean {\n if (first.type !== next.type) {\n return false;\n }\n if ((first.turnId ?? null) !== (next.turnId ?? null)) {\n return false;\n }\n return first.type !== \"sandbox.command.output.delta\" || firstSandboxName === nextSandboxName;\n}\n\nfunction deltaText(event: SessionEvent): string {\n if (event.type === \"agent.reasoning.delta\") {\n return reasoningText(event.payload);\n }\n const payload = asRecord(event.payload);\n if (event.type === \"sandbox.command.output.delta\") {\n // `chunk` is the canonical wire field (contracts SandboxCommandOutputDeltaPayload);\n // text/output are tolerated legacy shapes.\n for (const key of [\"chunk\", \"text\", \"output\"] as const) {\n if (typeof payload[key] === \"string\") {\n return payload[key] as string;\n }\n }\n return \"\";\n }\n return typeof payload.text === \"string\" ? payload.text : \"\";\n}\n\nfunction reasoningText(payload: unknown): string {\n const record = asRecord(payload);\n if (typeof record.text === \"string\") {\n return record.text;\n }\n const content = asRecord(asRecord(record.item).rawItem).content;\n if (!Array.isArray(content)) {\n return \"\";\n }\n return content\n .map((part) => {\n const text = asRecord(part).text;\n return typeof text === \"string\" ? text : \"\";\n })\n .join(\"\");\n}\n\nfunction sandboxDeltaName(payload: unknown): string | undefined {\n const name = asRecord(payload).name;\n return typeof name === \"string\" ? name : undefined;\n}\n\nfunction sandboxDeltaString(payload: unknown, key: \"stream\" | \"commandId\"): string | undefined {\n const value = asRecord(payload)[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" ? value as Record<string, unknown> : {};\n}\n","// packages/events/src/nats-jwt.ts — NATS JWT v2 signing for the auth-callout\n// responder (bring-your-own-compute M-AUTH; dossier §10.1 NATS Accounts per\n// workspace + §17 the isolation smoke).\n//\n// This is the cryptographic core of the auth-callout tenancy boundary. When an\n// external agent connects to NATS presenting its `oge_` enrollment bearer as the\n// connect auth-token, nats-server (configured with `auth_callout`) issues an\n// authorization request on `$SYS.REQ.USER.AUTH`. Our responder (auth-callout.ts)\n// validates the bearer and answers with a SIGNED authorization-response JWT that\n// embeds a SIGNED user JWT scoping the connection to publish/subscribe ONLY\n// `agent.<workspaceId>.>` (+ the reply `_INBOX.>`). That per-subject permission\n// set IS the per-workspace isolation: workspace A's agent literally cannot\n// pub/sub workspace B's subjects (§19 the NATS-Accounts-misconfig leak risk is\n// closed at the JWT-permission layer, not just by subject naming).\n//\n// WHY HAND-ROLL THE JWT ENCODING (vs a dep): the NATS JWT v2 wire format is small,\n// stable, and fully specified (ADR-26 + nats-io/jwt): a base64url header\n// `{\"typ\":\"JWT\",\"alg\":\"ed25519-nkey\"}`, base64url JSON claims whose `jti` is the\n// base32(SHA-512/256(claims-with-blank-jti)), and an ed25519 nkey signature over\n// `header.payload`. nkeys (re-exported by the `nats` package we already depend on)\n// gives us the ed25519 sign primitive; Node `crypto` gives SHA-512/256. So we own\n// the encoding in a few well-tested functions rather than pull an alpha\n// `@nats-io/jwt` (0.0.x) whose nkeys-version compat is uncertain. No `xkey`\n// encryption is used (the bearer is already an authenticated identity claim and\n// the wire is TLS — encryption is an optional ADR-26 hardening, off here).\n//\n// SECURITY: the account SIGNING SEED never leaves this process and is NEVER logged.\n// Callers pass it as a `string` seed; we `fromSeed` it once per sign. The bearer\n// the responder validates is HMAC-verified elsewhere (verifyEnrollmentBearer); this\n// module only mints the scoped NATS credential once identity is proven.\n\nimport { createHash } from \"node:crypto\";\nimport { nkeys } from \"nats\";\n\n/** The NATS JWT v2 header — constant for every token we mint (ADR-26 / nats-io/jwt:\n * `TokenTypeJwt=\"JWT\"`, `AlgorithmNkey=\"ed25519-nkey\"`). */\nconst JWT_HEADER = { typ: \"JWT\", alg: \"ed25519-nkey\" } as const;\n\n/** NATS user-claim `nats.type` discriminator + `nats.version` for v2 claims. */\nconst USER_CLAIM_TYPE = \"user\";\nconst AUTH_RESPONSE_CLAIM_TYPE = \"authorization_response\";\nconst NATS_CLAIM_VERSION = 2;\n\n/** A NATS permission set: subject allow/deny lists (ADR-26 `pub`/`sub` →\n * `allow`/`deny`). An empty/undefined list means \"no explicit grant\" — combined\n * with the agent scope below, the connection can ONLY reach what `allow` lists. */\nexport interface NatsPermission {\n allow?: string[];\n deny?: string[];\n}\n\n/** The pub/sub permissions embedded in a user JWT. */\nexport interface NatsPermissions {\n pub: NatsPermission;\n sub: NatsPermission;\n}\n\n/**\n * The minimal nkey keypair surface this module needs — exactly what\n * `nkeys.fromSeed(seed)` returns. Declared structurally so the module does not\n * leak the `nats` nkeys type through its public signature.\n */\ninterface NkeyPair {\n getPublicKey(): string;\n sign(input: Uint8Array): Uint8Array;\n}\n\n/** base64url (RawURLEncoding — no padding), matching nats-io/jwt's `serialize`. */\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\n/** RFC 4648 base32 (standard alphabet, NO padding) — the encoding nats-io/jwt\n * uses for the `jti` hash. Node has no built-in base32, so a tiny encoder. */\nconst BASE32_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\nfunction base32NoPadding(bytes: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let out = \"\";\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += BASE32_ALPHABET[(value >>> bits) & 31];\n }\n }\n if (bits > 0) {\n out += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n }\n return out;\n}\n\n/**\n * Compute the canonical NATS `jti`: base32(NoPadding, std-alphabet) of the\n * SHA-512/256 of the claims object SERIALIZED WITH AN EMPTY `jti` (nats-io/jwt's\n * `hash`). nats-server recomputes + verifies this on decode, so it must match\n * byte-for-byte. We serialize the SAME object we will sign, only with `jti:\"\"`.\n */\nfunction computeJti(claimsWithBlankJti: object): string {\n const json = JSON.stringify(claimsWithBlankJti);\n const digest = createHash(\"sha512-256\").update(json, \"utf8\").digest();\n return base32NoPadding(digest);\n}\n\n/**\n * Encode + sign a NATS v2 JWT. The `claims` MUST already carry `iss`/`sub`/`iat`\n * (+ optional `aud`/`exp`) and a `nats` block; this function fills `jti` (the\n * canonical hash), serializes `header.payload`, signs that with `signingKey`, and\n * appends the base64url signature. Returns the compact `header.payload.signature`.\n */\nfunction encodeJwt(claims: Record<string, unknown>, signingKey: NkeyPair): string {\n // jti is the hash of the claims with jti blanked — set it blank, hash, then set.\n const withBlankJti = { ...claims, jti: \"\" };\n const jti = computeJti(withBlankJti);\n const finalClaims = { ...claims, jti };\n\n const header = base64UrlEncode(Buffer.from(JSON.stringify(JWT_HEADER), \"utf8\"));\n const payload = base64UrlEncode(Buffer.from(JSON.stringify(finalClaims), \"utf8\"));\n const signingInput = `${header}.${payload}`;\n const signature = signingKey.sign(Buffer.from(signingInput, \"utf8\"));\n return `${signingInput}.${base64UrlEncode(signature)}`;\n}\n\n/**\n * Input to mint a workspace-scoped NATS user JWT for an enrolled agent.\n * - `userPublicKey` — the `user_nkey` from the authorization request; it MUST be\n * the `sub` of the user JWT (nats-server rejects a mismatch).\n * - `accountSeed` — the callout account SIGNING seed (`SA...`); both the user JWT\n * `iss` (its public key) and the signature come from it. NEVER logged.\n * - `name` — a human label for the user (the agent id), for server logs.\n * - `permissions` — the pub/sub allow/deny lists (the workspace scope).\n * - `expiresAtSeconds` — optional absolute `exp` (unix seconds). When set the\n * server will expire the connection's credential; we tie it to the bearer's\n * remaining life so a revoked/expired enrollment cannot outlive its bearer.\n */\nexport interface MintUserJwtInput {\n userPublicKey: string;\n accountSeed: string;\n name: string;\n permissions: NatsPermissions;\n /** The target account NAME (the `auth_callout.account`) the user binds to; the\n * embedded user JWT's `aud` in server-config mode. */\n audienceAccount: string;\n expiresAtSeconds?: number;\n}\n\n/**\n * Mint a signed NATS user JWT scoped by `permissions`. In auth-callout SERVER\n * mode the user JWT is signed by the callout ISSUER ACCOUNT key, and its `iss` is\n * that account's public key. The returned JWT is embedded as `nats.jwt` in the\n * authorization response.\n */\nexport function mintUserJwt(input: MintUserJwtInput): string {\n const accountKey = nkeys.fromSeed(Buffer.from(input.accountSeed)) as unknown as NkeyPair;\n const accountPublicKey = accountKey.getPublicKey();\n const nowSeconds = Math.floor(Date.now() / 1000);\n\n const natsBlock: Record<string, unknown> = {\n type: USER_CLAIM_TYPE,\n version: NATS_CLAIM_VERSION,\n pub: input.permissions.pub,\n sub: input.permissions.sub,\n // Unlimited subscriptions / data / payload (the workspace subject scope, NOT\n // a connection-resource quota, is the boundary here).\n subs: -1,\n data: -1,\n payload: -1,\n };\n\n const claims: Record<string, unknown> = {\n jti: \"\",\n iat: nowSeconds,\n iss: accountPublicKey,\n name: input.name,\n sub: input.userPublicKey,\n // SERVER-config-mode placement: nats-server reads the embedded user JWT's `aud`\n // as the target account NAME (the configured `auth_callout.account`). This is\n // how the authenticated user binds to that account; the workspace isolation is\n // then carried by the pub/sub permissions below.\n aud: input.audienceAccount,\n nats: natsBlock,\n };\n if (typeof input.expiresAtSeconds === \"number\") {\n claims.exp = input.expiresAtSeconds;\n }\n return encodeJwt(claims, accountKey);\n}\n\n/**\n * Input to mint the authorization RESPONSE JWT the responder publishes back on the\n * request's reply subject (ADR-26 §3).\n * - `userPublicKey` — the request's `user_nkey`; the response `sub`.\n * - `serverId` — the request's `nats.server_id.id` (the server's public key); the\n * response `aud`.\n * - `accountSeed` — the callout account signing seed; signs the response and is\n * its `iss` (public key). NEVER logged.\n * - `userJwt` — the embedded signed user JWT (omit on a denial).\n * - `error` — a human-readable denial message (omit on success). When present the\n * server denies the connection.\n */\nexport interface MintAuthResponseInput {\n userPublicKey: string;\n serverId: string;\n accountSeed: string;\n userJwt?: string;\n error?: string;\n}\n\n/**\n * Mint the signed authorization-response JWT. On success it carries the embedded\n * user JWT (`nats.jwt`); on denial it carries `nats.error` and NO user JWT, which\n * makes nats-server refuse the connection. Signed by the callout account key (its\n * public key is `iss`); `sub` is the user_nkey, `aud` is the server id.\n */\nexport function mintAuthResponse(input: MintAuthResponseInput): string {\n const accountKey = nkeys.fromSeed(Buffer.from(input.accountSeed)) as unknown as NkeyPair;\n const accountPublicKey = accountKey.getPublicKey();\n const nowSeconds = Math.floor(Date.now() / 1000);\n\n const natsBlock: Record<string, unknown> = {\n type: AUTH_RESPONSE_CLAIM_TYPE,\n version: NATS_CLAIM_VERSION,\n };\n if (input.userJwt) {\n natsBlock.jwt = input.userJwt;\n }\n if (input.error) {\n natsBlock.error = input.error;\n }\n\n const claims: Record<string, unknown> = {\n jti: \"\",\n iat: nowSeconds,\n iss: accountPublicKey,\n // The response `aud` MUST be the SERVER public key in server-config mode\n // (nats-server validates \"Audience must be a server public key\"). The\n // authenticated user is placed into the configured `auth_callout.account` (the\n // SAME account the responder + the privileged control plane connect into), so\n // `agent.<ws>.<id>.rpc` request/reply routes; the workspace isolation is carried\n // entirely by the user JWT's pub/sub subject permissions (NOT by cross-account\n // placement, which server-config-mode nats does not support — nats-io#4335).\n aud: input.serverId,\n sub: input.userPublicKey,\n nats: natsBlock,\n };\n return encodeJwt(claims, accountKey);\n}\n\n/**\n * The fields the responder needs out of the authorization REQUEST JWT (ADR-26 §2).\n * The request is itself a NATS JWT (`header.payload.signature`) the server signs;\n * we only DECODE it (the server proves its own identity by the connection, and the\n * embedded `auth_token` is independently HMAC-verified), so we read the payload\n * without re-verifying the server signature.\n */\nexport interface DecodedAuthRequest {\n /** The public user nkey the response user JWT MUST be `sub`-scoped to. */\n userNkey: string;\n /** The server's public id — the response `aud`. */\n serverId: string;\n /** The connect `auth_token` the client presented (our `oge_` bearer), if any. */\n authToken: string | undefined;\n /** The connect username, if any (unused today; present for completeness). */\n user: string | undefined;\n}\n\n/**\n * Decode the authorization-request JWT payload (the middle base64url segment). The\n * request shape (ADR-26 §2): `nats.user_nkey`, `nats.server_id.id`, and the\n * presented connect options under `nats.connect_opts` (`auth_token` / `user`).\n * Returns null on a malformed token so the caller can deny cleanly.\n */\nexport function decodeAuthRequest(token: string): DecodedAuthRequest | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n let payload: unknown;\n try {\n payload = JSON.parse(Buffer.from(parts[1]!, \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n if (typeof payload !== \"object\" || payload === null) {\n return null;\n }\n const nats = (payload as { nats?: unknown }).nats;\n if (typeof nats !== \"object\" || nats === null) {\n return null;\n }\n const natsObj = nats as {\n user_nkey?: unknown;\n server_id?: { id?: unknown } | unknown;\n connect_opts?: { auth_token?: unknown; user?: unknown } | unknown;\n };\n const userNkey = typeof natsObj.user_nkey === \"string\" ? natsObj.user_nkey : null;\n if (!userNkey) {\n return null;\n }\n const serverIdRaw =\n typeof natsObj.server_id === \"object\" && natsObj.server_id !== null\n ? (natsObj.server_id as { id?: unknown }).id\n : undefined;\n const serverId = typeof serverIdRaw === \"string\" ? serverIdRaw : \"\";\n const connectOpts =\n typeof natsObj.connect_opts === \"object\" && natsObj.connect_opts !== null\n ? (natsObj.connect_opts as { auth_token?: unknown; user?: unknown })\n : {};\n const authToken = typeof connectOpts.auth_token === \"string\" ? connectOpts.auth_token : undefined;\n const user = typeof connectOpts.user === \"string\" ? connectOpts.user : undefined;\n return { userNkey, serverId, authToken, user };\n}\n\n/**\n * Build the workspace-scoped permission set for an agent: it may publish + subscribe\n * ONLY `agent.<workspaceId>.>` (its own RPC/event/hello subtree) and the reply\n * `_INBOX.>` subtree (so request/reply round-trips work). Everything else is\n * implicitly denied (an allow-list with no other entries IS the deny-all-else).\n *\n * THE isolation assertion (§17): with `workspaceId=A`, the returned allow lists name\n * only `agent.A.>` — so a connection bearing this credential is rejected by\n * nats-server the instant it tries to pub/sub `agent.B.>`. This is the per-workspace\n * tenancy boundary, enforced cryptographically by the signed JWT, not by naming.\n */\nexport function workspaceAgentPermissions(workspaceId: string): NatsPermissions {\n const agentScope = `agent.${workspaceId}.>`;\n // The reply-inbox subtree must be reachable for request/reply (the control plane\n // requests on agent.<ws>.<id>.rpc with a reply inbox; the agent responds there).\n const inboxScope = \"_INBOX.>\";\n return {\n pub: { allow: [agentScope, inboxScope] },\n sub: { allow: [agentScope, inboxScope] },\n };\n}\n"],"mappings":";AACA,SAAS,qBAAqB,sBAA4D;AAC1F,SAAS,SAAS,iBAA2F;;;ACA7G,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWM,SAAS,2BAA2B,QAAwC;AACjF,QAAM,YAA4B,CAAC;AACnC,MAAI,MAAuB;AAE3B,QAAM,QAAQ,MAAM;AAClB,QAAI,CAAC,KAAK;AACR;AAAA,IACF;AACA,cAAU,KAAK;AAAA,MACb,GAAG,IAAI;AAAA,MACP,SAAS,IAAI,MAAM,SAAS,iCAGxB;AAAA,QACE,OAAO,IAAI;AAAA,QACX,gBAAgB,IAAI;AAAA,QACpB,GAAI,IA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SAAS,UAAU,OAA6B;AACrD,SAAO;AAAA,IACL,OAAO,MAAM,QAAQ;AAAA,IACrB,UAAU,MAAM,IAAI;AAAA,IACpB,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA,IAC9B;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;","names":["connect","nkeys"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/coalesce.ts","../src/nats-jwt.ts"],"sourcesContent":["import type { SessionBusMessage, SessionEvent, WorkspaceControlEvent } from \"@opengeni/contracts\";\nimport {\n appendSessionEvents,\n appendSessionEventsForTurnAttempt,\n sessionSubject,\n type AppendEventInput,\n type Database,\n} from \"@opengeni/db\";\nimport {\n connect,\n JSONCodec,\n type ConnectionOptions,\n type Msg,\n type NatsConnection,\n type Subscription,\n} from \"nats\";\n\nconst codec = JSONCodec<SessionBusMessage | SessionEvent | WorkspaceControlEvent>();\n\nexport type EventLogger = {\n debug?: (message: string, attributes?: Record<string, unknown>) => void;\n warn?: (message: string, attributes?: Record<string, unknown>) => void;\n};\n\nexport type EventBusOptions = {\n logger?: EventLogger;\n /** Test/host transport seam; production defaults to the nats.js connector. */\n connect?: typeof connect;\n};\n\nconst silentLogger: Required<EventLogger> = {\n debug: () => {},\n warn: () => {},\n};\n\nexport { coalesceSessionEventDeltas } from \"./coalesce\";\n\n/**\n * Reconnect + keepalive defaults applied to EVERY long-lived NATS connection\n * this package opens (the event bus AND the standalone auth-callout responder).\n *\n * The production outage these guard against: an in-cluster NATS broker pod\n * restart. nats.js's stock policy gives up after ~10 attempts (~20s) and the\n * client goes permanently CONNECTION_CLOSED — which takes the whole control\n * plane down with it: every session-create publishes events to NATS, and the\n * API-hosted auth-callout responder dies so BYO agents get \"authorization\n * violation\". Recovery then required a MANUAL api+worker restart. With these\n * options the client retries forever and auto-recovers the moment the broker\n * returns. Factored into one source of truth so the call sites never drift.\n *\n * - `reconnect` + `maxReconnectAttempts: -1` — never give up (infinite retry).\n * - `reconnectTimeWait` (2s base) + `reconnectJitter`/`reconnectJitterTLS`\n * (up to 1s) — a fleet of api/worker pods doesn't thundering-herd the broker\n * on recovery.\n * - `waitOnFirstConnect` — a broker briefly unavailable at boot must not\n * hard-fail the process; the client keeps trying instead of throwing.\n * - `pingInterval`/`maxPingOut` — promptly detect a silently-dead socket so the\n * reconnect machinery actually engages instead of hanging on a zombie.\n */\nconst RECONNECT_OPTIONS = {\n reconnect: true,\n maxReconnectAttempts: -1,\n reconnectTimeWait: 2_000,\n reconnectJitter: 1_000,\n reconnectJitterTLS: 1_000,\n waitOnFirstConnect: true,\n pingInterval: 20_000,\n maxPingOut: 3,\n} satisfies ConnectionOptions;\n\n/**\n * The single source of truth for a long-lived connection's resilience: merge the\n * reconnect/keepalive defaults UNDER the caller's connection options (servers +\n * optional auth/name). Every long-lived `connect()` in this package goes through\n * here so the two call sites can never diverge.\n */\nfunction withReconnectDefaults(options: ConnectionOptions): ConnectionOptions {\n return { ...RECONNECT_OPTIONS, ...options };\n}\n\n/** How long a best-effort publish waits on `flush()` before giving up (see `publish`). */\nconst PUBLISH_FLUSH_TIMEOUT_MS = 2_000;\n\n/**\n * Await `nc.flush()` but never longer than `timeoutMs`. With infinite reconnect a\n * `flush()` issued while the broker is down does NOT reject — it pends until the\n * broker returns, which can be minutes. Racing it against a timer keeps a long\n * outage from stalling an in-flight turn; the published message stays buffered\n * and is delivered on reconnect regardless. A flush rejection (connection fully\n * CLOSED) is swallowed here so the timeout race never leaks an unhandled\n * rejection — the caller's publish path is what logs the drop.\n */\nasync function flushWithTimeout(nc: NatsConnection, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs);\n });\n try {\n await Promise.race([nc.flush().catch(() => undefined), timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\n/**\n * Drain a long-lived connection's status async-iterator to the log so a future\n * broker outage is OBSERVABLE (disconnect → reconnecting → reconnect → update).\n * Fire-and-forget for the connection's lifetime; the loop ends when the\n * connection closes. `label` distinguishes the event-bus connection from the\n * auth-callout responder in the logs.\n */\nfunction logConnectionStatus(\n nc: NatsConnection,\n label: string,\n logger: EventLogger = silentLogger,\n onStatus?: (type: string) => void,\n): void {\n void (async () => {\n try {\n for await (const status of nc.status()) {\n onStatus?.(status.type);\n const attributes = { label, status: status.type, data: status.data };\n if (isWarnNatsStatus(status.type)) {\n (logger.warn ?? silentLogger.warn)(\"NATS connection status\", attributes);\n } else {\n (logger.debug ?? silentLogger.debug)(\"NATS connection status\", attributes);\n }\n }\n } catch {\n // The status iterator simply ends when the connection closes; never let it\n // throw out of this background loop.\n }\n })();\n}\n\nfunction isWarnNatsStatus(type: string): boolean {\n return type === \"disconnect\" || type === \"error\" || type === \"staleConnection\";\n}\n\nexport {\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n workspaceAgentPermissions,\n type DecodedAuthRequest,\n type MintAuthResponseInput,\n type MintUserJwtInput,\n type NatsPermission,\n type NatsPermissions,\n} from \"./nats-jwt\";\n\n// Re-export the raw NATS primitives a consumer needs to open a direct connection or\n// generate nkeys (the auth-callout responder's standalone connection, the\n// agent-simulating integration tests). This keeps `nats` an internal dependency of\n// this leaf — callers in the bun workspace reach it through @opengeni/events rather\n// than depending on `nats` directly.\nexport { connect, nkeys, type NatsConnection } from \"nats\";\n\n/**\n * A raw request/reply reply — just the response bytes. Mirrors the subset of the\n * NATS `Msg` shape a binary request/reply caller needs (`NatsControlRpc` consumes\n * exactly this). Kept minimal so the events package does not leak the `nats` `Msg`\n * type into the agent-loop-free runtime leaf.\n */\nexport type RequestReply = { data: Uint8Array };\n\n/**\n * The minimal request/reply connection the selfhosted control plane consumes\n * (structurally identical to `@opengeni/runtime`'s `NatsRequestConnection`). The\n * API/worker hand this accessor to `NatsControlRpc` so the control transport rides\n * the SAME managed NATS connection the event bus already owns — a NATS connection\n * natively supports both pub/sub and request/reply, so there is NEVER a second\n * connection.\n */\nexport interface RequestConnection {\n request(subject: string, payload: Uint8Array, opts: { timeout: number }): Promise<RequestReply>;\n}\n\n/**\n * The raw subscribe/publish surface the selfhosted OP-STREAM transport consumes\n * (structurally identical to `@opengeni/runtime`'s `NatsOpStreamConnection`):\n * a plain subscription for the runner's fire-and-forget op frames\n * (`agent.<ws>.<id>.op.<op_id>`) and a plain publish for the server's acks\n * (`agent.<ws>.<id>.ack`). Same managed connection as everything else — a NATS\n * connection natively supports all of it; there is NEVER a second connection.\n */\nexport interface OpStreamConnection {\n subscribe(subject: string): AsyncIterable<{ data: Uint8Array }> & { unsubscribe(): void };\n publish(subject: string, payload: Uint8Array): void;\n}\n\n/**\n * A handler answering a request/reply on a subscribed subject: given the request\n * bytes (+ the concrete subject the message landed on, for `agent.<ws>.<id>.rpc`\n * style wildcard routing), return the response bytes to reply with. A thrown error\n * leaves the request unanswered (the caller's request times out / sees no\n * responder), which the control plane maps to `agent_offline` / reconnecting.\n */\nexport type RequestHandler = (\n request: Uint8Array,\n subject: string,\n) => Promise<Uint8Array> | Uint8Array;\n\nexport type EventBus = {\n publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;\n subscribe: (\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n ) => Promise<() => void>;\n /** Best-effort live invalidation; the event is already durable in Postgres. */\n publishWorkspaceControl: (workspaceId: string, event: WorkspaceControlEvent) => Promise<void>;\n /** One workspace subscription fans a control change to every open descendant view. */\n subscribeWorkspaceControl: (\n workspaceId: string,\n onEvent: (event: WorkspaceControlEvent) => void | Promise<void>,\n ) => Promise<() => void>;\n /**\n * Issue a binary request/reply on a subject over the bus's NATS connection\n * (the selfhosted control plane: `agent.<ws>.<id>.rpc`). A new usage of what was\n * a one-way bus — same connection, native NATS request/reply. Rejects on a\n * no-responder (NATS 503) or a request timeout; the caller (`NatsControlRpc`)\n * maps those to `agent_offline` / `agent_reconnecting`, never a NotFound.\n */\n request: (\n subject: string,\n payload: Uint8Array,\n opts: { timeoutMs: number },\n ) => Promise<RequestReply>;\n /**\n * Subscribe-and-reply on a subject (the responder side — the enrolled agent, or\n * a test stand-in for it): for every request on `subject`, call `handler` and\n * `respond` with its bytes over the SAME connection. Returns an unsubscribe fn.\n * A subject may be a NATS wildcard (e.g. `agent.*.*.rpc`).\n */\n subscribeRequests: (subject: string, handler: RequestHandler) => () => void;\n /**\n * Subscribe to the agent EVENT plane (the one-way fire-and-forget heartbeats +\n * going-offline the agent PUBLISHES on `agent.<ws>.<id>.events`, NOT a\n * request/reply). The M10 metrics-ingestion consumer subscribes the wildcard\n * `agent.*.*.events` and gets each raw payload plus its concrete subject (so it\n * can extract `<ws>`/`<id>` for the per-enrollment upsert). Returns an\n * unsubscribe fn. Decoding the AgentEvent is the caller's concern (this leaf\n * does not depend on `@opengeni/agent-proto`).\n */\n subscribeAgentEvents: (\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n ) => () => void;\n /**\n * The `RequestConnection` accessor the selfhosted `NatsControlRpc` consumes —\n * the SAME managed connection (pub/sub + request/reply share it). The control\n * plane injects this so the transport never opens a second connection.\n */\n getRequestConnection: () => RequestConnection;\n /**\n * The `OpStreamConnection` accessor the selfhosted op-stream transport\n * consumes (`NatsOpStreamTransport`) — the same managed connection again.\n * Optional so bus test doubles that never exercise op-stream stay valid.\n */\n getOpStreamConnection?: () => OpStreamConnection;\n isConnected?: () => boolean;\n close: () => Promise<void>;\n};\n\n/**\n * Connect the event bus + control-plane request/reply over ONE managed NATS\n * connection. `auth` is the PRIVILEGED control-plane login (M-AUTH): when the\n * server runs with auth_callout, the api/worker authenticates as a static account\n * user permitted to request `agent.*.rpc` + receive its inbox replies. When `auth`\n * is omitted the connection is anonymous (local dev / a NATS without auth_callout)\n * — the existing behavior, unchanged.\n */\nexport async function createNatsEventBus(\n natsUrl: string,\n auth?: { user: string; pass: string },\n options: EventBusOptions = {},\n): Promise<EventBus> {\n const connectOptions: ConnectionOptions = { servers: natsUrl };\n if (auth) {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n }\n const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));\n let connected = true;\n logConnectionStatus(nc, \"event-bus\", options.logger, (type) => {\n if (\n type === \"disconnect\" ||\n type === \"reconnecting\" ||\n type === \"staleConnection\" ||\n type === \"error\"\n ) {\n connected = false;\n } else if (type === \"connect\" || type === \"reconnect\") {\n connected = true;\n }\n });\n const requestConnection: RequestConnection = {\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeout),\n };\n const opStreamConnection: OpStreamConnection = {\n subscribe: (subject) => nc.subscribe(subject),\n publish: (subject, payload) => {\n nc.publish(subject, payload);\n },\n };\n return {\n publish: async (workspaceId, sessionId, events) => {\n if (events.length === 0) {\n return;\n }\n // Best-effort LIVE fan-out. These events are ALREADY durably appended to\n // the DB before we get here (they carry a DB-assigned `sequence`), and\n // every consumer reconciles from that durable log — the server SSE stream\n // replays + gap-backfills via `listSessionEvents`, and the SDK client\n // reconnects and replays from the durable events endpoint. So a publish\n // that fails during a broker blip only delays LIVE delivery (healed by the\n // next successful publish's gap-backfill, or a stream reconnect); it must\n // never throw the in-flight turn to death.\n try {\n nc.publish(\n sessionSubject(workspaceId, sessionId),\n codec.encode({ workspaceId, sessionId, events }),\n );\n } catch (error) {\n // `publish()` throws synchronously only when the connection is fully\n // CLOSED (with infinite reconnect, effectively never outside shutdown).\n (options.logger?.warn ?? silentLogger.warn)(\n \"NATS live publish dropped; events are durable in the DB and reconcile on stream replay\",\n {\n workspaceId,\n sessionId,\n error: error instanceof Error ? error.message : String(error),\n },\n );\n return;\n }\n await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);\n },\n subscribe: async (workspaceId, sessionId, onEvents) =>\n subscribeSession(nc, workspaceId, sessionId, onEvents),\n publishWorkspaceControl: async (workspaceId, event) => {\n try {\n nc.publish(workspaceControlSubject(workspaceId), codec.encode(event));\n } catch (error) {\n (options.logger?.warn ?? silentLogger.warn)(\n \"NATS workspace-control invalidation dropped; clients reconcile from Postgres\",\n {\n workspaceId,\n revision: event.revision,\n error: error instanceof Error ? error.message : String(error),\n },\n );\n return;\n }\n await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);\n },\n subscribeWorkspaceControl: async (workspaceId, onEvent) => {\n const sub = nc.subscribe(workspaceControlSubject(workspaceId));\n void (async () => {\n for await (const msg of sub) {\n await onEvent(codec.decode(msg.data) as WorkspaceControlEvent);\n }\n })();\n return () => sub.unsubscribe();\n },\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),\n subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler),\n subscribeAgentEvents: (subject, handler) => subscribeAgentEvents(nc, subject, handler),\n getRequestConnection: () => requestConnection,\n getOpStreamConnection: () => opStreamConnection,\n isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),\n close: async () => {\n await nc.drain();\n },\n };\n}\n\n/**\n * A standalone NATS connection answering request/reply on ONE subject — the\n * transport primitive the auth-callout responder uses. It is DELIBERATELY a\n * SEPARATE connection from the event bus: the callout responder authenticates as\n * the callout account's `auth_users` user (a username/password or token in the\n * `AUTH` account), which is a DIFFERENT identity from the control-plane's\n * privileged account that the event bus + `NatsControlRpc` ride. One connection\n * per identity; never multiplex the two.\n *\n * `request`/`reply` here is the RAW NATS request/reply (`$SYS.REQ.USER.AUTH`): the\n * server publishes an authorization request with a reply inbox; the handler returns\n * the signed authorization-response bytes which we `respond` on that inbox.\n */\nexport interface ResponderConnection {\n /** Subscribe-and-reply on `subject`; returns an async close that drains. */\n close: () => Promise<void>;\n}\n\n/** Connection auth for a standalone NATS connection (the callout responder). */\nexport type NatsConnectAuth =\n | { kind: \"user-password\"; user: string; pass: string }\n | { kind: \"token\"; token: string }\n | { kind: \"anonymous\" };\n\n/**\n * Open a standalone NATS connection and subscribe `subject`, replying to every\n * request with `handler(requestBytes, subject)`. Used by the auth-callout\n * responder to serve `$SYS.REQ.USER.AUTH` as the callout auth user. Returns a\n * handle whose `close()` drains the connection. A handler that throws leaves the\n * request UNANSWERED — for auth-callout that means the server denies the\n * connection on its own timeout, which is the correct fail-closed behavior (a\n * responder bug must never accidentally grant access).\n */\nexport async function createResponderConnection(\n natsUrl: string,\n auth: NatsConnectAuth,\n subject: string,\n handler: RequestHandler,\n options: { name?: string; logger?: EventLogger; connect?: typeof connect } = {},\n): Promise<ResponderConnection> {\n const connectOptions: ConnectionOptions = { servers: natsUrl };\n if (options.name) {\n connectOptions.name = options.name;\n }\n if (auth.kind === \"user-password\") {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n } else if (auth.kind === \"token\") {\n connectOptions.token = auth.token;\n }\n const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));\n logConnectionStatus(\n nc,\n options.name ? `auth-callout:${options.name}` : \"auth-callout\",\n options.logger,\n );\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n if (!msg.reply) {\n continue;\n }\n try {\n const reply = await handler(msg.data, msg.subject);\n msg.respond(reply);\n } catch {\n // Leave UNANSWERED — fail-closed. The server denies the connect attempt\n // on its callout timeout; a responder error never grants access.\n }\n }\n })();\n return {\n close: async () => {\n sub.unsubscribe();\n await nc.drain();\n },\n };\n}\n\n/**\n * Optional timing seam for {@link appendAndPublishEvents}: `onAppend` fires after\n * the durable DB write, `onPublish` after the best-effort live fan-out (on both\n * success AND failure of the publish, so a broker blip still records its latency).\n * Kept as a plain callback so the events package takes no dependency on the\n * observability package; the worker wires it to Prometheus histograms.\n */\nexport type AppendPublishObserver = {\n onAppend?: (info: { durationSeconds: number; count: number }) => void;\n onPublish?: (info: { durationSeconds: number; count: number }) => void;\n};\n\nexport type AppendPublishOptions = AppendPublishObserver & {\n /** Test/host persistence seam; production uses the database implementation. */\n appendSessionEvents?: typeof appendSessionEvents;\n};\n\n/**\n * Invoke a phase-timing callback with the elapsed seconds since `startedAt` and the\n * event count, swallowing any throw so a metrics sink can never break the\n * append/publish path. Exported for direct unit testing: the wider test suite\n * installs a process-global `mock.module(\"@opengeni/events\")` that stubs\n * `appendAndPublishEvents` (spreading the real module for everything else), so the\n * observer wiring can only be exercised through a helper that survives that mock.\n */\nexport function observeSince(\n fn: ((info: { durationSeconds: number; count: number }) => void) | undefined,\n startedAt: number,\n count: number,\n): void {\n if (!fn) {\n return;\n }\n try {\n fn({ durationSeconds: Math.max(0, (performance.now() - startedAt) / 1000), count });\n } catch {\n // Metrics emission must never affect the append/publish path.\n }\n}\n\nexport async function appendAndPublishEvents(\n db: Database,\n bus: EventBus,\n workspaceId: string,\n sessionId: string,\n events: AppendEventInput[],\n options: AppendPublishOptions = {},\n): Promise<SessionEvent[]> {\n const appendStartedAt = performance.now();\n const appended = await (options.appendSessionEvents ?? appendSessionEvents)(\n db,\n workspaceId,\n sessionId,\n events,\n );\n observeSince(options.onAppend, appendStartedAt, appended.length);\n await publishDurableSessionEvents(bus, workspaceId, sessionId, appended, options);\n return appended;\n}\n\n/**\n * Best-effort live fanout for events another DB helper already committed in\n * the same transaction as related durable state. This must never append again.\n */\nexport async function publishDurableSessionEvents(\n bus: EventBus,\n workspaceId: string,\n sessionId: string,\n appended: SessionEvent[],\n observe?: AppendPublishObserver,\n): Promise<void> {\n if (appended.length === 0) {\n return;\n }\n // The committed DB events are the durable system of record; this publish is only a\n // best-effort LIVE fan-out. Guard it so NO EventBus implementation can throw an\n // in-flight agent turn to death on a transient NATS disconnect — consumers\n // reconcile any missed live events from the durable log via the events/stream\n // endpoint (DB replay + gap-backfill). The managed `createNatsEventBus` bus\n // already swallows internally, so this catch is the belt-and-suspenders guard\n // for any other bus impl (and a fully CLOSED connection during shutdown).\n const publishStartedAt = performance.now();\n try {\n await bus.publish(workspaceId, sessionId, appended);\n } catch (error) {\n console.warn(\n `[events] live publish failed for ${workspaceId}/${sessionId}; ${appended.length} event(s) are durable and reconcile on stream replay`,\n error,\n );\n }\n observeSince(observe?.onPublish, publishStartedAt, appended.length);\n}\n\n/** Best-effort fanout for a workspace-control event already committed in PostgreSQL. */\nexport async function publishDurableWorkspaceControlEvent(\n bus: EventBus,\n workspaceId: string,\n event: WorkspaceControlEvent,\n): Promise<void> {\n try {\n await bus.publishWorkspaceControl(workspaceId, event);\n } catch (error) {\n console.warn(\n `[events] workspace-control live publish failed for ${workspaceId} at revision ${event.revision}; the event is durable and reconciles on stream replay`,\n error,\n );\n }\n}\n\nexport async function appendAndPublishTurnEventsFenced(\n db: Database,\n bus: EventBus,\n workspaceId: string,\n sessionId: string,\n turnId: string,\n executionGeneration: number,\n attemptId: string,\n events: AppendEventInput[],\n): Promise<{ events: SessionEvent[]; accepted: boolean }> {\n const result = await appendSessionEventsForTurnAttempt(\n db,\n workspaceId,\n sessionId,\n turnId,\n executionGeneration,\n attemptId,\n events,\n );\n if (result.events.length === 0) return result;\n try {\n await bus.publish(workspaceId, sessionId, result.events);\n } catch (error) {\n console.warn(\n `[events] live fenced publish failed for ${workspaceId}/${sessionId}/${turnId}@${executionGeneration}/${attemptId}; ${result.events.length} event(s) are durable`,\n error,\n );\n }\n return result;\n}\n\nfunction subscribeSession(\n nc: NatsConnection,\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n): () => void {\n const sub: Subscription = nc.subscribe(sessionSubject(workspaceId, sessionId));\n void (async () => {\n for await (const msg of sub) {\n const decoded = codec.decode(msg.data) as SessionBusMessage | SessionEvent;\n const events = \"events\" in decoded ? decoded.events : [decoded];\n await onEvents(events);\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\n/**\n * A binary request/reply over the managed connection. Returns ONLY the reply\n * bytes (the `RequestReply` shape) — the request/reply error semantics (a\n * no-responder NATS 503, a request timeout) propagate as the rejected promise so\n * the caller owns the mapping. The reply is delivered via the connection's\n * built-in mux inbox; no extra subscription is created here.\n */\nasync function requestReply(\n nc: NatsConnection,\n subject: string,\n payload: Uint8Array,\n timeout: number,\n): Promise<RequestReply> {\n const msg: Msg = await nc.request(subject, payload, { timeout });\n return { data: msg.data };\n}\n\n/**\n * Subscribe to `subject` and reply to every request with the handler's bytes,\n * over the SAME connection. The responder side of request/reply: each delivered\n * `Msg` carries a `reply` inbox; `msg.respond(bytes)` publishes the answer there.\n * A handler that throws (or a message with no `reply` subject) is left unanswered\n * — the requester then sees a timeout, never a malformed reply.\n */\nfunction subscribeRequests(\n nc: NatsConnection,\n subject: string,\n handler: RequestHandler,\n): () => void {\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n // A request always carries a reply inbox; a plain publish to this subject\n // (no reply) is ignored — request/reply is the only contract here.\n if (!msg.reply) {\n continue;\n }\n try {\n const reply = await handler(msg.data, msg.subject);\n msg.respond(reply);\n } catch {\n // Leave the request unanswered: the requester's request times out, which\n // the selfhosted control plane reads as a transient blip (reconnecting),\n // never a malformed reply. The responder stays subscribed for the next op.\n }\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\n/**\n * Subscribe to the one-way agent event plane: deliver each published payload (the\n * agent's `AgentEvent` heartbeat / going-offline, NOT a request/reply) to the\n * handler with its concrete subject. A plain `nc.subscribe` (no reply); a handler\n * that throws is swallowed so one bad event never tears down the subscription\n * (ingestion is best-effort — a metrics gap is never fatal).\n */\nfunction subscribeAgentEvents(\n nc: NatsConnection,\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n): () => void {\n const sub: Subscription = nc.subscribe(subject);\n void (async () => {\n for await (const msg of sub) {\n try {\n await handler(msg.data, msg.subject);\n } catch {\n // Swallow: best-effort ingestion. The subscription stays live for the\n // next event.\n }\n }\n })();\n return () => {\n sub.unsubscribe();\n };\n}\n\nexport function formatSse<T extends { sequence: number; type: string }>(event: T): string {\n return [\n `id: ${event.sequence}`,\n `event: ${event.type}`,\n `data: ${JSON.stringify(event)}`,\n \"\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction workspaceControlSubject(workspaceId: string): string {\n return `workspaces.${workspaceId}.control`;\n}\n","import type { SessionEvent } from \"@opengeni/contracts\";\n\nconst COALESCIBLE_DELTA_TYPES = new Set([\n \"agent.message.delta\",\n \"agent.reasoning.delta\",\n \"sandbox.command.output.delta\",\n]);\n\ntype DeltaRun = {\n first: SessionEvent;\n lastSequence: number;\n text: string;\n sandboxName: string | undefined;\n sandboxStream: string | undefined;\n sandboxCommandId: string | undefined;\n};\n\nexport function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent[] {\n const coalesced: SessionEvent[] = [];\n let run: DeltaRun | null = null;\n\n const flush = () => {\n if (!run) {\n return;\n }\n coalesced.push({\n ...run.first,\n payload:\n run.first.type === \"sandbox.command.output.delta\"\n ? // Sandbox output keeps its CANONICAL field (`chunk` — the terminal and\n // projection read it) plus the stream/commandId identity of the run.\n {\n chunk: run.text,\n coalescedUntil: run.lastSequence,\n ...(run.sandboxStream !== undefined ? { stream: run.sandboxStream } : {}),\n ...(run.sandboxCommandId !== undefined ? { commandId: run.sandboxCommandId } : {}),\n ...(run.sandboxName !== undefined ? { name: run.sandboxName } : {}),\n }\n : {\n text: run.text,\n coalescedUntil: run.lastSequence,\n },\n });\n run = null;\n };\n\n for (const event of events) {\n if (!isCoalescibleDelta(event)) {\n flush();\n coalesced.push(event);\n continue;\n }\n\n const isSandbox = event.type === \"sandbox.command.output.delta\";\n const sandboxName = isSandbox ? sandboxDeltaName(event.payload) : undefined;\n const sandboxStream = isSandbox ? sandboxDeltaString(event.payload, \"stream\") : undefined;\n const sandboxCommandId = isSandbox ? sandboxDeltaString(event.payload, \"commandId\") : undefined;\n if (\n run &&\n sameDeltaRun(run.first, event, run.sandboxName, sandboxName) &&\n run.sandboxStream === sandboxStream &&\n run.sandboxCommandId === sandboxCommandId\n ) {\n run.text += deltaText(event);\n run.lastSequence = event.sequence;\n continue;\n }\n\n flush();\n run = {\n first: event,\n lastSequence: event.sequence,\n text: deltaText(event),\n sandboxName,\n sandboxStream,\n sandboxCommandId,\n };\n }\n\n flush();\n return coalesced;\n}\n\nfunction isCoalescibleDelta(event: SessionEvent): boolean {\n return COALESCIBLE_DELTA_TYPES.has(event.type);\n}\n\nfunction sameDeltaRun(\n first: SessionEvent,\n next: SessionEvent,\n firstSandboxName: string | undefined,\n nextSandboxName: string | undefined,\n): boolean {\n if (first.type !== next.type) {\n return false;\n }\n if ((first.turnId ?? null) !== (next.turnId ?? null)) {\n return false;\n }\n return first.type !== \"sandbox.command.output.delta\" || firstSandboxName === nextSandboxName;\n}\n\nfunction deltaText(event: SessionEvent): string {\n if (event.type === \"agent.reasoning.delta\") {\n return reasoningText(event.payload);\n }\n const payload = asRecord(event.payload);\n if (event.type === \"sandbox.command.output.delta\") {\n // `chunk` is the canonical wire field (contracts SandboxCommandOutputDeltaPayload);\n // text/output are tolerated legacy shapes.\n for (const key of [\"chunk\", \"text\", \"output\"] as const) {\n if (typeof payload[key] === \"string\") {\n return payload[key] as string;\n }\n }\n return \"\";\n }\n return typeof payload.text === \"string\" ? payload.text : \"\";\n}\n\nfunction reasoningText(payload: unknown): string {\n const record = asRecord(payload);\n if (typeof record.text === \"string\") {\n return record.text;\n }\n const content = asRecord(asRecord(record.item).rawItem).content;\n if (!Array.isArray(content)) {\n return \"\";\n }\n return content\n .map((part) => {\n const text = asRecord(part).text;\n return typeof text === \"string\" ? text : \"\";\n })\n .join(\"\");\n}\n\nfunction sandboxDeltaName(payload: unknown): string | undefined {\n const name = asRecord(payload).name;\n return typeof name === \"string\" ? name : undefined;\n}\n\nfunction sandboxDeltaString(payload: unknown, key: \"stream\" | \"commandId\"): string | undefined {\n const value = asRecord(payload)[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" ? (value as Record<string, unknown>) : {};\n}\n","// packages/events/src/nats-jwt.ts — NATS JWT v2 signing for the auth-callout\n// responder (bring-your-own-compute M-AUTH; dossier §10.1 NATS Accounts per\n// workspace + §17 the isolation smoke).\n//\n// This is the cryptographic core of the auth-callout tenancy boundary. When an\n// external agent connects to NATS presenting its `oge_` enrollment bearer as the\n// connect auth-token, nats-server (configured with `auth_callout`) issues an\n// authorization request on `$SYS.REQ.USER.AUTH`. Our responder (auth-callout.ts)\n// validates the bearer and answers with a SIGNED authorization-response JWT that\n// embeds a SIGNED user JWT scoping the connection to publish/subscribe ONLY\n// `agent.<workspaceId>.>` (+ the reply `_INBOX.>`). That per-subject permission\n// set IS the per-workspace isolation: workspace A's agent literally cannot\n// pub/sub workspace B's subjects (§19 the NATS-Accounts-misconfig leak risk is\n// closed at the JWT-permission layer, not just by subject naming).\n//\n// WHY HAND-ROLL THE JWT ENCODING (vs a dep): the NATS JWT v2 wire format is small,\n// stable, and fully specified (ADR-26 + nats-io/jwt): a base64url header\n// `{\"typ\":\"JWT\",\"alg\":\"ed25519-nkey\"}`, base64url JSON claims whose `jti` is the\n// base32(SHA-512/256(claims-with-blank-jti)), and an ed25519 nkey signature over\n// `header.payload`. nkeys (re-exported by the `nats` package we already depend on)\n// gives us the ed25519 sign primitive; Node `crypto` gives SHA-512/256. So we own\n// the encoding in a few well-tested functions rather than pull an alpha\n// `@nats-io/jwt` (0.0.x) whose nkeys-version compat is uncertain. No `xkey`\n// encryption is used (the bearer is already an authenticated identity claim and\n// the wire is TLS — encryption is an optional ADR-26 hardening, off here).\n//\n// SECURITY: the account SIGNING SEED never leaves this process and is NEVER logged.\n// Callers pass it as a `string` seed; we `fromSeed` it once per sign. The bearer\n// the responder validates is HMAC-verified elsewhere (verifyEnrollmentBearer); this\n// module only mints the scoped NATS credential once identity is proven.\n\nimport { createHash } from \"node:crypto\";\nimport { nkeys } from \"nats\";\n\n/** The NATS JWT v2 header — constant for every token we mint (ADR-26 / nats-io/jwt:\n * `TokenTypeJwt=\"JWT\"`, `AlgorithmNkey=\"ed25519-nkey\"`). */\nconst JWT_HEADER = { typ: \"JWT\", alg: \"ed25519-nkey\" } as const;\n\n/** NATS user-claim `nats.type` discriminator + `nats.version` for v2 claims. */\nconst USER_CLAIM_TYPE = \"user\";\nconst AUTH_RESPONSE_CLAIM_TYPE = \"authorization_response\";\nconst NATS_CLAIM_VERSION = 2;\n\n/** A NATS permission set: subject allow/deny lists (ADR-26 `pub`/`sub` →\n * `allow`/`deny`). An empty/undefined list means \"no explicit grant\" — combined\n * with the agent scope below, the connection can ONLY reach what `allow` lists. */\nexport interface NatsPermission {\n allow?: string[];\n deny?: string[];\n}\n\n/** The pub/sub permissions embedded in a user JWT. */\nexport interface NatsPermissions {\n pub: NatsPermission;\n sub: NatsPermission;\n}\n\n/**\n * The minimal nkey keypair surface this module needs — exactly what\n * `nkeys.fromSeed(seed)` returns. Declared structurally so the module does not\n * leak the `nats` nkeys type through its public signature.\n */\ninterface NkeyPair {\n getPublicKey(): string;\n sign(input: Uint8Array): Uint8Array;\n}\n\n/** base64url (RawURLEncoding — no padding), matching nats-io/jwt's `serialize`. */\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString(\"base64url\");\n}\n\n/** RFC 4648 base32 (standard alphabet, NO padding) — the encoding nats-io/jwt\n * uses for the `jti` hash. Node has no built-in base32, so a tiny encoder. */\nconst BASE32_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\nfunction base32NoPadding(bytes: Uint8Array): string {\n let bits = 0;\n let value = 0;\n let out = \"\";\n for (const byte of bytes) {\n value = (value << 8) | byte;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += BASE32_ALPHABET[(value >>> bits) & 31];\n }\n }\n if (bits > 0) {\n out += BASE32_ALPHABET[(value << (5 - bits)) & 31];\n }\n return out;\n}\n\n/**\n * Compute the canonical NATS `jti`: base32(NoPadding, std-alphabet) of the\n * SHA-512/256 of the claims object SERIALIZED WITH AN EMPTY `jti` (nats-io/jwt's\n * `hash`). nats-server recomputes + verifies this on decode, so it must match\n * byte-for-byte. We serialize the SAME object we will sign, only with `jti:\"\"`.\n */\nfunction computeJti(claimsWithBlankJti: object): string {\n const json = JSON.stringify(claimsWithBlankJti);\n const digest = createHash(\"sha512-256\").update(json, \"utf8\").digest();\n return base32NoPadding(digest);\n}\n\n/**\n * Encode + sign a NATS v2 JWT. The `claims` MUST already carry `iss`/`sub`/`iat`\n * (+ optional `aud`/`exp`) and a `nats` block; this function fills `jti` (the\n * canonical hash), serializes `header.payload`, signs that with `signingKey`, and\n * appends the base64url signature. Returns the compact `header.payload.signature`.\n */\nfunction encodeJwt(claims: Record<string, unknown>, signingKey: NkeyPair): string {\n // jti is the hash of the claims with jti blanked — set it blank, hash, then set.\n const withBlankJti = { ...claims, jti: \"\" };\n const jti = computeJti(withBlankJti);\n const finalClaims = { ...claims, jti };\n\n const header = base64UrlEncode(Buffer.from(JSON.stringify(JWT_HEADER), \"utf8\"));\n const payload = base64UrlEncode(Buffer.from(JSON.stringify(finalClaims), \"utf8\"));\n const signingInput = `${header}.${payload}`;\n const signature = signingKey.sign(Buffer.from(signingInput, \"utf8\"));\n return `${signingInput}.${base64UrlEncode(signature)}`;\n}\n\n/**\n * Input to mint a workspace-scoped NATS user JWT for an enrolled agent.\n * - `userPublicKey` — the `user_nkey` from the authorization request; it MUST be\n * the `sub` of the user JWT (nats-server rejects a mismatch).\n * - `accountSeed` — the callout account SIGNING seed (`SA...`); both the user JWT\n * `iss` (its public key) and the signature come from it. NEVER logged.\n * - `name` — a human label for the user (the agent id), for server logs.\n * - `permissions` — the pub/sub allow/deny lists (the workspace scope).\n * - `expiresAtSeconds` — optional absolute `exp` (unix seconds). When set the\n * server will expire the connection's credential; we tie it to the bearer's\n * remaining life so a revoked/expired enrollment cannot outlive its bearer.\n */\nexport interface MintUserJwtInput {\n userPublicKey: string;\n accountSeed: string;\n name: string;\n permissions: NatsPermissions;\n /** The target account NAME (the `auth_callout.account`) the user binds to; the\n * embedded user JWT's `aud` in server-config mode. */\n audienceAccount: string;\n expiresAtSeconds?: number;\n}\n\n/**\n * Mint a signed NATS user JWT scoped by `permissions`. In auth-callout SERVER\n * mode the user JWT is signed by the callout ISSUER ACCOUNT key, and its `iss` is\n * that account's public key. The returned JWT is embedded as `nats.jwt` in the\n * authorization response.\n */\nexport function mintUserJwt(input: MintUserJwtInput): string {\n const accountKey = nkeys.fromSeed(Buffer.from(input.accountSeed)) as unknown as NkeyPair;\n const accountPublicKey = accountKey.getPublicKey();\n const nowSeconds = Math.floor(Date.now() / 1000);\n\n const natsBlock: Record<string, unknown> = {\n type: USER_CLAIM_TYPE,\n version: NATS_CLAIM_VERSION,\n pub: input.permissions.pub,\n sub: input.permissions.sub,\n // Unlimited subscriptions / data / payload (the workspace subject scope, NOT\n // a connection-resource quota, is the boundary here).\n subs: -1,\n data: -1,\n payload: -1,\n };\n\n const claims: Record<string, unknown> = {\n jti: \"\",\n iat: nowSeconds,\n iss: accountPublicKey,\n name: input.name,\n sub: input.userPublicKey,\n // SERVER-config-mode placement: nats-server reads the embedded user JWT's `aud`\n // as the target account NAME (the configured `auth_callout.account`). This is\n // how the authenticated user binds to that account; the workspace isolation is\n // then carried by the pub/sub permissions below.\n aud: input.audienceAccount,\n nats: natsBlock,\n };\n if (typeof input.expiresAtSeconds === \"number\") {\n claims.exp = input.expiresAtSeconds;\n }\n return encodeJwt(claims, accountKey);\n}\n\n/**\n * Input to mint the authorization RESPONSE JWT the responder publishes back on the\n * request's reply subject (ADR-26 §3).\n * - `userPublicKey` — the request's `user_nkey`; the response `sub`.\n * - `serverId` — the request's `nats.server_id.id` (the server's public key); the\n * response `aud`.\n * - `accountSeed` — the callout account signing seed; signs the response and is\n * its `iss` (public key). NEVER logged.\n * - `userJwt` — the embedded signed user JWT (omit on a denial).\n * - `error` — a human-readable denial message (omit on success). When present the\n * server denies the connection.\n */\nexport interface MintAuthResponseInput {\n userPublicKey: string;\n serverId: string;\n accountSeed: string;\n userJwt?: string;\n error?: string;\n}\n\n/**\n * Mint the signed authorization-response JWT. On success it carries the embedded\n * user JWT (`nats.jwt`); on denial it carries `nats.error` and NO user JWT, which\n * makes nats-server refuse the connection. Signed by the callout account key (its\n * public key is `iss`); `sub` is the user_nkey, `aud` is the server id.\n */\nexport function mintAuthResponse(input: MintAuthResponseInput): string {\n const accountKey = nkeys.fromSeed(Buffer.from(input.accountSeed)) as unknown as NkeyPair;\n const accountPublicKey = accountKey.getPublicKey();\n const nowSeconds = Math.floor(Date.now() / 1000);\n\n const natsBlock: Record<string, unknown> = {\n type: AUTH_RESPONSE_CLAIM_TYPE,\n version: NATS_CLAIM_VERSION,\n };\n if (input.userJwt) {\n natsBlock.jwt = input.userJwt;\n }\n if (input.error) {\n natsBlock.error = input.error;\n }\n\n const claims: Record<string, unknown> = {\n jti: \"\",\n iat: nowSeconds,\n iss: accountPublicKey,\n // The response `aud` MUST be the SERVER public key in server-config mode\n // (nats-server validates \"Audience must be a server public key\"). The\n // authenticated user is placed into the configured `auth_callout.account` (the\n // SAME account the responder + the privileged control plane connect into), so\n // `agent.<ws>.<id>.rpc` request/reply routes; the workspace isolation is carried\n // entirely by the user JWT's pub/sub subject permissions (NOT by cross-account\n // placement, which server-config-mode nats does not support — nats-io#4335).\n aud: input.serverId,\n sub: input.userPublicKey,\n nats: natsBlock,\n };\n return encodeJwt(claims, accountKey);\n}\n\n/**\n * The fields the responder needs out of the authorization REQUEST JWT (ADR-26 §2).\n * The request is itself a NATS JWT (`header.payload.signature`) the server signs;\n * we only DECODE it (the server proves its own identity by the connection, and the\n * embedded `auth_token` is independently HMAC-verified), so we read the payload\n * without re-verifying the server signature.\n */\nexport interface DecodedAuthRequest {\n /** The public user nkey the response user JWT MUST be `sub`-scoped to. */\n userNkey: string;\n /** The server's public id — the response `aud`. */\n serverId: string;\n /** The connect `auth_token` the client presented (our `oge_` bearer), if any. */\n authToken: string | undefined;\n /** The connect username, if any (unused today; present for completeness). */\n user: string | undefined;\n}\n\n/**\n * Decode the authorization-request JWT payload (the middle base64url segment). The\n * request shape (ADR-26 §2): `nats.user_nkey`, `nats.server_id.id`, and the\n * presented connect options under `nats.connect_opts` (`auth_token` / `user`).\n * Returns null on a malformed token so the caller can deny cleanly.\n */\nexport function decodeAuthRequest(token: string): DecodedAuthRequest | null {\n const parts = token.split(\".\");\n if (parts.length !== 3) {\n return null;\n }\n let payload: unknown;\n try {\n payload = JSON.parse(Buffer.from(parts[1]!, \"base64url\").toString(\"utf8\"));\n } catch {\n return null;\n }\n if (typeof payload !== \"object\" || payload === null) {\n return null;\n }\n const nats = (payload as { nats?: unknown }).nats;\n if (typeof nats !== \"object\" || nats === null) {\n return null;\n }\n const natsObj = nats as {\n user_nkey?: unknown;\n server_id?: { id?: unknown } | unknown;\n connect_opts?: { auth_token?: unknown; user?: unknown } | unknown;\n };\n const userNkey = typeof natsObj.user_nkey === \"string\" ? natsObj.user_nkey : null;\n if (!userNkey) {\n return null;\n }\n const serverIdRaw =\n typeof natsObj.server_id === \"object\" && natsObj.server_id !== null\n ? (natsObj.server_id as { id?: unknown }).id\n : undefined;\n const serverId = typeof serverIdRaw === \"string\" ? serverIdRaw : \"\";\n const connectOpts =\n typeof natsObj.connect_opts === \"object\" && natsObj.connect_opts !== null\n ? (natsObj.connect_opts as { auth_token?: unknown; user?: unknown })\n : {};\n const authToken = typeof connectOpts.auth_token === \"string\" ? connectOpts.auth_token : undefined;\n const user = typeof connectOpts.user === \"string\" ? connectOpts.user : undefined;\n return { userNkey, serverId, authToken, user };\n}\n\n/**\n * Build the workspace-scoped permission set for an agent: it may publish + subscribe\n * ONLY `agent.<workspaceId>.>` (its own RPC/event/hello subtree) and the reply\n * `_INBOX.>` subtree (so request/reply round-trips work). Everything else is\n * implicitly denied (an allow-list with no other entries IS the deny-all-else).\n *\n * THE isolation assertion (§17): with `workspaceId=A`, the returned allow lists name\n * only `agent.A.>` — so a connection bearing this credential is rejected by\n * nats-server the instant it tries to pub/sub `agent.B.>`. This is the per-workspace\n * tenancy boundary, enforced cryptographically by the signed JWT, not by naming.\n */\nexport function workspaceAgentPermissions(workspaceId: string): NatsPermissions {\n const agentScope = `agent.${workspaceId}.>`;\n // The reply-inbox subtree must be reachable for request/reply (the control plane\n // requests on agent.<ws>.<id>.rpc with a reply inbox; the agent responds there).\n const inboxScope = \"_INBOX.>\";\n return {\n pub: { allow: [agentScope, inboxScope] },\n sub: { allow: [agentScope, inboxScope] },\n };\n}\n"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;;;ACbP,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWM,SAAS,2BAA2B,QAAwC;AACjF,QAAM,YAA4B,CAAC;AACnC,MAAI,MAAuB;AAE3B,QAAM,QAAQ,MAAM;AAClB,QAAI,CAAC,KAAK;AACR;AAAA,IACF;AACA,cAAU,KAAK;AAAA,MACb,GAAG,IAAI;AAAA,MACP,SACE,IAAI,MAAM,SAAS;AAAA;AAAA;AAAA,QAGf;AAAA,UACE,OAAO,IAAI;AAAA,UACX,gBAAgB,IAAI;AAAA,UACpB,GAAI,IAAI,kBAAkB,SAAY,EAAE,QAAQ,IAAI,cAAc,IAAI,CAAC;AAAA,UACvE,GAAI,IAAI,qBAAqB,SAAY,EAAE,WAAW,IAAI,iBAAiB,IAAI,CAAC;AAAA,UAChF,GAAI,IAAI,gBAAgB,SAAY,EAAE,MAAM,IAAI,YAAY,IAAI,CAAC;AAAA,QACnE;AAAA,UACA;AAAA,QACE,MAAM,IAAI;AAAA,QACV,gBAAgB,IAAI;AAAA,MACtB;AAAA,IACR,CAAC;AACD,UAAM;AAAA,EACR;AAEA,aAAW,SAAS,QAAQ;AAC1B,QAAI,CAAC,mBAAmB,KAAK,GAAG;AAC9B,YAAM;AACN,gBAAU,KAAK,KAAK;AACpB;AAAA,IACF;AAEA,UAAM,YAAY,MAAM,SAAS;AACjC,UAAM,cAAc,YAAY,iBAAiB,MAAM,OAAO,IAAI;AAClE,UAAM,gBAAgB,YAAY,mBAAmB,MAAM,SAAS,QAAQ,IAAI;AAChF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oB,GAAG,UAAU,OAAO;AAC9C,QAAM,YAAY;AAChB,qBAAiB,OAAO,KAAK;AAC3B,UAAI;AACF,cAAM,QAAQ,IAAI,MAAM,IAAI,OAAO;AAAA,MACrC,QAAQ;AAAA,MAGR;AAAA,IACF;AAAA,EACF,GAAG;AACH,SAAO,MAAM;AACX,QAAI,YAAY;AAAA,EAClB;AACF;AAEO,SAAS,UAAwD,OAAkB;AACxF,SAAO;AAAA,IACL,OAAO,MAAM,QAAQ;AAAA,IACrB,UAAU,MAAM,IAAI;AAAA,IACpB,SAAS,KAAK,UAAU,KAAK,CAAC;AAAA,IAC9B;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,wBAAwB,aAA6B;AAC5D,SAAO,cAAc,WAAW;AAClC;","names":["connect","nkeys"]}
|
package/package.json
CHANGED
|
@@ -1,8 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/events",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"type": "module",
|
|
3
|
+
"version": "0.3.1",
|
|
5
4
|
"license": "Apache-2.0",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Cloudgeni-ai/opengeni.git",
|
|
8
|
+
"directory": "packages/events"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
6
15
|
"main": "./dist/index.js",
|
|
7
16
|
"module": "./dist/index.js",
|
|
8
17
|
"types": "./dist/index.d.ts",
|
|
@@ -12,27 +21,18 @@
|
|
|
12
21
|
"import": "./dist/index.js"
|
|
13
22
|
}
|
|
14
23
|
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist",
|
|
17
|
-
"src"
|
|
18
|
-
],
|
|
19
24
|
"publishConfig": {
|
|
20
25
|
"access": "public",
|
|
21
26
|
"provenance": true
|
|
22
27
|
},
|
|
23
28
|
"scripts": {
|
|
24
29
|
"build": "tsup",
|
|
25
|
-
"typecheck": "
|
|
30
|
+
"typecheck": "tsgo --noEmit",
|
|
26
31
|
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
27
32
|
},
|
|
28
33
|
"dependencies": {
|
|
29
|
-
"@opengeni/contracts": "^0.
|
|
30
|
-
"@opengeni/db": "^0.
|
|
34
|
+
"@opengeni/contracts": "^0.10.0",
|
|
35
|
+
"@opengeni/db": "^0.7.1",
|
|
31
36
|
"nats": "^2.29.3"
|
|
32
|
-
},
|
|
33
|
-
"repository": {
|
|
34
|
-
"type": "git",
|
|
35
|
-
"url": "git+https://github.com/Cloudgeni-ai/opengeni.git",
|
|
36
|
-
"directory": "packages/events"
|
|
37
37
|
}
|
|
38
38
|
}
|
package/src/coalesce.ts
CHANGED
|
@@ -25,20 +25,21 @@ export function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent
|
|
|
25
25
|
}
|
|
26
26
|
coalesced.push({
|
|
27
27
|
...run.first,
|
|
28
|
-
payload:
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
28
|
+
payload:
|
|
29
|
+
run.first.type === "sandbox.command.output.delta"
|
|
30
|
+
? // Sandbox output keeps its CANONICAL field (`chunk` — the terminal and
|
|
31
|
+
// projection read it) plus the stream/commandId identity of the run.
|
|
32
|
+
{
|
|
33
|
+
chunk: run.text,
|
|
34
|
+
coalescedUntil: run.lastSequence,
|
|
35
|
+
...(run.sandboxStream !== undefined ? { stream: run.sandboxStream } : {}),
|
|
36
|
+
...(run.sandboxCommandId !== undefined ? { commandId: run.sandboxCommandId } : {}),
|
|
37
|
+
...(run.sandboxName !== undefined ? { name: run.sandboxName } : {}),
|
|
38
|
+
}
|
|
39
|
+
: {
|
|
40
|
+
text: run.text,
|
|
41
|
+
coalescedUntil: run.lastSequence,
|
|
42
|
+
},
|
|
42
43
|
});
|
|
43
44
|
run = null;
|
|
44
45
|
};
|
|
@@ -55,10 +56,10 @@ export function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent
|
|
|
55
56
|
const sandboxStream = isSandbox ? sandboxDeltaString(event.payload, "stream") : undefined;
|
|
56
57
|
const sandboxCommandId = isSandbox ? sandboxDeltaString(event.payload, "commandId") : undefined;
|
|
57
58
|
if (
|
|
58
|
-
run
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
59
|
+
run &&
|
|
60
|
+
sameDeltaRun(run.first, event, run.sandboxName, sandboxName) &&
|
|
61
|
+
run.sandboxStream === sandboxStream &&
|
|
62
|
+
run.sandboxCommandId === sandboxCommandId
|
|
62
63
|
) {
|
|
63
64
|
run.text += deltaText(event);
|
|
64
65
|
run.lastSequence = event.sequence;
|
|
@@ -145,5 +146,5 @@ function sandboxDeltaString(payload: unknown, key: "stream" | "commandId"): stri
|
|
|
145
146
|
}
|
|
146
147
|
|
|
147
148
|
function asRecord(value: unknown): Record<string, unknown> {
|
|
148
|
-
return value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
149
|
+
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
|
|
149
150
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,8 +1,21 @@
|
|
|
1
|
-
import type { SessionBusMessage, SessionEvent } from "@opengeni/contracts";
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import type { SessionBusMessage, SessionEvent, WorkspaceControlEvent } from "@opengeni/contracts";
|
|
2
|
+
import {
|
|
3
|
+
appendSessionEvents,
|
|
4
|
+
appendSessionEventsForTurnAttempt,
|
|
5
|
+
sessionSubject,
|
|
6
|
+
type AppendEventInput,
|
|
7
|
+
type Database,
|
|
8
|
+
} from "@opengeni/db";
|
|
9
|
+
import {
|
|
10
|
+
connect,
|
|
11
|
+
JSONCodec,
|
|
12
|
+
type ConnectionOptions,
|
|
13
|
+
type Msg,
|
|
14
|
+
type NatsConnection,
|
|
15
|
+
type Subscription,
|
|
16
|
+
} from "nats";
|
|
4
17
|
|
|
5
|
-
const codec = JSONCodec<SessionBusMessage | SessionEvent>();
|
|
18
|
+
const codec = JSONCodec<SessionBusMessage | SessionEvent | WorkspaceControlEvent>();
|
|
6
19
|
|
|
7
20
|
export type EventLogger = {
|
|
8
21
|
debug?: (message: string, attributes?: Record<string, unknown>) => void;
|
|
@@ -11,6 +24,8 @@ export type EventLogger = {
|
|
|
11
24
|
|
|
12
25
|
export type EventBusOptions = {
|
|
13
26
|
logger?: EventLogger;
|
|
27
|
+
/** Test/host transport seam; production defaults to the nats.js connector. */
|
|
28
|
+
connect?: typeof connect;
|
|
14
29
|
};
|
|
15
30
|
|
|
16
31
|
const silentLogger: Required<EventLogger> = {
|
|
@@ -163,6 +178,19 @@ export interface RequestConnection {
|
|
|
163
178
|
request(subject: string, payload: Uint8Array, opts: { timeout: number }): Promise<RequestReply>;
|
|
164
179
|
}
|
|
165
180
|
|
|
181
|
+
/**
|
|
182
|
+
* The raw subscribe/publish surface the selfhosted OP-STREAM transport consumes
|
|
183
|
+
* (structurally identical to `@opengeni/runtime`'s `NatsOpStreamConnection`):
|
|
184
|
+
* a plain subscription for the runner's fire-and-forget op frames
|
|
185
|
+
* (`agent.<ws>.<id>.op.<op_id>`) and a plain publish for the server's acks
|
|
186
|
+
* (`agent.<ws>.<id>.ack`). Same managed connection as everything else — a NATS
|
|
187
|
+
* connection natively supports all of it; there is NEVER a second connection.
|
|
188
|
+
*/
|
|
189
|
+
export interface OpStreamConnection {
|
|
190
|
+
subscribe(subject: string): AsyncIterable<{ data: Uint8Array }> & { unsubscribe(): void };
|
|
191
|
+
publish(subject: string, payload: Uint8Array): void;
|
|
192
|
+
}
|
|
193
|
+
|
|
166
194
|
/**
|
|
167
195
|
* A handler answering a request/reply on a subscribed subject: given the request
|
|
168
196
|
* bytes (+ the concrete subject the message landed on, for `agent.<ws>.<id>.rpc`
|
|
@@ -170,11 +198,25 @@ export interface RequestConnection {
|
|
|
170
198
|
* leaves the request unanswered (the caller's request times out / sees no
|
|
171
199
|
* responder), which the control plane maps to `agent_offline` / reconnecting.
|
|
172
200
|
*/
|
|
173
|
-
export type RequestHandler = (
|
|
201
|
+
export type RequestHandler = (
|
|
202
|
+
request: Uint8Array,
|
|
203
|
+
subject: string,
|
|
204
|
+
) => Promise<Uint8Array> | Uint8Array;
|
|
174
205
|
|
|
175
206
|
export type EventBus = {
|
|
176
207
|
publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;
|
|
177
|
-
subscribe: (
|
|
208
|
+
subscribe: (
|
|
209
|
+
workspaceId: string,
|
|
210
|
+
sessionId: string,
|
|
211
|
+
onEvents: (events: SessionEvent[]) => void | Promise<void>,
|
|
212
|
+
) => Promise<() => void>;
|
|
213
|
+
/** Best-effort live invalidation; the event is already durable in Postgres. */
|
|
214
|
+
publishWorkspaceControl: (workspaceId: string, event: WorkspaceControlEvent) => Promise<void>;
|
|
215
|
+
/** One workspace subscription fans a control change to every open descendant view. */
|
|
216
|
+
subscribeWorkspaceControl: (
|
|
217
|
+
workspaceId: string,
|
|
218
|
+
onEvent: (event: WorkspaceControlEvent) => void | Promise<void>,
|
|
219
|
+
) => Promise<() => void>;
|
|
178
220
|
/**
|
|
179
221
|
* Issue a binary request/reply on a subject over the bus's NATS connection
|
|
180
222
|
* (the selfhosted control plane: `agent.<ws>.<id>.rpc`). A new usage of what was
|
|
@@ -182,7 +224,11 @@ export type EventBus = {
|
|
|
182
224
|
* no-responder (NATS 503) or a request timeout; the caller (`NatsControlRpc`)
|
|
183
225
|
* maps those to `agent_offline` / `agent_reconnecting`, never a NotFound.
|
|
184
226
|
*/
|
|
185
|
-
request: (
|
|
227
|
+
request: (
|
|
228
|
+
subject: string,
|
|
229
|
+
payload: Uint8Array,
|
|
230
|
+
opts: { timeoutMs: number },
|
|
231
|
+
) => Promise<RequestReply>;
|
|
186
232
|
/**
|
|
187
233
|
* Subscribe-and-reply on a subject (the responder side — the enrolled agent, or
|
|
188
234
|
* a test stand-in for it): for every request on `subject`, call `handler` and
|
|
@@ -209,6 +255,12 @@ export type EventBus = {
|
|
|
209
255
|
* plane injects this so the transport never opens a second connection.
|
|
210
256
|
*/
|
|
211
257
|
getRequestConnection: () => RequestConnection;
|
|
258
|
+
/**
|
|
259
|
+
* The `OpStreamConnection` accessor the selfhosted op-stream transport
|
|
260
|
+
* consumes (`NatsOpStreamTransport`) — the same managed connection again.
|
|
261
|
+
* Optional so bus test doubles that never exercise op-stream stay valid.
|
|
262
|
+
*/
|
|
263
|
+
getOpStreamConnection?: () => OpStreamConnection;
|
|
212
264
|
isConnected?: () => boolean;
|
|
213
265
|
close: () => Promise<void>;
|
|
214
266
|
};
|
|
@@ -231,10 +283,15 @@ export async function createNatsEventBus(
|
|
|
231
283
|
connectOptions.user = auth.user;
|
|
232
284
|
connectOptions.pass = auth.pass;
|
|
233
285
|
}
|
|
234
|
-
const nc = await connect(withReconnectDefaults(connectOptions));
|
|
286
|
+
const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));
|
|
235
287
|
let connected = true;
|
|
236
288
|
logConnectionStatus(nc, "event-bus", options.logger, (type) => {
|
|
237
|
-
if (
|
|
289
|
+
if (
|
|
290
|
+
type === "disconnect" ||
|
|
291
|
+
type === "reconnecting" ||
|
|
292
|
+
type === "staleConnection" ||
|
|
293
|
+
type === "error"
|
|
294
|
+
) {
|
|
238
295
|
connected = false;
|
|
239
296
|
} else if (type === "connect" || type === "reconnect") {
|
|
240
297
|
connected = true;
|
|
@@ -243,6 +300,12 @@ export async function createNatsEventBus(
|
|
|
243
300
|
const requestConnection: RequestConnection = {
|
|
244
301
|
request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeout),
|
|
245
302
|
};
|
|
303
|
+
const opStreamConnection: OpStreamConnection = {
|
|
304
|
+
subscribe: (subject) => nc.subscribe(subject),
|
|
305
|
+
publish: (subject, payload) => {
|
|
306
|
+
nc.publish(subject, payload);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
246
309
|
return {
|
|
247
310
|
publish: async (workspaceId, sessionId, events) => {
|
|
248
311
|
if (events.length === 0) {
|
|
@@ -257,24 +320,57 @@ export async function createNatsEventBus(
|
|
|
257
320
|
// next successful publish's gap-backfill, or a stream reconnect); it must
|
|
258
321
|
// never throw the in-flight turn to death.
|
|
259
322
|
try {
|
|
260
|
-
nc.publish(
|
|
323
|
+
nc.publish(
|
|
324
|
+
sessionSubject(workspaceId, sessionId),
|
|
325
|
+
codec.encode({ workspaceId, sessionId, events }),
|
|
326
|
+
);
|
|
261
327
|
} catch (error) {
|
|
262
328
|
// `publish()` throws synchronously only when the connection is fully
|
|
263
329
|
// CLOSED (with infinite reconnect, effectively never outside shutdown).
|
|
264
|
-
(options.logger?.warn ?? silentLogger.warn)(
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
330
|
+
(options.logger?.warn ?? silentLogger.warn)(
|
|
331
|
+
"NATS live publish dropped; events are durable in the DB and reconcile on stream replay",
|
|
332
|
+
{
|
|
333
|
+
workspaceId,
|
|
334
|
+
sessionId,
|
|
335
|
+
error: error instanceof Error ? error.message : String(error),
|
|
336
|
+
},
|
|
337
|
+
);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);
|
|
341
|
+
},
|
|
342
|
+
subscribe: async (workspaceId, sessionId, onEvents) =>
|
|
343
|
+
subscribeSession(nc, workspaceId, sessionId, onEvents),
|
|
344
|
+
publishWorkspaceControl: async (workspaceId, event) => {
|
|
345
|
+
try {
|
|
346
|
+
nc.publish(workspaceControlSubject(workspaceId), codec.encode(event));
|
|
347
|
+
} catch (error) {
|
|
348
|
+
(options.logger?.warn ?? silentLogger.warn)(
|
|
349
|
+
"NATS workspace-control invalidation dropped; clients reconcile from Postgres",
|
|
350
|
+
{
|
|
351
|
+
workspaceId,
|
|
352
|
+
revision: event.revision,
|
|
353
|
+
error: error instanceof Error ? error.message : String(error),
|
|
354
|
+
},
|
|
355
|
+
);
|
|
269
356
|
return;
|
|
270
357
|
}
|
|
271
358
|
await flushWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);
|
|
272
359
|
},
|
|
273
|
-
|
|
360
|
+
subscribeWorkspaceControl: async (workspaceId, onEvent) => {
|
|
361
|
+
const sub = nc.subscribe(workspaceControlSubject(workspaceId));
|
|
362
|
+
void (async () => {
|
|
363
|
+
for await (const msg of sub) {
|
|
364
|
+
await onEvent(codec.decode(msg.data) as WorkspaceControlEvent);
|
|
365
|
+
}
|
|
366
|
+
})();
|
|
367
|
+
return () => sub.unsubscribe();
|
|
368
|
+
},
|
|
274
369
|
request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),
|
|
275
370
|
subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler),
|
|
276
371
|
subscribeAgentEvents: (subject, handler) => subscribeAgentEvents(nc, subject, handler),
|
|
277
372
|
getRequestConnection: () => requestConnection,
|
|
373
|
+
getOpStreamConnection: () => opStreamConnection,
|
|
278
374
|
isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),
|
|
279
375
|
close: async () => {
|
|
280
376
|
await nc.drain();
|
|
@@ -320,7 +416,7 @@ export async function createResponderConnection(
|
|
|
320
416
|
auth: NatsConnectAuth,
|
|
321
417
|
subject: string,
|
|
322
418
|
handler: RequestHandler,
|
|
323
|
-
options: { name?: string; logger?: EventLogger } = {},
|
|
419
|
+
options: { name?: string; logger?: EventLogger; connect?: typeof connect } = {},
|
|
324
420
|
): Promise<ResponderConnection> {
|
|
325
421
|
const connectOptions: ConnectionOptions = { servers: natsUrl };
|
|
326
422
|
if (options.name) {
|
|
@@ -332,8 +428,12 @@ export async function createResponderConnection(
|
|
|
332
428
|
} else if (auth.kind === "token") {
|
|
333
429
|
connectOptions.token = auth.token;
|
|
334
430
|
}
|
|
335
|
-
const nc = await connect(withReconnectDefaults(connectOptions));
|
|
336
|
-
logConnectionStatus(
|
|
431
|
+
const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));
|
|
432
|
+
logConnectionStatus(
|
|
433
|
+
nc,
|
|
434
|
+
options.name ? `auth-callout:${options.name}` : "auth-callout",
|
|
435
|
+
options.logger,
|
|
436
|
+
);
|
|
337
437
|
const sub: Subscription = nc.subscribe(subject);
|
|
338
438
|
void (async () => {
|
|
339
439
|
for await (const msg of sub) {
|
|
@@ -357,15 +457,88 @@ export async function createResponderConnection(
|
|
|
357
457
|
};
|
|
358
458
|
}
|
|
359
459
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
460
|
+
/**
|
|
461
|
+
* Optional timing seam for {@link appendAndPublishEvents}: `onAppend` fires after
|
|
462
|
+
* the durable DB write, `onPublish` after the best-effort live fan-out (on both
|
|
463
|
+
* success AND failure of the publish, so a broker blip still records its latency).
|
|
464
|
+
* Kept as a plain callback so the events package takes no dependency on the
|
|
465
|
+
* observability package; the worker wires it to Prometheus histograms.
|
|
466
|
+
*/
|
|
467
|
+
export type AppendPublishObserver = {
|
|
468
|
+
onAppend?: (info: { durationSeconds: number; count: number }) => void;
|
|
469
|
+
onPublish?: (info: { durationSeconds: number; count: number }) => void;
|
|
470
|
+
};
|
|
471
|
+
|
|
472
|
+
export type AppendPublishOptions = AppendPublishObserver & {
|
|
473
|
+
/** Test/host persistence seam; production uses the database implementation. */
|
|
474
|
+
appendSessionEvents?: typeof appendSessionEvents;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Invoke a phase-timing callback with the elapsed seconds since `startedAt` and the
|
|
479
|
+
* event count, swallowing any throw so a metrics sink can never break the
|
|
480
|
+
* append/publish path. Exported for direct unit testing: the wider test suite
|
|
481
|
+
* installs a process-global `mock.module("@opengeni/events")` that stubs
|
|
482
|
+
* `appendAndPublishEvents` (spreading the real module for everything else), so the
|
|
483
|
+
* observer wiring can only be exercised through a helper that survives that mock.
|
|
484
|
+
*/
|
|
485
|
+
export function observeSince(
|
|
486
|
+
fn: ((info: { durationSeconds: number; count: number }) => void) | undefined,
|
|
487
|
+
startedAt: number,
|
|
488
|
+
count: number,
|
|
489
|
+
): void {
|
|
490
|
+
if (!fn) {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
fn({ durationSeconds: Math.max(0, (performance.now() - startedAt) / 1000), count });
|
|
495
|
+
} catch {
|
|
496
|
+
// Metrics emission must never affect the append/publish path.
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
export async function appendAndPublishEvents(
|
|
501
|
+
db: Database,
|
|
502
|
+
bus: EventBus,
|
|
503
|
+
workspaceId: string,
|
|
504
|
+
sessionId: string,
|
|
505
|
+
events: AppendEventInput[],
|
|
506
|
+
options: AppendPublishOptions = {},
|
|
507
|
+
): Promise<SessionEvent[]> {
|
|
508
|
+
const appendStartedAt = performance.now();
|
|
509
|
+
const appended = await (options.appendSessionEvents ?? appendSessionEvents)(
|
|
510
|
+
db,
|
|
511
|
+
workspaceId,
|
|
512
|
+
sessionId,
|
|
513
|
+
events,
|
|
514
|
+
);
|
|
515
|
+
observeSince(options.onAppend, appendStartedAt, appended.length);
|
|
516
|
+
await publishDurableSessionEvents(bus, workspaceId, sessionId, appended, options);
|
|
517
|
+
return appended;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Best-effort live fanout for events another DB helper already committed in
|
|
522
|
+
* the same transaction as related durable state. This must never append again.
|
|
523
|
+
*/
|
|
524
|
+
export async function publishDurableSessionEvents(
|
|
525
|
+
bus: EventBus,
|
|
526
|
+
workspaceId: string,
|
|
527
|
+
sessionId: string,
|
|
528
|
+
appended: SessionEvent[],
|
|
529
|
+
observe?: AppendPublishObserver,
|
|
530
|
+
): Promise<void> {
|
|
531
|
+
if (appended.length === 0) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
// The committed DB events are the durable system of record; this publish is only a
|
|
363
535
|
// best-effort LIVE fan-out. Guard it so NO EventBus implementation can throw an
|
|
364
536
|
// in-flight agent turn to death on a transient NATS disconnect — consumers
|
|
365
537
|
// reconcile any missed live events from the durable log via the events/stream
|
|
366
538
|
// endpoint (DB replay + gap-backfill). The managed `createNatsEventBus` bus
|
|
367
539
|
// already swallows internally, so this catch is the belt-and-suspenders guard
|
|
368
540
|
// for any other bus impl (and a fully CLOSED connection during shutdown).
|
|
541
|
+
const publishStartedAt = performance.now();
|
|
369
542
|
try {
|
|
370
543
|
await bus.publish(workspaceId, sessionId, appended);
|
|
371
544
|
} catch (error) {
|
|
@@ -374,10 +547,62 @@ export async function appendAndPublishEvents(db: Database, bus: EventBus, worksp
|
|
|
374
547
|
error,
|
|
375
548
|
);
|
|
376
549
|
}
|
|
377
|
-
|
|
550
|
+
observeSince(observe?.onPublish, publishStartedAt, appended.length);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Best-effort fanout for a workspace-control event already committed in PostgreSQL. */
|
|
554
|
+
export async function publishDurableWorkspaceControlEvent(
|
|
555
|
+
bus: EventBus,
|
|
556
|
+
workspaceId: string,
|
|
557
|
+
event: WorkspaceControlEvent,
|
|
558
|
+
): Promise<void> {
|
|
559
|
+
try {
|
|
560
|
+
await bus.publishWorkspaceControl(workspaceId, event);
|
|
561
|
+
} catch (error) {
|
|
562
|
+
console.warn(
|
|
563
|
+
`[events] workspace-control live publish failed for ${workspaceId} at revision ${event.revision}; the event is durable and reconciles on stream replay`,
|
|
564
|
+
error,
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
export async function appendAndPublishTurnEventsFenced(
|
|
570
|
+
db: Database,
|
|
571
|
+
bus: EventBus,
|
|
572
|
+
workspaceId: string,
|
|
573
|
+
sessionId: string,
|
|
574
|
+
turnId: string,
|
|
575
|
+
executionGeneration: number,
|
|
576
|
+
attemptId: string,
|
|
577
|
+
events: AppendEventInput[],
|
|
578
|
+
): Promise<{ events: SessionEvent[]; accepted: boolean }> {
|
|
579
|
+
const result = await appendSessionEventsForTurnAttempt(
|
|
580
|
+
db,
|
|
581
|
+
workspaceId,
|
|
582
|
+
sessionId,
|
|
583
|
+
turnId,
|
|
584
|
+
executionGeneration,
|
|
585
|
+
attemptId,
|
|
586
|
+
events,
|
|
587
|
+
);
|
|
588
|
+
if (result.events.length === 0) return result;
|
|
589
|
+
try {
|
|
590
|
+
await bus.publish(workspaceId, sessionId, result.events);
|
|
591
|
+
} catch (error) {
|
|
592
|
+
console.warn(
|
|
593
|
+
`[events] live fenced publish failed for ${workspaceId}/${sessionId}/${turnId}@${executionGeneration}/${attemptId}; ${result.events.length} event(s) are durable`,
|
|
594
|
+
error,
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
return result;
|
|
378
598
|
}
|
|
379
599
|
|
|
380
|
-
function subscribeSession(
|
|
600
|
+
function subscribeSession(
|
|
601
|
+
nc: NatsConnection,
|
|
602
|
+
workspaceId: string,
|
|
603
|
+
sessionId: string,
|
|
604
|
+
onEvents: (events: SessionEvent[]) => void | Promise<void>,
|
|
605
|
+
): () => void {
|
|
381
606
|
const sub: Subscription = nc.subscribe(sessionSubject(workspaceId, sessionId));
|
|
382
607
|
void (async () => {
|
|
383
608
|
for await (const msg of sub) {
|
|
@@ -398,7 +623,12 @@ function subscribeSession(nc: NatsConnection, workspaceId: string, sessionId: st
|
|
|
398
623
|
* the caller owns the mapping. The reply is delivered via the connection's
|
|
399
624
|
* built-in mux inbox; no extra subscription is created here.
|
|
400
625
|
*/
|
|
401
|
-
async function requestReply(
|
|
626
|
+
async function requestReply(
|
|
627
|
+
nc: NatsConnection,
|
|
628
|
+
subject: string,
|
|
629
|
+
payload: Uint8Array,
|
|
630
|
+
timeout: number,
|
|
631
|
+
): Promise<RequestReply> {
|
|
402
632
|
const msg: Msg = await nc.request(subject, payload, { timeout });
|
|
403
633
|
return { data: msg.data };
|
|
404
634
|
}
|
|
@@ -410,7 +640,11 @@ async function requestReply(nc: NatsConnection, subject: string, payload: Uint8A
|
|
|
410
640
|
* A handler that throws (or a message with no `reply` subject) is left unanswered
|
|
411
641
|
* — the requester then sees a timeout, never a malformed reply.
|
|
412
642
|
*/
|
|
413
|
-
function subscribeRequests(
|
|
643
|
+
function subscribeRequests(
|
|
644
|
+
nc: NatsConnection,
|
|
645
|
+
subject: string,
|
|
646
|
+
handler: RequestHandler,
|
|
647
|
+
): () => void {
|
|
414
648
|
const sub: Subscription = nc.subscribe(subject);
|
|
415
649
|
void (async () => {
|
|
416
650
|
for await (const msg of sub) {
|
|
@@ -462,7 +696,7 @@ function subscribeAgentEvents(
|
|
|
462
696
|
};
|
|
463
697
|
}
|
|
464
698
|
|
|
465
|
-
export function formatSse(event:
|
|
699
|
+
export function formatSse<T extends { sequence: number; type: string }>(event: T): string {
|
|
466
700
|
return [
|
|
467
701
|
`id: ${event.sequence}`,
|
|
468
702
|
`event: ${event.type}`,
|
|
@@ -471,3 +705,7 @@ export function formatSse(event: SessionEvent): string {
|
|
|
471
705
|
"",
|
|
472
706
|
].join("\n");
|
|
473
707
|
}
|
|
708
|
+
|
|
709
|
+
function workspaceControlSubject(workspaceId: string): string {
|
|
710
|
+
return `workspaces.${workspaceId}.control`;
|
|
711
|
+
}
|