Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/rooms

Shared rooms where spawned agents and their spawner exchange messages, with push wakes and a blocking wait fallback.

FollowForkOpen app

Files

rooms.ts

756 lines · 38.8 KB · TypeScript
import { type Caps, type CleanupSettings, defaultCaps, defaultCleanup, parseCaps, parseCleanup } from './config.ts'
import { type Db, ensureSchema, first, num, str } from './db.ts'
import { invalid, RoomError } from './errors.ts'
import { hashSecret, isJoinCodeShape, isMemberTokenShape, newJoinCode, newMemberId, newMemberToken, newMessageId, newRoomId, newWatchId } from './ids.ts'
import { bodyText, clip, safetyLine, sanitizeJson, sanitizeText, wrapUntrusted } from './text.ts'
import type { Sealer } from './seal.ts'
import { buildWakePayload, decideWake, describeTarget, parseWatchConfig, planDelivery, type WakeAction, type WakeTarget, type WatchConfig, type WatchState } from './wake.ts'

export type Via = 'cli' | 'http' | 'ws' | 'wake'
export const vias: Array<Via> = ['cli', 'http', 'ws', 'wake']

export type RoomEvent = { topic: string; idempotencyKey: string; payload: Record<string, unknown> }

/** Platform hooks. Every hook is optional so the core runs in tests and in any Kody runtime. */
export type Deps = {
	fetch?: typeof fetch
	runJob?: (jobId: string) => Promise<unknown>
	/** `events.dispatch`. Failures are logged and must not break the room write. */
	dispatchEvent?: ((event: RoomEvent) => Promise<unknown>) | null
	broadcast?: (roomId: string, data: Record<string, unknown>) => Promise<unknown>
	/** Public app origin plus base path, without a trailing slash. */
	appUrl?: string | null
	/** Encrypts agent-owned webhook URLs and keys at rest. Throws when the owner has not set it up. */
	sealer?: () => Promise<Sealer>
}

export type Ctx = { db: Db; now: () => number; deps: Deps }

export type Auth = { token?: string | null; kodyUserId?: string | null }

export type Member = {
	id: string
	roomId: string
	name: string
	role: 'creator' | 'member'
	via: Via
	kodyUserId: string | null
	joinedAt: number
	lastSeenAt: number
	listeningUntil: number
	leftAt: number | null
}

export type Room = {
	id: string
	purpose: string | null
	creatorUserId: string
	creatorMemberId: string | null
	status: 'open' | 'closed'
	seq: number
	caps: Caps
	createdAt: number
	updatedAt: number
	closedAt: number | null
}

/** Message envelope copied from kody.exchange, plus `seq`, `untrusted`, and a wrapped `display`. */
export type RoomMessage = {
	id: string
	at: string
	from: { agent_id: string; name: string }
	thread: string
	kind: 'message' | 'system' | 'blob'
	body: unknown
	refs: Array<{ type: string; id: string }>
	seq: number
	untrusted: true
	display: string
}

const listeningWindowMs = 45_000
const unreachableAfterFailures = 3
const iso = (ms: number) => new Date(ms).toISOString()

function rowToRoom(row: Record<string, unknown>): Room {
	return {
		id: String(row.id),
		purpose: str(row.purpose),
		creatorUserId: String(row.creator_user_id),
		creatorMemberId: str(row.creator_member_id),
		status: row.status === 'closed' ? 'closed' : 'open',
		seq: Number(row.seq),
		caps: { ...defaultCaps, ...(JSON.parse(String(row.caps_json)) as Partial<Caps>) },
		createdAt: Number(row.created_at),
		updatedAt: Number(row.updated_at),
		closedAt: num(row.closed_at),
	}
}

function rowToMember(row: Record<string, unknown>): Member {
	return {
		id: String(row.id),
		roomId: String(row.room_id),
		name: String(row.name),
		role: row.role === 'creator' ? 'creator' : 'member',
		via: (vias as Array<string>).includes(String(row.via)) ? (row.via as Via) : 'cli',
		kodyUserId: str(row.kody_user_id),
		joinedAt: Number(row.joined_at),
		lastSeenAt: Number(row.last_seen_at),
		listeningUntil: Number(row.listening_until),
		leftAt: num(row.left_at),
	}
}

function rowToMessage(row: Record<string, unknown>): RoomMessage {
	const body = JSON.parse(String(row.body_json))
	const message = {
		id: String(row.id),
		at: iso(Number(row.at)),
		from: { agent_id: String(row.from_id), name: String(row.from_name) },
		thread: String(row.room_id),
		kind: String(row.kind) as RoomMessage['kind'],
		body,
		refs: JSON.parse(String(row.refs_json)),
		seq: Number(row.seq),
		untrusted: true as const,
	}
	return {
		...message,
		display: wrapUntrusted({ text: bodyText(body), fromId: message.from.agent_id, fromName: message.from.name, messageId: message.id, seq: message.seq }),
	}
}

async function open(ctx: Ctx) {
	await ensureSchema(ctx.db)
	return ctx.db
}

export async function getRoom(ctx: Ctx, roomId: string) {
	const row = await first(await open(ctx), 'SELECT * FROM rooms WHERE id = ?', [roomId])
	if (!row) throw new RoomError('not_found', 'Room not found.')
	return rowToRoom(row)
}

