export type AdvisoryPresenceState = "idle" | "busy" | "paused" | "offline"; export interface PresenceWriter { setStatus( status: AdvisoryPresenceState, note?: string, signal?: AbortSignal, ): Promise<{ readonly ok: boolean; readonly error?: unknown }>; } export interface PresenceProjectionStatus { readonly state: AdvisoryPresenceState | null; readonly note: string | null; readonly degraded: boolean; readonly lastError: string | null; } /** Best-effort advisory projection; it never gates lease or delivery state. */ export class PresenceProjector { readonly #writer: PresenceWriter; readonly #minimumIntervalMs: number; readonly #now: () => number; #lastPublished: { state: AdvisoryPresenceState; note?: string; at: number } | undefined; #lastModelNoteAt: number | undefined; #status: PresenceProjectionStatus = { state: null, note: null, degraded: false, lastError: null, }; constructor(options: { readonly writer: PresenceWriter; readonly minimumIntervalMs?: number; readonly now?: () => number; }) { this.#writer = options.writer; this.#minimumIntervalMs = options.minimumIntervalMs ?? 5_000; this.#now = options.now ?? Date.now; } snapshot(): PresenceProjectionStatus { return { ...this.#status }; } async idle(signal?: AbortSignal): Promise { await this.#publish("idle", undefined, false, signal); } async busy(signal?: AbortSignal): Promise { await this.#publish("busy", undefined, false, signal); } async paused(signal?: AbortSignal): Promise { await this.#publish("paused", undefined, true, signal); } async offline(signal?: AbortSignal): Promise { await this.#publish("offline", undefined, true, signal); } async modelNote(model: string, signal?: AbortSignal): Promise { const note = `model=${bounded(model, 120)}`; const now = this.#now(); if (this.#lastModelNoteAt !== undefined && now - this.#lastModelNoteAt < this.#minimumIntervalMs) return; this.#lastModelNoteAt = now; const state = this.#lastPublished?.state ?? "idle"; await this.#publish(state, note, false, signal); } async #publish( state: AdvisoryPresenceState, note: string | undefined, force: boolean, signal?: AbortSignal, ): Promise { const now = this.#now(); const last = this.#lastPublished; const duplicate = last?.state === state && last.note === note; if (!force && duplicate && last && now - last.at < this.#minimumIntervalMs) return; try { const result = await this.#writer.setStatus(state, note, signal); if (!result.ok) throw toError(result.error ?? "AMQ presence update failed"); this.#lastPublished = { state, ...(note ? { note } : {}), at: now }; this.#status = { state, note: note ?? null, degraded: false, lastError: null }; } catch (error) { this.#status = { state, note: note ?? null, degraded: true, lastError: toError(error).message, }; } } } function bounded(value: string, maximum: number): string { return value.length <= maximum ? value : `${value.slice(0, maximum - 1)}…`; } function toError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }