Files
cobble/src/functions/backend/db/chatrooms/ensure-chatroom-session.ts
T
tbenandClaude Opus 5.5 7b762fd384 Let workers ask each other through the coordinator in chatrooms
A worker asks for another bot's help with ask_crew. The coordinator
reads the request, asks the right bot (in a workspace, only its
members), and sends the answer back into the asking bot's
conversation, waking it. Each exchange is kept as a read-only
chatroom: listed in the main rail after the workspaces, or in the
workspace's rail for requests made there, with live status rows for
each bot while it's open and a Stop button.

Room sessions are hidden from every conversation list, other bots'
words reach the model fenced as data, and turns, nesting and open
rooms are capped. Closed rooms are pruned after a retention period
and past a cap per place (Settings > General).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-27 18:57:34 +01:00

58 lines
2.0 KiB
TypeScript

import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_SESSIONS, BUN_SQLITE_COBBLE_CHATROOMS, BunSQLiteTables } from "@/db/types/db";
type Params = {
chatroom: Pick<BUN_SQLITE_COBBLE_CHATROOMS, "id" | "user_id" | "workspace_id" | "title">;
bot_id: number | string;
};
/**
* A bot's part of a chatroom: its session there (status `chatroom`), made
* the first time it takes part. It holds the bot's messages and jobs in
* the room and never shows in the bot's own conversation.
*/
export default async function ensureChatroomSession({
chatroom,
bot_id,
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
const found = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT * FROM bot_sessions WHERE chatroom_id = ? AND bot_id = ? LIMIT 1`,
values: [chatroom.id!, bot_id],
})
).payload?.[0];
if (found?.id) return found;
const now = Date.now();
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_SESSIONS, (typeof BunSQLiteTables)[number]>({
table: "bot_sessions",
data: [
{
user_id: chatroom.user_id,
bot_id: Number(bot_id),
workspace_id: chatroom.workspace_id || undefined,
chatroom_id: chatroom.id,
status: "chatroom",
title: chatroom.title || undefined,
last_activity_at: now,
},
],
});
const id = res.postInsertReturn?.insertId;
if (!res.success || !id) {
throw new Error(`Couldn't start the bot's part of the chatroom: ${res.msg}`);
}
return (
(
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
sql: `SELECT * FROM bot_sessions WHERE id = ? LIMIT 1`,
values: [id],
})
).payload?.[0] || { id, user_id: chatroom.user_id, bot_id: Number(bot_id), chatroom_id: chatroom.id, status: "chatroom" }
);
}