// The gateway (lab 08): one place every event goes through. // // channels (terminal, web) --message--> gateway --one queue per session--> assistant // scheduler (lab 09) --job-----> | // +--deliver--> outbox + every channel adapter // // The gateway decides WHO is speaking (only the owner is served), WHICH session a message // belongs to (session scope and identity links), and WHEN it runs (one turn at a time per // session). Channels and the scheduler never call the assistant directly. import { appendFile, mkdir, readFile } from 'node:fs/promises'; import path from 'node:path'; import type { App } from '../app.ts'; import type { AnswerResult, AssistantResult } from '../core/assistant.ts'; import type { RecoveryReport, Session } from '../sessions/session.ts'; import { sessionKey } from '../sessions/session-store.ts'; import { KeyedQueue } from './queue.ts'; export interface InboundMessage { channel: string; /** Who sent it, as known to the channel ("owner" for the local terminal and web chat). */ sender: string; text: string; } export interface OutboundMessage { ts: string; /** "scheduled" for job results, "notice" for anything else the assistant starts itself. */ kind: 'scheduled' | 'notice'; /** Where it came from, for example "job:daily-review". */ source: string; text: string; } export interface ChannelAdapter { readonly name: string; /** Show a message the assistant sends on its own (a reminder, a job result). */ deliver?(message: OutboundMessage): void | Promise; } export interface TurnObserver { onText?: (delta: string) => void; onTool?: (event: { name: string; phase: 'start' | 'end'; isError?: boolean }) => void; signal?: AbortSignal; } export class NotOwnerError extends Error {} export class Gateway { readonly app: App; private readonly queue = new KeyedQueue(); private readonly sessions = new Map(); private readonly recoveries = new Map(); private readonly adapters: ChannelAdapter[] = []; private readonly inFlight = new Set(); private readonly outboxFile: string; private closed = false; constructor(app: App) { this.app = app; this.outboxFile = path.join(app.config.paths.dataDir, 'outbox.jsonl'); } register(adapter: ChannelAdapter): void { this.adapters.push(adapter); } /** Identity links: "web:owner" and "terminal:owner" are the same person if both are listed. */ isOwner(channel: string, sender: string): boolean { return this.app.config.owner.identities.includes(`${channel}:${sender}`); } sessionKeyFor(channel: string): string { return sessionKey('steward', this.app.config.gateway.scope, channel); } /** The open session for a key (opened once, then cached). */ async session(key: string): Promise { let session = this.sessions.get(key); if (!session) { const opened = await this.app.sessions.open(key); session = opened.session; this.sessions.set(key, session); this.recoveries.set(key, opened.recovery); } return session; } recovery(key: string): RecoveryReport | undefined { return this.recoveries.get(key); } /** A message from a channel. */ async handleMessage( message: InboundMessage, observer: TurnObserver = {}, ): Promise { if (!this.isOwner(message.channel, message.sender)) { throw new NotOwnerError(`${message.channel}:${message.sender} is not the owner`); } const key = this.sessionKeyFor(message.channel); return this.enqueue(key, observer, async (signal) => { const session = await this.session(key); return this.app.assistant.reply(session, message.text, { channel: message.channel, ...observer, signal, }); }); } /** Runs a prompt in its own session: scheduled jobs (lab 09) use this. */ async runInSession( key: string, channel: string, text: string, observer: TurnObserver = {}, ): Promise { return this.enqueue(key, observer, async (signal) => { const session = await this.session(key); return this.app.assistant.reply(session, text, { channel, ...observer, signal }); }); } /** All waiting approval requests in open sessions, with their session keys. */ async pendingApprovals(): Promise< { key: string; approvalId: string; summary: string; reason: string }[] > { const keys = (await this.app.sessions.list()).map((s) => s.key); const out: { key: string; approvalId: string; summary: string; reason: string }[] = []; for (const key of keys) { // Read-only: opening a session runs crash recovery, which must never touch a log that a // helper (lab 10) or another task is writing right now. const session = this.sessions.get(key) ?? (await this.app.sessions.peek(key)); if (!session) continue; for (const r of session.pendingApprovals()) { out.push({ key, approvalId: r.approvalId, summary: r.summary, reason: r.reason }); } } return out; } /** Answers an approval request from any channel, whichever session it belongs to. */ async answerApproval( approvalId: string, decision: 'approved' | 'denied', options: { channel: string; sender: string; always?: boolean } & TurnObserver, ): Promise { if (!this.isOwner(options.channel, options.sender)) { throw new NotOwnerError(`${options.channel}:${options.sender} is not the owner`); } const match = (await this.pendingApprovals()).find((p) => p.approvalId === approvalId); if (!match) return { status: 'unknown' }; return this.enqueue(match.key, options, async (signal) => { const session = await this.session(match.key); return this.app.assistant.answerApproval(session, approvalId, decision, { ...options, signal, }); }); } /** Starts a new conversation for a channel's session key (`/new`). */ /** Starts a fresh log for a channel's session, or for an explicit session key. */ async newConversation(channel: string, explicitKey?: string): Promise { const key = explicitKey ?? this.sessionKeyFor(channel); return this.queue.run(key, async () => { const session = await this.app.sessions.rotate(key); this.sessions.set(key, session); return session; }); } /** Sends a message the assistant starts on its own to the outbox and every channel. */ async deliver(message: Omit): Promise { const full: OutboundMessage = { ts: new Date().toISOString(), ...message }; await mkdir(path.dirname(this.outboxFile), { recursive: true }); await appendFile(this.outboxFile, JSON.stringify(full) + '\n', 'utf8'); for (const adapter of this.adapters) { try { await adapter.deliver?.(full); } catch { // One broken channel must not stop delivery to the others; the outbox has it anyway. } } } /** The latest outbox messages, oldest first. */ async outbox(count = 20): Promise { try { const lines = (await readFile(this.outboxFile, 'utf8')).trim().split('\n').filter(Boolean); return lines.slice(-count).flatMap((line) => { try { return [JSON.parse(line) as OutboundMessage]; } catch { return []; } }); } catch { return []; } } stats(): { queueDepth: number; openSessions: number; inFlight: number } { return { queueDepth: this.queue.depth, openSessions: this.sessions.size, inFlight: this.inFlight.size, }; } /** * Graceful shutdown (lab 12): refuse new work, cancel turns in flight (each is recorded as * interrupted in its session log), and wait for the queues to drain. */ async close(timeoutMs = 10_000): Promise { this.closed = true; for (const controller of this.inFlight) controller.abort('the gateway shut down'); await Promise.race([ this.queue.idle(), new Promise((resolve) => setTimeout(resolve, timeoutMs).unref()), ]); } private enqueue( key: string, observer: TurnObserver, work: (signal: AbortSignal) => Promise, ): Promise { if (this.closed) return Promise.reject(new Error('the gateway is shutting down')); return this.queue.run(key, async () => { // Queued before shutdown but not started yet: do not start it now. if (this.closed) throw new Error('the gateway is shutting down'); const controller = new AbortController(); const signal = observer.signal ? AbortSignal.any([observer.signal, controller.signal]) : controller.signal; this.inFlight.add(controller); try { return await work(signal); } finally { this.inFlight.delete(controller); } }); } }