Gracefully drain in-flight messages and close the NATS connection. Stops all JetStream consumers, then drains core subscriptions.
Connect to NATS. No-op (no error) when NATS is not configured. Concurrency-safe: concurrent calls share the same connection attempt.
Create a durable JetStream audit stream for tenant (idempotent).
Requires JetStream enabled on the server: nats-server --jetstream
OptionalstreamName: stringJoin a queue group — NATS delivers each task to exactly ONE worker. Built-in load balancing across all workers in the same group name.
Subscribe to all events for a tenant across scope, model, and agent subjects. Returns a named object so callers can unsubscribe each category individually.
Subscribe to ALL scope events for a tenant across every scope and every event type — no type filtering applied.
Use this for SSE relay routes that forward the full event stream to clients. Any new scope event type is automatically included without code changes here.
Subscribe to veto activations for a tenant.
⚠ CRITICAL PATH — veto must halt ALL swarm agents in <10ms.
Recommended pattern:
client.events.onVetoActivated('acme', async (event) => {
await swarm.halt(event.scopeId, { reason: event.reason });
});
Set nats.onHandlerError in ClientConfig to ensure veto failures
are surfaced and trigger fallback halt logic.
Publish a typed scope event.
Tenant ownership is enforced: the derived subject must belong to tenant.
Subscribe to the durable audit stream, replaying all events from the beginning.
Uses the nats.js v2 Consumers API with correct enum deliver policy (H-4/H-5).
The consumer messages handle is stored in _consumers and stopped on close() (H-6 fix).
Must call enableAuditStream(tenant) first (idempotent, safe to call again).
OptionalconsumerName: stringOptionalstreamName: stringCleanup function — call it to stop this specific audit subscription
Invoke handler and route errors to
onHandlerErrorcallback or console.error.Extracted as a named method so it is directly testable and so the error routing logic is shared between _sub() and subscribeAudit(). Never re-throws inside a void IIFE — that would create an unhandled rejection rather than a visible NATS connection error (HIGH-NEW-9 fix).