import type { BotAccount } from '../atproto/bot.ts' import { noteFollow } from '../atproto/identity.ts' import type { StreamerActions } from '../atproto/streamer.ts' import type { ChannelRow, Store } from '../db/store.ts' import { env } from '../env.ts' import { Jetstream } from '../jetstream.ts' import { ChatSocket, getLiveUsers } from '../streamplace.ts' import { publish, type Platform } from './platform.ts' import { ChannelRuntime, toIncoming } from './runtime.ts' /** The real Streamplace side effects: the bot account posts, the streamer's session moderates. */ export function makePlatform(bot: BotAccount, streamer: StreamerActions): Platform { return { botDid: () => bot.did, canSend: () => bot.ready, send: (channel, text, reply) => bot.send(channel, text, reply), hide: async (channel, uri) => { await streamer.hide(channel, uri) }, block: (channel, subject) => streamer.block(channel, subject), unblock: (channel, uri) => streamer.unblock(channel, uri), findBlocks: (channel, subject) => streamer.findBlocks(channel, subject), pin: async (channel, uri, expiresAt) => { await streamer.pin(channel, uri, expiresAt) }, updateStream: (channel, patch) => streamer.updateLivestream(channel, patch), } } interface Live { runtime: ChannelRuntime socket: ChatSocket | null } export class BotManager { private store: Store private platform: Platform private channels = new Map() private follows: Jetstream private posts: Jetstream private intervals: NodeJS.Timeout[] = [] private reloadTimers = new Map() constructor(store: Store, platform: Platform) { this.store = store this.platform = platform this.follows = new Jetstream(store, 'follows', ['app.bsky.graph.follow', 'place.stream.live.teleport']) this.posts = new Jetstream(store, 'posts', ['app.bsky.feed.post'], []) } /** The runtime for a channel the bot has joined (and is listening to). */ get(channelId: string): ChannelRuntime | undefined { const c = this.channels.get(channelId) return c?.socket ? c.runtime : undefined } /** Every runtime in memory, joined or not. */ all(): ChannelRuntime[] { return [...this.channels.values()].map((c) => c.runtime) } /** A runtime for any channel, even one the bot hasn't joined (used by the dashboard and config tester). */ runtimeFor(channelId: string): ChannelRuntime | undefined { const live = this.channels.get(channelId) if (live) return live.runtime const row = this.store.getChannel(channelId) if (!row) return undefined const rt = new ChannelRuntime(row, this.store, this.platform) this.channels.set(channelId, { runtime: rt, socket: null }) return rt } status(channelId: string) { const live = this.channels.get(channelId) return { joined: !!live?.socket, connected: live?.runtime.socketConnected ?? false } } async start() { for (const row of this.store.listJoinedChannels()) this.join(row) this.store.on('change', ({ channelId, what }) => { if (what === 'channel') return this.syncChannel(channelId) // A user lookalike set changed: rebuild every channel using one. if (channelId === '*') { if (what === 'lookalikes') for (const { runtime } of this.channels.values()) if (runtime.cfg.get('lookalikes').some((id) => id.startsWith('user:'))) runtime.reload() return } // Coalesce bursts of edits into one rebuild. clearTimeout(this.reloadTimers.get(channelId)) this.reloadTimers.set( channelId, setTimeout(() => { this.reloadTimers.delete(channelId) this.channels.get(channelId)?.runtime.reload() // A preset changed: rebuild every channel that installed it. if (channelId.startsWith('preset:')) { const slug = channelId.slice('preset:'.length) for (const { runtime } of this.channels.values()) if (runtime.cfg.get('presets').includes(slug)) runtime.reload() } if (what === 'modules.bskyposts') this.refreshPostWatch() }, 150), ) }) this.store.on('audit', (row) => publish(row.channel_id, { type: 'audit', entry: row })) if (!env.botEnabled) { console.log('[bot] BOT_ENABLED=0: not connecting to chats.') return } this.follows.on('commit', (evt) => { const c = evt.commit if (c.operation !== 'create' || !c.record) return if (c.collection === 'app.bsky.graph.follow') { const subject = c.record.subject as string const rt = this.get(subject) if (!rt) return noteFollow(evt.did, subject, `at://${evt.did}/${c.collection}/${c.rkey}`, String(c.record.createdAt ?? new Date().toISOString())) void rt.onFollow(evt.did) } else if (c.collection === 'place.stream.live.teleport') { const rt = this.get(evt.did) const target = c.record.streamer as string | undefined if (rt && target) void rt.onTeleportOut(target) } }) this.follows.start() this.posts.on('commit', (evt) => { const c = evt.commit if (c.operation !== 'create' || !c.record) return const uri = `at://${evt.did}/${c.collection}/${c.rkey}` for (const { runtime, socket } of this.channels.values()) if (socket) void runtime.modules.onBskyPost(evt.did, uri, c.record as { text?: string; reply?: unknown }) }) this.refreshPostWatch() this.posts.start() const every = (ms: number, fn: () => unknown) => { const run = () => Promise.resolve(fn()).catch((err) => console.warn('[bot] background task failed:', err)) void run() this.intervals.push(setInterval(run, ms)) } every(30_000, () => this.pollLive()) every(15_000, () => this.liftExpiredPunishments()) every(15_000, () => Promise.all([...this.channels.values()].filter((c) => c.socket).map((c) => c.runtime.tickTimers()))) every(30_000, () => this.expireDocs()) every(10 * 60_000, () => { for (const c of this.channels.values()) if (c.socket) c.runtime.loyaltyTick() }) every(6 * 3600_000, () => this.trimHistory()) } private syncChannel(channelId: string) { const row = this.store.getChannel(channelId) const live = this.channels.get(channelId) if (!row) { if (live) this.part(channelId) return } if (row.kind !== 'channel') return if (row.bot_joined && !live?.socket) this.join(row) else if (!row.bot_joined && live?.socket) this.part(channelId) else live?.runtime.reload() } join(row: ChannelRow) { let entry = this.channels.get(row.id) if (!entry) { entry = { runtime: new ChannelRuntime(row, this.store, this.platform), socket: null } this.channels.set(row.id, entry) } if (!env.botEnabled || entry.socket) return const rt = entry.runtime const socket = new ChatSocket(row.id) socket.on('message', (view) => { rt.onMessage(toIncoming(view)).catch((err) => console.warn(`[${row.handle}] message failed:`, err)) }) socket.on('history', (view) => rt.rememberHistory(toIncoming(view))) socket.on('livestream', (view) => void rt.onLivestreamFrame(view)) socket.on('viewers', (n) => rt.setViewers(n)) socket.on('teleport', (t) => void rt.onTeleport(t.source, t.viewers)) socket.on('status', (s) => { rt.socketConnected = s === 'connected' publish(row.id, { type: 'status', status: { connected: rt.socketConnected } }) }) socket.start() entry.socket = socket console.log(`[bot] joined @${row.handle}`) } part(channelId: string) { const entry = this.channels.get(channelId) if (!entry) return entry.socket?.stop() this.channels.delete(channelId) console.log(`[bot] left ${channelId}`) } private async pollLive() { const joined = [...this.channels.values()].filter((c) => c.socket) if (!joined.length) return const live = await getLiveUsers() const byDid = new Map(live.map((v) => [v.author.did, v])) await Promise.all(joined.map((c) => c.runtime.updateLive(byDid.get(c.runtime.channelId) ?? null))) } private refreshPostWatch() { const dids = new Set() for (const row of this.store.listJoinedChannels()) { const s = this.store.getSingleton(row.id, 'modules.bskyposts') if (s.enabled) for (const a of s.accounts) dids.add(a.did) } this.posts.setDids([...dids]) } private async liftExpiredPunishments() { const due = this.store.db.all<{ id: number; channel_id: string; did: string; handle: string; block_uri: string | null }>( 'SELECT id, channel_id, did, handle, block_uri FROM punishments WHERE lifted_at IS NULL AND expires_at IS NOT NULL AND expires_at <= ? LIMIT 50', Date.now(), ) for (const p of due) { try { if (p.block_uri) await this.platform.unblock(p.channel_id, p.block_uri) this.store.db.run('UPDATE punishments SET lifted_at = ? WHERE id = ?', Date.now(), p.id) } catch (err) { // Keep retrying, but give up after a day so a revoked session can't wedge the queue. const row = this.store.db.get<{ expires_at: number }>('SELECT expires_at FROM punishments WHERE id = ?', p.id) if (row && Date.now() - row.expires_at > 86400_000) { this.store.db.run('UPDATE punishments SET lifted_at = ? WHERE id = ?', Date.now(), p.id) this.store.audit(p.channel_id, { did: null, handle: 'superbot' }, 'error', `Couldn’t lift the timeout on @${p.handle}: ${err instanceof Error ? err.message : err}`) } } } } /** Disable or delete commands, keywords and blocked terms whose expiry time has passed. */ private expireDocs() { const rows = this.store.db.all<{ id: string; channel_id: string; kind: string; data: string }>( "SELECT id, channel_id, kind, data FROM docs WHERE kind IN ('command', 'keyword', 'blocked_term') AND json_extract(data, '$.expiry.mode') != 'none' AND json_extract(data, '$.expiry.at') <= ?", new Date().toISOString(), ) for (const row of rows) { const data = JSON.parse(row.data) const label = row.kind === 'command' ? `!${data.name}` : row.kind === 'keyword' ? data.name : data.phrase?.text const kind = row.kind as 'command' | 'keyword' | 'blocked_term' if (data.expiry.mode === 'delete') { this.store.deleteDoc(row.channel_id, kind, row.id) this.store.audit(row.channel_id, { did: null, handle: 'superbot' }, 'expiry', `Deleted ${row.kind.replace('_', ' ')} ${label} (expired)`) } else { this.store.updateDoc(row.channel_id, kind, row.id, { ...data, enabled: false, expiry: { mode: 'none', at: null } }) this.store.audit(row.channel_id, { did: null, handle: 'superbot' }, 'expiry', `Disabled ${row.kind.replace('_', ' ')} ${label} (expired)`) } } } private trimHistory() { const cutoff = new Date(Date.now() - 14 * 86400_000).toISOString() this.store.db.run('DELETE FROM chat_messages WHERE created_at < ?', cutoff) this.store.db.run('DELETE FROM strikes WHERE at < ?', Date.now() - 7 * 86400_000) this.store.db.run("DELETE FROM media_queue WHERE status IN ('played', 'skipped', 'removed') AND created_at < ?", cutoff) } stop() { for (const i of this.intervals) clearInterval(i) for (const c of this.channels.values()) c.socket?.stop() this.follows.stop() this.posts.stop() } }