export function parseName(value: unknown) {
	if (typeof value !== 'string') invalid('name is required (who you are in the room, 1 to 60 characters).')
	const name = clip(sanitizeText(value).replace(/\s+/g, ' ').trim(), 60)
	if (!name) invalid('name is required (who you are in the room, 1 to 60 characters).')
	if (['system', 'your-agent-name'].includes(name.toLowerCase())) invalid(`"${name}" is reserved. Ask your operator what this agent should be called.`)
	return name
}

export function parseVia(value: unknown, fallback: Via): Via {
	if (value == null) return fallback
	if (!(vias as Array<unknown>).includes(value)) invalid('via must be cli, http, ws, or wake.')
	return value as Via
}

/** Package-level settings (caps and cleanup). */
export async function readSettings(ctx: Ctx): Promise<{ caps: Caps; cleanup: CleanupSettings }> {
	const db = await open(ctx)
	const rows = (await db.sql('SELECT key, value_json FROM settings')).rows
	const values = Object.fromEntries(rows.map((row) => [String(row.key), JSON.parse(String(row.value_json))]))
	return { caps: parseCaps(values.caps ?? null), cleanup: parseCleanup(values.cleanup ?? null) }
}

export async function writeSettings(ctx: Ctx, input: { caps?: unknown; cleanup?: unknown }) {
	const current = await readSettings(ctx)
	const next = { caps: parseCaps(input.caps ?? null, current.caps), cleanup: parseCleanup(input.cleanup ?? null, current.cleanup) }
	for (const [key, value] of Object.entries(next)) {
		await ctx.db.sql('INSERT INTO settings (key, value_json) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value_json = excluded.value_json', [key, JSON.stringify(value)])
	}
	return next
}

/**
 * Resolve the acting member. A room token works anywhere; a Kody user who
 * created the room acts as its creator member without a token.
 */
export async function resolveMember(ctx: Ctx, roomId: string | null, auth: Auth): Promise<{ room: Room; member: Member }> {
	const db = await open(ctx)
	let row: Record<string, unknown> | null = null
	if (auth.token) {
		if (!isMemberTokenShape(auth.token)) throw new RoomError('unauthorized', 'Room token is malformed.')
		row = await first(db, 'SELECT * FROM members WHERE token_hash = ?', [await hashSecret('token', auth.token)])
		if (!row) throw new RoomError('unauthorized', 'Room token is not valid (revoked, left, or wrong).')
		if (roomId && String(row.room_id) !== roomId) throw new RoomError('forbidden', 'This token belongs to a different room.')
	} else if (auth.kodyUserId && roomId) {
		const room = await getRoom(ctx, roomId)
		if (room.creatorUserId !== auth.kodyUserId || !room.creatorMemberId) {
			throw new RoomError('unauthorized', 'Pass token (the room token from create or join). Only the room creator may act without one.')
		}
		row = await first(db, 'SELECT * FROM members WHERE id = ?', [room.creatorMemberId])
	} else {
		throw new RoomError('unauthorized', roomId ? 'Pass token (the room token from create or join).' : 'Pass room and token.')
	}
	if (!row) throw new RoomError('unauthorized', 'Member not found.')
	const member = rowToMember(row)
	if (member.leftAt != null) throw new RoomError('unauthorized', 'You left this room. Ask for a new invite to rejoin.')
	return { room: await getRoom(ctx, member.roomId), member }
}

async function touch(ctx: Ctx, member: Member, via: Via, listeningMs = 0) {
	const now = ctx.now()
	await ctx.db.sql('UPDATE members SET last_seen_at = ?, via = ?, listening_until = MAX(listening_until, ?) WHERE id = ?', [now, via, listeningMs > 0 ? now + listeningMs : 0, member.id])
}

async function mintInvites(ctx: Ctx, room: Room, createdBy: string, count: number, nameHint: string | null) {
	const now = ctx.now()
	const expiresAt = now + room.caps.inviteTtlHours * 3600_000
	const invites: Array<{ code: string; expiresAt: string }> = []
	for (let i = 0; i < count; i++) {
		const code = newJoinCode()
		await ctx.db.sql('INSERT INTO invites (code_hash, room_id, created_by, name_hint, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)', [await hashSecret('code', code), room.id, createdBy, nameHint, now, expiresAt])
		invites.push({ code, expiresAt: iso(expiresAt) })
	}
	return invites
}

function requireOpen(room: Room) {
	if (room.status !== 'open') throw new RoomError('room_closed', 'This room is closed. Read is still allowed; writes are not.')
}

function requireCreator(room: Room, member: Member) {
	if (member.id !== room.creatorMemberId) throw new RoomError('forbidden', 'Only the room creator may do this.')
}

