@opengeni/events 4.2.1-canary.39593846423001 → 4.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/chunk-FIR764WR.js +17 -0
- package/dist/chunk-FIR764WR.js.map +1 -0
- package/dist/durable-fanout.d.ts +15 -0
- package/dist/durable-fanout.js +9 -0
- package/dist/durable-fanout.js.map +1 -0
- package/dist/index.d.ts +2 -15
- package/dist/index.js +5 -10
- package/dist/index.js.map +1 -1
- package/package.json +7 -3
- package/src/durable-fanout.ts +35 -0
- package/src/index.ts +9 -35
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/durable-fanout.ts
|
|
2
|
+
var SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1;
|
|
3
|
+
function requireSessionEventDurableFanoutCapability(bus) {
|
|
4
|
+
const capability = bus?.sessionEventDurableFanout;
|
|
5
|
+
if (capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION || typeof capability.subscribeRecovery !== "function") {
|
|
6
|
+
throw new Error(
|
|
7
|
+
"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect"
|
|
8
|
+
);
|
|
9
|
+
}
|
|
10
|
+
return capability;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
15
|
+
requireSessionEventDurableFanoutCapability
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=chunk-FIR764WR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/durable-fanout.ts"],"sourcesContent":["// The broker-independent durable event recovery contract.\n/**\n * Versioned recovery contract for already-durable session-event fanout.\n *\n * A publisher acknowledgement alone cannot prove that every API subscriber was\n * connected for the live message. Supported broker-backed buses must therefore\n * notify consumers after transport subscriptions have been restored so an\n * already-open SSE stream can run one bounded Postgres catch-up. A bus that can\n * never disconnect may implement this as a listener registry that never fires.\n */\nexport const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1 as const;\n\nexport type SessionEventDurableFanoutCapability = {\n version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;\n subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;\n};\n\nexport function requireSessionEventDurableFanoutCapability(\n bus: unknown,\n): SessionEventDurableFanoutCapability {\n const capability = (bus as { sessionEventDurableFanout?: unknown } | null)\n ?.sessionEventDurableFanout as\n | { version?: unknown; subscribeRecovery?: unknown }\n | null\n | undefined;\n if (\n capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION ||\n typeof capability.subscribeRecovery !== \"function\"\n ) {\n throw new Error(\n \"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect\",\n );\n }\n return capability as SessionEventDurableFanoutCapability;\n}\n"],"mappings":";AAUO,IAAM,kDAAkD;AAOxD,SAAS,2CACd,KACqC;AACrC,QAAM,aAAc,KAChB;AAIJ,MACE,YAAY,YAAY,mDACxB,OAAO,WAAW,sBAAsB,YACxC;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Versioned recovery contract for already-durable session-event fanout.
|
|
3
|
+
*
|
|
4
|
+
* A publisher acknowledgement alone cannot prove that every API subscriber was
|
|
5
|
+
* connected for the live message. Supported broker-backed buses must therefore
|
|
6
|
+
* notify consumers after transport subscriptions have been restored so an
|
|
7
|
+
* already-open SSE stream can run one bounded Postgres catch-up. A bus that can
|
|
8
|
+
* never disconnect may implement this as a listener registry that never fires.
|
|
9
|
+
*/
|
|
10
|
+
export declare const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION: 1;
|
|
11
|
+
export type SessionEventDurableFanoutCapability = {
|
|
12
|
+
version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;
|
|
13
|
+
subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;
|
|
14
|
+
};
|
|
15
|
+
export declare function requireSessionEventDurableFanoutCapability(bus: unknown): SessionEventDurableFanoutCapability;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
3
|
+
requireSessionEventDurableFanoutCapability
|
|
4
|
+
} from "./chunk-FIR764WR.js";
|
|
5
|
+
export {
|
|
6
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
7
|
+
requireSessionEventDurableFanoutCapability
|
|
8
|
+
};
|
|
9
|
+
//# sourceMappingURL=durable-fanout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { type SessionEventDurableFanoutCapability } from "./durable-fanout.js";
|
|
2
|
+
export { SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION, requireSessionEventDurableFanoutCapability, type SessionEventDurableFanoutCapability, } from "./durable-fanout.js";
|
|
1
3
|
import { type SessionEvent, type WorkspaceControlEvent } from "@opengeni/contracts";
|
|
2
4
|
import { appendSessionEvents, type AppendEventInput, type CanonicalTurnStartupMilestoneReceipt, type Database, type SessionEventAppendObserver, type SessionEventMutationInput } from "@opengeni/db";
|
|
3
5
|
import { connect } from "nats";
|
|
@@ -137,21 +139,6 @@ export interface OpStreamConnection {
|
|
|
137
139
|
* responder), which the control plane maps to `agent_offline` / reconnecting.
|
|
138
140
|
*/
|
|
139
141
|
export type RequestHandler = (request: Uint8Array, subject: string) => Promise<Uint8Array> | Uint8Array;
|
|
140
|
-
/**
|
|
141
|
-
* Versioned recovery contract for already-durable session-event fanout.
|
|
142
|
-
*
|
|
143
|
-
* A publisher acknowledgement alone cannot prove that every API subscriber was
|
|
144
|
-
* connected for the live message. Supported broker-backed buses must therefore
|
|
145
|
-
* notify consumers after transport subscriptions have been restored so an
|
|
146
|
-
* already-open SSE stream can run one bounded Postgres catch-up. A bus that can
|
|
147
|
-
* never disconnect may implement this as a listener registry that never fires.
|
|
148
|
-
*/
|
|
149
|
-
export declare const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION: 1;
|
|
150
|
-
export type SessionEventDurableFanoutCapability = {
|
|
151
|
-
version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;
|
|
152
|
-
subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;
|
|
153
|
-
};
|
|
154
|
-
export declare function requireSessionEventDurableFanoutCapability(bus: unknown): SessionEventDurableFanoutCapability;
|
|
155
142
|
export type EventBus = {
|
|
156
143
|
/**
|
|
157
144
|
* Mandatory paired recovery contract for durable session-event publication.
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
3
|
+
requireSessionEventDurableFanoutCapability
|
|
4
|
+
} from "./chunk-FIR764WR.js";
|
|
5
|
+
|
|
1
6
|
// src/index.ts
|
|
2
7
|
import {
|
|
3
8
|
boundSessionEvent,
|
|
@@ -657,16 +662,6 @@ function subscribeWithResubscribe(nc, context, onMessage, resubscribeDelayMs = n
|
|
|
657
662
|
sub?.unsubscribe();
|
|
658
663
|
};
|
|
659
664
|
}
|
|
660
|
-
var SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1;
|
|
661
|
-
function requireSessionEventDurableFanoutCapability(bus) {
|
|
662
|
-
const capability = bus?.sessionEventDurableFanout;
|
|
663
|
-
if (capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION || typeof capability.subscribeRecovery !== "function") {
|
|
664
|
-
throw new Error(
|
|
665
|
-
"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect"
|
|
666
|
-
);
|
|
667
|
-
}
|
|
668
|
-
return capability;
|
|
669
|
-
}
|
|
670
665
|
async function createNatsEventBus(natsUrl, auth, options = {}) {
|
|
671
666
|
const connectOptions = { servers: natsUrl };
|
|
672
667
|
if (auth) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/recovering-request.ts","../src/coalesce.ts","../src/nats-jwt.ts"],"sourcesContent":["import {\n boundSessionEvent,\n boundWorkspaceControlEvent,\n sessionEventJsonBytes,\n sessionEventPayloadTruncation,\n type SessionBusMessage,\n type SessionEvent,\n type SessionEventBoundarySurface,\n type WorkspaceControlEvent,\n} from \"@opengeni/contracts\";\nimport {\n appendSessionEvents,\n appendSessionEventsForTurnAttempt,\n sessionSubject,\n type AppendEventInput,\n type CanonicalTurnStartupMilestoneReceipt,\n type Database,\n type SessionEventAppendObserver,\n type SessionEventMutationInput,\n} from \"@opengeni/db\";\nimport {\n connect,\n headers as natsHeaders,\n JSONCodec,\n type ConnectionOptions,\n type Msg,\n type NatsConnection,\n type Subscription,\n type Status,\n} from \"nats\";\nimport { recoveringRequest } from \"./recovering-request\";\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 * Metrics seam: called once for every subscription that ends without being\n * unsubscribed (see {@link natsSubscriptionTerminationCounter}). A throwing\n * sink is ignored.\n */\n onSubscriptionTerminated?: (termination: NatsSubscriptionTermination) => void;\n /** Test seam for the responder resubscribe backoff; production uses {@link natsResubscribeDelayMs}. */\n resubscribeDelayMs?: (attempt: number) => number;\n};\n\nconst silentLogger: Required<EventLogger> = {\n debug: () => {},\n warn: () => {},\n};\n\nexport {\n SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES,\n coalesceSessionEventDeltas,\n coalesceSessionEventDeltasWithCoverage,\n reasoningDeltaSeparator,\n type CoalescedSessionEventPage,\n} 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 * - `ignoreAuthErrorAbort` - nats.js otherwise stops reconnecting for good\n * after the same auth error twice in a row, which is exactly what a broker\n * or auth-callout responder restart produces for a few seconds.\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 ignoreAuthErrorAbort: true,\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/** Comfortably below NATS Core's common 1 MiB max_payload default. */\nexport const SESSION_EVENT_NATS_MESSAGE_MAX_BYTES = 512 * 1024;\n/** Payload is <=64 KiB; the larger envelope leaves deterministic wire headroom. */\nexport const SESSION_EVENT_SSE_FRAME_MAX_BYTES = 96 * 1024;\n/** Independent count+byte envelope for one durable HTTP replay response. */\nexport const SESSION_EVENT_HTTP_PAGE_MAX_BYTES = 1024 * 1024;\n/** Workspace invalidations are one compact event, never a broker evidence blob. */\nexport const WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES = 32 * 1024;\n/** Count+byte envelope for one workspace-control REST replay page. */\nexport const WORKSPACE_CONTROL_HTTP_PAGE_MAX_BYTES = 1024 * 1024;\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 * Flush a durable outbox publication and reject unless the NATS server confirms\n * the write within the bounded wait. A timeout can still leave the original\n * bytes buffered for reconnect, so callers must remain duplicate-safe when they\n * retry the durable obligation.\n */\nasync function flushConfirmedWithTimeout(nc: NatsConnection, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`NATS publish confirmation timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n try {\n await Promise.race([nc.flush(), 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, status: Status) => void,\n): void {\n void (async () => {\n try {\n for await (const status of nc.status()) {\n onStatus?.(status.type, status);\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\n/** Closed, content-free description of a subscription failure for logs. */\nfunction subscriptionFailureAttributes(error: unknown): Record<string, unknown> {\n if (!error || typeof error !== \"object\") return { errorType: typeof error };\n try {\n const candidate = error as { name?: unknown; code?: unknown };\n return {\n errorName: typeof candidate.name === \"string\" ? candidate.name.slice(0, 64) : \"unknown\",\n ...(typeof candidate.code === \"string\" ? { errorCode: candidate.code.slice(0, 64) } : {}),\n };\n } catch {\n return { errorName: \"unknown\" };\n }\n}\n\n/**\n * Closed label set for {@link NatsSubscriptionTermination}. Each value names one\n * subscription role this package owns; no subject, tenant, or payload\n * dimension is ever admitted, so a metric sink can use them as labels.\n */\nexport const NATS_SUBSCRIPTION_KINDS = [\n \"session_events\",\n \"workspace_control\",\n \"request_responder\",\n \"agent_events\",\n \"auth_callout\",\n] as const;\nexport type NatsSubscriptionKind = (typeof NATS_SUBSCRIPTION_KINDS)[number];\n\n/**\n * What happens after an unexpected end: a per-consumer subscription tells its\n * consumer (`consumer_reconnect`, e.g. session SSE fails retryably and the\n * client replays from Postgres), a process-lifetime responder resubscribes with\n * bounded backoff (`resubscribe`), and a consumer that registered no hook only\n * relies on its own durable re-read (`none`).\n */\nexport const NATS_SUBSCRIPTION_RECOVERIES = [\"consumer_reconnect\", \"resubscribe\", \"none\"] as const;\nexport type NatsSubscriptionRecovery = (typeof NATS_SUBSCRIPTION_RECOVERIES)[number];\n\nexport type NatsSubscriptionTermination = {\n kind: NatsSubscriptionKind;\n recovery: NatsSubscriptionRecovery;\n};\n\n/** Prometheus counter name for {@link natsSubscriptionTerminationCounter}. */\nexport const NATS_SUBSCRIPTION_TERMINATIONS_METRIC =\n \"opengeni_nats_subscription_terminations_total\";\n\n/**\n * Adapt a counter sink (the API/worker `Observability`) into the\n * `onSubscriptionTerminated` hook. Labels are the closed kind/recovery sets.\n */\nexport function natsSubscriptionTerminationCounter(sink: {\n incrementCounter(input: { name: string; help?: string; labels?: Record<string, string> }): void;\n}): (termination: NatsSubscriptionTermination) => void {\n return ({ kind, recovery }) => {\n sink.incrementCounter({\n name: NATS_SUBSCRIPTION_TERMINATIONS_METRIC,\n help: \"NATS subscriptions that ended without being unsubscribed, by subscription kind and recovery path.\",\n labels: { kind, recovery },\n });\n };\n}\n\n/** Per-subscription consumer options for {@link EventBus.subscribe}. */\nexport type BusSubscriptionOptions = {\n /**\n * Called at most once when the live transport subscription ends while the\n * consumer still holds it (a broker-side error such as a permissions\n * violation, or an iterator end the consumer did not request). Live events\n * stop after this call, so the consumer must reconcile from Postgres: session\n * and workspace-control SSE fail the stream retryably and the client\n * reconnects and replays. Never called after the returned unsubscribe runs or\n * while the bus itself is closing.\n */\n onTerminated?: (error: unknown) => void;\n};\n\n/** Bounded resubscribe backoff for process-lifetime responders: 1 s doubling to 30 s, plus up to 1 s jitter. */\nexport function natsResubscribeDelayMs(\n attempt: number,\n random: () => number = Math.random,\n): number {\n const exponent = Number.isFinite(attempt) ? Math.min(Math.max(0, Math.trunc(attempt) - 1), 5) : 0;\n const sample = random();\n const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1 - Number.EPSILON) : 0;\n return Math.min(30_000, 1_000 * 2 ** exponent) + Math.floor(unit * 1_000);\n}\n\ntype SubscriptionContext = {\n label: string;\n kind: NatsSubscriptionKind;\n subject: string;\n queue?: string;\n logger?: EventLogger | undefined;\n onSubscriptionTerminated?: ((termination: NatsSubscriptionTermination) => void) | undefined;\n};\n\ntype SubscriptionEnd = { error: unknown } | { error?: undefined };\n\n/**\n * Pump one subscription for its lifetime from a detached loop. The loop must\n * never reject: the API's fatal process boundary exits on any unhandled\n * rejection, so a single broker-side subscription error (a permissions\n * violation delivered to this subscription, a malformed payload, a throwing\n * consumer) used to take down every request and SSE stream on the pod. A\n * per-message failure is isolated so one poison message cannot end delivery.\n * The end of the iterator, with or without an error, is reported to `onEnded`\n * so the owner can decide whether it was requested (unsubscribe, bus close) or\n * must be surfaced: consumers reconcile from Postgres and process-lifetime\n * responders resubscribe (see {@link subscribeWithTermination} and\n * {@link subscribeWithResubscribe}). Logs never carry message payloads.\n */\nfunction pumpSubscription<T>(\n subscription: AsyncIterable<T>,\n context: SubscriptionContext,\n onMessage: (message: T) => void | Promise<void>,\n onEnded: (end: SubscriptionEnd) => void,\n): void {\n const warn = context.logger?.warn ?? silentLogger.warn;\n void (async () => {\n let end: SubscriptionEnd = {};\n try {\n for await (const message of subscription) {\n try {\n await onMessage(message);\n } catch (error) {\n try {\n warn(\"NATS subscription message dropped\", {\n label: context.label,\n subject: context.subject,\n ...subscriptionFailureAttributes(error),\n });\n } catch {\n // Logging must never end delivery.\n }\n }\n }\n } catch (error) {\n end = { error };\n }\n try {\n onEnded(end);\n } catch {\n // A termination observer must never escape the detached loop.\n }\n })();\n}\n\n/** Log + count one unexpected subscription end. Never throws. */\nfunction reportSubscriptionTermination(\n context: SubscriptionContext,\n recovery: NatsSubscriptionRecovery,\n end: SubscriptionEnd,\n): void {\n try {\n (context.logger?.warn ?? silentLogger.warn)(\n \"error\" in end && end.error !== undefined\n ? \"NATS subscription ended with an error\"\n : \"NATS subscription ended unexpectedly\",\n {\n label: context.label,\n subject: context.subject,\n recovery,\n ...(\"error\" in end && end.error !== undefined\n ? subscriptionFailureAttributes(end.error)\n : {}),\n },\n );\n } catch {\n // Logging must never escape the detached loop.\n }\n try {\n context.onSubscriptionTerminated?.({ kind: context.kind, recovery });\n } catch {\n // A metrics sink must never escape the detached loop.\n }\n}\n\nfunction connectionShuttingDown(nc: NatsConnection): boolean {\n return nc.isClosed() || nc.isDraining();\n}\n\n/**\n * A per-consumer subscription (one SSE stream, one MCP wait). An end that the\n * consumer did not request is logged, counted, and handed to the consumer's\n * `onTerminated` exactly once so it can reconcile from Postgres instead of\n * silently receiving nothing while its heartbeats continue.\n */\nfunction subscribeWithTermination(\n nc: NatsConnection,\n context: SubscriptionContext,\n onMessage: (message: Msg) => void | Promise<void>,\n options: BusSubscriptionOptions | undefined,\n): () => void {\n const sub: Subscription = nc.subscribe(context.subject);\n let released = false;\n const onTerminated = options?.onTerminated;\n pumpSubscription(sub, context, onMessage, (end) => {\n if (released || connectionShuttingDown(nc)) return;\n reportSubscriptionTermination(context, onTerminated ? \"consumer_reconnect\" : \"none\", end);\n try {\n onTerminated?.(\"error\" in end ? end.error : undefined);\n } catch {\n // The consumer hook must never escape the detached loop.\n }\n });\n return () => {\n released = true;\n sub.unsubscribe();\n };\n}\n\n/**\n * A process-lifetime responder (auth callout, Codemode requests, agent-event\n * ingestion). Nothing else would ever re-create it, so an unexpected end is\n * logged, counted, and followed by a resubscribe after bounded backoff; the\n * backoff resets once the new subscription delivers a message. The initial\n * subscribe still throws synchronously to the caller. Resubscribing stops for\n * good when the owner unsubscribes or the connection closes or drains.\n */\nfunction subscribeWithResubscribe(\n nc: NatsConnection,\n context: SubscriptionContext,\n onMessage: (message: Msg) => void | Promise<void>,\n resubscribeDelayMs: (attempt: number) => number = natsResubscribeDelayMs,\n): () => void {\n let stopped = false;\n let current: Subscription | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let consecutiveFailures = 0;\n const pump = (sub: Subscription) => {\n current = sub;\n pumpSubscription(\n sub,\n context,\n async (message: Msg) => {\n consecutiveFailures = 0;\n await onMessage(message);\n },\n (end) => {\n if (current === sub) current = null;\n if (stopped || connectionShuttingDown(nc)) return;\n reportSubscriptionTermination(context, \"resubscribe\", end);\n schedule();\n },\n );\n };\n const schedule = () => {\n if (stopped || connectionShuttingDown(nc)) return;\n consecutiveFailures += 1;\n let delayMs = 30_000;\n try {\n delayMs = resubscribeDelayMs(consecutiveFailures);\n } catch {\n // Keep the bounded default.\n }\n timer = setTimeout(() => {\n timer = null;\n if (stopped || connectionShuttingDown(nc)) return;\n let sub: Subscription;\n try {\n sub = nc.subscribe(context.subject, context.queue ? { queue: context.queue } : undefined);\n } catch (error) {\n reportSubscriptionTermination(context, \"resubscribe\", { error });\n schedule();\n return;\n }\n pump(sub);\n }, delayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n pump(nc.subscribe(context.subject, context.queue ? { queue: context.queue } : undefined));\n return () => {\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n const sub = current;\n current = null;\n sub?.unsubscribe();\n };\n}\n\nexport {\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n parseAgentConnectionName,\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; headers?: { get(name: string): string } };\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 supportsHeaders?: boolean;\n request(\n subject: string,\n payload: Uint8Array,\n /** resendOn opts into identical redelivery on that subject's notifications\n * and local reconnect. Only safe reads or journaled deliveries may opt in.\n * `headers` are the request headers of a plain (non-resending) request. */\n opts: { timeout: number; resendOn?: string; headers?: Record<string, string> },\n ): 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 * (the exact process generation's `.op.<op_id>`) and a plain publish for acks\n * (that same generation's `.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 /** Subscription/publish barrier used before reading durable authority. */\n flush?(): Promise<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 exact-process 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\n/**\n * Versioned recovery contract for already-durable session-event fanout.\n *\n * A publisher acknowledgement alone cannot prove that every API subscriber was\n * connected for the live message. Supported broker-backed buses must therefore\n * notify consumers after transport subscriptions have been restored so an\n * already-open SSE stream can run one bounded Postgres catch-up. A bus that can\n * never disconnect may implement this as a listener registry that never fires.\n */\nexport const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1 as const;\n\nexport type SessionEventDurableFanoutCapability = {\n version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;\n subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;\n};\n\nexport function requireSessionEventDurableFanoutCapability(\n bus: unknown,\n): SessionEventDurableFanoutCapability {\n const capability = (bus as { sessionEventDurableFanout?: unknown } | null)\n ?.sessionEventDurableFanout as\n | { version?: unknown; subscribeRecovery?: unknown }\n | null\n | undefined;\n if (\n capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION ||\n typeof capability.subscribeRecovery !== \"function\"\n ) {\n throw new Error(\n \"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect\",\n );\n }\n return capability as SessionEventDurableFanoutCapability;\n}\n\nexport type EventBus = {\n /**\n * Mandatory paired recovery contract for durable session-event publication.\n * API and worker instances sharing one broker must expose the same semantics.\n */\n sessionEventDurableFanout: SessionEventDurableFanoutCapability;\n /**\n * Publish a session-event batch. Embedding implementations without the\n * optional publishConfirmed capability must resolve only after their\n * transport has accepted the batch and reject transport failures so durable\n * outbox callers can retry safely. Ordinary live-fanout callers remain\n * best-effort because they catch failures around this contract.\n */\n publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;\n /**\n * Publish an already-durable batch and reject unless the transport confirms\n * acceptance with a stronger provider-specific acknowledgement. Optional for\n * embedding-host buses; durable fanout reconcilers fall back to the required\n * publish promise when this capability is unavailable.\n */\n publishConfirmed?: (\n workspaceId: string,\n sessionId: string,\n events: SessionEvent[],\n ) => Promise<void>;\n /**\n * Live session-event fanout. `options.onTerminated` reports a transport\n * subscription that ended while still held; implementations whose\n * subscriptions can end on their own should call it so the consumer\n * reconciles from Postgres. Buses that never end a held subscription may\n * ignore it.\n */\n subscribe: (\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n options?: BusSubscriptionOptions,\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 options?: BusSubscriptionOptions,\n ) => Promise<() => void>;\n /**\n * Issue a binary request/reply on a subject over the bus's NATS connection\n * (the selfhosted control plane's exact claimed process subject). 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.*.*.connection.*.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 its exact process `.events`, NOT a\n * request/reply). The M10 metrics-ingestion consumer subscribes the wildcard\n * `agent.*.*.connection.*.events` and gets each raw payload plus its concrete\n * subject (so it can extract `<ws>`/`<id>`/`<instance>`). Returns an\n * unsubscribe fn. Decoding the AgentEvent is the caller's concern (this leaf\n * does not depend on `@opengeni/agent-proto`).\n * An optional queue distributes each delivery to one member of that group;\n * omitting it preserves broadcast delivery to every subscriber.\n */\n subscribeAgentEvents: (\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n options?: { queue?: string },\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 exact generation-fenced agent RPC subjects + receive\n * 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 let reconnectGeneration = 0;\n const reconnectSubscribers = new Set<(generation: number) => void>();\n const requestObservers = new Set<(status: Status) => void>();\n logConnectionStatus(nc, \"event-bus\", options.logger, (type, status) => {\n for (const observer of requestObservers) observer(status);\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 if (type === \"reconnect\") {\n reconnectGeneration += 1;\n for (const subscriber of reconnectSubscribers) {\n try {\n subscriber(reconnectGeneration);\n } catch (error) {\n (options.logger?.warn ?? silentLogger.warn)(\"NATS reconnect observer failed\", {\n label: \"event-bus\",\n reconnectGeneration,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n });\n const requestConnection: RequestConnection = {\n supportsHeaders: true,\n request: async (subject, payload, opts) =>\n opts.resendOn\n ? recoveringRequest(nc, subject, payload, opts, (observer) => {\n requestObservers.add(observer);\n return () => requestObservers.delete(observer);\n })\n : requestReply(nc, subject, payload, opts.timeout, opts.headers),\n };\n const opStreamConnection: OpStreamConnection = {\n subscribe: (subject) => nc.subscribe(subject),\n publish: (subject, payload) => {\n nc.publish(subject, payload);\n },\n flush: () => nc.flush(),\n };\n const publishSessionEvents = (\n workspaceId: string,\n sessionId: string,\n events: SessionEvent[],\n ): void => {\n const batches = sessionEventBatchesByBytes(workspaceId, sessionId, events);\n for (const batch of batches) {\n nc.publish(\n sessionSubject(workspaceId, sessionId),\n codec.encode({ workspaceId, sessionId, events: batch }),\n );\n }\n if (batches.length > 1) {\n (options.logger?.debug ?? silentLogger.debug)(\"NATS session event batch chunked\", {\n workspaceId,\n sessionId,\n eventCount: events.length,\n batchCount: batches.length,\n maxMessageBytes: SESSION_EVENT_NATS_MESSAGE_MAX_BYTES,\n });\n }\n observeEventBoundaries(batches.flat(), options.logger);\n };\n return {\n sessionEventDurableFanout: {\n version: SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,\n subscribeRecovery: (onRecovery) => {\n reconnectSubscribers.add(onRecovery);\n return () => reconnectSubscribers.delete(onRecovery);\n },\n },\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 publishSessionEvents(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)(\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 publishConfirmed: async (workspaceId, sessionId, events) => {\n if (events.length === 0) {\n return;\n }\n publishSessionEvents(workspaceId, sessionId, events);\n await flushConfirmedWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);\n },\n subscribe: async (workspaceId, sessionId, onEvents, subscriptionOptions) =>\n subscribeSession(nc, workspaceId, sessionId, onEvents, options, subscriptionOptions),\n publishWorkspaceControl: async (workspaceId, event) => {\n try {\n const encoded = workspaceControlEventNatsPayload(event);\n nc.publish(workspaceControlSubject(workspaceId), encoded);\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, subscriptionOptions) =>\n subscribeWithTermination(\n nc,\n {\n label: \"workspace-control\",\n kind: \"workspace_control\",\n subject: workspaceControlSubject(workspaceId),\n logger: options.logger,\n onSubscriptionTerminated: options.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n await onEvent(\n boundWorkspaceControlEvent(codec.decode(msg.data) as WorkspaceControlEvent, {\n surface: \"nats_legacy_guard\",\n }),\n );\n },\n subscriptionOptions,\n ),\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),\n subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler, options),\n subscribeAgentEvents: (subject, handler, subscriptionOptions) =>\n subscribeAgentEvents(nc, subject, handler, options, subscriptionOptions),\n getRequestConnection: () => requestConnection,\n getOpStreamConnection: () => opStreamConnection,\n isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),\n close: async () => {\n reconnectSubscribers.clear();\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: {\n name?: string;\n logger?: EventLogger;\n connect?: typeof connect;\n onSubscriptionTerminated?: (termination: NatsSubscriptionTermination) => void;\n resubscribeDelayMs?: (attempt: number) => number;\n } = {},\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 // A dead callout subscription would deny every Connected Machine connect\n // while the API pod still looks healthy, so an unexpected end resubscribes.\n const unsubscribe = subscribeWithResubscribe(\n nc,\n {\n label: options.name ? `auth-callout:${options.name}` : \"auth-callout\",\n kind: \"auth_callout\",\n subject,\n logger: options.logger,\n onSubscriptionTerminated: options.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n if (!msg.reply) {\n return;\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 options.resubscribeDelayMs,\n );\n return {\n close: async () => {\n unsubscribe();\n await nc.drain();\n },\n };\n}\n\n/** One NATS message as the agent gateway carries it over a host's link. */\nexport type AgentLinkNatsMessage = {\n subject: string;\n reply?: string;\n headers?: Array<[string, string]>;\n data: Uint8Array;\n};\n\n/**\n * The NATS connection the compute agent gateway bridges every sandbox agent's\n * traffic through: plain subscribe and publish, with reply subjects and\n * headers, on the privileged control-plane identity. The gateway itself\n * enforces each agent's subject permissions before it calls these.\n */\nexport interface AgentLinkNats {\n /** The server's max_payload. */\n maxPayload(): number;\n subscribe(\n subject: string,\n queue: string | undefined,\n onMessage: (message: AgentLinkNatsMessage) => void,\n ): () => void;\n publish(\n subject: string,\n data: Uint8Array,\n options?: { reply?: string; headers?: Array<[string, string]> },\n ): void;\n close(): Promise<void>;\n}\n\nexport async function createAgentLinkNatsConnection(\n natsUrl: string,\n auth: { user: string; pass: string } | undefined,\n options: { name?: string; logger?: EventLogger; connect?: typeof connect } = {},\n): Promise<AgentLinkNats> {\n const connectOptions: ConnectionOptions = {\n servers: natsUrl,\n name: options.name ?? \"opengeni-agent-gateway\",\n };\n if (auth) {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n }\n const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));\n logConnectionStatus(nc, \"agent-gateway\", options.logger);\n return {\n maxPayload: () => nc.info?.max_payload ?? 1024 * 1024,\n subscribe: (subject, queue, onMessage) => {\n const subscription = nc.subscribe(subject, {\n ...(queue ? { queue } : {}),\n callback: (error, msg) => {\n if (error) return;\n const pairs: Array<[string, string]> = [];\n if (msg.headers) {\n for (const key of msg.headers.keys()) {\n for (const value of msg.headers.values(key)) pairs.push([key, value]);\n }\n }\n onMessage({\n subject: msg.subject,\n ...(msg.reply ? { reply: msg.reply } : {}),\n ...(pairs.length > 0 ? { headers: pairs } : {}),\n data: msg.data,\n });\n },\n });\n return () => {\n try {\n subscription.unsubscribe();\n } catch {\n // A closed connection has no subscription left to end.\n }\n };\n },\n publish: (subject, data, publishOptions = {}) => {\n let hdrs: ReturnType<typeof natsHeaders> | undefined;\n if (publishOptions.headers && publishOptions.headers.length > 0) {\n hdrs = natsHeaders();\n for (const [key, value] of publishOptions.headers) hdrs.append(key, value);\n }\n nc.publish(subject, data, {\n ...(publishOptions.reply ? { reply: publishOptions.reply } : {}),\n ...(hdrs ? { headers: hdrs } : {}),\n });\n },\n close: async () => {\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 onAppendPhase?: SessionEventAppendObserver[\"onPhase\"];\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({\n durationSeconds: Math.max(0, (performance.now() - startedAt) / 1000),\n count,\n });\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 {\n console.warn(\"[events] live publish failed; durable events reconcile on stream replay\", {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"session_event_live_publish_failed\",\n origin: \"events\",\n eventCount: appended.length,\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 {\n console.warn(\n \"[events] workspace-control live publish failed; durable event reconciles on stream replay\",\n {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"workspace_control_live_publish_failed\",\n origin: \"events\",\n },\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 observe?: AppendPublishObserver,\n mutate?: SessionEventMutationInput,\n): Promise<{\n events: SessionEvent[];\n accepted: boolean;\n canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];\n}> {\n const appendStartedAt = performance.now();\n const result = await appendSessionEventsForTurnAttempt(\n db,\n workspaceId,\n sessionId,\n turnId,\n executionGeneration,\n attemptId,\n events,\n observe?.onAppendPhase ? { onPhase: observe.onAppendPhase } : undefined,\n mutate,\n );\n observeSince(observe?.onAppend, appendStartedAt, result.events.length);\n if (result.events.length === 0) return result;\n const publishStartedAt = performance.now();\n try {\n await bus.publish(workspaceId, sessionId, result.events);\n } catch {\n console.warn(\"[events] live fenced publish failed; events remain durable\", {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"fenced_event_live_publish_failed\",\n origin: \"events\",\n eventCount: result.events.length,\n });\n }\n observeSince(observe?.onPublish, publishStartedAt, result.events.length);\n return result;\n}\n\nfunction subscribeSession(\n nc: NatsConnection,\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n busOptions: EventBusOptions,\n subscriptionOptions: BusSubscriptionOptions | undefined,\n): () => void {\n return subscribeWithTermination(\n nc,\n {\n label: \"session-events\",\n kind: \"session_events\",\n subject: sessionSubject(workspaceId, sessionId),\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n const decoded = codec.decode(msg.data) as SessionBusMessage | SessionEvent;\n const events = (\"events\" in decoded ? decoded.events : [decoded]).map((event) =>\n boundSessionEventForSurface(event, \"nats_legacy_guard\"),\n );\n await onEvents(events);\n },\n subscriptionOptions,\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 requestHeaders?: Record<string, string>,\n): Promise<RequestReply> {\n let sent: ReturnType<typeof natsHeaders> | undefined;\n for (const [name, value] of Object.entries(requestHeaders ?? {})) {\n sent ??= natsHeaders();\n sent.set(name, value);\n }\n const msg: Msg = await nc.request(subject, payload, {\n timeout,\n ...(sent ? { headers: sent } : {}),\n });\n return { data: msg.data, ...(msg.headers ? { headers: msg.headers } : {}) };\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 busOptions: EventBusOptions,\n): () => void {\n return subscribeWithResubscribe(\n nc,\n {\n label: \"request-responder\",\n kind: \"request_responder\",\n subject,\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\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 return;\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 busOptions.resubscribeDelayMs,\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 busOptions: EventBusOptions,\n subscriptionOptions?: { queue?: string },\n): () => void {\n return subscribeWithResubscribe(\n nc,\n {\n label: \"agent-events\",\n kind: \"agent_events\",\n subject,\n ...(subscriptionOptions?.queue ? { queue: subscriptionOptions.queue } : {}),\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\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 busOptions.resubscribeDelayMs,\n );\n}\n\nexport function formatSse<T extends { sequence: number; type: string }>(\n event: T,\n idSequence = event.sequence,\n): string {\n const trustedId =\n Number.isSafeInteger(idSequence) && idSequence >= event.sequence ? idSequence : event.sequence;\n // Legacy type strings may not be legal SSE field values. Keep the canonical\n // event unchanged in JSON; only the transport dispatch name needs a fallback.\n const dispatchType = /[\\r\\n]/u.test(event.type) ? \"session.event.envelope_omitted\" : event.type;\n return [\n `id: ${trustedId}`,\n `event: ${dispatchType}`,\n `data: ${JSON.stringify(event)}`,\n \"\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Canonical one-event NATS payload with an exact broker byte assertion. */\nexport function workspaceControlEventNatsPayload(event: WorkspaceControlEvent): Uint8Array {\n const bounded = boundWorkspaceControlEvent(event, {\n surface: \"nats_legacy_guard\",\n });\n const encoded = codec.encode(bounded);\n if (encoded.byteLength > WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES) {\n throw new RangeError(\n `Workspace-control event cannot fit in the NATS envelope (${encoded.byteLength} > ${WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES} bytes)`,\n );\n }\n return encoded;\n}\n\n/** Defensively bounds current and historical workspace invalidations per frame. */\nexport function formatWorkspaceControlEventSse(event: WorkspaceControlEvent): string {\n const bounded = boundWorkspaceControlEvent(event, {\n surface: \"sse_legacy_guard\",\n });\n const formatted = formatSse(bounded);\n const bytes = new TextEncoder().encode(formatted).byteLength;\n if (bytes > SESSION_EVENT_SSE_FRAME_MAX_BYTES) {\n throw new RangeError(\n `Bounded workspace-control SSE frame exceeds its envelope (${bytes} > ${SESSION_EVENT_SSE_FRAME_MAX_BYTES} bytes)`,\n );\n }\n return formatted;\n}\n\n/** Serialize exact durable content; the SSE queue backpressures whole frames. */\nexport function formatSessionEventSse(\n event: SessionEvent,\n coveredThrough = event.sequence,\n): string {\n // Session content is not a diagnostic preview. Page replay and coalescing\n // bound accumulation without rewriting an individual durable event.\n return formatSse(event, coveredThrough);\n}\n\n/**\n * Split an already-durable batch by exact encoded NATS bytes. Each event is\n * defensively normalized first so historical oversized rows cannot exceed the\n * broker envelope. Sequence and ordering are unchanged across chunks.\n */\nexport function sessionEventBatchesByBytes(\n workspaceId: string,\n sessionId: string,\n events: readonly SessionEvent[],\n maxBytes = SESSION_EVENT_NATS_MESSAGE_MAX_BYTES,\n): SessionEvent[][] {\n const bounded = events.map((event) => boundSessionEventForSurface(event, \"nats_legacy_guard\"));\n const batches: SessionEvent[][] = [];\n let current: SessionEvent[] = [];\n for (const event of bounded) {\n const candidate = [...current, event];\n const encodedBytes = codec.encode({\n workspaceId,\n sessionId,\n events: candidate,\n }).byteLength;\n if (current.length > 0 && encodedBytes > maxBytes) {\n batches.push(current);\n current = [event];\n } else {\n current = candidate;\n }\n }\n if (current.length > 0) batches.push(current);\n for (const batch of batches) {\n const encodedBytes = codec.encode({\n workspaceId,\n sessionId,\n events: batch,\n }).byteLength;\n if (encodedBytes > maxBytes) {\n throw new RangeError(\n `Session event cannot fit in the configured NATS envelope (${encodedBytes} > ${maxBytes} bytes)`,\n );\n }\n }\n return batches;\n}\n\n/** Select whole HTTP events; one oversized event travels alone with its cursor. */\nexport function boundSessionEventHttpPage(\n events: readonly SessionEvent[],\n options: {\n direction: \"after\" | \"before\";\n maxBytes?: number;\n /** Bounded previews are opt-in for diagnostic consumers, never chat. */\n eventProjection?: \"bounded\" | \"exact\";\n /** Out-of-band raw coverage for events synthesized by trusted coalescing. */\n coveredThroughBySequence?: ReadonlyMap<number, number>;\n },\n): {\n events: SessionEvent[];\n truncated: boolean;\n nextSequence: number | null;\n bytes: number;\n} {\n const maxBytes = options.maxBytes ?? SESSION_EVENT_HTTP_PAGE_MAX_BYTES;\n const selected: SessionEvent[] = [];\n let bytes = 2; // []\n const projected =\n options.eventProjection !== \"bounded\"\n ? [...events]\n : events.map((event) => boundSessionEventForSurface(event, \"http_projection\"));\n const candidates = options.direction === \"after\" ? projected : [...projected].reverse();\n for (const event of candidates) {\n const eventBytes = sessionEventJsonBytes(event);\n const separator = selected.length === 0 ? 0 : 1;\n if (selected.length > 0 && bytes + separator + eventBytes > maxBytes) break;\n selected.push(event);\n bytes += separator + eventBytes;\n }\n if (options.direction === \"before\") selected.reverse();\n if (projected.length > 0 && selected.length === 0) {\n throw new RangeError(\n `A bounded session event cannot fit in the configured HTTP page envelope (${maxBytes} bytes)`,\n );\n }\n const truncated = selected.length < projected.length;\n const edge = options.direction === \"after\" ? selected.at(-1) : selected[0];\n return {\n events: selected,\n truncated,\n nextSequence:\n edge === undefined\n ? null\n : options.direction === \"after\"\n ? Math.max(\n edge.sequence,\n options.coveredThroughBySequence?.get(edge.sequence) ?? edge.sequence,\n )\n : edge.sequence,\n bytes,\n };\n}\n\n/** Return one count+byte-bounded workspace-control page and resume cursor. */\nexport function boundWorkspaceControlHttpPage(\n events: readonly WorkspaceControlEvent[],\n maxBytes = WORKSPACE_CONTROL_HTTP_PAGE_MAX_BYTES,\n): {\n events: WorkspaceControlEvent[];\n truncated: boolean;\n nextSequence: number | null;\n bytes: number;\n} {\n const projected = events.map((event) =>\n boundWorkspaceControlEvent(event, { surface: \"http_projection\" }),\n );\n const selected: WorkspaceControlEvent[] = [];\n let bytes = 2; // []\n for (const event of projected) {\n const eventBytes = sessionEventJsonBytes(event);\n const separator = selected.length === 0 ? 0 : 1;\n if (bytes + separator + eventBytes > maxBytes) break;\n selected.push(event);\n bytes += separator + eventBytes;\n }\n if (projected.length > 0 && selected.length === 0) {\n throw new RangeError(\n `A bounded workspace-control event cannot fit in the HTTP page envelope (${maxBytes} bytes)`,\n );\n }\n return {\n events: selected,\n truncated: selected.length < projected.length,\n nextSequence: selected.at(-1)?.sequence ?? null,\n bytes,\n };\n}\n\n/** Raw durable cursor covered by a possibly coalesced compact event. */\nexport function sessionEventResumeSequence(event: SessionEvent): number {\n return typeof event.coveredThrough === \"number\" &&\n Number.isSafeInteger(event.coveredThrough) &&\n event.coveredThrough >= event.sequence\n ? event.coveredThrough\n : event.sequence;\n}\n\nfunction boundSessionEventForSurface(\n event: SessionEvent,\n surface: SessionEventBoundarySurface,\n): SessionEvent {\n return boundSessionEvent(event, { surface });\n}\n\nfunction observeEventBoundaries(events: readonly SessionEvent[], logger?: EventLogger): void {\n for (const event of events) {\n const boundary = sessionEventPayloadTruncation(event.payload);\n if (!boundary) continue;\n (logger?.debug ?? silentLogger.debug)(\"Session event payload is a bounded audit preview\", {\n eventType: event.type,\n surface: boundary.surface,\n reason: boundary.reason,\n originalBytes: boundary.originalBytes,\n deliveredBytes: boundary.deliveredBytes,\n estimatedOriginalTokens: boundary.estimatedOriginalTokens,\n estimatedDeliveredTokens: boundary.estimatedDeliveredTokens,\n fullEvidenceAvailable: boundary.fullEvidence.available,\n retainedOutputKind: boundary.fullEvidence.available ? boundary.fullEvidence.kind : null,\n });\n }\n}\n\nfunction workspaceControlSubject(workspaceId: string): string {\n return `workspaces.${workspaceId}.control`;\n}\n","import {\n createInbox,\n ErrorCode,\n NatsError,\n type Msg,\n type NatsConnection,\n type Subscription,\n type Status,\n} from \"nats\";\n\n/** Opt-in only for a caller that can safely resend the SAME delivery. Listen\n * before publishing so a responder reconnect cannot strand an outstanding\n * request until its operation deadline. One inbox and deadline survive resends;\n * neither receipt recovery nor transport reconnect grants another execution. */\nexport async function recoveringRequest(\n connection: NatsConnection,\n subject: string,\n payload: Uint8Array,\n options: { timeout: number; resendOn?: string },\n observeTransport: (listener: (status: Status) => void) => () => void,\n): Promise<Msg> {\n const subscriptions: Subscription[] = [];\n let removeReconnect: (() => void) | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n let published = false;\n let resent = false;\n try {\n return await new Promise<Msg>((resolve, reject) => {\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n // A refusal of a resend cannot certify that the original did not run.\n reject(\n resent\n ? Object.assign(NatsError.errorForCode(ErrorCode.Timeout), { cause: error })\n : error,\n );\n };\n const inbox = createInbox();\n const send = () => {\n if (settled) return;\n resent ||= published;\n try {\n connection.publish(subject, payload, { reply: inbox });\n published = true;\n } catch (error) {\n fail(error);\n }\n };\n const watch = (subscription: Subscription) => {\n subscriptions.push(subscription);\n void subscription.closed.then(() =>\n fail(NatsError.errorForCode(ErrorCode.ConnectionClosed)),\n );\n };\n watch(\n connection.subscribe(inbox, {\n callback: (error, message) => {\n if (error) return fail(error);\n if (message.data.length === 0 && message.headers?.code === 503) {\n return fail(NatsError.errorForCode(ErrorCode.NoResponders));\n }\n if (!settled) {\n settled = true;\n resolve(message);\n }\n },\n }),\n );\n if (options.resendOn) {\n watch(\n connection.subscribe(options.resendOn, {\n callback: (error) => (error ? fail(error) : send()),\n }),\n );\n }\n removeReconnect = observeTransport((status) => {\n if (status.type === \"reconnect\") send();\n // Core NATS publishes authorization errors on its status feed, not the\n // reply inbox. Preserve the ordinary request API's fail-fast behavior.\n if (\n status.permissionContext?.operation === \"publish\" &&\n status.permissionContext.subject === subject\n ) {\n fail(NatsError.errorForCode(ErrorCode.PermissionsViolation));\n }\n });\n timer = setTimeout(() => fail(NatsError.errorForCode(ErrorCode.Timeout)), options.timeout);\n send();\n });\n } finally {\n settled = true;\n clearTimeout(timer);\n removeReconnect?.();\n for (const subscription of subscriptions) subscription.unsubscribe();\n }\n}\n","import { sessionEventPayloadTruncation, 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\n/** Flush long runs incrementally before concatenation can become unbounded. */\nexport const SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES = 48 * 1024;\nconst encoder = new TextEncoder();\n\n/**\n * Some providers stream each reasoning summary part as its own delta\n * (\"**Checking the workspace**\", then \"**Inspecting guidance**\"). Readers join\n * reasoning fragments with this separator, so a part that opens bold right\n * after one that closed bold starts a new paragraph instead of colliding\n * (\"****\"). Every place that merges reasoning fragments (the worker's\n * write-time merge, this read-side coalescer, the React projection) must use\n * the same rule, so the rendered text never depends on fragment boundaries.\n */\nexport function reasoningDeltaSeparator(previous: string, next: string): string {\n return previous.endsWith(\"**\") && next.startsWith(\"**\") ? \"\\n\\n\" : \"\";\n}\n\nexport type CoalescedSessionEventPage = {\n events: SessionEvent[];\n /** Durable raw sequence covered by each returned synthetic event sequence. */\n coveredThroughBySequence: ReadonlyMap<number, number>;\n};\n\ntype DeltaRun = {\n first: SessionEvent;\n lastSequence: number;\n text: string;\n textBytes: number;\n sandboxName: string | undefined;\n sandboxStream: string | undefined;\n sandboxCommandId: string | undefined;\n messageId: string | undefined;\n phase: string | undefined;\n};\n\nexport function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent[] {\n return coalesceSessionEventDeltasWithCoverage(events).events;\n}\n\nexport function coalesceSessionEventDeltasWithCoverage(\n events: SessionEvent[],\n): CoalescedSessionEventPage {\n const coalesced: SessionEvent[] = [];\n const coveredThroughBySequence = new Map<number, number>();\n let run: DeltaRun | null = null;\n\n const flush = () => {\n if (!run) {\n return;\n }\n const 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 ...(run.messageId !== undefined ? { messageId: run.messageId } : {}),\n ...(run.phase !== undefined ? { phase: run.phase } : {}),\n };\n coalesced.push({\n ...run.first,\n coveredThrough: run.lastSequence,\n payload,\n });\n coveredThroughBySequence.set(run.first.sequence, run.lastSequence);\n run = null;\n };\n\n for (const event of events) {\n if (!isCoalescibleDelta(event)) {\n flush();\n coalesced.push(event);\n coveredThroughBySequence.set(event.sequence, event.sequence);\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 const text = deltaText(event);\n const messageId =\n event.type === \"agent.message.delta\" && typeof asRecord(event.payload).messageId === \"string\"\n ? (asRecord(event.payload).messageId as string)\n : undefined;\n // One provider message has one phase; keep it on the coalesced delta.\n const phase =\n event.type === \"agent.message.delta\" && typeof asRecord(event.payload).phase === \"string\"\n ? (asRecord(event.payload).phase as string)\n : undefined;\n if (\n run &&\n sameDeltaRun(run.first, event, run.sandboxName, sandboxName) &&\n run.sandboxStream === sandboxStream &&\n run.sandboxCommandId === sandboxCommandId &&\n run.messageId === messageId &&\n run.phase === phase\n ) {\n const piece =\n (event.type === \"agent.reasoning.delta\" ? reasoningDeltaSeparator(run.text, text) : \"\") +\n text;\n const textBytes = encoder.encode(piece).byteLength;\n if (\n (run.textBytes === 0 && textBytes <= SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES) ||\n run.textBytes + textBytes <= SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES\n ) {\n run.text += piece;\n run.textBytes += textBytes;\n run.lastSequence = storedCoverageEnd(event);\n continue;\n }\n // The current segment is already useful and bounded. Flush before adding\n // the next raw delta rather than building the full run and truncating it\n // only after a multi-megabyte intermediate allocation.\n flush();\n } else {\n flush();\n }\n\n run = {\n first: event,\n lastSequence: storedCoverageEnd(event),\n text,\n textBytes: encoder.encode(text).byteLength,\n sandboxName,\n sandboxStream,\n sandboxCommandId,\n messageId,\n phase,\n };\n }\n\n flush();\n return { events: coalesced, coveredThroughBySequence };\n}\n\n/**\n * A stored delta may already cover later sequences: a folded run (see\n * docs/session-storage-lifecycle.md) keeps `coalescedUntil`, the last sequence\n * whose text it holds.\n */\nfunction storedCoverageEnd(event: SessionEvent): number {\n const until = asRecord(event.payload).coalescedUntil;\n return typeof until === \"number\" && Number.isSafeInteger(until) && until > event.sequence\n ? until\n : event.sequence;\n}\n\nfunction isCoalescibleDelta(event: SessionEvent): boolean {\n return (\n COALESCIBLE_DELTA_TYPES.has(event.type) && sessionEventPayloadTruncation(event.payload) === null\n );\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; 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 its\n// generation-fenced process subtree\n// `agent.<workspaceId>.<agentId>.connection.<instanceId>.>` (+ reply\n// `_INBOX.>`). That exact scope prevents both cross-workspace access and a stale\n// process sharing credentials with its live successor.\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// validates the seed and derives its public identity once; native Node `crypto`\n// supplies Ed25519 signing and 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; the current seed's imported native key is\n// reused until the configured seed changes. 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, createPrivateKey, sign, type KeyObject } 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\ntype AccountSigner = { seed: string; publicKey: string; privateKey: KeyObject };\nlet currentAccountSigner: AccountSigner | undefined;\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\";\n\nfunction accountSigner(seed: string): AccountSigner {\n if (currentAccountSigner?.seed === seed) return currentAccountSigner;\n // Keep nkeys' checksum, prefix and seed-length validation. Public identity\n // derivation happens only on import, not twice for every authorization.\n const account = nkeys.fromSeed(Buffer.from(seed));\n const publicKey = account.getPublicKey();\n if (publicKey.startsWith(\"X\")) {\n // X25519 curve seeds cannot sign; preserve nkeys' existing rejection.\n throw new nkeys.NKeysError(nkeys.NKeysErrorCode.InvalidCurveOperation);\n }\n // The already-validated NKey is base32(two prefix bytes + 32 seed bytes +\n // two CRC bytes). Decode the seed without depending on nkeys' private APIs.\n const decoded = Buffer.alloc(Math.floor((seed.length * 5) / 8));\n let bits = 0,\n value = 0,\n offset = 0;\n for (const char of seed) {\n value = (value << 5) | BASE32_ALPHABET.indexOf(char);\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n decoded[offset++] = (value >>> bits) & 255;\n }\n }\n // RFC 8410 PKCS#8 Ed25519 PrivateKeyInfo: algorithm OID 1.3.101.112 and\n // a nested OCTET STRING holding the 32-byte seed (no algorithm parameters).\n const privateKey = createPrivateKey({\n key: Buffer.concat([\n Buffer.from(\"302e020100300506032b657004220420\", \"hex\"),\n decoded.subarray(2, 34),\n ]),\n format: \"der\",\n type: \"pkcs8\",\n });\n return (currentAccountSigner = { seed, publicKey, privateKey });\n}\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: AccountSigner): 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 = sign(null, Buffer.from(signingInput, \"utf8\"), signingKey.privateKey);\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 = accountSigner(input.accountSeed);\n const accountPublicKey = accountKey.publicKey;\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 = accountSigner(input.accountSeed);\n const accountPublicKey = accountKey.publicKey;\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 // exact generation-fenced agent request/reply routes; 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 /** Client-reported process identity. Opengeni agents use a strict\n * `opengeni-agent/connection/<uuid>` shape; auth-callout rejects anything\n * else before granting machine subjects. */\n name: 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; name?: 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 const name = typeof connectOpts.name === \"string\" ? connectOpts.name : undefined;\n return { userNkey, serverId, authToken, user, name };\n}\n\nconst AGENT_CONNECTION_NAME_PREFIX = \"opengeni-agent/connection/\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Parse the exact process instance carried by the NATS CONNECT name. The value\n * is authority material used in subjects, so arbitrary tokens/dots are never\n * accepted. */\nexport function parseAgentConnectionName(name: string | undefined): string | null {\n if (!name?.startsWith(AGENT_CONNECTION_NAME_PREFIX)) return null;\n const instanceId = name.slice(AGENT_CONNECTION_NAME_PREFIX.length);\n return UUID_PATTERN.test(instanceId) ? instanceId.toLowerCase() : null;\n}\n\n/**\n * Build the exact process-scoped permission set for an authenticated agent. In\n * production agentId + connectionInstanceId are mandatory, restricting both\n * directions to that claimed daemon's RPC/event/hello/op subtree. It may publish\n * to `_INBOX.>` only to answer control-plane requests; it never needs to read\n * another connection's reply inbox.\n * The workspace-only fallback exists solely for legacy isolated callers/tests.\n *\n * THE isolation assertion (§17): with workspace A, agent B, instance C, the\n * production allow lists name only `agent.A.B.connection.C.>` and `_INBOX.>`.\n * NATS rejects every other workspace, agent, or process generation.\n */\nexport function workspaceAgentPermissions(\n workspaceId: string,\n agentId?: string,\n connectionInstanceId?: string,\n): NatsPermissions {\n const agentScope =\n agentId && connectionInstanceId\n ? `agent.${workspaceId}.${agentId}.connection.${connectionInstanceId}.>`\n : `agent.${workspaceId}.>`;\n // The reply-inbox subtree must be reachable for request/reply (the control plane\n // requests on the exact process RPC subject with a reply inbox; the agent responds there).\n const inboxScope = \"_INBOX.>\";\n return {\n pub: { allow: [agentScope, inboxScope] },\n sub: { allow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;AAAA,EACH;AACF;AAEA,SAAS,wBAAwB,aAA6B;AAC5D,SAAO,cAAc,WAAW;AAClC;","names":["sessionEventPayloadTruncation","connect","nkeys","sessionEventPayloadTruncation"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/recovering-request.ts","../src/coalesce.ts","../src/nats-jwt.ts"],"sourcesContent":["import {\n SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,\n type SessionEventDurableFanoutCapability,\n} from \"./durable-fanout\";\nexport {\n SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,\n requireSessionEventDurableFanoutCapability,\n type SessionEventDurableFanoutCapability,\n} from \"./durable-fanout\";\nimport {\n boundSessionEvent,\n boundWorkspaceControlEvent,\n sessionEventJsonBytes,\n sessionEventPayloadTruncation,\n type SessionBusMessage,\n type SessionEvent,\n type SessionEventBoundarySurface,\n type WorkspaceControlEvent,\n} from \"@opengeni/contracts\";\nimport {\n appendSessionEvents,\n appendSessionEventsForTurnAttempt,\n sessionSubject,\n type AppendEventInput,\n type CanonicalTurnStartupMilestoneReceipt,\n type Database,\n type SessionEventAppendObserver,\n type SessionEventMutationInput,\n} from \"@opengeni/db\";\nimport {\n connect,\n headers as natsHeaders,\n JSONCodec,\n type ConnectionOptions,\n type Msg,\n type NatsConnection,\n type Subscription,\n type Status,\n} from \"nats\";\nimport { recoveringRequest } from \"./recovering-request\";\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 * Metrics seam: called once for every subscription that ends without being\n * unsubscribed (see {@link natsSubscriptionTerminationCounter}). A throwing\n * sink is ignored.\n */\n onSubscriptionTerminated?: (termination: NatsSubscriptionTermination) => void;\n /** Test seam for the responder resubscribe backoff; production uses {@link natsResubscribeDelayMs}. */\n resubscribeDelayMs?: (attempt: number) => number;\n};\n\nconst silentLogger: Required<EventLogger> = {\n debug: () => {},\n warn: () => {},\n};\n\nexport {\n SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES,\n coalesceSessionEventDeltas,\n coalesceSessionEventDeltasWithCoverage,\n reasoningDeltaSeparator,\n type CoalescedSessionEventPage,\n} 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 * - `ignoreAuthErrorAbort` - nats.js otherwise stops reconnecting for good\n * after the same auth error twice in a row, which is exactly what a broker\n * or auth-callout responder restart produces for a few seconds.\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 ignoreAuthErrorAbort: true,\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/** Comfortably below NATS Core's common 1 MiB max_payload default. */\nexport const SESSION_EVENT_NATS_MESSAGE_MAX_BYTES = 512 * 1024;\n/** Payload is <=64 KiB; the larger envelope leaves deterministic wire headroom. */\nexport const SESSION_EVENT_SSE_FRAME_MAX_BYTES = 96 * 1024;\n/** Independent count+byte envelope for one durable HTTP replay response. */\nexport const SESSION_EVENT_HTTP_PAGE_MAX_BYTES = 1024 * 1024;\n/** Workspace invalidations are one compact event, never a broker evidence blob. */\nexport const WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES = 32 * 1024;\n/** Count+byte envelope for one workspace-control REST replay page. */\nexport const WORKSPACE_CONTROL_HTTP_PAGE_MAX_BYTES = 1024 * 1024;\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 * Flush a durable outbox publication and reject unless the NATS server confirms\n * the write within the bounded wait. A timeout can still leave the original\n * bytes buffered for reconnect, so callers must remain duplicate-safe when they\n * retry the durable obligation.\n */\nasync function flushConfirmedWithTimeout(nc: NatsConnection, timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => reject(new Error(`NATS publish confirmation timed out after ${timeoutMs}ms`)),\n timeoutMs,\n );\n });\n try {\n await Promise.race([nc.flush(), 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, status: Status) => void,\n): void {\n void (async () => {\n try {\n for await (const status of nc.status()) {\n onStatus?.(status.type, status);\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\n/** Closed, content-free description of a subscription failure for logs. */\nfunction subscriptionFailureAttributes(error: unknown): Record<string, unknown> {\n if (!error || typeof error !== \"object\") return { errorType: typeof error };\n try {\n const candidate = error as { name?: unknown; code?: unknown };\n return {\n errorName: typeof candidate.name === \"string\" ? candidate.name.slice(0, 64) : \"unknown\",\n ...(typeof candidate.code === \"string\" ? { errorCode: candidate.code.slice(0, 64) } : {}),\n };\n } catch {\n return { errorName: \"unknown\" };\n }\n}\n\n/**\n * Closed label set for {@link NatsSubscriptionTermination}. Each value names one\n * subscription role this package owns; no subject, tenant, or payload\n * dimension is ever admitted, so a metric sink can use them as labels.\n */\nexport const NATS_SUBSCRIPTION_KINDS = [\n \"session_events\",\n \"workspace_control\",\n \"request_responder\",\n \"agent_events\",\n \"auth_callout\",\n] as const;\nexport type NatsSubscriptionKind = (typeof NATS_SUBSCRIPTION_KINDS)[number];\n\n/**\n * What happens after an unexpected end: a per-consumer subscription tells its\n * consumer (`consumer_reconnect`, e.g. session SSE fails retryably and the\n * client replays from Postgres), a process-lifetime responder resubscribes with\n * bounded backoff (`resubscribe`), and a consumer that registered no hook only\n * relies on its own durable re-read (`none`).\n */\nexport const NATS_SUBSCRIPTION_RECOVERIES = [\"consumer_reconnect\", \"resubscribe\", \"none\"] as const;\nexport type NatsSubscriptionRecovery = (typeof NATS_SUBSCRIPTION_RECOVERIES)[number];\n\nexport type NatsSubscriptionTermination = {\n kind: NatsSubscriptionKind;\n recovery: NatsSubscriptionRecovery;\n};\n\n/** Prometheus counter name for {@link natsSubscriptionTerminationCounter}. */\nexport const NATS_SUBSCRIPTION_TERMINATIONS_METRIC =\n \"opengeni_nats_subscription_terminations_total\";\n\n/**\n * Adapt a counter sink (the API/worker `Observability`) into the\n * `onSubscriptionTerminated` hook. Labels are the closed kind/recovery sets.\n */\nexport function natsSubscriptionTerminationCounter(sink: {\n incrementCounter(input: { name: string; help?: string; labels?: Record<string, string> }): void;\n}): (termination: NatsSubscriptionTermination) => void {\n return ({ kind, recovery }) => {\n sink.incrementCounter({\n name: NATS_SUBSCRIPTION_TERMINATIONS_METRIC,\n help: \"NATS subscriptions that ended without being unsubscribed, by subscription kind and recovery path.\",\n labels: { kind, recovery },\n });\n };\n}\n\n/** Per-subscription consumer options for {@link EventBus.subscribe}. */\nexport type BusSubscriptionOptions = {\n /**\n * Called at most once when the live transport subscription ends while the\n * consumer still holds it (a broker-side error such as a permissions\n * violation, or an iterator end the consumer did not request). Live events\n * stop after this call, so the consumer must reconcile from Postgres: session\n * and workspace-control SSE fail the stream retryably and the client\n * reconnects and replays. Never called after the returned unsubscribe runs or\n * while the bus itself is closing.\n */\n onTerminated?: (error: unknown) => void;\n};\n\n/** Bounded resubscribe backoff for process-lifetime responders: 1 s doubling to 30 s, plus up to 1 s jitter. */\nexport function natsResubscribeDelayMs(\n attempt: number,\n random: () => number = Math.random,\n): number {\n const exponent = Number.isFinite(attempt) ? Math.min(Math.max(0, Math.trunc(attempt) - 1), 5) : 0;\n const sample = random();\n const unit = Number.isFinite(sample) ? Math.min(Math.max(sample, 0), 1 - Number.EPSILON) : 0;\n return Math.min(30_000, 1_000 * 2 ** exponent) + Math.floor(unit * 1_000);\n}\n\ntype SubscriptionContext = {\n label: string;\n kind: NatsSubscriptionKind;\n subject: string;\n queue?: string;\n logger?: EventLogger | undefined;\n onSubscriptionTerminated?: ((termination: NatsSubscriptionTermination) => void) | undefined;\n};\n\ntype SubscriptionEnd = { error: unknown } | { error?: undefined };\n\n/**\n * Pump one subscription for its lifetime from a detached loop. The loop must\n * never reject: the API's fatal process boundary exits on any unhandled\n * rejection, so a single broker-side subscription error (a permissions\n * violation delivered to this subscription, a malformed payload, a throwing\n * consumer) used to take down every request and SSE stream on the pod. A\n * per-message failure is isolated so one poison message cannot end delivery.\n * The end of the iterator, with or without an error, is reported to `onEnded`\n * so the owner can decide whether it was requested (unsubscribe, bus close) or\n * must be surfaced: consumers reconcile from Postgres and process-lifetime\n * responders resubscribe (see {@link subscribeWithTermination} and\n * {@link subscribeWithResubscribe}). Logs never carry message payloads.\n */\nfunction pumpSubscription<T>(\n subscription: AsyncIterable<T>,\n context: SubscriptionContext,\n onMessage: (message: T) => void | Promise<void>,\n onEnded: (end: SubscriptionEnd) => void,\n): void {\n const warn = context.logger?.warn ?? silentLogger.warn;\n void (async () => {\n let end: SubscriptionEnd = {};\n try {\n for await (const message of subscription) {\n try {\n await onMessage(message);\n } catch (error) {\n try {\n warn(\"NATS subscription message dropped\", {\n label: context.label,\n subject: context.subject,\n ...subscriptionFailureAttributes(error),\n });\n } catch {\n // Logging must never end delivery.\n }\n }\n }\n } catch (error) {\n end = { error };\n }\n try {\n onEnded(end);\n } catch {\n // A termination observer must never escape the detached loop.\n }\n })();\n}\n\n/** Log + count one unexpected subscription end. Never throws. */\nfunction reportSubscriptionTermination(\n context: SubscriptionContext,\n recovery: NatsSubscriptionRecovery,\n end: SubscriptionEnd,\n): void {\n try {\n (context.logger?.warn ?? silentLogger.warn)(\n \"error\" in end && end.error !== undefined\n ? \"NATS subscription ended with an error\"\n : \"NATS subscription ended unexpectedly\",\n {\n label: context.label,\n subject: context.subject,\n recovery,\n ...(\"error\" in end && end.error !== undefined\n ? subscriptionFailureAttributes(end.error)\n : {}),\n },\n );\n } catch {\n // Logging must never escape the detached loop.\n }\n try {\n context.onSubscriptionTerminated?.({ kind: context.kind, recovery });\n } catch {\n // A metrics sink must never escape the detached loop.\n }\n}\n\nfunction connectionShuttingDown(nc: NatsConnection): boolean {\n return nc.isClosed() || nc.isDraining();\n}\n\n/**\n * A per-consumer subscription (one SSE stream, one MCP wait). An end that the\n * consumer did not request is logged, counted, and handed to the consumer's\n * `onTerminated` exactly once so it can reconcile from Postgres instead of\n * silently receiving nothing while its heartbeats continue.\n */\nfunction subscribeWithTermination(\n nc: NatsConnection,\n context: SubscriptionContext,\n onMessage: (message: Msg) => void | Promise<void>,\n options: BusSubscriptionOptions | undefined,\n): () => void {\n const sub: Subscription = nc.subscribe(context.subject);\n let released = false;\n const onTerminated = options?.onTerminated;\n pumpSubscription(sub, context, onMessage, (end) => {\n if (released || connectionShuttingDown(nc)) return;\n reportSubscriptionTermination(context, onTerminated ? \"consumer_reconnect\" : \"none\", end);\n try {\n onTerminated?.(\"error\" in end ? end.error : undefined);\n } catch {\n // The consumer hook must never escape the detached loop.\n }\n });\n return () => {\n released = true;\n sub.unsubscribe();\n };\n}\n\n/**\n * A process-lifetime responder (auth callout, Codemode requests, agent-event\n * ingestion). Nothing else would ever re-create it, so an unexpected end is\n * logged, counted, and followed by a resubscribe after bounded backoff; the\n * backoff resets once the new subscription delivers a message. The initial\n * subscribe still throws synchronously to the caller. Resubscribing stops for\n * good when the owner unsubscribes or the connection closes or drains.\n */\nfunction subscribeWithResubscribe(\n nc: NatsConnection,\n context: SubscriptionContext,\n onMessage: (message: Msg) => void | Promise<void>,\n resubscribeDelayMs: (attempt: number) => number = natsResubscribeDelayMs,\n): () => void {\n let stopped = false;\n let current: Subscription | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n let consecutiveFailures = 0;\n const pump = (sub: Subscription) => {\n current = sub;\n pumpSubscription(\n sub,\n context,\n async (message: Msg) => {\n consecutiveFailures = 0;\n await onMessage(message);\n },\n (end) => {\n if (current === sub) current = null;\n if (stopped || connectionShuttingDown(nc)) return;\n reportSubscriptionTermination(context, \"resubscribe\", end);\n schedule();\n },\n );\n };\n const schedule = () => {\n if (stopped || connectionShuttingDown(nc)) return;\n consecutiveFailures += 1;\n let delayMs = 30_000;\n try {\n delayMs = resubscribeDelayMs(consecutiveFailures);\n } catch {\n // Keep the bounded default.\n }\n timer = setTimeout(() => {\n timer = null;\n if (stopped || connectionShuttingDown(nc)) return;\n let sub: Subscription;\n try {\n sub = nc.subscribe(context.subject, context.queue ? { queue: context.queue } : undefined);\n } catch (error) {\n reportSubscriptionTermination(context, \"resubscribe\", { error });\n schedule();\n return;\n }\n pump(sub);\n }, delayMs);\n (timer as { unref?: () => void }).unref?.();\n };\n pump(nc.subscribe(context.subject, context.queue ? { queue: context.queue } : undefined));\n return () => {\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n const sub = current;\n current = null;\n sub?.unsubscribe();\n };\n}\n\nexport {\n decodeAuthRequest,\n mintAuthResponse,\n mintUserJwt,\n parseAgentConnectionName,\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; headers?: { get(name: string): string } };\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 supportsHeaders?: boolean;\n request(\n subject: string,\n payload: Uint8Array,\n /** resendOn opts into identical redelivery on that subject's notifications\n * and local reconnect. Only safe reads or journaled deliveries may opt in.\n * `headers` are the request headers of a plain (non-resending) request. */\n opts: { timeout: number; resendOn?: string; headers?: Record<string, string> },\n ): 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 * (the exact process generation's `.op.<op_id>`) and a plain publish for acks\n * (that same generation's `.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 /** Subscription/publish barrier used before reading durable authority. */\n flush?(): Promise<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 exact-process 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 /**\n * Mandatory paired recovery contract for durable session-event publication.\n * API and worker instances sharing one broker must expose the same semantics.\n */\n sessionEventDurableFanout: SessionEventDurableFanoutCapability;\n /**\n * Publish a session-event batch. Embedding implementations without the\n * optional publishConfirmed capability must resolve only after their\n * transport has accepted the batch and reject transport failures so durable\n * outbox callers can retry safely. Ordinary live-fanout callers remain\n * best-effort because they catch failures around this contract.\n */\n publish: (workspaceId: string, sessionId: string, events: SessionEvent[]) => Promise<void>;\n /**\n * Publish an already-durable batch and reject unless the transport confirms\n * acceptance with a stronger provider-specific acknowledgement. Optional for\n * embedding-host buses; durable fanout reconcilers fall back to the required\n * publish promise when this capability is unavailable.\n */\n publishConfirmed?: (\n workspaceId: string,\n sessionId: string,\n events: SessionEvent[],\n ) => Promise<void>;\n /**\n * Live session-event fanout. `options.onTerminated` reports a transport\n * subscription that ended while still held; implementations whose\n * subscriptions can end on their own should call it so the consumer\n * reconciles from Postgres. Buses that never end a held subscription may\n * ignore it.\n */\n subscribe: (\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n options?: BusSubscriptionOptions,\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 options?: BusSubscriptionOptions,\n ) => Promise<() => void>;\n /**\n * Issue a binary request/reply on a subject over the bus's NATS connection\n * (the selfhosted control plane's exact claimed process subject). 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.*.*.connection.*.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 its exact process `.events`, NOT a\n * request/reply). The M10 metrics-ingestion consumer subscribes the wildcard\n * `agent.*.*.connection.*.events` and gets each raw payload plus its concrete\n * subject (so it can extract `<ws>`/`<id>`/`<instance>`). Returns an\n * unsubscribe fn. Decoding the AgentEvent is the caller's concern (this leaf\n * does not depend on `@opengeni/agent-proto`).\n * An optional queue distributes each delivery to one member of that group;\n * omitting it preserves broadcast delivery to every subscriber.\n */\n subscribeAgentEvents: (\n subject: string,\n handler: (payload: Uint8Array, subject: string) => void | Promise<void>,\n options?: { queue?: string },\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 exact generation-fenced agent RPC subjects + receive\n * 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 let reconnectGeneration = 0;\n const reconnectSubscribers = new Set<(generation: number) => void>();\n const requestObservers = new Set<(status: Status) => void>();\n logConnectionStatus(nc, \"event-bus\", options.logger, (type, status) => {\n for (const observer of requestObservers) observer(status);\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 if (type === \"reconnect\") {\n reconnectGeneration += 1;\n for (const subscriber of reconnectSubscribers) {\n try {\n subscriber(reconnectGeneration);\n } catch (error) {\n (options.logger?.warn ?? silentLogger.warn)(\"NATS reconnect observer failed\", {\n label: \"event-bus\",\n reconnectGeneration,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n });\n const requestConnection: RequestConnection = {\n supportsHeaders: true,\n request: async (subject, payload, opts) =>\n opts.resendOn\n ? recoveringRequest(nc, subject, payload, opts, (observer) => {\n requestObservers.add(observer);\n return () => requestObservers.delete(observer);\n })\n : requestReply(nc, subject, payload, opts.timeout, opts.headers),\n };\n const opStreamConnection: OpStreamConnection = {\n subscribe: (subject) => nc.subscribe(subject),\n publish: (subject, payload) => {\n nc.publish(subject, payload);\n },\n flush: () => nc.flush(),\n };\n const publishSessionEvents = (\n workspaceId: string,\n sessionId: string,\n events: SessionEvent[],\n ): void => {\n const batches = sessionEventBatchesByBytes(workspaceId, sessionId, events);\n for (const batch of batches) {\n nc.publish(\n sessionSubject(workspaceId, sessionId),\n codec.encode({ workspaceId, sessionId, events: batch }),\n );\n }\n if (batches.length > 1) {\n (options.logger?.debug ?? silentLogger.debug)(\"NATS session event batch chunked\", {\n workspaceId,\n sessionId,\n eventCount: events.length,\n batchCount: batches.length,\n maxMessageBytes: SESSION_EVENT_NATS_MESSAGE_MAX_BYTES,\n });\n }\n observeEventBoundaries(batches.flat(), options.logger);\n };\n return {\n sessionEventDurableFanout: {\n version: SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,\n subscribeRecovery: (onRecovery) => {\n reconnectSubscribers.add(onRecovery);\n return () => reconnectSubscribers.delete(onRecovery);\n },\n },\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 publishSessionEvents(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)(\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 publishConfirmed: async (workspaceId, sessionId, events) => {\n if (events.length === 0) {\n return;\n }\n publishSessionEvents(workspaceId, sessionId, events);\n await flushConfirmedWithTimeout(nc, PUBLISH_FLUSH_TIMEOUT_MS);\n },\n subscribe: async (workspaceId, sessionId, onEvents, subscriptionOptions) =>\n subscribeSession(nc, workspaceId, sessionId, onEvents, options, subscriptionOptions),\n publishWorkspaceControl: async (workspaceId, event) => {\n try {\n const encoded = workspaceControlEventNatsPayload(event);\n nc.publish(workspaceControlSubject(workspaceId), encoded);\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, subscriptionOptions) =>\n subscribeWithTermination(\n nc,\n {\n label: \"workspace-control\",\n kind: \"workspace_control\",\n subject: workspaceControlSubject(workspaceId),\n logger: options.logger,\n onSubscriptionTerminated: options.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n await onEvent(\n boundWorkspaceControlEvent(codec.decode(msg.data) as WorkspaceControlEvent, {\n surface: \"nats_legacy_guard\",\n }),\n );\n },\n subscriptionOptions,\n ),\n request: async (subject, payload, opts) => requestReply(nc, subject, payload, opts.timeoutMs),\n subscribeRequests: (subject, handler) => subscribeRequests(nc, subject, handler, options),\n subscribeAgentEvents: (subject, handler, subscriptionOptions) =>\n subscribeAgentEvents(nc, subject, handler, options, subscriptionOptions),\n getRequestConnection: () => requestConnection,\n getOpStreamConnection: () => opStreamConnection,\n isConnected: () => connected && !nc.isClosed() && !nc.isDraining(),\n close: async () => {\n reconnectSubscribers.clear();\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: {\n name?: string;\n logger?: EventLogger;\n connect?: typeof connect;\n onSubscriptionTerminated?: (termination: NatsSubscriptionTermination) => void;\n resubscribeDelayMs?: (attempt: number) => number;\n } = {},\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 // A dead callout subscription would deny every Connected Machine connect\n // while the API pod still looks healthy, so an unexpected end resubscribes.\n const unsubscribe = subscribeWithResubscribe(\n nc,\n {\n label: options.name ? `auth-callout:${options.name}` : \"auth-callout\",\n kind: \"auth_callout\",\n subject,\n logger: options.logger,\n onSubscriptionTerminated: options.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n if (!msg.reply) {\n return;\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 options.resubscribeDelayMs,\n );\n return {\n close: async () => {\n unsubscribe();\n await nc.drain();\n },\n };\n}\n\n/** One NATS message as the agent gateway carries it over a host's link. */\nexport type AgentLinkNatsMessage = {\n subject: string;\n reply?: string;\n headers?: Array<[string, string]>;\n data: Uint8Array;\n};\n\n/**\n * The NATS connection the compute agent gateway bridges every sandbox agent's\n * traffic through: plain subscribe and publish, with reply subjects and\n * headers, on the privileged control-plane identity. The gateway itself\n * enforces each agent's subject permissions before it calls these.\n */\nexport interface AgentLinkNats {\n /** The server's max_payload. */\n maxPayload(): number;\n subscribe(\n subject: string,\n queue: string | undefined,\n onMessage: (message: AgentLinkNatsMessage) => void,\n ): () => void;\n publish(\n subject: string,\n data: Uint8Array,\n options?: { reply?: string; headers?: Array<[string, string]> },\n ): void;\n close(): Promise<void>;\n}\n\nexport async function createAgentLinkNatsConnection(\n natsUrl: string,\n auth: { user: string; pass: string } | undefined,\n options: { name?: string; logger?: EventLogger; connect?: typeof connect } = {},\n): Promise<AgentLinkNats> {\n const connectOptions: ConnectionOptions = {\n servers: natsUrl,\n name: options.name ?? \"opengeni-agent-gateway\",\n };\n if (auth) {\n connectOptions.user = auth.user;\n connectOptions.pass = auth.pass;\n }\n const nc = await (options.connect ?? connect)(withReconnectDefaults(connectOptions));\n logConnectionStatus(nc, \"agent-gateway\", options.logger);\n return {\n maxPayload: () => nc.info?.max_payload ?? 1024 * 1024,\n subscribe: (subject, queue, onMessage) => {\n const subscription = nc.subscribe(subject, {\n ...(queue ? { queue } : {}),\n callback: (error, msg) => {\n if (error) return;\n const pairs: Array<[string, string]> = [];\n if (msg.headers) {\n for (const key of msg.headers.keys()) {\n for (const value of msg.headers.values(key)) pairs.push([key, value]);\n }\n }\n onMessage({\n subject: msg.subject,\n ...(msg.reply ? { reply: msg.reply } : {}),\n ...(pairs.length > 0 ? { headers: pairs } : {}),\n data: msg.data,\n });\n },\n });\n return () => {\n try {\n subscription.unsubscribe();\n } catch {\n // A closed connection has no subscription left to end.\n }\n };\n },\n publish: (subject, data, publishOptions = {}) => {\n let hdrs: ReturnType<typeof natsHeaders> | undefined;\n if (publishOptions.headers && publishOptions.headers.length > 0) {\n hdrs = natsHeaders();\n for (const [key, value] of publishOptions.headers) hdrs.append(key, value);\n }\n nc.publish(subject, data, {\n ...(publishOptions.reply ? { reply: publishOptions.reply } : {}),\n ...(hdrs ? { headers: hdrs } : {}),\n });\n },\n close: async () => {\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 onAppendPhase?: SessionEventAppendObserver[\"onPhase\"];\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({\n durationSeconds: Math.max(0, (performance.now() - startedAt) / 1000),\n count,\n });\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 {\n console.warn(\"[events] live publish failed; durable events reconcile on stream replay\", {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"session_event_live_publish_failed\",\n origin: \"events\",\n eventCount: appended.length,\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 {\n console.warn(\n \"[events] workspace-control live publish failed; durable event reconciles on stream replay\",\n {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"workspace_control_live_publish_failed\",\n origin: \"events\",\n },\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 observe?: AppendPublishObserver,\n mutate?: SessionEventMutationInput,\n): Promise<{\n events: SessionEvent[];\n accepted: boolean;\n canonicalStartupMilestones: CanonicalTurnStartupMilestoneReceipt[];\n}> {\n const appendStartedAt = performance.now();\n const result = await appendSessionEventsForTurnAttempt(\n db,\n workspaceId,\n sessionId,\n turnId,\n executionGeneration,\n attemptId,\n events,\n observe?.onAppendPhase ? { onPhase: observe.onAppendPhase } : undefined,\n mutate,\n );\n observeSince(observe?.onAppend, appendStartedAt, result.events.length);\n if (result.events.length === 0) return result;\n const publishStartedAt = performance.now();\n try {\n await bus.publish(workspaceId, sessionId, result.events);\n } catch {\n console.warn(\"[events] live fenced publish failed; events remain durable\", {\n errorClass: \"EventPublishOperationError\",\n errorCode: \"fenced_event_live_publish_failed\",\n origin: \"events\",\n eventCount: result.events.length,\n });\n }\n observeSince(observe?.onPublish, publishStartedAt, result.events.length);\n return result;\n}\n\nfunction subscribeSession(\n nc: NatsConnection,\n workspaceId: string,\n sessionId: string,\n onEvents: (events: SessionEvent[]) => void | Promise<void>,\n busOptions: EventBusOptions,\n subscriptionOptions: BusSubscriptionOptions | undefined,\n): () => void {\n return subscribeWithTermination(\n nc,\n {\n label: \"session-events\",\n kind: \"session_events\",\n subject: sessionSubject(workspaceId, sessionId),\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\n const decoded = codec.decode(msg.data) as SessionBusMessage | SessionEvent;\n const events = (\"events\" in decoded ? decoded.events : [decoded]).map((event) =>\n boundSessionEventForSurface(event, \"nats_legacy_guard\"),\n );\n await onEvents(events);\n },\n subscriptionOptions,\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 requestHeaders?: Record<string, string>,\n): Promise<RequestReply> {\n let sent: ReturnType<typeof natsHeaders> | undefined;\n for (const [name, value] of Object.entries(requestHeaders ?? {})) {\n sent ??= natsHeaders();\n sent.set(name, value);\n }\n const msg: Msg = await nc.request(subject, payload, {\n timeout,\n ...(sent ? { headers: sent } : {}),\n });\n return { data: msg.data, ...(msg.headers ? { headers: msg.headers } : {}) };\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 busOptions: EventBusOptions,\n): () => void {\n return subscribeWithResubscribe(\n nc,\n {\n label: \"request-responder\",\n kind: \"request_responder\",\n subject,\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\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 return;\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 busOptions.resubscribeDelayMs,\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 busOptions: EventBusOptions,\n subscriptionOptions?: { queue?: string },\n): () => void {\n return subscribeWithResubscribe(\n nc,\n {\n label: \"agent-events\",\n kind: \"agent_events\",\n subject,\n ...(subscriptionOptions?.queue ? { queue: subscriptionOptions.queue } : {}),\n logger: busOptions.logger,\n onSubscriptionTerminated: busOptions.onSubscriptionTerminated,\n },\n async (msg: Msg) => {\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 busOptions.resubscribeDelayMs,\n );\n}\n\nexport function formatSse<T extends { sequence: number; type: string }>(\n event: T,\n idSequence = event.sequence,\n): string {\n const trustedId =\n Number.isSafeInteger(idSequence) && idSequence >= event.sequence ? idSequence : event.sequence;\n // Legacy type strings may not be legal SSE field values. Keep the canonical\n // event unchanged in JSON; only the transport dispatch name needs a fallback.\n const dispatchType = /[\\r\\n]/u.test(event.type) ? \"session.event.envelope_omitted\" : event.type;\n return [\n `id: ${trustedId}`,\n `event: ${dispatchType}`,\n `data: ${JSON.stringify(event)}`,\n \"\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** Canonical one-event NATS payload with an exact broker byte assertion. */\nexport function workspaceControlEventNatsPayload(event: WorkspaceControlEvent): Uint8Array {\n const bounded = boundWorkspaceControlEvent(event, {\n surface: \"nats_legacy_guard\",\n });\n const encoded = codec.encode(bounded);\n if (encoded.byteLength > WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES) {\n throw new RangeError(\n `Workspace-control event cannot fit in the NATS envelope (${encoded.byteLength} > ${WORKSPACE_CONTROL_NATS_MESSAGE_MAX_BYTES} bytes)`,\n );\n }\n return encoded;\n}\n\n/** Defensively bounds current and historical workspace invalidations per frame. */\nexport function formatWorkspaceControlEventSse(event: WorkspaceControlEvent): string {\n const bounded = boundWorkspaceControlEvent(event, {\n surface: \"sse_legacy_guard\",\n });\n const formatted = formatSse(bounded);\n const bytes = new TextEncoder().encode(formatted).byteLength;\n if (bytes > SESSION_EVENT_SSE_FRAME_MAX_BYTES) {\n throw new RangeError(\n `Bounded workspace-control SSE frame exceeds its envelope (${bytes} > ${SESSION_EVENT_SSE_FRAME_MAX_BYTES} bytes)`,\n );\n }\n return formatted;\n}\n\n/** Serialize exact durable content; the SSE queue backpressures whole frames. */\nexport function formatSessionEventSse(\n event: SessionEvent,\n coveredThrough = event.sequence,\n): string {\n // Session content is not a diagnostic preview. Page replay and coalescing\n // bound accumulation without rewriting an individual durable event.\n return formatSse(event, coveredThrough);\n}\n\n/**\n * Split an already-durable batch by exact encoded NATS bytes. Each event is\n * defensively normalized first so historical oversized rows cannot exceed the\n * broker envelope. Sequence and ordering are unchanged across chunks.\n */\nexport function sessionEventBatchesByBytes(\n workspaceId: string,\n sessionId: string,\n events: readonly SessionEvent[],\n maxBytes = SESSION_EVENT_NATS_MESSAGE_MAX_BYTES,\n): SessionEvent[][] {\n const bounded = events.map((event) => boundSessionEventForSurface(event, \"nats_legacy_guard\"));\n const batches: SessionEvent[][] = [];\n let current: SessionEvent[] = [];\n for (const event of bounded) {\n const candidate = [...current, event];\n const encodedBytes = codec.encode({\n workspaceId,\n sessionId,\n events: candidate,\n }).byteLength;\n if (current.length > 0 && encodedBytes > maxBytes) {\n batches.push(current);\n current = [event];\n } else {\n current = candidate;\n }\n }\n if (current.length > 0) batches.push(current);\n for (const batch of batches) {\n const encodedBytes = codec.encode({\n workspaceId,\n sessionId,\n events: batch,\n }).byteLength;\n if (encodedBytes > maxBytes) {\n throw new RangeError(\n `Session event cannot fit in the configured NATS envelope (${encodedBytes} > ${maxBytes} bytes)`,\n );\n }\n }\n return batches;\n}\n\n/** Select whole HTTP events; one oversized event travels alone with its cursor. */\nexport function boundSessionEventHttpPage(\n events: readonly SessionEvent[],\n options: {\n direction: \"after\" | \"before\";\n maxBytes?: number;\n /** Bounded previews are opt-in for diagnostic consumers, never chat. */\n eventProjection?: \"bounded\" | \"exact\";\n /** Out-of-band raw coverage for events synthesized by trusted coalescing. */\n coveredThroughBySequence?: ReadonlyMap<number, number>;\n },\n): {\n events: SessionEvent[];\n truncated: boolean;\n nextSequence: number | null;\n bytes: number;\n} {\n const maxBytes = options.maxBytes ?? SESSION_EVENT_HTTP_PAGE_MAX_BYTES;\n const selected: SessionEvent[] = [];\n let bytes = 2; // []\n const projected =\n options.eventProjection !== \"bounded\"\n ? [...events]\n : events.map((event) => boundSessionEventForSurface(event, \"http_projection\"));\n const candidates = options.direction === \"after\" ? projected : [...projected].reverse();\n for (const event of candidates) {\n const eventBytes = sessionEventJsonBytes(event);\n const separator = selected.length === 0 ? 0 : 1;\n if (selected.length > 0 && bytes + separator + eventBytes > maxBytes) break;\n selected.push(event);\n bytes += separator + eventBytes;\n }\n if (options.direction === \"before\") selected.reverse();\n if (projected.length > 0 && selected.length === 0) {\n throw new RangeError(\n `A bounded session event cannot fit in the configured HTTP page envelope (${maxBytes} bytes)`,\n );\n }\n const truncated = selected.length < projected.length;\n const edge = options.direction === \"after\" ? selected.at(-1) : selected[0];\n return {\n events: selected,\n truncated,\n nextSequence:\n edge === undefined\n ? null\n : options.direction === \"after\"\n ? Math.max(\n edge.sequence,\n options.coveredThroughBySequence?.get(edge.sequence) ?? edge.sequence,\n )\n : edge.sequence,\n bytes,\n };\n}\n\n/** Return one count+byte-bounded workspace-control page and resume cursor. */\nexport function boundWorkspaceControlHttpPage(\n events: readonly WorkspaceControlEvent[],\n maxBytes = WORKSPACE_CONTROL_HTTP_PAGE_MAX_BYTES,\n): {\n events: WorkspaceControlEvent[];\n truncated: boolean;\n nextSequence: number | null;\n bytes: number;\n} {\n const projected = events.map((event) =>\n boundWorkspaceControlEvent(event, { surface: \"http_projection\" }),\n );\n const selected: WorkspaceControlEvent[] = [];\n let bytes = 2; // []\n for (const event of projected) {\n const eventBytes = sessionEventJsonBytes(event);\n const separator = selected.length === 0 ? 0 : 1;\n if (bytes + separator + eventBytes > maxBytes) break;\n selected.push(event);\n bytes += separator + eventBytes;\n }\n if (projected.length > 0 && selected.length === 0) {\n throw new RangeError(\n `A bounded workspace-control event cannot fit in the HTTP page envelope (${maxBytes} bytes)`,\n );\n }\n return {\n events: selected,\n truncated: selected.length < projected.length,\n nextSequence: selected.at(-1)?.sequence ?? null,\n bytes,\n };\n}\n\n/** Raw durable cursor covered by a possibly coalesced compact event. */\nexport function sessionEventResumeSequence(event: SessionEvent): number {\n return typeof event.coveredThrough === \"number\" &&\n Number.isSafeInteger(event.coveredThrough) &&\n event.coveredThrough >= event.sequence\n ? event.coveredThrough\n : event.sequence;\n}\n\nfunction boundSessionEventForSurface(\n event: SessionEvent,\n surface: SessionEventBoundarySurface,\n): SessionEvent {\n return boundSessionEvent(event, { surface });\n}\n\nfunction observeEventBoundaries(events: readonly SessionEvent[], logger?: EventLogger): void {\n for (const event of events) {\n const boundary = sessionEventPayloadTruncation(event.payload);\n if (!boundary) continue;\n (logger?.debug ?? silentLogger.debug)(\"Session event payload is a bounded audit preview\", {\n eventType: event.type,\n surface: boundary.surface,\n reason: boundary.reason,\n originalBytes: boundary.originalBytes,\n deliveredBytes: boundary.deliveredBytes,\n estimatedOriginalTokens: boundary.estimatedOriginalTokens,\n estimatedDeliveredTokens: boundary.estimatedDeliveredTokens,\n fullEvidenceAvailable: boundary.fullEvidence.available,\n retainedOutputKind: boundary.fullEvidence.available ? boundary.fullEvidence.kind : null,\n });\n }\n}\n\nfunction workspaceControlSubject(workspaceId: string): string {\n return `workspaces.${workspaceId}.control`;\n}\n","import {\n createInbox,\n ErrorCode,\n NatsError,\n type Msg,\n type NatsConnection,\n type Subscription,\n type Status,\n} from \"nats\";\n\n/** Opt-in only for a caller that can safely resend the SAME delivery. Listen\n * before publishing so a responder reconnect cannot strand an outstanding\n * request until its operation deadline. One inbox and deadline survive resends;\n * neither receipt recovery nor transport reconnect grants another execution. */\nexport async function recoveringRequest(\n connection: NatsConnection,\n subject: string,\n payload: Uint8Array,\n options: { timeout: number; resendOn?: string },\n observeTransport: (listener: (status: Status) => void) => () => void,\n): Promise<Msg> {\n const subscriptions: Subscription[] = [];\n let removeReconnect: (() => void) | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n let published = false;\n let resent = false;\n try {\n return await new Promise<Msg>((resolve, reject) => {\n const fail = (error: unknown) => {\n if (settled) return;\n settled = true;\n // A refusal of a resend cannot certify that the original did not run.\n reject(\n resent\n ? Object.assign(NatsError.errorForCode(ErrorCode.Timeout), { cause: error })\n : error,\n );\n };\n const inbox = createInbox();\n const send = () => {\n if (settled) return;\n resent ||= published;\n try {\n connection.publish(subject, payload, { reply: inbox });\n published = true;\n } catch (error) {\n fail(error);\n }\n };\n const watch = (subscription: Subscription) => {\n subscriptions.push(subscription);\n void subscription.closed.then(() =>\n fail(NatsError.errorForCode(ErrorCode.ConnectionClosed)),\n );\n };\n watch(\n connection.subscribe(inbox, {\n callback: (error, message) => {\n if (error) return fail(error);\n if (message.data.length === 0 && message.headers?.code === 503) {\n return fail(NatsError.errorForCode(ErrorCode.NoResponders));\n }\n if (!settled) {\n settled = true;\n resolve(message);\n }\n },\n }),\n );\n if (options.resendOn) {\n watch(\n connection.subscribe(options.resendOn, {\n callback: (error) => (error ? fail(error) : send()),\n }),\n );\n }\n removeReconnect = observeTransport((status) => {\n if (status.type === \"reconnect\") send();\n // Core NATS publishes authorization errors on its status feed, not the\n // reply inbox. Preserve the ordinary request API's fail-fast behavior.\n if (\n status.permissionContext?.operation === \"publish\" &&\n status.permissionContext.subject === subject\n ) {\n fail(NatsError.errorForCode(ErrorCode.PermissionsViolation));\n }\n });\n timer = setTimeout(() => fail(NatsError.errorForCode(ErrorCode.Timeout)), options.timeout);\n send();\n });\n } finally {\n settled = true;\n clearTimeout(timer);\n removeReconnect?.();\n for (const subscription of subscriptions) subscription.unsubscribe();\n }\n}\n","import { sessionEventPayloadTruncation, 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\n/** Flush long runs incrementally before concatenation can become unbounded. */\nexport const SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES = 48 * 1024;\nconst encoder = new TextEncoder();\n\n/**\n * Some providers stream each reasoning summary part as its own delta\n * (\"**Checking the workspace**\", then \"**Inspecting guidance**\"). Readers join\n * reasoning fragments with this separator, so a part that opens bold right\n * after one that closed bold starts a new paragraph instead of colliding\n * (\"****\"). Every place that merges reasoning fragments (the worker's\n * write-time merge, this read-side coalescer, the React projection) must use\n * the same rule, so the rendered text never depends on fragment boundaries.\n */\nexport function reasoningDeltaSeparator(previous: string, next: string): string {\n return previous.endsWith(\"**\") && next.startsWith(\"**\") ? \"\\n\\n\" : \"\";\n}\n\nexport type CoalescedSessionEventPage = {\n events: SessionEvent[];\n /** Durable raw sequence covered by each returned synthetic event sequence. */\n coveredThroughBySequence: ReadonlyMap<number, number>;\n};\n\ntype DeltaRun = {\n first: SessionEvent;\n lastSequence: number;\n text: string;\n textBytes: number;\n sandboxName: string | undefined;\n sandboxStream: string | undefined;\n sandboxCommandId: string | undefined;\n messageId: string | undefined;\n phase: string | undefined;\n};\n\nexport function coalesceSessionEventDeltas(events: SessionEvent[]): SessionEvent[] {\n return coalesceSessionEventDeltasWithCoverage(events).events;\n}\n\nexport function coalesceSessionEventDeltasWithCoverage(\n events: SessionEvent[],\n): CoalescedSessionEventPage {\n const coalesced: SessionEvent[] = [];\n const coveredThroughBySequence = new Map<number, number>();\n let run: DeltaRun | null = null;\n\n const flush = () => {\n if (!run) {\n return;\n }\n const 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 ...(run.messageId !== undefined ? { messageId: run.messageId } : {}),\n ...(run.phase !== undefined ? { phase: run.phase } : {}),\n };\n coalesced.push({\n ...run.first,\n coveredThrough: run.lastSequence,\n payload,\n });\n coveredThroughBySequence.set(run.first.sequence, run.lastSequence);\n run = null;\n };\n\n for (const event of events) {\n if (!isCoalescibleDelta(event)) {\n flush();\n coalesced.push(event);\n coveredThroughBySequence.set(event.sequence, event.sequence);\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 const text = deltaText(event);\n const messageId =\n event.type === \"agent.message.delta\" && typeof asRecord(event.payload).messageId === \"string\"\n ? (asRecord(event.payload).messageId as string)\n : undefined;\n // One provider message has one phase; keep it on the coalesced delta.\n const phase =\n event.type === \"agent.message.delta\" && typeof asRecord(event.payload).phase === \"string\"\n ? (asRecord(event.payload).phase as string)\n : undefined;\n if (\n run &&\n sameDeltaRun(run.first, event, run.sandboxName, sandboxName) &&\n run.sandboxStream === sandboxStream &&\n run.sandboxCommandId === sandboxCommandId &&\n run.messageId === messageId &&\n run.phase === phase\n ) {\n const piece =\n (event.type === \"agent.reasoning.delta\" ? reasoningDeltaSeparator(run.text, text) : \"\") +\n text;\n const textBytes = encoder.encode(piece).byteLength;\n if (\n (run.textBytes === 0 && textBytes <= SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES) ||\n run.textBytes + textBytes <= SESSION_EVENT_COALESCED_TEXT_TARGET_BYTES\n ) {\n run.text += piece;\n run.textBytes += textBytes;\n run.lastSequence = storedCoverageEnd(event);\n continue;\n }\n // The current segment is already useful and bounded. Flush before adding\n // the next raw delta rather than building the full run and truncating it\n // only after a multi-megabyte intermediate allocation.\n flush();\n } else {\n flush();\n }\n\n run = {\n first: event,\n lastSequence: storedCoverageEnd(event),\n text,\n textBytes: encoder.encode(text).byteLength,\n sandboxName,\n sandboxStream,\n sandboxCommandId,\n messageId,\n phase,\n };\n }\n\n flush();\n return { events: coalesced, coveredThroughBySequence };\n}\n\n/**\n * A stored delta may already cover later sequences: a folded run (see\n * docs/session-storage-lifecycle.md) keeps `coalescedUntil`, the last sequence\n * whose text it holds.\n */\nfunction storedCoverageEnd(event: SessionEvent): number {\n const until = asRecord(event.payload).coalescedUntil;\n return typeof until === \"number\" && Number.isSafeInteger(until) && until > event.sequence\n ? until\n : event.sequence;\n}\n\nfunction isCoalescibleDelta(event: SessionEvent): boolean {\n return (\n COALESCIBLE_DELTA_TYPES.has(event.type) && sessionEventPayloadTruncation(event.payload) === null\n );\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; 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 its\n// generation-fenced process subtree\n// `agent.<workspaceId>.<agentId>.connection.<instanceId>.>` (+ reply\n// `_INBOX.>`). That exact scope prevents both cross-workspace access and a stale\n// process sharing credentials with its live successor.\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// validates the seed and derives its public identity once; native Node `crypto`\n// supplies Ed25519 signing and 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; the current seed's imported native key is\n// reused until the configured seed changes. 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, createPrivateKey, sign, type KeyObject } 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\ntype AccountSigner = { seed: string; publicKey: string; privateKey: KeyObject };\nlet currentAccountSigner: AccountSigner | undefined;\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\";\n\nfunction accountSigner(seed: string): AccountSigner {\n if (currentAccountSigner?.seed === seed) return currentAccountSigner;\n // Keep nkeys' checksum, prefix and seed-length validation. Public identity\n // derivation happens only on import, not twice for every authorization.\n const account = nkeys.fromSeed(Buffer.from(seed));\n const publicKey = account.getPublicKey();\n if (publicKey.startsWith(\"X\")) {\n // X25519 curve seeds cannot sign; preserve nkeys' existing rejection.\n throw new nkeys.NKeysError(nkeys.NKeysErrorCode.InvalidCurveOperation);\n }\n // The already-validated NKey is base32(two prefix bytes + 32 seed bytes +\n // two CRC bytes). Decode the seed without depending on nkeys' private APIs.\n const decoded = Buffer.alloc(Math.floor((seed.length * 5) / 8));\n let bits = 0,\n value = 0,\n offset = 0;\n for (const char of seed) {\n value = (value << 5) | BASE32_ALPHABET.indexOf(char);\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n decoded[offset++] = (value >>> bits) & 255;\n }\n }\n // RFC 8410 PKCS#8 Ed25519 PrivateKeyInfo: algorithm OID 1.3.101.112 and\n // a nested OCTET STRING holding the 32-byte seed (no algorithm parameters).\n const privateKey = createPrivateKey({\n key: Buffer.concat([\n Buffer.from(\"302e020100300506032b657004220420\", \"hex\"),\n decoded.subarray(2, 34),\n ]),\n format: \"der\",\n type: \"pkcs8\",\n });\n return (currentAccountSigner = { seed, publicKey, privateKey });\n}\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: AccountSigner): 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 = sign(null, Buffer.from(signingInput, \"utf8\"), signingKey.privateKey);\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 = accountSigner(input.accountSeed);\n const accountPublicKey = accountKey.publicKey;\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 = accountSigner(input.accountSeed);\n const accountPublicKey = accountKey.publicKey;\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 // exact generation-fenced agent request/reply routes; 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 /** Client-reported process identity. Opengeni agents use a strict\n * `opengeni-agent/connection/<uuid>` shape; auth-callout rejects anything\n * else before granting machine subjects. */\n name: 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; name?: 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 const name = typeof connectOpts.name === \"string\" ? connectOpts.name : undefined;\n return { userNkey, serverId, authToken, user, name };\n}\n\nconst AGENT_CONNECTION_NAME_PREFIX = \"opengeni-agent/connection/\";\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Parse the exact process instance carried by the NATS CONNECT name. The value\n * is authority material used in subjects, so arbitrary tokens/dots are never\n * accepted. */\nexport function parseAgentConnectionName(name: string | undefined): string | null {\n if (!name?.startsWith(AGENT_CONNECTION_NAME_PREFIX)) return null;\n const instanceId = name.slice(AGENT_CONNECTION_NAME_PREFIX.length);\n return UUID_PATTERN.test(instanceId) ? instanceId.toLowerCase() : null;\n}\n\n/**\n * Build the exact process-scoped permission set for an authenticated agent. In\n * production agentId + connectionInstanceId are mandatory, restricting both\n * directions to that claimed daemon's RPC/event/hello/op subtree. It may publish\n * to `_INBOX.>` only to answer control-plane requests; it never needs to read\n * another connection's reply inbox.\n * The workspace-only fallback exists solely for legacy isolated callers/tests.\n *\n * THE isolation assertion (§17): with workspace A, agent B, instance C, the\n * production allow lists name only `agent.A.B.connection.C.>` and `_INBOX.>`.\n * NATS rejects every other workspace, agent, or process generation.\n */\nexport function workspaceAgentPermissions(\n workspaceId: string,\n agentId?: string,\n connectionInstanceId?: string,\n): NatsPermissions {\n const agentScope =\n agentId && connectionInstanceId\n ? `agent.${workspaceId}.${agentId}.connection.${connectionInstanceId}.>`\n : `agent.${workspaceId}.>`;\n // The reply-inbox subtree must be reachable for request/reply (the control plane\n // requests on the exact process RPC subject with a reply inbox; the agent responds there).\n const inboxScope = \"_INBOX.>\";\n return {\n pub: { allow: [agentScope, inboxScope] },\n sub: { allow: [agentScope] },\n };\n}\n"],"mappings":";;;;;;AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,iCAAAA;AAAA,OAKK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX;AAAA,OAMK;;;ACtCP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AAMP,eAAsB,kBACpB,YACA,SACA,SACA,SACA,kBACc;AACd,QAAM,gBAAgC,CAAC;AACvC,MAAI;AACJ,MAAI;AACJ,MAAI,UAAU;AACd,MAAI,YAAY;AAChB,MAAI,SAAS;AACb,MAAI;AACF,WAAO,MAAM,IAAI,QAAa,CAAC,SAAS,WAAW;AACjD,YAAM,OAAO,CAAC,UAAmB;AAC/B,YAAI,QAAS;AACb,kBAAU;AAEV;AAAA,UACE,SACI,OAAO,OAAO,UAAU,aAAa,UAAU,OAAO,GAAG,EAAE,OAAO,MAAM,CAAC,IACzE;AAAA,QACN;AAAA,MACF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Q;AAC1B,UAAM,WAAWC,+BAA8B,MAAM,OAAO;AAC5D,QAAI,CAAC,SAAU;AACf,KAAC,QAAQ,SAAS,aAAa,OAAO,oDAAoD;AAAA,MACxF,WAAW,MAAM;AAAA,MACjB,SAAS,SAAS;AAAA,MAClB,QAAQ,SAAS;AAAA,MACjB,eAAe,SAAS;AAAA,MACxB,gBAAgB,SAAS;AAAA,MACzB,yBAAyB,SAAS;AAAA,MAClC,0BAA0B,SAAS;AAAA,MACnC,uBAAuB,SAAS,aAAa;AAAA,MAC7C,oBAAoB,SAAS,aAAa,YAAY,SAAS,aAAa,OAAO;AAAA,IACrF,CAAC;AAAA,EACH;AACF;AAEA,SAAS,wBAAwB,aAA6B;AAC5D,SAAO,cAAc,WAAW;AAClC;","names":["sessionEventPayloadTruncation","connect","nkeys","sessionEventPayloadTruncation"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/events",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.3.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -19,6 +19,10 @@
|
|
|
19
19
|
".": {
|
|
20
20
|
"types": "./dist/index.d.ts",
|
|
21
21
|
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./durable-fanout": {
|
|
24
|
+
"types": "./dist/durable-fanout.d.ts",
|
|
25
|
+
"import": "./dist/durable-fanout.js"
|
|
22
26
|
}
|
|
23
27
|
},
|
|
24
28
|
"publishConfig": {
|
|
@@ -31,8 +35,8 @@
|
|
|
31
35
|
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
32
36
|
},
|
|
33
37
|
"dependencies": {
|
|
34
|
-
"@opengeni/contracts": "4.
|
|
35
|
-
"@opengeni/db": "4.
|
|
38
|
+
"@opengeni/contracts": "4.3.1",
|
|
39
|
+
"@opengeni/db": "4.3.1",
|
|
36
40
|
"nats": "^2.29.3"
|
|
37
41
|
}
|
|
38
42
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The broker-independent durable event recovery contract.
|
|
2
|
+
/**
|
|
3
|
+
* Versioned recovery contract for already-durable session-event fanout.
|
|
4
|
+
*
|
|
5
|
+
* A publisher acknowledgement alone cannot prove that every API subscriber was
|
|
6
|
+
* connected for the live message. Supported broker-backed buses must therefore
|
|
7
|
+
* notify consumers after transport subscriptions have been restored so an
|
|
8
|
+
* already-open SSE stream can run one bounded Postgres catch-up. A bus that can
|
|
9
|
+
* never disconnect may implement this as a listener registry that never fires.
|
|
10
|
+
*/
|
|
11
|
+
export const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1 as const;
|
|
12
|
+
|
|
13
|
+
export type SessionEventDurableFanoutCapability = {
|
|
14
|
+
version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;
|
|
15
|
+
subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function requireSessionEventDurableFanoutCapability(
|
|
19
|
+
bus: unknown,
|
|
20
|
+
): SessionEventDurableFanoutCapability {
|
|
21
|
+
const capability = (bus as { sessionEventDurableFanout?: unknown } | null)
|
|
22
|
+
?.sessionEventDurableFanout as
|
|
23
|
+
| { version?: unknown; subscribeRecovery?: unknown }
|
|
24
|
+
| null
|
|
25
|
+
| undefined;
|
|
26
|
+
if (
|
|
27
|
+
capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION ||
|
|
28
|
+
typeof capability.subscribeRecovery !== "function"
|
|
29
|
+
) {
|
|
30
|
+
throw new Error(
|
|
31
|
+
"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect",
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
return capability as SessionEventDurableFanoutCapability;
|
|
35
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
3
|
+
type SessionEventDurableFanoutCapability,
|
|
4
|
+
} from "./durable-fanout";
|
|
5
|
+
export {
|
|
6
|
+
SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION,
|
|
7
|
+
requireSessionEventDurableFanoutCapability,
|
|
8
|
+
type SessionEventDurableFanoutCapability,
|
|
9
|
+
} from "./durable-fanout";
|
|
1
10
|
import {
|
|
2
11
|
boundSessionEvent,
|
|
3
12
|
boundWorkspaceControlEvent,
|
|
@@ -565,41 +574,6 @@ export type RequestHandler = (
|
|
|
565
574
|
subject: string,
|
|
566
575
|
) => Promise<Uint8Array> | Uint8Array;
|
|
567
576
|
|
|
568
|
-
/**
|
|
569
|
-
* Versioned recovery contract for already-durable session-event fanout.
|
|
570
|
-
*
|
|
571
|
-
* A publisher acknowledgement alone cannot prove that every API subscriber was
|
|
572
|
-
* connected for the live message. Supported broker-backed buses must therefore
|
|
573
|
-
* notify consumers after transport subscriptions have been restored so an
|
|
574
|
-
* already-open SSE stream can run one bounded Postgres catch-up. A bus that can
|
|
575
|
-
* never disconnect may implement this as a listener registry that never fires.
|
|
576
|
-
*/
|
|
577
|
-
export const SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION = 1 as const;
|
|
578
|
-
|
|
579
|
-
export type SessionEventDurableFanoutCapability = {
|
|
580
|
-
version: typeof SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION;
|
|
581
|
-
subscribeRecovery: (onRecovery: (generation: number) => void) => () => void;
|
|
582
|
-
};
|
|
583
|
-
|
|
584
|
-
export function requireSessionEventDurableFanoutCapability(
|
|
585
|
-
bus: unknown,
|
|
586
|
-
): SessionEventDurableFanoutCapability {
|
|
587
|
-
const capability = (bus as { sessionEventDurableFanout?: unknown } | null)
|
|
588
|
-
?.sessionEventDurableFanout as
|
|
589
|
-
| { version?: unknown; subscribeRecovery?: unknown }
|
|
590
|
-
| null
|
|
591
|
-
| undefined;
|
|
592
|
-
if (
|
|
593
|
-
capability?.version !== SESSION_EVENT_DURABLE_FANOUT_CAPABILITY_VERSION ||
|
|
594
|
-
typeof capability.subscribeRecovery !== "function"
|
|
595
|
-
) {
|
|
596
|
-
throw new Error(
|
|
597
|
-
"EventBus must provide sessionEventDurableFanout v1 so accepted durable publications reconcile after subscriber reconnect",
|
|
598
|
-
);
|
|
599
|
-
}
|
|
600
|
-
return capability as SessionEventDurableFanoutCapability;
|
|
601
|
-
}
|
|
602
|
-
|
|
603
577
|
export type EventBus = {
|
|
604
578
|
/**
|
|
605
579
|
* Mandatory paired recovery contract for durable session-event publication.
|