/** Create a room, its creator member, and `invites` one-time join codes. */
export async function createRoom(ctx: Ctx, input: { creatorUserId: string; name: string; purpose?: string | null; caps?: unknown; invites?: number; via?: Via; wake?: unknown; ownerTargets?: boolean }) {
	const db = await open(ctx)
	const wake = await parseWake(ctx, input.wake, input.ownerTargets ?? false)
	const settings = await readSettings(ctx)
	const caps = parseCaps(input.caps ?? null, settings.caps)
	const live = await first(db, "SELECT COUNT(*) AS c FROM rooms WHERE creator_user_id = ? AND status = 'open'", [input.creatorUserId])
	if (Number(live?.c ?? 0) >= settings.caps.liveRoomsPerCreator) {
		throw new RoomError('rate_limited', `You already have ${settings.caps.liveRoomsPerCreator} live rooms.`, { hint: 'Close a room you no longer need with close, then retry.' })
	}
	const inviteCount = input.invites ?? 1
	if (!Number.isInteger(inviteCount) || inviteCount < 0 || inviteCount > caps.membersPerRoom - 1) invalid(`invites must be an integer from 0 to ${caps.membersPerRoom - 1}.`)
	const purpose = input.purpose == null ? null : clip(sanitizeText(String(input.purpose)).trim(), 500) || null
	const now = ctx.now()
	const roomId = newRoomId()
	const memberId = newMemberId()
	const token = newMemberToken()
	await db.sql('INSERT INTO rooms (id, purpose, creator_user_id, creator_member_id, status, seq, caps_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)', [roomId, purpose, input.creatorUserId, memberId, 'open', JSON.stringify(caps), now, now])
	await db.sql('INSERT INTO members (id, room_id, name, role, token_hash, kody_user_id, via, joined_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [memberId, roomId, input.name, 'creator', await hashSecret('token', token), input.creatorUserId, input.via ?? 'cli', now, now])
	const room = await getRoom(ctx, roomId)
	const invites = await mintInvites(ctx, room, memberId, inviteCount, null)
	const watch = wake ? await saveWatch(ctx, room.id, memberId, wake) : null
	await appendSystem(ctx, room, `${input.name} opened the room.`)
	return { room: publicRoom(ctx, room), member: { agent_id: memberId, name: input.name, token }, invites, watch }
}

/** Mint more one-time join codes. Creator only. */
export async function createInvites(ctx: Ctx, room: Room, member: Member, input: { count?: number; nameHint?: string | null }) {
	requireOpen(room)
	requireCreator(room, member)
	const count = input.count ?? 1
	if (!Number.isInteger(count) || count < 1 || count > room.caps.membersPerRoom) invalid(`count must be an integer from 1 to ${room.caps.membersPerRoom}.`)
	const nameHint = input.nameHint == null ? null : clip(sanitizeText(String(input.nameHint)), 60)
	return mintInvites(ctx, room, member.id, count, nameHint)
}

/** Trade a one-time join code for a room-scoped member token. */
export async function joinRoom(ctx: Ctx, input: { code: string; name: string; via: Via; kodyUserId?: string | null; wake?: unknown; ownerTargets?: boolean }) {
	const db = await open(ctx)
	const wake = await parseWake(ctx, input.wake, input.ownerTargets ?? false)
	if (!isJoinCodeShape(input.code)) throw new RoomError('unauthorized', 'Join code is malformed.')
	const codeHash = await hashSecret('code', input.code)
	const invite = await first(db, 'SELECT * FROM invites WHERE code_hash = ?', [codeHash])
	if (!invite) throw new RoomError('unauthorized', 'Join code is not valid.')
	if (invite.used_at != null) throw new RoomError('invite_used', 'This join code was already used. Ask the room creator for a new one.')
	const now = ctx.now()
	if (Number(invite.expires_at) <= now) throw new RoomError('invite_expired', 'This join code expired. Ask the room creator for a new one.')
	const room = await getRoom(ctx, String(invite.room_id))
	requireOpen(room)
	const active = await first(db, 'SELECT COUNT(*) AS c FROM members WHERE room_id = ? AND left_at IS NULL', [room.id])
	if (Number(active?.c ?? 0) >= room.caps.membersPerRoom) throw new RoomError('room_full', `Room is full (${room.caps.membersPerRoom} members).`, { hint: 'Ask the creator to raise caps.membersPerRoom or wait for someone to leave.' })
	const memberId = newMemberId()
	const claimed = await db.sql('UPDATE invites SET used_at = ?, used_by = ? WHERE code_hash = ? AND used_at IS NULL RETURNING code_hash', [now, memberId, codeHash])
	if (claimed.rows.length === 0) throw new RoomError('invite_used', 'This join code was already used.')
	const token = newMemberToken()
	await db.sql('INSERT INTO members (id, room_id, name, role, token_hash, kody_user_id, via, joined_at, last_seen_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [memberId, room.id, input.name, 'member', await hashSecret('token', token), input.kodyUserId ?? null, input.via, now, now])
	const watch = wake ? await saveWatch(ctx, room.id, memberId, wake) : null
	await appendSystem(ctx, room, `${input.name} joined.`)
	await emitRoomEvent(ctx, { topic: '@kody/rooms.room.joined', idempotencyKey: `rooms:joined:${memberId}`, payload: { roomId: room.id, memberId, name: input.name, via: input.via, at: iso(now) } })
	return { room: publicRoom(ctx, await getRoom(ctx, room.id)), member: { agent_id: memberId, name: input.name, token }, watch }
}

function parseBody(value: unknown, caps: Caps) {
	if (value == null || value === '') invalid('body is required: a string or a JSON object (peers read body.text).')
	const body = typeof value === 'string' ? { text: value } : value
	if (typeof body !== 'object' || Array.isArray(body)) invalid('body must be a string or a JSON object.')
	const clean = sanitizeJson(body)
	const bytes = new TextEncoder().encode(JSON.stringify(clean)).length
	if (bytes > caps.messageBytes) throw new RoomError('too_large', `Message is ${bytes} bytes; the cap is ${caps.messageBytes}.`, { hint: 'Split it into smaller messages or share a link.' })
	return clean
}

function parseRefs(value: unknown) {
	if (value == null) return []
	if (!Array.isArray(value) || value.length > 20) invalid('refs must be an array of up to 20 { type, id } objects.')
	return value.map((ref) => {
		if (!ref || typeof ref !== 'object' || typeof ref.type !== 'string' || typeof ref.id !== 'string' || !ref.type || !ref.id || ref.type.length > 100 || ref.id.length > 500 || Object.keys(ref).length !== 2) {
			invalid('Each ref must be exactly { type: string, id: string }.')
		}
		return { type: sanitizeText(ref.type), id: sanitizeText(ref.id) }
	})
}

async function windowCount(ctx: Ctx, column: 'from_id' | 'room_id', id: string, windowMs: number) {
	const since = ctx.now() - windowMs
	const row = await first(ctx.db, `SELECT COUNT(*) AS c, MIN(at) AS oldest FROM messages WHERE ${column} = ? AND at > ? AND kind != 'system'`, [id, since])
	return { count: Number(row?.c ?? 0), retryAfterSeconds: row?.oldest == null ? 1 : (Number(row.oldest) + windowMs - ctx.now()) / 1000 }
}

async function insertMessage(ctx: Ctx, room: Room, input: { fromId: string; fromName: string; kind: RoomMessage['kind']; body: unknown; refs: Array<{ type: string; id: string }> }) {
	const now = ctx.now()
	const bumped = await ctx.db.sql("UPDATE rooms SET seq = seq + 1, updated_at = ? WHERE id = ? AND (status = 'open' OR ? = 'system') RETURNING seq", [now, room.id, input.kind])
	const seq = num(bumped.rows[0]?.seq)
	if (seq == null) throw new RoomError('room_closed', 'This room is closed.')
	const id = newMessageId()
	await ctx.db.sql('INSERT INTO messages (room_id, seq, id, at, from_id, from_name, kind, body_json, refs_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [room.id, seq, id, now, input.fromId, input.fromName, input.kind, JSON.stringify(input.body), JSON.stringify(input.refs)])
	const message = rowToMessage({ room_id: room.id, seq, id, at: now, from_id: input.fromId, from_name: input.fromName, kind: input.kind, body_json: JSON.stringify(input.body), refs_json: JSON.stringify(input.refs) })
	await ctx.deps.broadcast?.(room.id, { type: 'message', message }).catch(() => {})
	return message
}

async function appendSystem(ctx: Ctx, room: Room, text: string) {
	const message = await insertMessage(ctx, room, { fromId: 'system', fromName: 'system', kind: 'system', body: { text }, refs: [] })
	await deliverWakes(ctx, room, message)
	return message
}

/** Post a message. Enforces caps, then fans out wakes to other members' watches. */
export async function postMessage(ctx: Ctx, room: Room, member: Member, input: { body: unknown; kind?: unknown; refs?: unknown; via: Via }) {
	requireOpen(room)
	const kind = input.kind ?? 'message'
	if (kind !== 'message' && kind !== 'blob') invalid('kind must be "message" or "blob" (system is reserved).')
	const body = parseBody(input.body, room.caps)
	const refs = parseRefs(input.refs)
	const mine = await windowCount(ctx, 'from_id', member.id, 3600_000)
	if (mine.count >= room.caps.postsPerMemberPerHour) {
		throw new RoomError('rate_limited', `You posted ${mine.count} messages in the last hour (cap ${room.caps.postsPerMemberPerHour}).`, { retryAfterSeconds: mine.retryAfterSeconds, hint: 'Batch replies into one message.' })
	}
	const daily = await windowCount(ctx, 'room_id', room.id, 86400_000)
	if (daily.count >= room.caps.postsPerRoomPerDay) {
		throw new RoomError('rate_limited', `Room has ${daily.count} posts in the last day (cap ${room.caps.postsPerRoomPerDay}).`, { retryAfterSeconds: daily.retryAfterSeconds })
	}
	await touch(ctx, member, input.via)
	const message = await insertMessage(ctx, room, { fromId: member.id, fromName: member.name, kind, body, refs })
	const wakes = await deliverWakes(ctx, room, message)
	await emitRoomEvent(ctx, { topic: '@kody/rooms.room.message', idempotencyKey: `rooms:message:${message.id}`, payload: messageEventPayload(room.id, message) })
	return { message, cursor: message.seq, wakes }
}

/** Messages after a cursor, oldest first. */
export async function readMessages(ctx: Ctx, room: Room, member: Member | null, input: { after?: unknown; limit?: unknown; via?: Via }) {
	const after = parseCursor(input.after)
	const limit = input.limit == null ? 50 : Number(input.limit)
	if (!Number.isInteger(limit) || limit < 1 || limit > 200) invalid('limit must be an integer from 1 to 200.')
	const rows = (await (await open(ctx)).sql('SELECT * FROM messages WHERE room_id = ? AND seq > ? ORDER BY seq LIMIT ?', [room.id, after, limit + 1])).rows
	if (member && input.via) await touch(ctx, member, input.via)
	const messages = rows.slice(0, limit).map(rowToMessage)
	return {
		status: 'ok' as const,
		roomStatus: room.status,
		messages,
		cursor: messages.at(-1)?.seq ?? after,
		hasMore: rows.length > limit,
		safety: safetyLine,
	}
}

export function parseCursor(value: unknown) {
	if (value == null || value === '') return 0
	const after = Number(value)
	if (!Number.isInteger(after) || after < 0) invalid('after must be a non-negative integer cursor (the seq of the last message you saw).')
	return after
}

export type WaitResult = { status: 'message' | 'timeout' | 'closed'; messages: Array<RoomMessage>; cursor: number; safety: string; waitedMs: number }

/**
 * Block until a peer message arrives after `after`, the room closes, or the
 * timeout passes. Checks the room's cheap `seq` every 2 s, backing off to 5 s,
 * and marks the member listening meanwhile. Own messages advance the cursor
 * but do not end the wait.
 */
export async function waitForMessages(ctx: Ctx, room: Room, member: Member, input: { after?: unknown; timeoutMs: number; via: Via; sleep?: (ms: number) => Promise<void> }): Promise<WaitResult> {
	const sleep = input.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
	const started = ctx.now()
	const deadline = started + input.timeoutMs
	let cursor = parseCursor(input.after)
	let interval = 2000
	const done = (status: WaitResult['status'], messages: Array<RoomMessage> = []) => ({ status, messages, cursor, safety: safetyLine, waitedMs: ctx.now() - started })
	try {
		for (;;) {
			const row = await first(ctx.db, 'SELECT seq, status FROM rooms WHERE id = ?', [room.id])
			if (!row) throw new RoomError('not_found', 'Room not found.')
			await touch(ctx, member, input.via, interval + 15_000)
			if (Number(row.seq) > cursor) {
				const { messages } = await readMessages(ctx, room, null, { after: cursor, limit: 100 })
				if (messages.length > 0) {
					cursor = messages.at(-1)!.seq
					if (messages.some((message) => message.from.agent_id !== member.id)) return done('message', messages)
				}
			}
			if (row.status === 'closed') return done('closed')
			const left = deadline - ctx.now()
			if (left <= 0) return done('timeout')
			await sleep(Math.min(interval, left))
			if (ctx.now() - started >= 30_000) interval = Math.min(5000, interval + 1000)
		}
	} finally {
		await ctx.db.sql('UPDATE members SET listening_until = 0, last_seen_at = ? WHERE id = ?', [ctx.now(), member.id])
	}
}

function presence(ctx: Ctx, member: Member, watch: Record<string, unknown> | undefined) {
	const now = ctx.now()
	const config = watch ? (JSON.parse(String(watch.config_json)) as WatchConfig) : null
	const failures = Number(watch?.consecutive_failures ?? 0)
	return {
		agent_id: member.id,
		name: member.name,
		role: member.role,
		joinedAt: iso(member.joinedAt),
		lastSeenAt: iso(member.lastSeenAt),
		via: member.via,
		listening: member.listeningUntil > now || now - member.lastSeenAt < listeningWindowMs,
		reachable: Boolean(config && config.targets.length > 0 && failures < unreachableAfterFailures),
		...(member.leftAt == null ? {} : { leftAt: iso(member.leftAt) }),
		wake: config
			? {
					mode: config.mode,
					minIntervalSeconds: config.minIntervalSeconds,
					targets: config.targets.map(describeTarget),
					lastDeliveryAt: watch?.last_delivery_at == null ? null : iso(Number(watch.last_delivery_at)),
					lastDeliveryOk: watch?.last_delivery_ok == null ? null : Number(watch.last_delivery_ok) === 1,
					consecutiveFailures: failures,
				}
			: null,
	}
}

function publicRoom(ctx: Ctx, room: Room) {
	const appUrl = ctx.deps.appUrl ?? null
	return {
		id: room.id,
		purpose: room.purpose,
		status: room.status,
		seq: room.seq,
		createdAt: iso(room.createdAt),
		closedAt: room.closedAt == null ? null : iso(room.closedAt),
		caps: room.caps,
		appUrl,
		viewUrl: appUrl ? `${appUrl}/rooms/${room.id}` : null,
	}
}

/** Room info plus every member's presence. */
export async function roomStatus(ctx: Ctx, room: Room, member: Member | null, via?: Via) {
	if (member && via) await touch(ctx, member, via)
	const db = await open(ctx)
	const members = (await db.sql('SELECT * FROM members WHERE room_id = ? ORDER BY joined_at', [room.id])).rows.map(rowToMember)
	const watches = new Map((await db.sql('SELECT * FROM watches WHERE room_id = ?', [room.id])).rows.map((row) => [String(row.member_id), row]))
	const fresh = await getRoom(ctx, room.id)
	return {
		status: 'ok' as const,
		room: publicRoom(ctx, fresh),
		you: member ? { agent_id: member.id, name: member.name, role: member.role } : null,
		members: members.map((m) => presence(ctx, m, watches.get(m.id))),
		safety: safetyLine,
	}
}

/** Leave: revoke this member's token and drop their watch. */
export async function leaveRoom(ctx: Ctx, room: Room, member: Member) {
	const now = ctx.now()
	await ctx.db.sql('UPDATE members SET left_at = ?, token_hash = NULL, listening_until = 0 WHERE id = ?', [now, member.id])
	await ctx.db.sql('DELETE FROM watches WHERE member_id = ?', [member.id])
	if (room.status === 'open') await appendSystem(ctx, room, `${member.name} left.`)
	return { status: 'ok' as const, left: true, roomId: room.id }
}

/** Close a room. Creator only. Unused invites and every wake watch (with its sealed keys) are deleted; tokens become read-only. */
export async function closeRoom(ctx: Ctx, room: Room, member: Member) {
	requireCreator(room, member)
	if (room.status === 'closed') return { status: 'ok' as const, closed: true, already: true, roomId: room.id }
	const now = ctx.now()
	await appendSystem(ctx, room, 'The room was closed.')
	await ctx.db.sql("UPDATE rooms SET status = 'closed', closed_at = ?, updated_at = ? WHERE id = ?", [now, now, room.id])
	await ctx.db.sql('DELETE FROM invites WHERE room_id = ? AND used_at IS NULL', [room.id])
	await ctx.db.sql('DELETE FROM watches WHERE room_id = ?', [room.id])
	await ctx.deps.broadcast?.(room.id, { type: 'closed', roomId: room.id }).catch(() => {})
	await emitRoomEvent(ctx, { topic: '@kody/rooms.room.closed', idempotencyKey: `rooms:closed:${room.id}`, payload: { roomId: room.id, at: iso(now) } })
	return { status: 'ok' as const, closed: true, already: false, roomId: room.id }
}

/**
 * Register (or replace) the wake watch for a member. Members set their own;
 * the creator may set one for any member (the spawner wiring a child).
 */
export async function setWatch(ctx: Ctx, room: Room, actor: Member, input: { memberId?: string | null; config: WatchConfig }) {
	requireOpen(room)
	const memberId = input.memberId ?? actor.id
	if (memberId !== actor.id) requireCreator(room, actor)
	const target = await first(ctx.db, 'SELECT id FROM members WHERE id = ? AND room_id = ? AND left_at IS NULL', [memberId, room.id])
	if (!target) throw new RoomError('not_found', 'Member not found in this room.')
	return saveWatch(ctx, room.id, memberId, input.config)
}

const sealedKeyMarker = '<sealed>'

/** Parse an optional `wake` given at create or join time; fail before any write if it cannot be sealed. */
async function parseWake(ctx: Ctx, value: unknown, ownerTargets: boolean) {
	if (value == null) return null
	if (typeof value !== 'object' || Array.isArray(value)) invalid('wake must be an object of watch options with targets.')
	const config = parseWatchConfig(value as Record<string, unknown>, { ownerTargets })
	if (config.targets.some((target) => target.type === 'webhook')) await getSealer(ctx)
	return config
}

/**
 * Store a watch. Webhook URLs and keys are sealed (encrypted, bound to the
 * member) and replaced in the stored config by the bare host, so no read path
 * can return them.
 */
async function saveWatch(ctx: Ctx, roomId: string, memberId: string, config: WatchConfig) {
	const secrets = config.targets.map((target) => (target.type === 'webhook' ? { url: target.url, key: target.key } : null))
	let sealed: string | null = null
	if (secrets.some(Boolean)) {
		const sealer = await getSealer(ctx)
		sealed = await sealer.seal(JSON.stringify(secrets), memberId)
	}
	const stored: WatchConfig = {
		...config,
		targets: config.targets.map((target) =>
			target.type === 'webhook' ? { ...target, url: `https://${/^https:\/\/([^/?#]+)/.exec(target.url)![1]}`, key: target.key ? sealedKeyMarker : null } : target,
		),
	}
	const now = ctx.now()
	await ctx.db.sql(
		`INSERT INTO watches (id, room_id, member_id, config_json, sealed, armed, fired_once, pending_count, created_at, updated_at)
		 VALUES (?, ?, ?, ?, ?, 1, 0, 0, ?, ?)
		 ON CONFLICT(member_id) DO UPDATE SET config_json = excluded.config_json, sealed = excluded.sealed, armed = 1, fired_once = 0, pending_count = 0, consecutive_failures = 0, updated_at = excluded.updated_at`,
		[newWatchId(), roomId, memberId, JSON.stringify(stored), sealed, now, now],
	)
	return { status: 'ok' as const, memberId, mode: config.mode, targets: stored.targets.map(describeTarget) }
}

async function getSealer(ctx: Ctx) {
	if (!ctx.deps.sealer) throw new RoomError('unavailable', 'Webhook wake targets are not available here: no wake key encryption is configured.')
	return ctx.deps.sealer()
}

/** Restore sealed webhook URLs and keys for delivery. */
async function unsealTargets(ctx: Ctx, watch: Record<string, unknown>, config: WatchConfig): Promise<Array<WakeTarget>> {
	if (watch.sealed == null) return config.targets
	const secrets = JSON.parse(await (await getSealer(ctx)).open(String(watch.sealed), String(watch.member_id))) as Array<{ url: string; key: string | null } | null>
	return config.targets.map((target, index) => {
		const secret = secrets[index]
		return target.type === 'webhook' && secret ? { ...target, url: secret.url, key: secret.key } : target
	})
}

export async function removeWatch(ctx: Ctx, room: Room, actor: Member, input: { memberId?: string | null }) {
	const memberId = input.memberId ?? actor.id
	if (memberId !== actor.id) requireCreator(room, actor)
	const removed = await ctx.db.sql('DELETE FROM watches WHERE member_id = ? AND room_id = ? RETURNING id', [memberId, room.id])
	return { status: 'ok' as const, memberId, removed: removed.rows.length > 0 }
}

const eventPayloadBudget = 60 * 1024

function utf8Bytes(text: string) {
	return new TextEncoder().encode(text).length
}

function clipToBytes(text: string, max: number) {
	if (max <= 0) return ''
	const bytes = new TextEncoder().encode(text)
	if (bytes.length <= max) return text
	const ellipsis = new TextEncoder().encode('…')
	let end = Math.max(0, max - ellipsis.length)
	while (end > 0 && (bytes[end] & 0b1100_0000) === 0b1000_0000) end--
	const out = new Uint8Array(end + ellipsis.length)
	out.set(bytes.subarray(0, end))
	out.set(ellipsis, end)
	return new TextDecoder().decode(out)
}

/** Build a @kody/rooms.room.message payload that stays under the 64 KiB event cap. */
function messageEventPayload(roomId: string, message: RoomMessage): Record<string, unknown> {
	const prompt = wrapUntrusted({
		text: bodyText(message.body),
		fromId: message.from.agent_id,
		fromName: message.from.name,
		messageId: message.id,
		seq: message.seq,
	})
	const payload: Record<string, unknown> = {
		roomId,
		memberId: message.from.agent_id,
		messageId: message.id,
		cursor: message.seq,
		fromId: message.from.agent_id,
		fromName: message.from.name,
		prompt,
	}
	const size = utf8Bytes(JSON.stringify(payload))
	if (size <= eventPayloadBudget) return payload
	const overhead = size - utf8Bytes(String(payload.prompt))
	payload.prompt = clipToBytes(prompt, Math.max(0, eventPayloadBudget - overhead))
	return payload
}

/** Emit a declared package event. Never throws: a failed emit must not break the room write. */
async function emitRoomEvent(ctx: Ctx, event: RoomEvent) {
	const dispatch = ctx.deps.dispatchEvent
	if (!dispatch) {
		console.warn(`rooms event emit skipped (no dispatch binding) topic=${event.topic} key=${event.idempotencyKey}`)
		return
	}
	try {
		const result = (await dispatch(event)) as { status?: unknown } | null
		const status = result && typeof result === 'object' && result.status != null ? String(result.status) : 'ok'
		console.info(`rooms event emit topic=${event.topic} key=${event.idempotencyKey} status=${status}`)
	} catch (error) {
		const detail = error instanceof Error ? error.message.replace(/\s+/g, ' ').slice(0, 200) : 'emit failed'
		console.error(`rooms event emit failed topic=${event.topic} key=${event.idempotencyKey}: ${detail}`)
	}
}

async function runAction(ctx: Ctx, action: WakeAction): Promise<{ ok: boolean; detail: string }> {
	try {
		if (action.kind === 'http') {
			const doFetch = ctx.deps.fetch ?? fetch
			// No AbortSignal: Kody's fetch gateway cannot serialize one, so race a timer instead.
			let timer: ReturnType<typeof setTimeout> | undefined
			const timeout = new Promise<never>((_, reject) => {
				timer = setTimeout(() => reject(Object.assign(new Error('timeout'), { name: 'TimeoutError' })), action.timeoutMs)
			})
			const response = await Promise.race([doFetch(action.url, { method: action.method, headers: action.headers, body: action.body, redirect: action.noRedirect ? 'manual' : 'follow' }), timeout]).finally(() => clearTimeout(timer))
			await response.body?.cancel().catch(() => {})
			// Agent keys go only to the exact registered URL: never follow a redirect.
			if (action.noRedirect && (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400))) return { ok: false, detail: 'redirect_refused' }
			const ok = response.ok || (action.busyIsOk && response.status === 409)
			return { ok, detail: `HTTP ${response.status}` }
		}
		if (action.kind === 'job') {
			if (!ctx.deps.runJob) return { ok: false, detail: 'jobs_unavailable' }
			await ctx.deps.runJob(action.jobId)
			return { ok: true, detail: 'job_started' }
		}
		return { ok: false, detail: 'unknown_action' }
	} catch (error) {
		const name = error instanceof Error ? error.name : 'Error'
		return { ok: false, detail: name === 'TimeoutError' ? 'timeout' : clip(`${name}: ${error instanceof Error ? error.message : String(error)}`.replace(/https?:\/\/\S+/g, '<url>'), 200) }
	}
}

/** Evaluate every watch in the room for one new message and deliver wakes. */
async function deliverWakes(ctx: Ctx, room: Room, message: RoomMessage) {
	const watches = (await ctx.db.sql('SELECT w.* FROM watches w JOIN members m ON m.id = w.member_id WHERE w.room_id = ? AND m.left_at IS NULL', [room.id])).rows
	const results: Array<{ memberId: string; fired: boolean; reason: string; deliveries: Array<{ target: string; ok: boolean; detail: string }> }> = []
	await Promise.all(
		watches.map(async (watch) => {
			const config = JSON.parse(String(watch.config_json)) as WatchConfig
			const memberId = String(watch.member_id)
			const state: WatchState = { armed: Number(watch.armed) === 1, firedOnce: Number(watch.fired_once) === 1, pendingCount: Number(watch.pending_count), lastFiredAt: num(watch.last_fired_at) }
			const now = ctx.now()
			const wakeMessage = { seq: message.seq, id: message.id, at: message.at, kind: message.kind, fromId: message.from.agent_id, fromName: message.from.name, text: bodyText(message.body) }
			const decision = decideWake({ config, state, watcherId: memberId, message: wakeMessage, now })
			await ctx.db.sql('UPDATE watches SET armed = ?, fired_once = ?, pending_count = ?, last_fired_at = ? WHERE id = ?', [decision.next.armed ? 1 : 0, decision.next.firedOnce ? 1 : 0, decision.next.pendingCount, decision.next.lastFiredAt, watch.id])
			if (!decision.fire) {
				results.push({ memberId, fired: false, reason: decision.reason, deliveries: [] })
				return
			}
			const appUrl = ctx.deps.appUrl ?? null
			const payload = buildWakePayload({ roomId: room.id, memberId, config, batchCount: decision.batchCount, message: wakeMessage, viewUrl: appUrl ? `${appUrl}/rooms/${room.id}` : null, appUrl })
			const targets = await unsealTargets(ctx, watch, config).catch(() => null)
			const deliveries = targets
				? await Promise.all(targets.map(async (target) => ({ target: target.type, ...(await runAction(ctx, planDelivery(target, payload, String(watch.id)))) })))
				: config.targets.map((target) => ({ target: target.type, ok: false, detail: 'sealed_unavailable' }))
			const ok = deliveries.some((delivery) => delivery.ok)
			await ctx.db.sql('UPDATE watches SET last_delivery_at = ?, last_delivery_ok = ?, consecutive_failures = CASE WHEN ? = 1 THEN 0 ELSE consecutive_failures + 1 END WHERE id = ?', [now, ok ? 1 : 0, ok ? 1 : 0, watch.id])
			for (const delivery of deliveries) {
				await ctx.db.sql('INSERT INTO deliveries (watch_id, room_id, member_id, target, seq, at, ok, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [watch.id, room.id, memberId, delivery.target, message.seq, now, delivery.ok ? 1 : 0, delivery.detail])
			}
			await ctx.db.sql('DELETE FROM deliveries WHERE member_id = ? AND id <= (SELECT MAX(id) - 50 FROM deliveries WHERE member_id = ?)', [memberId, memberId])
			results.push({ memberId, fired: true, reason: decision.reason, deliveries })
		}),
	)
	return results
}

/** Recent delivery results for a member's watch (newest first, secret-free). */
export async function listDeliveries(ctx: Ctx, memberId: string, limit = 20) {
	const rows = (await ctx.db.sql('SELECT target, seq, at, ok, detail FROM deliveries WHERE member_id = ? ORDER BY id DESC LIMIT ?', [memberId, limit])).rows
	return rows.map((row) => ({ target: String(row.target), cursor: Number(row.seq), at: iso(Number(row.at)), ok: Number(row.ok) === 1, detail: str(row.detail) }))
}

/**
 * Delete old rooms. Off by default: without `cleanup.enabled` in settings it
 * only reports what it would delete.
 */
export async function cleanupRooms(ctx: Ctx, input: { dryRun?: boolean }) {
	const { cleanup } = await readSettings(ctx)
	const now = ctx.now()
	const closedBefore = now - cleanup.closedRoomRetentionDays * 86400_000
	const idleBefore = cleanup.idleRoomRetentionDays == null ? null : now - cleanup.idleRoomRetentionDays * 86400_000
	const rows = (
		await ctx.db.sql(
			"SELECT id FROM rooms WHERE (status = 'closed' AND closed_at < ?) OR (? IS NOT NULL AND updated_at < ?) LIMIT 100",
			[closedBefore, idleBefore, idleBefore ?? 0],
		)
	).rows
	const ids = rows.map((row) => String(row.id))
	const dryRun = input.dryRun !== false || !cleanup.enabled
	if (!dryRun) {
		for (const id of ids) {
			for (const table of ['messages', 'invites', 'watches', 'deliveries', 'members']) {
				await ctx.db.sql(`DELETE FROM ${table} WHERE room_id = ?`, [id])
			}
			await ctx.db.sql('DELETE FROM rooms WHERE id = ?', [id])
		}
	}
	return { status: 'ok' as const, dryRun, enabled: cleanup.enabled, roomIds: ids, deleted: dryRun ? 0 : ids.length }
}

/**
 * Rooms a signed-in Kody visitor may view: every room for members of the
 * owning org, otherwise rooms they created or joined as that Kody user.
 */
export async function listRoomsForViewer(ctx: Ctx, viewer: { userId: string | null; orgMember: boolean }, limit = 200) {
	const db = await open(ctx)
	const where = viewer.orgMember ? '1 = 1' : 'r.creator_user_id = ? OR r.id IN (SELECT room_id FROM members WHERE kody_user_id = ?)'
	const params = viewer.orgMember ? [] : [viewer.userId, viewer.userId]
	const rows = (
		await db.sql(
			`SELECT r.id, r.purpose, r.status, r.creator_user_id, r.created_at, r.updated_at,
				(SELECT COUNT(*) FROM members m WHERE m.room_id = r.id AND m.left_at IS NULL) AS member_count
			 FROM rooms r WHERE ${where} ORDER BY r.updated_at DESC LIMIT ?`,
			[...params, limit],
		)
	).rows
	return rows.map((row) => ({
		id: String(row.id),
		purpose: str(row.purpose),
		status: row.status === 'closed' ? ('closed' as const) : ('open' as const),
		memberCount: Number(row.member_count),
		createdAt: iso(Number(row.created_at)),
		lastActivityAt: iso(Number(row.updated_at)),
		createdByYou: viewer.userId != null && String(row.creator_user_id) === viewer.userId,
	}))
}

/** Whether a signed-in visitor may view one room (same rule as the list). */
export async function canViewRoom(ctx: Ctx, room: Room, viewer: { userId: string | null; orgMember: boolean }) {
	if (viewer.orgMember) return true
	if (!viewer.userId) return false
	if (room.creatorUserId === viewer.userId) return true
	return (await first(await open(ctx), 'SELECT 1 AS ok FROM members WHERE room_id = ? AND kody_user_id = ?', [room.id, viewer.userId])) != null
}