diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ca09305..65b3bc39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Breaking: remove group chats from the server, web client, and API. Upgrading permanently deletes group histories, group pins, queued group notifications, and files used only by groups. Member bots, direct chats, memories, skills, and bot-library files remain. Back up the complete data directory before upgrading; recovering removed groups requires restoring that backup with the previous server version. + - Remove Fallow from development dependencies, Git hooks, and CI. Lint, formatting, type checks, tests, and documentation checks remain in place. - Add `bun run dev:emulate` for credential-free local bot chat with scripted replies, streaming, tool calls, errors, and cancellation. Run emulator-backed verification separately with the local-only `bun run check:emulate` command. - Bot avatars show what their bot is doing, using `open-bot-avatar` 0.3.0: three hopping dots while it thinks, bent over the work while it writes, searches, remembers, or uses tools, an exclamation mark while it retries, a short celebration when a reply finishes, and waiting in a group chat while it answers next. Live avatars ease from one state to the next instead of restarting. The `/avatars` page previews every state. Paused bots and disabled automations no longer show a dimmed, still avatar. diff --git a/GLOSSARY.md b/GLOSSARY.md index 0f099cb5..58105f94 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -54,16 +54,12 @@ _Avoid_: Contact, recipient The credential a voice gateway connects with. It reaches only the account's lines, their bots' chats, and call requests; the owner issues and revokes it in settings. _Avoid_: API key, password, session -**Group chat**: -A conversation between the owner and several bots, with one shared transcript in which every message shows its sender. It is separate from each member's bot chat. -_Avoid_: Room, channel, group session - **Transcript**: -The complete visible history of a bot chat or group chat, including messages, replies, tool activity, and compaction events. +The complete visible history of a bot chat, including messages, replies, tool activity, and compaction events. _Avoid_: Model context **Library**: -The files the owner sent in a bot chat or group chat, kept for the owner to browse and for the bot to read. Each bot and each group chat has its own. +The files the owner sent in a bot chat, kept for the owner to browse and for the bot to read. Each bot has its own. _Avoid_: Drive, storage, attachments folder **File description**: @@ -131,7 +127,7 @@ One webhook address on the event relay, named by the owner and usable by every b _Avoid_: Webhook, hook, trigger **Workspace**: -A bot's persistent files, on a disk only that bot and its jobs can reach. A bot with coding reads, edits, and runs commands there itself, in its chat and group chats, and its jobs work there too. The machine running them starts and stops as needed. +A bot's persistent files, on a disk only that bot and its jobs can reach. A bot with coding reads, edits, and runs commands there itself, in its bot chat, and its jobs work there too. The machine running them starts and stops as needed. _Avoid_: Sandbox, container, VM (in product language) **Workspace notes**: diff --git a/apps/docs/content/clients/web.md b/apps/docs/content/clients/web.md index 4b326bb1..7818edc5 100644 --- a/apps/docs/content/clients/web.md +++ b/apps/docs/content/clients/web.md @@ -12,20 +12,19 @@ Sign in with the account you created when you ## Sidebar -| Section | What's there | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Pinned** | Up to nine bot chats and group chats. Pin or unpin one from its **More** menu, and drag pins to reorder them. Your other apps show the same pins. | -| **Bots** | Each bot's chat, with its jobs and desktop. | -| **Group chats** | Chats with several bots. | -| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. | -| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | -| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. | -| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. | -| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. | +| Section | What's there | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | +| **Pinned** | Up to nine bot chats. Pin or unpin one from its **More** menu, and drag pins to reorder them. Your other apps show the same pins. | +| **Bots** | Each bot's chat, with its jobs and desktop. | +| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. | +| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. | +| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. | +| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. | +| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. | Press `⌘K`, or `Ctrl+K`, or select **Search** in the sidebar to open the -command palette. It jumps to a bot, group chat, workspace page, or settings -section, creates a bot or group chat, and switches the theme. To search inside +command palette. It jumps to a bot, workspace page, or settings +section, creates a bot, and switches the theme. To search inside conversations, ask a bot. It [searches its transcripts](/concepts/chats#searching-the-transcript) for you. @@ -84,12 +83,12 @@ job actions waiting for your approval. Each kind has its own sound: Turn the sounds off with **Sound** in the same section. The tab title counts replies you haven't seen yet, such as `(3) Atlas | Crumble`, -until you open their chats. It also names the bot or group chat you have open. +until you open their chats. It also names the bot chat you have open. ### Push notifications on other devices Server push notifications are separate from browser notifications and the tab -counter. A visible, focused web tab displaying a bot or group chat suppresses +counter. A visible, focused web tab displaying a bot chat suppresses pushes for that chat on every device of your account. The web app also acknowledges each reply after its text or matching request diff --git a/apps/docs/content/concepts/chats.mdx b/apps/docs/content/concepts/chats.mdx index 797dd6e4..93c293e4 100644 --- a/apps/docs/content/concepts/chats.mdx +++ b/apps/docs/content/concepts/chats.mdx @@ -54,11 +54,10 @@ Removing it from the composer removes it from the draft, not the library. Uploading the same content again reuses the entry in that library. A bot's details list its five newest files; select one to download it. Select -**See all** there, or **Library** in a group chat, to open the full library. +**See all** there to open the full library. It lists files newest first as a list or a grid. Select a file to download it, or use its menu to delete it. Select **Upload**, or drop files onto the page, -to add files to the library without sending a message. Each bot and each -group chat has its own library. Files sent on Discord don't reach the bot or +to add files to the library without sending a message. Each bot has its own library. Files sent on Discord don't reach the bot or its library. The bot receives small UTF-8 text files inline, up to 32 KB of text. Crumble @@ -71,8 +70,7 @@ The bot's library tool can list files, search the whole library by name, description, and text, read a file's text in parts, and search within a file. Bots keep a short description of what each file is, such as "birth certificate", so they can find a scan or photo later from how you refer to it. -The library page doesn't show these descriptions. In a group chat it reaches the group library and its own library, not -another member's. Coding and desktop jobs reach their bot's library. A bot +The library page doesn't show these descriptions. Coding and desktop jobs reach their bot's library. A bot with a workspace can copy a file there to inspect other formats. PNG, JPEG, GIF, and WebP images up to 5 MB reach the model as images; larger @@ -95,7 +93,7 @@ place and answers anyway. The next turn tries the image again. Deleting a library file stops future downloads and changes its transcript entry to **File deleted**. A queued message still arrives, with a deleted-file note. What the bot already read stays in its working context until compaction. -Deleting the bot or group chat also removes its library. +Deleting the bot also removes its library. Files attached before the library update aren't migrated: their transcript entries show **File deleted**. Older native clients need an update before they @@ -114,11 +112,4 @@ the domain renewal in March?" A bot searches only what it's allowed to see: -| Where you ask | What the bot searches | -| ------------- | -------------------------------------------------- | -| Its bot chat | That chat, and the group chats the bot belongs to. | -| A group chat | Only that group chat. | - -In a group chat, a bot can't search its bot chat with you, even if you ask it -to. For how group chats work, see -[Group Chats](/concepts/group-chats). +A bot searches only its own bot chat. diff --git a/apps/docs/content/concepts/group-chats.md b/apps/docs/content/concepts/group-chats.md deleted file mode 100644 index c23b6e33..00000000 --- a/apps/docs/content/concepts/group-chats.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Group Chats -description: Talk to two to six bots at once in a shared transcript. -sidebar: - order: 3 ---- - -A group chat is one conversation between you and two to six of your bots. -Everyone sees the same transcript, and every message shows who sent it. Group -chats are separate from each bot's own bot chat. - -## Who Answers - -Mentions decide which bots wake up for a message: - -- A message from you without mentions wakes every bot in the group. -- Mention bots with `@`, or reply to one of their messages, to wake only those - bots. -- A bot's message wakes only the bots it mentions. - -A bot that wakes up with nothing to add can stay -silent, or react with an emoji. - -## Limits - -Group chats are for talking. Some things a bot can do in its own chat are off -here: - -| Limit | What happens | -| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| **Turn limit** | After 8 bot turns in a row without a message from you, the group pauses until you write again. | -| **Late joiners** | A bot added after the first message gets a summary of the conversation so far. | -| **No background work** | Bots can't start coding jobs or desktop jobs, and can't hand work to other bots. A bot with **Coding** still works in its workspace itself. | -| **Private memory only** | Bots can save to their own memory, not to shared memory. | - -The turn limit is what stops two polite bots from thanking each other forever. - -## Files - -Attach any file up to 100 MB in the web client. It goes into the group's own -library, separate from each member's bot library. Bots receive small text and -extracted PDF text inline, and references for other files, as in a -[bot chat](/concepts/chats#files). - -Images up to 5 MB reach models that can read them. A text-only model gets -only the image's name unless the account has a -[vision model](/getting-started/providers#vision-model), which describes it. -Larger images arrive as references. - -Each member's library tool can read this group's library and its own bot -library, not another member's. Anything a bot quotes from its own files in a -group answer becomes visible to you and every member of the group. diff --git a/apps/docs/content/concepts/memory-and-skills.md b/apps/docs/content/concepts/memory-and-skills.md index b03d0793..08bbf01a 100644 --- a/apps/docs/content/concepts/memory-and-skills.md +++ b/apps/docs/content/concepts/memory-and-skills.md @@ -15,7 +15,7 @@ a project's details. A bot needs the **Memory** capability to save them. A memory is either the bot's own, or **shared** with every one of your bots that has memory turned on. Every memory records where it came from: a bot -chat, you, a scheduled task, another bot, or a group chat. +chat, you, a scheduled task, or another bot. Review and edit memories on the **Memory** page. @@ -110,10 +110,7 @@ revert it. After a turn with a lot of tool use, a background review looks at what the bot did and may update its skills or memories. These are learned changes. -Every turn counts: chat turns, scheduled runs, event automations, and group chat -turns, plus each coding job's work once the job reports back. A review of a -group chat turn, like the turn itself, changes only the bot's own memory, never -shared memory. The review never saves instructions it finds in outside data, +Every turn counts: chat turns, scheduled runs, event automations, and each coding job's work once the job reports back. The review never saves instructions it finds in outside data, such as an event's payload or a web page. **Every change to a skill or memory is recorded with its before and after diff --git a/apps/docs/content/concepts/web-search.md b/apps/docs/content/concepts/web-search.md index 99bd9dc4..990c5e2c 100644 --- a/apps/docs/content/concepts/web-search.md +++ b/apps/docs/content/concepts/web-search.md @@ -6,7 +6,7 @@ sidebar: --- A bot with the **Web search** capability can search the web and read pages, in -bot chats and in group chats. New bots created in the web app have it on by +bot chats. New bots created in the web app have it on by default. Existing bots keep their current settings. ## Providers diff --git a/apps/docs/content/concepts/workspaces.mdx b/apps/docs/content/concepts/workspaces.mdx index 9f47d079..adb47866 100644 --- a/apps/docs/content/concepts/workspaces.mdx +++ b/apps/docs/content/concepts/workspaces.mdx @@ -19,8 +19,7 @@ The server has to support workspaces before bots can use them. See ## Working in the Workspace A bot with **Coding** works in its workspace itself, the way a coding agent -does: it reads and edits files and runs shell commands right in the chat, and -in group chats too. You see each step as tool activity in the transcript. +does: it reads and edits files and runs shell commands right in the bot chat. You see each step as tool activity in the transcript. Chatting alone never starts the machine; the first command does. ## Jobs diff --git a/apps/docs/content/contributing/architecture.mdx b/apps/docs/content/contributing/architecture.mdx index 60ce9cca..044de92f 100644 --- a/apps/docs/content/contributing/architecture.mdx +++ b/apps/docs/content/contributing/architecture.mdx @@ -15,9 +15,9 @@ flowchart TD Browser["Web app (/ui) and API clients"] --> Auth["Better Auth session
auth.sqlite"] Auth --> Tenant["Private user runtime
app/tenant.ts"] Tenant --> API["Hono HTTP and SSE API
/v1"] - API --> Services["Effect services
Bots, BotRuntime, GroupChats, BotSkills, Scheduler"] - Services --> Product["Product SQLite
store.sqlite via Drizzle
agents, groups, skills, memories,
schedules, credentials, changes"] - Services --> Pi["Pi Durable SQLite stores
per-bot and per-group transcripts,
coding and desktop jobs, reviews"] + API --> Services["Effect services
Bots, BotRuntime, BotSkills, Scheduler"] + Services --> Product["Product SQLite
store.sqlite via Drizzle
agents, skills, memories,
schedules, credentials, changes"] + Services --> Pi["Pi Durable SQLite stores
per-bot transcripts,
coding and desktop jobs, reviews"] Pi --> Workspaces["MachineWorkspaces
Microsandbox microVM or Railway sandbox,
credential proxy and Xvnc"] ``` @@ -36,15 +36,13 @@ CRUMBLE_DATA_DIR/ ├── push.sqlite push store ├── agents/ │ └── BOT_ID.sqlite one Pi Durable store per bot - ├── groups/ - │ └── GROUP_ID.sqlite one per group chat └── claude/ Claude Code config for this account ``` ## Boundaries Server code lives in feature folders under `apps/server/src/`, such as -`bots/`, `group-chats/`, `jobs/`, `workspaces/`, and `credentials/`. +`bots/`, `jobs/`, `workspaces/`, and `credentials/`. ### Accounts @@ -59,7 +57,7 @@ anyone signed in. `app/tenant.ts`. Each account is one Effect `Layer` graph: Drizzle repositories over `ProductDatabase`, then feature services (`Bots`, `BotRuntime`, -`GroupChats`, `BotSkills`, `Scheduler`, `BotWorkspaces`, `Plugins`). Features +`BotSkills`, `Scheduler`, `BotWorkspaces`, `Plugins`). Features register their bot tools in `BotExtensions`. Tagged errors (`shared/errors.ts`) map to HTTP status codes at the Hono boundary. @@ -68,11 +66,10 @@ map to HTTP status codes at the Hono boundary. The two stores split along one line: the product store holds what you configure, and Pi Durable holds what happens. -| Store | File | Holds | -| --------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | -| Product SQLite | `store.sqlite` | Agent profiles, group definitions, memories, skill packages, `learned_changes`, schedules, MCP servers, and encrypted credentials. | -| Pi Durable, per bot | `agents/.sqlite` | Conversation entries, working context, tool calls, compaction, coding and desktop job conversations, and post-turn reviews. | -| Pi Durable, per group | `groups/.sqlite` | The group chat's shared transcript. | +| Store | File | Holds | +| ------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | +| Product SQLite | `store.sqlite` | Agent profiles, memories, skill packages, `learned_changes`, schedules, MCP servers, and encrypted credentials. | +| Pi Durable, per bot | `agents/.sqlite` | Conversation entries, working context, tool calls, compaction, coding and desktop job conversations, and post-turn reviews. | ### Plugins and Claude Code diff --git a/apps/docs/content/contributing/index.md b/apps/docs/content/contributing/index.md index ef9d3abd..8fa56a1e 100644 --- a/apps/docs/content/contributing/index.md +++ b/apps/docs/content/contributing/index.md @@ -129,8 +129,7 @@ bun run openapi:generate Chat attention belongs to the authenticated account, independently of push registration or notification permission. A chat reference has a `kind` of -`bot` or `group` and an `id`, such as `{ "kind": "bot", "id": "CHAT_ID" }`. -Bot chats and group chats are separate namespaces. +`bot` and an `id`, such as `{ "kind": "bot", "id": "CHAT_ID" }`. - Send `PUT /v1/chat-attention/views/{viewId}` with `{ "chat": CHAT }` when a view becomes active. Send `{ "chat": null }` when it loses attention. @@ -143,7 +142,7 @@ Bot chats and group chats are separate namespaces. only after displaying the referenced content. Batch 1-100 distinct event IDs; retry failed batches only while the same account remains signed in. -Replace `CHAT_ID` with the bot or group chat ID and `CHAT` with that chat +Replace `CHAT_ID` with the bot ID and `CHAT` with that chat reference. Replace `EVENT_ID` with the reply event ID. Both routes return `204` on success. Unknown or inaccessible chats and mismatched events return `404`. Seen batches are atomic and idempotent. @@ -181,7 +180,7 @@ Native clients must implement: and serialized presence reports that cannot follow a clear with stale state. On macOS, a window losing activity must clear its own view. Verify web-to-native -and native-to-native suppression locally after adoption, including group chats. +and native-to-native suppression locally after adoption. No simulator, emulator, or native UI checks run in CI. ## Releasing diff --git a/apps/docs/content/getting-started/first-bot.md b/apps/docs/content/getting-started/first-bot.md index 9e72536d..3acbd9fe 100644 --- a/apps/docs/content/getting-started/first-bot.md +++ b/apps/docs/content/getting-started/first-bot.md @@ -38,8 +38,7 @@ choice. Live avatars respect your system's reduced-motion setting. An avatar shows what its bot is doing. While the bot thinks, its body turns into three hopping dots. While it writes, searches, remembers, or uses tools, it bends over the work. When it retries, it shows an exclamation mark. When a reply -finishes, it celebrates for a few seconds. In a group chat, a bot that answers -next waits its turn. +finishes, it celebrates for a few seconds. Bots without a saved definition get a fresh gallery avatar with default colors. The bot ID selects the shape; previous avatar shapes and colors don't affect it. @@ -60,4 +59,4 @@ Tell it something about yourself and ask it to remember. This one needs the **Memory** capability. Without it, the fact stays in the [transcript](/concepts/chats), but the bot can't save it to memory. -Add a second bot and start a [group chat](/concepts/group-chats) with both. +Add more bots for different responsibilities, each with its own bot chat. diff --git a/apps/docs/content/getting-started/providers.md b/apps/docs/content/getting-started/providers.md index cc7733fa..576bb0c2 100644 --- a/apps/docs/content/getting-started/providers.md +++ b/apps/docs/content/getting-started/providers.md @@ -100,7 +100,7 @@ that read images. | Vision model | A bot whose model can't read images | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Off** | Refuses images in its bot chat, and gets only each image's name in group chats. | +| **Off** | Refuses images in its bot chat. | | **Set** | Gets the vision model's description of each image, including any visible text, and can ask it follow-up questions about an image. The transcript keeps the image. | The vision model describes each image once per conversation, and its tokens and diff --git a/apps/docs/content/reference/api.md b/apps/docs/content/reference/api.md index 30476aa0..077250ca 100644 --- a/apps/docs/content/reference/api.md +++ b/apps/docs/content/reference/api.md @@ -51,7 +51,6 @@ The token reaches no other route. | **Message gateways** | `GET /v1/message-gateways`, `PUT /v1/message-gateways/{id}` | | **Bots** | `/v1/agents`, `/v1/agents/{id}`, `POST /v1/agents/{id}/duplicate` | | **Bot chat** | `/v1/agents/{id}/chat`, `/v1/agents/{id}/chat/history`, `POST /v1/agents/{id}/messages`, `POST /v1/agents/{id}/abort`, `POST /v1/agents/{id}/compact`, `/v1/agents/{id}/attachments/{entryId}/{index}` | -| **Group chats** | `/v1/group-chats`, `/v1/group-chats/{id}`, `/v1/group-chats/{id}/chat`, `/v1/group-chats/{id}/history`, `POST /v1/group-chats/{id}/messages`, `POST /v1/group-chats/{id}/stop` | | **Jobs** | `/v1/agents/{id}/coding-jobs`, `/v1/agents/{id}/coding-jobs/{name}/history`, `/v1/agents/{id}/desktop-jobs`, `/v1/agents/{id}/desktop-jobs/{name}/history` | | **Bot desktop** | `POST /v1/agents/{id}/desktop/viewer`, `/v1/agents/{id}/desktop/control`, `GET /v1/agents/{id}/desktop/status` | | **Credentials** | `/v1/agents/{id}/credentials`, `/v1/agents/{id}/credentials/{name}`, `/v1/agents/{id}/credentials/{name}/uses` | @@ -71,15 +70,15 @@ The token reaches no other route. ## Library files -Each bot and each group chat has its own library. Use the same account session +Each bot has its own library. Use the same account session as for messages. File IDs belong to one library and can't be sent in another. -| Operation | Bot library | Group library | -| --------- | --------------------------------------- | -------------------------------------------- | -| Upload | `POST /v1/agents/{id}/files` | `POST /v1/group-chats/{id}/files` | -| List | `GET /v1/agents/{id}/files` | `GET /v1/group-chats/{id}/files` | -| Download | `GET /v1/agents/{id}/files/{fileId}` | `GET /v1/group-chats/{id}/files/{fileId}` | -| Delete | `DELETE /v1/agents/{id}/files/{fileId}` | `DELETE /v1/group-chats/{id}/files/{fileId}` | +| Operation | Bot library | +| --------- | --------------------------------------- | +| Upload | `POST /v1/agents/{id}/files` | +| List | `GET /v1/agents/{id}/files` | +| Download | `GET /v1/agents/{id}/files/{fileId}` | +| Delete | `DELETE /v1/agents/{id}/files/{fileId}` | Upload raw bytes, not JSON or multipart data. Set `Content-Type` to the file's MIME type and `X-File-Name` to its percent-encoded UTF-8 name. Any file type is @@ -118,7 +117,7 @@ type; other downloads use `application/octet-stream`. A deleted file returns Transcript messages expose `files` with each file's ID, name, MIME type, and size, or `{ "id": "...", "deleted": true }`. Legacy attachments appear as deleted files. The bot attachment endpoint remains only for desktop screenshots; -the group attachment endpoint is removed. +Other file downloads use the bot library endpoints. ## Transcript and display fields @@ -168,7 +167,6 @@ Streams use Server-Sent Events: | Stream | Event | JSON Schema | | ----------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `/v1/agents/{id}/events` | `snapshot` | `openapi/chat-snapshot.schema.json` | -| `/v1/group-chats/{id}/events` | `snapshot` | `openapi/group-chat-snapshot.schema.json` | | `/v1/agents/{id}/desktop/events` | `control` | `openapi/desktop-control.schema.json` | | `/v1/events` | `activity`, `learned` | `openapi/activity-event.schema.json`, `openapi/learned-event.schema.json` | | `/v1/voice/events` | `config`, `call`, `cancel`, `replaced` | `openapi/voice-gateway-config.schema.json`, `openapi/voice-call.schema.json`, `openapi/voice-call-cancel.schema.json`, `openapi/voice-gateway-replaced.schema.json` | diff --git a/apps/docs/content/reference/glossary.md b/apps/docs/content/reference/glossary.md index d4709ad9..a9d43c73 100644 --- a/apps/docs/content/reference/glossary.md +++ b/apps/docs/content/reference/glossary.md @@ -79,15 +79,9 @@ The credential a voice gateway connects with. It reaches only the account's line Avoid: API key, password, session. -### Group chat - -A conversation between the owner and several bots, with one shared transcript in which every message shows its sender. It is separate from each member's bot chat. - -Avoid: Room, channel, group session. - ### Transcript -The complete visible history of a bot chat or group chat, including messages, replies, tool activity, and compaction events. +The complete visible history of a bot chat, including messages, replies, tool activity, and compaction events. Avoid: Model context. @@ -177,7 +171,7 @@ Avoid: Webhook, hook, trigger. ### Workspace -A bot's persistent files, on a disk only that bot and its jobs can reach. A bot with coding reads, edits, and runs commands there itself, in its chat and group chats, and its jobs work there too. The machine running them starts and stops as needed. +A bot's persistent files, on a disk only that bot and its jobs can reach. A bot with coding reads, edits, and runs commands there itself, in its bot chat, and its jobs work there too. The machine running them starts and stops as needed. Avoid: Sandbox, container, VM (in product language). diff --git a/apps/docs/content/self-hosting/configuration.md b/apps/docs/content/self-hosting/configuration.md index 584854d4..3269c2d5 100644 --- a/apps/docs/content/self-hosting/configuration.md +++ b/apps/docs/content/self-hosting/configuration.md @@ -135,7 +135,7 @@ configuration stops accounts from starting, with an error that begins New pushes become eligible at least three seconds after entering the server's queue. This delay is fixed, not configurable. Before each delivery or retry, the server suppresses pushes to every device when the reply was acknowledged -as displayed or its bot or group chat is active in any reporting client. +as displayed or its bot chat is active in any reporting client. Suppressed pushes do not return when you leave the chat. The web app reports attention only while the chat is displayed in a visible, @@ -165,3 +165,11 @@ and unread counters are unchanged. | `CRUMBLE_CLAUDE_COMMAND` | `claude` | Path to the Claude Code executable, if it isn't on `PATH`. | | `CRUMBLE_CLAUDE_TELEMETRY` | Enabled | Set to `0`, `false`, `no`, or `off` to turn off Claude Code telemetry. | | `NODE_ENV` | Unset | Set to `production` to minify the web app. | + +## Upgrade from group chats + +Back up the complete data directory before upgrading. Group chats are removed permanently during startup, including their histories, pins, queued notifications, and group-only uploads. This includes private group histories inside member bots' stores. + +Member bots, direct bot chats, memories, skills, and bot libraries remain. Files still referenced by a bot library are preserved. The upgrade removes group provenance from retained memories and learned changes, but keeps their content and revert history. + +Group APIs and older clients' group features no longer work. There is no export or conversion into bot chats. Cleanup finishes before bots or notification workers start and retries after interruption. A cleanup failure prevents startup. Restore the backup with the previous server version to recover removed data. diff --git a/apps/server/drizzle/store/20261122205418_remove_group_chats/migration.sql b/apps/server/drizzle/store/20261122205418_remove_group_chats/migration.sql new file mode 100644 index 00000000..d96461bd --- /dev/null +++ b/apps/server/drizzle/store/20261122205418_remove_group_chats/migration.sql @@ -0,0 +1,35 @@ +PRAGMA foreign_keys=OFF;--> statement-breakpoint +CREATE TABLE `__new_deleted_library_files` ( + `id` text PRIMARY KEY, + `agent_id` text NOT NULL, + `name` text NOT NULL, + CONSTRAINT `fk_deleted_library_files_agent_id_agents_id_fk` FOREIGN KEY (`agent_id`) REFERENCES `agents`(`id`) ON DELETE CASCADE +); +--> statement-breakpoint +INSERT INTO `__new_deleted_library_files`(`id`, `agent_id`, `name`) SELECT `id`, `agent_id`, `name` FROM `deleted_library_files`;--> statement-breakpoint +DROP TABLE `deleted_library_files`;--> statement-breakpoint +ALTER TABLE `__new_deleted_library_files` RENAME TO `deleted_library_files`;--> statement-breakpoint +PRAGMA foreign_keys=ON;--> statement-breakpoint +PRAGMA foreign_keys=OFF;--> statement-breakpoint +CREATE TABLE `__new_library_files` ( + `id` text PRIMARY KEY, + `agent_id` text NOT NULL, + `name` text NOT NULL, + `mime_type` text NOT NULL, + `size` integer NOT NULL, + `hash` text NOT NULL, + `text` text NOT NULL, + `description` text, + `created_at` text NOT NULL, + CONSTRAINT `fk_library_files_agent_id_agents_id_fk` FOREIGN KEY (`agent_id`) REFERENCES `agents`(`id`) ON DELETE CASCADE +); +--> statement-breakpoint +INSERT INTO `__new_library_files`(`id`, `agent_id`, `name`, `mime_type`, `size`, `hash`, `text`, `description`, `created_at`) SELECT `id`, `agent_id`, `name`, `mime_type`, `size`, `hash`, `text`, `description`, `created_at` FROM `library_files`;--> statement-breakpoint +DROP TABLE `library_files`;--> statement-breakpoint +ALTER TABLE `__new_library_files` RENAME TO `library_files`;--> statement-breakpoint +PRAGMA foreign_keys=ON;--> statement-breakpoint +DROP INDEX IF EXISTS `library_files_group_hash`;--> statement-breakpoint +CREATE UNIQUE INDEX `library_files_bot_hash` ON `library_files` (`agent_id`,`hash`);--> statement-breakpoint +DROP TABLE IF EXISTS `group_turns`;--> statement-breakpoint +DROP TABLE IF EXISTS `group_members`;--> statement-breakpoint +DROP TABLE IF EXISTS `group_chats`; \ No newline at end of file diff --git a/apps/server/drizzle/store/20261122205418_remove_group_chats/snapshot.json b/apps/server/drizzle/store/20261122205418_remove_group_chats/snapshot.json new file mode 100644 index 00000000..195afc9f --- /dev/null +++ b/apps/server/drizzle/store/20261122205418_remove_group_chats/snapshot.json @@ -0,0 +1,4393 @@ +{ + "version": "7", + "dialect": "sqlite", + "id": "7993b593-9620-4407-92e1-ad645bad22ee", + "prevIds": ["754af695-7011-48e8-a06b-745a5cadabeb"], + "ddl": [ + { + "name": "event_runs", + "entityType": "tables" + }, + { + "name": "script_runs", + "entityType": "tables" + }, + { + "name": "desktop_control", + "entityType": "tables" + }, + { + "name": "desktop_fills", + "entityType": "tables" + }, + { + "name": "held_actions", + "entityType": "tables" + }, + { + "name": "bot_message_requests", + "entityType": "tables" + }, + { + "name": "delegation_receipts", + "entityType": "tables" + }, + { + "name": "relayed_job_questions", + "entityType": "tables" + }, + { + "name": "bot_requests", + "entityType": "tables" + }, + { + "name": "bot_secret_requests", + "entityType": "tables" + }, + { + "name": "bot_secret_uses", + "entityType": "tables" + }, + { + "name": "executions", + "entityType": "tables" + }, + { + "name": "schedules", + "entityType": "tables" + }, + { + "name": "agents", + "entityType": "tables" + }, + { + "name": "conversations", + "entityType": "tables" + }, + { + "name": "agent_credentials", + "entityType": "tables" + }, + { + "name": "credential_authorities", + "entityType": "tables" + }, + { + "name": "event_sources", + "entityType": "tables" + }, + { + "name": "relay_events", + "entityType": "tables" + }, + { + "name": "deleted_library_files", + "entityType": "tables" + }, + { + "name": "library_files", + "entityType": "tables" + }, + { + "name": "github_account_bots", + "entityType": "tables" + }, + { + "name": "github_accounts", + "entityType": "tables" + }, + { + "name": "github_app_bots", + "entityType": "tables" + }, + { + "name": "github_app_users", + "entityType": "tables" + }, + { + "name": "github_apps", + "entityType": "tables" + }, + { + "name": "mcp_servers", + "entityType": "tables" + }, + { + "name": "learned_changes", + "entityType": "tables" + }, + { + "name": "review_results", + "entityType": "tables" + }, + { + "name": "pending_reviews", + "entityType": "tables" + }, + { + "name": "review_counters", + "entityType": "tables" + }, + { + "name": "logins", + "entityType": "tables" + }, + { + "name": "memories", + "entityType": "tables" + }, + { + "name": "gateway_cooldowns", + "entityType": "tables" + }, + { + "name": "gateway_receipts", + "entityType": "tables" + }, + { + "name": "gateway_sent_messages", + "entityType": "tables" + }, + { + "name": "password_managers", + "entityType": "tables" + }, + { + "name": "provider_credentials", + "entityType": "tables" + }, + { + "name": "credentials", + "entityType": "tables" + }, + { + "name": "settings", + "entityType": "tables" + }, + { + "name": "skill_documents", + "entityType": "tables" + }, + { + "name": "skill_updates", + "entityType": "tables" + }, + { + "name": "skills", + "entityType": "tables" + }, + { + "name": "call_requests", + "entityType": "tables" + }, + { + "table": "event_runs", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "event_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "schedule_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "attempts", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "error", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "schedule_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "command", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "exit_code", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "output", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "''", + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "dropped_bytes", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "error", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "started_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "script_runs", + "name": "finished_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_control", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_control", + "name": "holder", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_control", + "name": "changes", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_control", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "id", + "type": "integer", + "notNull": false, + "autoincrement": true, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "value", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "label", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "browser", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "desktop_fills", + "name": "filled_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "job", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "action", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "page", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "owner_messages", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "reason", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "decline_reason", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "held_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "held_actions", + "name": "decided_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_message_requests", + "name": "request_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_message_requests", + "name": "source_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_message_requests", + "name": "target_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_message_requests", + "name": "recipient", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_message_requests", + "name": "message", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "delegation_receipts", + "name": "execution_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "delegation_receipts", + "name": "source_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "delegation_receipts", + "name": "target_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relayed_job_questions", + "name": "question_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relayed_job_questions", + "name": "reporter_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relayed_job_questions", + "name": "assignee_agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relayed_job_questions", + "name": "kind", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relayed_job_questions", + "name": "job", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "proposal", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "reason", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "created_agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "requested_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_requests", + "name": "decided_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "kind", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "hosts", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "reason", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "one_time_code", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_requests", + "name": "requested_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "id", + "type": "integer", + "notNull": false, + "autoincrement": true, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "kind", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "host", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "error", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "bot_secret_uses", + "name": "detail", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "conversation_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "schedule_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "submission_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "request_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "prompt", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "reply_to", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "error", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "attachments", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "executions", + "name": "attachments_digest", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "kind", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "'prompt'", + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "prompt", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "command", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "timeout_seconds", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "600", + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "notify", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "true", + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "cron", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "timezone", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "run_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "event_source_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "enabled", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "next_run_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "schedules", + "name": "created_by_agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "avatar", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "description", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "instructions", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "provider", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "model", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "web_search_provider", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "enabled", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "tools", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "mcp_servers", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "inference", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "'{}'", + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "shared_skills", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "'[]'", + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "desktop_model", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "review_model", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agents", + "name": "review", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "title", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "archived", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "chat", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "conversations", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "hosts", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "last_used_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "placeholder", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "agent_credentials", + "name": "github", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "entityType": "columns" + }, + { + "table": "credential_authorities", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credential_authorities", + "name": "certificate", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credential_authorities", + "name": "key", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_sources", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_sources", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_sources", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "source_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "received_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "method", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "query", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "headers", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "body", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "relay_events", + "name": "stored_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "deleted_library_files", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "deleted_library_files", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "deleted_library_files", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "mime_type", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "size", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "hash", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "text", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "description", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "library_files", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_account_bots", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_account_bots", + "name": "account_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_account_bots", + "name": "assigned_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_accounts", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_accounts", + "name": "login", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_accounts", + "name": "user_id", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_accounts", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_bots", + "name": "app_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_bots", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_bots", + "name": "assigned_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "app_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "login", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "user_id", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "token", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "expires_at", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "refresh_token", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_app_users", + "name": "refresh_expires_at", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "app_id", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "slug", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "client_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "private_key", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "bot_user_id", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "html_url", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "account", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "installation_id", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "github_apps", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "url", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "enabled", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "mcp_servers", + "name": "oauth_client_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "actor", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "target", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "target_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "action", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "before_state", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "after_state", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "source", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "reverts_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "learned_changes", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_results", + "name": "execution_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_results", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_results", + "name": "change_ids", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_results", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "pending_reviews", + "name": "execution_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "pending_reviews", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "pending_reviews", + "name": "conversation_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "pending_reviews", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_counters", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "review_counters", + "name": "skill_rounds", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "review_counters", + "name": "memory_rounds", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "hosts", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "logins", + "name": "last_used_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "content", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "memories", + "name": "source", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_cooldowns", + "name": "adapter_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_cooldowns", + "name": "scope", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_cooldowns", + "name": "channel_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_cooldowns", + "name": "until", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "adapter_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "message_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "channel_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "sender_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "is_direct_message", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "bot_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "request_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "text", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "execution_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "chunks", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "sent", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "state", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "created_at", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "expires_at", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "attempt_count", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "next_attempt_at", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "failed_at", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_receipts", + "name": "finished_at", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "adapter_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "channel_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "external_message_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "receipt_message_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "bot_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "gateway_sent_messages", + "name": "expires_at", + "type": "integer", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "password_managers", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "password_managers", + "name": "token", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "password_managers", + "name": "connected_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "provider_credentials", + "name": "provider", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "provider_credentials", + "name": "type", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "provider_credentials", + "name": "value", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credentials", + "name": "key", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credentials", + "name": "value", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credentials", + "name": "password_manager", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "credentials", + "name": "reference", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "settings", + "name": "key", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "settings", + "name": "value", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_documents", + "name": "skill_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_documents", + "name": "path", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_documents", + "name": "content", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_updates", + "name": "skill_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_updates", + "name": "commit", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_updates", + "name": "digest", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skill_updates", + "name": "checked_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "name", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "instructions", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "created_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "updated_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "agent_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "description", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "''", + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "created_by", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "'owner'", + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "source_execution_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "use_count", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "0", + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "last_used_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "state", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": "'active'", + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "pinned", + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": "false", + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "copied_from_skill_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "skills", + "name": "origin", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "agent_id", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "number", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "callee", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "goal", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "opening", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "status", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "call_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "conversation_id", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "outcome", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "error", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "requested_at", + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "decided_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "call_requests", + "name": "ended_at", + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "entityType": "columns" + }, + { + "table": "event_runs", + "name": "event_runs_once", + "columns": [ + { + "value": "event_id", + "isExpression": false + }, + { + "value": "schedule_id", + "isExpression": false + } + ], + "isUnique": true, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "event_runs", + "name": "event_runs_by_schedule", + "columns": [ + { + "value": "schedule_id", + "isExpression": false + }, + { + "value": "status", + "isExpression": false + }, + { + "value": "event_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "script_runs", + "name": "script_runs_by_schedule", + "columns": [ + { + "value": "schedule_id", + "isExpression": false + }, + { + "value": "started_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "script_runs", + "name": "script_runs_by_time", + "columns": [ + { + "value": "started_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "desktop_fills", + "name": "desktop_fills_agent", + "columns": [ + { + "value": "agent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "held_actions", + "name": "held_actions_agent", + "columns": [ + { + "value": "agent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "bot_requests", + "name": "bot_requests_by_agent", + "columns": [ + { + "value": "agent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "bot_secret_uses", + "name": "bot_secret_uses_by_secret", + "columns": [ + { + "value": "agent_id", + "isExpression": false + }, + { + "value": "kind", + "isExpression": false + }, + { + "value": "name", + "isExpression": false + }, + { + "value": "id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "bot_secret_uses", + "name": "bot_secret_uses_by_time", + "columns": [ + { + "value": "at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "executions", + "name": "executions_conversation_request", + "columns": [ + { + "value": "conversation_id", + "isExpression": false + }, + { + "value": "request_id", + "isExpression": false + } + ], + "isUnique": true, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "relay_events", + "name": "relay_events_by_stored_at", + "columns": [ + { + "value": "stored_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "library_files", + "name": "library_files_bot_hash", + "columns": [ + { + "value": "agent_id", + "isExpression": false + }, + { + "value": "hash", + "isExpression": false + } + ], + "isUnique": true, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "learned_changes", + "name": "learned_changes_agent", + "columns": [ + { + "value": "agent_id", + "isExpression": false + }, + { + "value": "created_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "gateway_cooldowns", + "name": "gateway_cooldowns_expiry", + "columns": [ + { + "value": "until", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "gateway_receipts", + "name": "gateway_receipts_pending", + "columns": [ + { + "value": "state", + "isExpression": false + }, + { + "value": "next_attempt_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "gateway_receipts", + "name": "gateway_receipts_retention", + "columns": [ + { + "value": "finished_at", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "gateway_sent_messages", + "name": "gateway_sent_messages_receipt", + "columns": [ + { + "value": "adapter_id", + "isExpression": false + }, + { + "value": "receipt_message_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "call_requests", + "name": "call_requests_by_agent", + "columns": [ + { + "value": "agent_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "call_requests", + "name": "call_requests_by_call", + "columns": [ + { + "value": "call_id", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "entityType": "indexes" + }, + { + "table": "event_runs", + "name": "fk_event_runs_event_id_relay_events_id_fk", + "columns": ["event_id"], + "tableTo": "relay_events", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "event_runs", + "name": "fk_event_runs_schedule_id_schedules_id_fk", + "columns": ["schedule_id"], + "tableTo": "schedules", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "script_runs", + "name": "fk_script_runs_schedule_id_schedules_id_fk", + "columns": ["schedule_id"], + "tableTo": "schedules", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "desktop_control", + "name": "fk_desktop_control_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "desktop_fills", + "name": "fk_desktop_fills_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "held_actions", + "name": "fk_held_actions_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_message_requests", + "name": "fk_bot_message_requests_source_agent_id_agents_id_fk", + "columns": ["source_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_message_requests", + "name": "fk_bot_message_requests_target_agent_id_agents_id_fk", + "columns": ["target_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "delegation_receipts", + "name": "fk_delegation_receipts_execution_id_executions_id_fk", + "columns": ["execution_id"], + "tableTo": "executions", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "delegation_receipts", + "name": "fk_delegation_receipts_source_agent_id_agents_id_fk", + "columns": ["source_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "delegation_receipts", + "name": "fk_delegation_receipts_target_agent_id_agents_id_fk", + "columns": ["target_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "relayed_job_questions", + "name": "fk_relayed_job_questions_reporter_agent_id_agents_id_fk", + "columns": ["reporter_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "relayed_job_questions", + "name": "fk_relayed_job_questions_assignee_agent_id_agents_id_fk", + "columns": ["assignee_agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_requests", + "name": "fk_bot_requests_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_secret_requests", + "name": "fk_bot_secret_requests_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_secret_uses", + "name": "fk_bot_secret_uses_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "executions", + "name": "fk_executions_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "executions", + "name": "fk_executions_conversation_id_conversations_id_fk", + "columns": ["conversation_id"], + "tableTo": "conversations", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "executions", + "name": "fk_executions_schedule_id_schedules_id_fk", + "columns": ["schedule_id"], + "tableTo": "schedules", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "SET NULL", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "schedules", + "name": "fk_schedules_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "conversations", + "name": "fk_conversations_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "agent_credentials", + "name": "fk_agent_credentials_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "credential_authorities", + "name": "fk_credential_authorities_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "deleted_library_files", + "name": "fk_deleted_library_files_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "library_files", + "name": "fk_library_files_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "github_account_bots", + "name": "fk_github_account_bots_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "github_account_bots", + "name": "fk_github_account_bots_account_id_github_accounts_id_fk", + "columns": ["account_id"], + "tableTo": "github_accounts", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "github_app_bots", + "name": "fk_github_app_bots_app_id_github_apps_id_fk", + "columns": ["app_id"], + "tableTo": "github_apps", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "github_app_bots", + "name": "fk_github_app_bots_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "github_app_users", + "name": "fk_github_app_users_app_id_github_apps_id_fk", + "columns": ["app_id"], + "tableTo": "github_apps", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "mcp_servers", + "name": "fk_mcp_servers_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "review_results", + "name": "fk_review_results_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "pending_reviews", + "name": "fk_pending_reviews_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "review_counters", + "name": "fk_review_counters_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "logins", + "name": "fk_logins_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "memories", + "name": "fk_memories_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "gateway_sent_messages", + "name": "fk_gateway_sent_messages_adapter_id_receipt_message_id_gateway_receipts_adapter_id_message_id_fk", + "columns": ["adapter_id", "receipt_message_id"], + "tableTo": "gateway_receipts", + "columnsTo": ["adapter_id", "message_id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "credentials", + "name": "fk_credentials_password_manager_password_managers_id_fk", + "columns": ["password_manager"], + "tableTo": "password_managers", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "RESTRICT", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "skill_documents", + "name": "fk_skill_documents_skill_id_skills_id_fk", + "columns": ["skill_id"], + "tableTo": "skills", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "skill_updates", + "name": "fk_skill_updates_skill_id_skills_id_fk", + "columns": ["skill_id"], + "tableTo": "skills", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "skills", + "name": "fk_skills_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "call_requests", + "name": "fk_call_requests_agent_id_agents_id_fk", + "columns": ["agent_id"], + "tableTo": "agents", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "entityType": "fks" + }, + { + "table": "bot_secret_requests", + "name": "bot_secret_requests_pk", + "columns": ["agent_id", "kind", "name"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "agent_credentials", + "name": "agent_credentials_pk", + "columns": ["agent_id", "name"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "github_app_bots", + "name": "github_app_bots_pk", + "columns": ["app_id", "agent_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "logins", + "name": "logins_pk", + "columns": ["agent_id", "name"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "gateway_cooldowns", + "name": "gateway_cooldowns_pk", + "columns": ["adapter_id", "scope", "channel_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "gateway_receipts", + "name": "gateway_receipts_pk", + "columns": ["adapter_id", "message_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "gateway_sent_messages", + "name": "gateway_sent_messages_pk", + "columns": ["adapter_id", "channel_id", "external_message_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "skill_documents", + "name": "skill_documents_pk", + "columns": ["skill_id", "path"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "event_runs", + "name": "event_runs_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "script_runs", + "name": "script_runs_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "desktop_control", + "name": "desktop_control_pk", + "columns": ["agent_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "desktop_fills", + "name": "desktop_fills_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "held_actions", + "name": "held_actions_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "bot_message_requests", + "name": "bot_message_requests_pk", + "columns": ["request_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "delegation_receipts", + "name": "delegation_receipts_pk", + "columns": ["execution_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "relayed_job_questions", + "name": "relayed_job_questions_pk", + "columns": ["question_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "bot_requests", + "name": "bot_requests_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "bot_secret_uses", + "name": "bot_secret_uses_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "executions", + "name": "executions_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "schedules", + "name": "schedules_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "agents", + "name": "agents_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "conversations", + "name": "conversations_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "credential_authorities", + "name": "credential_authorities_pk", + "columns": ["agent_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "event_sources", + "name": "event_sources_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "relay_events", + "name": "relay_events_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "deleted_library_files", + "name": "deleted_library_files_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "library_files", + "name": "library_files_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "github_account_bots", + "name": "github_account_bots_pk", + "columns": ["agent_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "github_accounts", + "name": "github_accounts_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "github_app_users", + "name": "github_app_users_pk", + "columns": ["app_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "github_apps", + "name": "github_apps_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "mcp_servers", + "name": "mcp_servers_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "learned_changes", + "name": "learned_changes_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "review_results", + "name": "review_results_pk", + "columns": ["execution_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "pending_reviews", + "name": "pending_reviews_pk", + "columns": ["execution_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "review_counters", + "name": "review_counters_pk", + "columns": ["agent_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "memories", + "name": "memories_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "password_managers", + "name": "password_managers_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "provider_credentials", + "name": "provider_credentials_pk", + "columns": ["provider"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "credentials", + "name": "credentials_pk", + "columns": ["key"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "settings", + "name": "settings_pk", + "columns": ["key"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "skill_updates", + "name": "skill_updates_pk", + "columns": ["skill_id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "skills", + "name": "skills_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "call_requests", + "name": "call_requests_pk", + "columns": ["id"], + "nameExplicit": false, + "entityType": "pks" + }, + { + "table": "agent_credentials", + "name": "agent_credentials_placeholder_unique", + "columns": ["placeholder"], + "nameExplicit": false, + "entityType": "uniques" + }, + { + "table": "github_accounts", + "name": "github_accounts_user_id_unique", + "columns": ["user_id"], + "nameExplicit": false, + "entityType": "uniques" + }, + { + "table": "bot_secret_requests", + "name": "bot_secret_requests_kind", + "value": "\"kind\" IN ('credential', 'login')", + "entityType": "checks" + }, + { + "table": "bot_secret_uses", + "name": "bot_secret_uses_kind", + "value": "\"kind\" IN ('credential', 'login')", + "entityType": "checks" + }, + { + "table": "password_managers", + "name": "password_managers_id", + "value": "\"id\" IN ('1password', 'bitwarden')", + "entityType": "checks" + }, + { + "table": "provider_credentials", + "name": "provider_credentials_type", + "value": "\"type\" IN ('api_key', 'oauth')", + "entityType": "checks" + }, + { + "table": "credentials", + "name": "credentials_source", + "value": "(\"value\" IS NOT NULL AND \"password_manager\" IS NULL AND \"reference\" IS NULL) OR (\"value\" IS NULL AND \"password_manager\" IS NOT NULL AND \"reference\" IS NOT NULL)", + "entityType": "checks" + } + ], + "renames": [] +} diff --git a/apps/server/src/app/api-requests.ts b/apps/server/src/app/api-requests.ts index 536c530d..61aceac7 100644 --- a/apps/server/src/app/api-requests.ts +++ b/apps/server/src/app/api-requests.ts @@ -104,12 +104,12 @@ export function pathRegister( return run ? registerWith(app, run) : registerWith(app, noServices); } -const messagePaths = [routes.sendMessage, routes.sendGroupMessage].map( +const messagePaths = [routes.sendMessage].map( (route) => new RegExp(`^${route.getRoutingPath().replace(/:[^/]+/g, "[^/]+")}$`), ); -const uploadPaths = [routes.uploadFile, routes.uploadGroupFile].map( +const uploadPaths = [routes.uploadFile].map( (route) => new RegExp(`^${route.getRoutingPath().replace(/:[^/]+/g, "[^/]+")}$`), ); diff --git a/apps/server/src/app/api.test.ts b/apps/server/src/app/api.test.ts index 4c703d19..554b0b2f 100644 --- a/apps/server/src/app/api.test.ts +++ b/apps/server/src/app/api.test.ts @@ -742,10 +742,10 @@ describe("HTTP API for bots, chats, and activity", () => { const response: Response = await req(app, "/v1/events"); const reader = response.body!.getReader(); - service.announce({ type: "pins", pinnedConversations: ["group:g1"] }); - const text = await readUntil(reader, '"group:g1"'); + service.announce({ type: "pins", pinnedConversations: ["agent:b1"] }); + const text = await readUntil(reader, '"agent:b1"'); expect(text).toContain( - 'event: pins\ndata: {"pinnedConversations":["group:g1"]}', + 'event: pins\ndata: {"pinnedConversations":["agent:b1"]}', ); expect(text).not.toContain('event: activity\ndata: {"type":"pins"'); await reader.cancel(); @@ -1449,8 +1449,8 @@ describe("HTTP API for MCP servers, skills, and memory", () => { store.createMemory({ agentId: agent.id, content: "older" }); store.createMemory({ agentId: agent.id, - content: "from a group", - source: { kind: "group", groupId: "group-1", name: "Trip" }, + content: "from a bot", + source: { kind: "bot", agentId: agent.id, name: "Ada" }, }); const memories = memoryResponse @@ -1467,7 +1467,7 @@ describe("HTTP API for MCP servers, skills, and memory", () => { expect.arrayContaining([ { kind: "owner" }, null, - { kind: "group", groupId: "group-1", name: "Trip" }, + { kind: "bot", agentId: agent.id, name: "Ada" }, ]), ); store.close(); diff --git a/apps/server/src/app/api.ts b/apps/server/src/app/api.ts index 0b0f3663..3088c2e4 100644 --- a/apps/server/src/app/api.ts +++ b/apps/server/src/app/api.ts @@ -21,8 +21,6 @@ import { registerJudgeModelRoutes } from "../bot-desktop/judge-settings"; import { registerVisionModelRoutes } from "../vision/vision-api"; import { registerBotRequestRoutes } from "../bot-requests/bot-requests-api"; import type { BotRequests } from "../bot-requests/bot-requests"; -import { registerGroupChatRoutes } from "../group-chats/group-chats-api"; -import { GroupChats, groupChatsAccess } from "../group-chats/group-chats"; import { registerMcpServerRoutes } from "../integrations/mcp-servers-api"; import type { McpServers } from "../integrations/mcp-servers"; import { registerMemoryRoutes } from "../memory/memory-api"; @@ -72,7 +70,6 @@ export type ApiServices = | BotWorkspaces | OwnerSkills | EventSources - | GroupChats | McpServers | MessageGateway | Plugins @@ -114,7 +111,6 @@ function apiContext( workspaces: Context.get(services, BotWorkspaces), plugins, jobKinds: pluginJobKinds(plugins).map((kind) => kind.kind), - groupChats: groupChatsAccess(Context.get(services, GroupChats)), externalAuth: new Map( pluginProviders(plugins).flatMap(({ provider, externalAuth }) => externalAuth ? [[provider.id, externalAuth] as const] : [], @@ -161,7 +157,6 @@ const featureRoutes: ReadonlyArray<(api: ApiContext) => void> = [ registerAgentRoutes, registerChatRoutes, registerBotActivityRoutes, - registerGroupChatRoutes, registerFileRoutes, registerCredentialRoutes, registerGitHubAppRoutes, diff --git a/apps/server/src/app/auth.test.ts b/apps/server/src/app/auth.test.ts index 861f8d91..9572e012 100644 --- a/apps/server/src/app/auth.test.ts +++ b/apps/server/src/app/auth.test.ts @@ -210,6 +210,30 @@ test("a new account has no pins", async () => { } }); +test("restart removes only group pins and preserves bot order and sessions", async () => { + const dataDir = mkdtempSync(join(tmpdir(), "auth-group-pins-")); + let accounts = await createAuth(dataDir, ORIGIN); + const { token } = await signUp(accounts, "upgrade-pins@example.com"); + accounts.close(); + const database = new Database(join(dataDir, "auth.sqlite")); + database + .query("UPDATE user SET pinnedConversations = ?") + .run(JSON.stringify(["agent:second", "group:old", "agent:first"])); + database.close(); + + for (let attempt = 0; attempt < 2; attempt++) { + accounts = await createAuth(dataDir, ORIGIN); + try { + expect(await pinsOf(accounts, token!)).toEqual([ + "agent:second", + "agent:first", + ]); + } finally { + accounts.close(); + } + } +}); + test("saves pins in order", async () => { const accounts = await createAuth( mkdtempSync(join(tmpdir(), "auth-")), @@ -219,11 +243,11 @@ test("saves pins in order", async () => { try { const { token } = await signUp(accounts, "pins@example.com"); const saved = await authRequest(accounts, token!, "update-user", { - pinnedConversations: ["group:g1", "agent:b1"], + pinnedConversations: ["agent:b2", "agent:b1"], }); expect(saved.status).toBe(200); - expect(await pinsOf(accounts, token!)).toEqual(["group:g1", "agent:b1"]); + expect(await pinsOf(accounts, token!)).toEqual(["agent:b2", "agent:b1"]); } finally { accounts.close(); } @@ -246,6 +270,7 @@ test("rejects more than nine pins, duplicates, and malformed keys", async () => tooMany, ["agent:a", "agent:a"], ["bot:a"], + ["group:obsolete"], ]) { const response = await authRequest(accounts, token!, "update-user", { pinnedConversations, diff --git a/apps/server/src/app/auth.ts b/apps/server/src/app/auth.ts index 33a53eb7..6b9bc8e8 100644 --- a/apps/server/src/app/auth.ts +++ b/apps/server/src/app/auth.ts @@ -292,6 +292,28 @@ export async function createAuth( try { const { runMigrations } = await getMigrations(options); await runMigrations(); + database.transaction(() => { + const rows = database + .query<{ id: string; pins: string | null }, []>( + "SELECT id, pinnedConversations AS pins FROM user", + ) + .all(); + + for (const row of rows) { + if (row.pins === null) continue; + + const pins = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Array(Schema.String)), + )(row.pins); + + const retained = pins.filter((pin) => !pin.startsWith("group:")); + + if (retained.length !== pins.length) + database + .query("UPDATE user SET pinnedConversations = ? WHERE id = ?") + .run(JSON.stringify(retained), row.id); + } + })(); const auth = betterAuth(options); const users = drizzle({ client: database }); const { adapter } = await auth.$context; diff --git a/apps/server/src/app/group-chat-upgrade.test.ts b/apps/server/src/app/group-chat-upgrade.test.ts new file mode 100644 index 00000000..9893251f --- /dev/null +++ b/apps/server/src/app/group-chat-upgrade.test.ts @@ -0,0 +1,1011 @@ +import { afterEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; +import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node"; +import { Effect } from "effect"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Store } from "../../test/support/store"; +import { agentInput } from "../contract/agents"; +import { AgentRuntime } from "../bots/runtime"; +import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; +import { defineAnchorTask } from "../shared/anchor-task"; +import { createModels } from "@earendil-works/pi-ai"; +import { + fauxAssistantMessage, + fauxProvider, +} from "@earendil-works/pi-ai/providers/faux"; +import { migrateFile, migrationsFolder } from "../shared/database"; +import { removeLegacyGroupChats } from "./group-chat-upgrade"; +import { openReviewConversation, ReviewAnchor } from "../learning/review-kind"; +import { defineDoc } from "@earendil-works/pi-durable"; + +const directories: string[] = []; +function temporary() { + const directory = mkdtempSync(join(tmpdir(), "group-chat-upgrade-")); + directories.push(directory); + return directory; +} +afterEach(() => { + for (const directory of directories.splice(0)) + rmSync(directory, { recursive: true, force: true }); +}); + +async function privateHistory(directory: string, agentId: string) { + mkdirSync(join(directory, "agents"), { recursive: true }); + const path = join(directory, "agents", `${agentId}.sqlite`); + const storage = await openNodeSqliteStorage(path); + await storage.close(BACKGROUND_CONTEXT); + const db = new Database(path); + const register = (id: number, kind: string) => + db.query("INSERT INTO record_ids VALUES (?, ?)").run(id, kind); + const conversation = ( + id: number, + task: number | null = null, + owner: number | null = null, + ) => { + register(id, "conversation"); + db.query("INSERT INTO conversations VALUES (?, ?, ?, ?)").run( + id, + owner, + task, + JSON.stringify({ + id, + ...(task === null + ? {} + : { owner: { conversationId: owner, taskId: task } }), + }), + ); + }; + const task = ( + id: number, + conversationId: number, + kind: string, + owner?: number, + ) => { + register(id, "task"); + const record = { + id, + conversationId, + kind, + version: 1, + input: null, + ...(owner === undefined ? {} : { owner }), + state: { + status: "terminal", + outcome: { status: "completed", result: null }, + }, + }; + db.query("INSERT INTO tasks VALUES (?, ?, ?, 'terminal', 0, 0, ?)").run( + id, + conversationId, + JSON.stringify(kind), + JSON.stringify(record), + ); + }; + const entry = (id: number, conversationId: number, content: string) => { + register(id, "entry"); + db.query("INSERT INTO entries VALUES (?, ?, NULL, 10, ?)").run( + id, + conversationId, + JSON.stringify({ + id, + conversationId, + kind: "message", + data: { content }, + }), + ); + }; + const document = ( + id: number, + kind: string, + scope: string, + owner: number, + retired = false, + ) => { + register(id, "document"); + db.query("INSERT INTO documents VALUES (?, ?, 0, ?, ?, ?, 10, ?, ?)").run( + id, + JSON.stringify(kind), + JSON.stringify(""), + scope, + owner, + retired ? 11 : null, + JSON.stringify({ + id, + kind, + scope: { + kind: scope, + ...(scope === "conversation" + ? { conversationId: owner } + : scope === "task" + ? { taskId: owner } + : {}), + }, + createdAt: 10, + ...(retired ? { retiredAt: 11 } : {}), + }), + ); + db.query("INSERT INTO document_revisions VALUES (?, 10, 'base', 1, ?)").run( + id, + JSON.stringify({ + groupId: + scope === "conversation" && owner === 3 ? "deleted-group" : null, + content: "document sentinel", + }), + ); + }; + conversation(1); + task(2, 1, "crumble.group-anchor"); + conversation(3, 2, 1); + entry(4, 3, "private group transcript"); + task(5, 3, "generation"); + task(6, 3, "tool", 5); + conversation(7, 6, 3); + entry(8, 7, "nested private history"); + document(9, "crumble.group-conversation", "conversation", 3); + document(10, "retired-document", "conversation", 7, true); + document(11, "task-document", "task", 2); + register(12, "submission"); + db.query("INSERT INTO submissions VALUES (12, 3, ?, 'done', ?)").run( + JSON.stringify("private-input"), + JSON.stringify({ + id: 12, + conversationId: 3, + type: "write", + status: "done", + entry: 4, + }), + ); + entry(20, 1, "direct chat sentinel"); + task(21, 1, "crumble.review-anchor"); + conversation(22, 21, 1); + entry(23, 22, "unrelated review sentinel"); + task(24, 1, "crumble.outside-call-anchor"); + conversation(25, 24, 1); + entry(26, 25, "outside call sentinel"); + document(27, "session-document", "session", 0); + document(28, "root-document", "conversation", 1); + document(29, "review-document", "task", 21); + db.run("UPDATE durable_metadata SET next_id = '1000', next_seq = 100"); + db.close(); + return path; +} + +async function fixture() { + const directory = temporary(); + const store = new Store(directory); + const agents = ["member", "former", "deleted"].map((id) => + store.createAgent(agentInput.parse({ name: id }), id), + ); + for (const agent of agents) { + for (const id of [1, 3, 7, 22, 25]) { + store.createConversation( + { agentId: agent.id, title: id === 1 ? "Direct" : "Private" }, + `${agent.id}:${id}`, + ); + if (id === 3) store.archiveConversation(`${agent.id}:${id}`); + } + for (const id of [1, 3, 22, 25]) { + store.createExecution( + { + agentId: agent.id, + conversationId: `${agent.id}:${id}`, + requestId: `request-${id}`, + prompt: "sentinel", + scheduleId: null, + submissionId: null, + status: "done", + error: null, + }, + `${agent.id}-execution-${id}`, + ); + store.addPendingReview( + `${agent.id}-execution-${id}`, + agent.id, + `${agent.id}:${id}`, + ); + } + } + const source = { + executionId: "former-execution-3", + conversationId: "former:3", + groupId: "deleted-group", + }; + const memory = store.createMemory( + { + agentId: "former", + content: "after", + source: null, + }, + "retained-memory", + ); + const skill = store.createSkill( + { + agentId: "former", + name: "learned", + description: "retained", + instructions: "Keep these instructions", + documents: [], + createdBy: "bot", + sourceExecutionId: "former-execution-3", + }, + "retained-skill", + { actor: "bot", source }, + ); + store.close(); + const db = new Database(join(directory, "store.sqlite")); + const legacy = readFileSync( + new URL("../../test/fixtures/legacy-store-schema.sql", import.meta.url), + "utf8", + ); + for (const table of ["group_chats", "group_members", "group_turns"]) + db.run( + legacy + .split("\n") + .find((line) => line.startsWith(`CREATE TABLE ${table} `))!, + ); + db.run("DROP TABLE library_files; DROP TABLE deleted_library_files"); + for (const migration of [ + "20261111192433_file_library", + "20261111195518_file_library_deleted", + "20261112101421_library_file_descriptions", + ]) + for (const statement of readFileSync( + join(migrationsFolder("store"), migration, "migration.sql"), + "utf8", + ).split("--> statement-breakpoint")) + db.run(statement); + db.run( + "DELETE FROM __drizzle_migrations WHERE name = '20261122205418_remove_group_chats'; INSERT INTO group_chats (id, name, created_at, updated_at) VALUES ('live-group', 'Legacy', 'now', 'now'); INSERT INTO group_members (group_id, agent_id, joined_at, conversation_id) VALUES ('live-group', 'member', 'now', 'member:3'); INSERT INTO group_turns VALUES ('member-execution-3', 'live-group', 'member', 1, 0, 'settled', 'now')", + ); + const legacySource = { + kind: "group", + groupId: "deleted-group", + name: "Old group", + }; + db.query("UPDATE memories SET source = ? WHERE id = ?").run( + JSON.stringify(legacySource), + memory.id, + ); + const legacyMemory = { ...memory, source: legacySource }; + db.run("UPDATE conversations SET chat = 1 WHERE id LIKE '%:1'"); + db.query( + "INSERT INTO learned_changes (id, agent_id, actor, target, target_id, action, before_state, after_state, source, reverts_id, created_at) VALUES (?, 'former', 'bot', 'memory', ?, 'update', ?, ?, ?, NULL, ?)", + ).run( + "memory-change", + memory.id, + JSON.stringify({ ...legacyMemory, content: "before" }), + JSON.stringify(legacyMemory), + JSON.stringify(source), + memory.createdAt, + ); + db.query( + "INSERT INTO learned_changes (id, agent_id, actor, target, target_id, action, before_state, after_state, source, reverts_id, created_at) VALUES ('older-revert', 'former', 'owner', 'memory', ?, 'revert', NULL, NULL, NULL, 'older-change', ?)", + ).run(memory.id, memory.createdAt); + for (const agent of agents) + for (const id of [1, 3, 22, 25]) + db.query("INSERT INTO review_results VALUES (?, ?, '[]', ?)").run( + `${agent.id}-execution-${id}`, + agent.id, + memory.createdAt, + ); + db.run( + "INSERT INTO pending_reviews VALUES ('coding-job:former:7:12', 'former', 'former:7', 'now'); INSERT INTO review_results VALUES ('coding-job:former:7:12', 'former', '[]', 'now'); INSERT INTO review_results VALUES ('coding-job:former:3:12', 'former', '[]', 'now')", + ); + const exclusive = "a".repeat(64); + const shared = "b".repeat(64); + for (const [id, agent, group, hash] of [ + ["exclusive", null, "live-group", exclusive], + ["group-shared", null, "live-group", shared], + ["bot-shared", "former", null, shared], + ]) + db.query( + "INSERT INTO library_files (id, agent_id, group_id, name, mime_type, size, hash, text, created_at) VALUES (?, ?, ?, ?, 'application/pdf', 5, ?, 'extracted', ?)", + ).run(id!, agent!, group!, `${id}.pdf`, hash!, memory.createdAt); + db.run( + "INSERT INTO deleted_library_files VALUES ('group-tombstone', NULL, 'live-group', 'old.pdf'); INSERT INTO deleted_library_files VALUES ('bot-tombstone', 'former', NULL, 'bot.pdf')", + ); + db.close(); + mkdirSync(join(directory, "files"), { recursive: true }); + for (const hash of [exclusive, shared]) + for (const suffix of ["", ".txt", ".pdf.txt"]) + writeFileSync( + join(directory, "files", `${hash}${suffix}`), + `${hash}${suffix} sentinel`, + ); + mkdirSync(join(directory, "groups")); + for (const name of [ + "live-group.sqlite", + "orphan.sqlite-wal", + "orphan.sqlite-shm", + ]) + writeFileSync( + join(directory, "groups", name), + "shared transcript sentinel", + ); + for (const agent of agents) await privateHistory(directory, agent.id); + await Effect.runPromise( + migrateFile(join(directory, "push.sqlite"), migrationsFolder("push")), + ); + const push = new Database(join(directory, "push.sqlite")); + push.run( + "INSERT INTO push_settings VALUES ('credentials', 'retained'); INSERT INTO push_devices VALUES ('device', 'ios', 'apns', 'disposable-token', 'sandbox', 'test', 1, 'now')", + ); + for (const [id, kind, event] of [ + ["bot", "bot", { type: "reply", origin: "owner" }], + ["associated", "group", { type: "reply" }], + ["group-id", "bot", { type: "reply", groupId: "deleted-group" }], + ["group-origin", "bot", { type: "reply", origin: "group" }], + [ + "nested-group-origin", + "bot", + { type: "reply", origin: { kind: "group" } }, + ], + ] as const) { + push.query("INSERT INTO chat_views VALUES (?, ?, ?, 1)").run(id, kind, id); + push + .query( + "INSERT INTO reply_associations VALUES (?, ?, ?, 'message', 'entry', '{}', 0)", + ) + .run(id, kind, id); + push + .query("INSERT INTO push_outbox VALUES (?, ?, ?, 'now', 9999999999999)") + .run(id, id, JSON.stringify(event)); + push + .query("INSERT INTO push_delivery VALUES (?, 'device', 0, 0, 0)") + .run(id); + } + push.close(); + return { directory, exclusive, shared, memory, skill }; +} + +function rows(path: string, sql: string) { + const db = new Database(path, { create: false }); + db.run("PRAGMA query_only = ON"); + try { + return db.query(sql).all(); + } finally { + db.close(); + } +} + +test("real legacy-anchor harness history is purged without resuming it or changing the direct chat", async () => { + const directory = temporary(); + const store = new Store(directory); + const agent = { + ...store.createAgent(agentInput.parse({ name: "Legacy bot" }), "harness"), + provider: "faux" as never, + model: "test", + }; + store.close(); + const faux = fauxProvider({ provider: "faux", models: [{ id: "test" }] }); + const models = createModels(); + models.setProvider(faux.provider); + const runtime = new AgentRuntime( + join(directory, "agents"), + runtimeCallbacks({ models }), + ); + let group = ""; + try { + faux.setResponses([ + fauxAssistantMessage("direct sentinel"), + fauxAssistantMessage("legacy group sentinel"), + ]); + const direct = await runtime.openChat(agent); + await runtime.wait( + await runtime.submit(agent, direct, "direct prompt", "direct"), + agent, + ); + group = await runtime.openAnchored( + agent, + defineAnchorTask("crumble.group-anchor"), + async () => {}, + ); + await runtime.wait( + await runtime.submit(agent, group, "legacy group prompt", "legacy"), + agent, + ); + } finally { + await runtime.close(); + } + const path = join(directory, "agents", "harness.sqlite"); + const before = rows(path, "SELECT * FROM entries WHERE conversation_id = 1"); + const counters = rows(path, "SELECT * FROM durable_metadata"); + const db = new Database(join(directory, "store.sqlite")); + db.run( + "DELETE FROM __drizzle_migrations WHERE name = '20261122205418_remove_group_chats'", + ); + db.close(); + await removeLegacyGroupChats(directory); + expect(rows(path, "SELECT * FROM entries WHERE conversation_id = 1")).toEqual( + before, + ); + expect(rows(path, "SELECT * FROM durable_metadata")).toEqual(counters); + expect( + rows( + path, + `SELECT id FROM conversations WHERE id = ${Number(group.split(":")[1])}`, + ), + ).toEqual([]); + expect( + JSON.stringify(rows(path, "SELECT record FROM entries")), + ).not.toContain("legacy group sentinel"); + expect(faux.getPendingResponseCount()).toBe(0); +}); + +test("sibling group reviews, including orphan documents, are inventoried and replayed without touching direct reviews", async () => { + const directory = temporary(); + const store = new Store(directory); + const agent = { + ...store.createAgent(agentInput.parse({ name: "Reviews" }), "reviews"), + provider: "faux" as never, + model: "test", + }; + const faux = fauxProvider({ provider: "faux", models: [{ id: "test" }] }); + const models = createModels(); + models.setProvider(faux.provider); + const runtime = new AgentRuntime( + join(directory, "agents"), + runtimeCallbacks({ models }), + ); + let group = ""; + const removed: string[] = []; + let retained = ""; + try { + await runtime.openChat(agent); + group = await runtime.openAnchored( + agent, + defineAnchorTask("crumble.group-anchor"), + async () => {}, + ); + for (const execution of [ + "group-pending", + "group-orphan", + "direct-review", + ]) { + const conversation = await openReviewConversation( + runtime, + agent, + { + id: execution, + conversationId: execution === "direct-review" ? "reviews:1" : group, + }, + { memory: true, skills: false }, + 100000, + ); + faux.setResponses([fauxAssistantMessage(`${execution} transcript`)]); + await runtime.wait( + await runtime.submit(agent, conversation, "review", execution), + agent, + ); + if (execution === "direct-review") retained = conversation; + else removed.push(conversation); + } + removed.push( + await runtime.openAnchored(agent, ReviewAnchor, async () => {}), + ); + const legacyReview = defineDoc<{ + executionId: string; + groupId: string | null; + }>({ + kind: "crumble.review-conversation", + version: 1, + scope: "conversation", + history: "latest", + fork: "initial", + initial: () => ({ executionId: "missing-execution", groupId: null }), + checkpointWhen: () => false, + }); + removed.push( + await runtime.openAnchored(agent, ReviewAnchor, async (tx, id) => { + const document = await tx.doc(legacyReview, id); + document.groupId = "deleted-group"; + }), + ); + } finally { + await runtime.close(); + } + store.createConversation({ agentId: agent.id, title: "Group" }, group); + for (const execution of [ + "group-pending", + "group-orphan", + "group-pending-only", + ]) + store.createExecution( + { + agentId: agent.id, + conversationId: group, + requestId: execution, + prompt: "group", + scheduleId: null, + submissionId: null, + status: "done", + error: null, + }, + execution, + ); + for (const conversation of [...removed, retained]) + store.createConversation( + { agentId: agent.id, title: "Review" }, + conversation, + ); + store.addPendingReview("group-pending", agent.id, removed[0]!); + store.addPendingReview("group-pending-only", agent.id, removed[2]!); + store.addPendingReview("direct-review", agent.id, retained); + store.close(); + const storePath = join(directory, "store.sqlite"); + const db = new Database(storePath); + db.run( + "DELETE FROM __drizzle_migrations WHERE name = '20261122205418_remove_group_chats'", + ); + db.close(); + const path = join(directory, "agents", "reviews.sqlite"); + const counters = rows(path, "SELECT * FROM durable_metadata"); + const sentinel = rows( + path, + `SELECT * FROM entries WHERE conversation_id IN (1, ${Number(retained.split(":")[1])})`, + ); + mkdirSync(join(directory, "groups")); + mkdirSync(join(directory, "groups", "blocked.sqlite")); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow(); + const manifest = readFileSync( + join(directory, "group-chat-removal.json"), + "utf8", + ); + for (const conversation of removed) { + expect(manifest).toContain(conversation); + expect( + rows( + path, + `SELECT id FROM conversations WHERE id = ${Number(conversation.split(":")[1])}`, + ), + ).toEqual([]); + } + expect( + rows( + path, + "SELECT id FROM tasks WHERE kind = json_quote('crumble.review-anchor')", + ), + ).toHaveLength(1); + rmSync(join(directory, "groups", "blocked.sqlite"), { recursive: true }); + await removeLegacyGroupChats(directory); + await removeLegacyGroupChats(directory); + expect(rows(path, "SELECT * FROM durable_metadata")).toEqual(counters); + expect( + rows( + path, + `SELECT * FROM entries WHERE conversation_id IN (1, ${Number(retained.split(":")[1])})`, + ), + ).toEqual(sentinel); + expect( + rows(storePath, "SELECT conversation_id FROM pending_reviews"), + ).toEqual([{ conversation_id: retained }]); + expect(rows(storePath, "SELECT id FROM conversations")).toEqual([ + { id: retained }, + ]); + expect(rows(storePath, "SELECT id FROM executions")).toEqual([]); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(false); + const reopened = await openNodeSqliteStorage(path); + await reopened.close(BACKGROUND_CONTEXT); + expect(rows(path, "SELECT id FROM conversations")).toHaveLength(2); +}); + +test("fresh installs are bot-only and completed migrations bypass the legacy Pi schema guard", async () => { + const directory = temporary(); + const store = new Store(directory); + const agent = store.createAgent( + agentInput.parse({ name: "Future bot" }), + "future", + ); + store.close(); + const path = await privateHistory(directory, agent.id); + const db = new Database(path); + db.run("UPDATE durable_schema SET version = 99"); + db.close(); + await removeLegacyGroupChats(directory); + expect(rows(path, "SELECT id FROM conversations WHERE id = 3")).toEqual([ + { id: 3 }, + ]); + expect( + rows( + join(directory, "store.sqlite"), + "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'group_%'", + ), + ).toEqual([]); + for (const table of ["library_files", "deleted_library_files"]) { + const columns = rows( + join(directory, "store.sqlite"), + `PRAGMA table_info(${table})`, + ) as { name: string; notnull: number }[]; + expect(columns.some((column) => column.name === "group_id")).toBe(false); + expect(columns.find((column) => column.name === "agent_id")?.notnull).toBe( + 1, + ); + } + writeFileSync( + join(directory, "group-chat-removal.json"), + JSON.stringify({ + version: 1, + privateHistories: [ + { + agentId: agent.id, + conversations: [3], + tasks: [2], + entries: [], + submissions: [], + documents: [], + }, + ], + conversations: [], + executions: [], + hashes: [], + groupFiles: [], + }), + ); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow( + "Unsupported Pi", + ); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(true); +}); + +test("the forward migration preserves bot files and tombstones after a legacy purge", async () => { + const { directory, shared } = await fixture(); + await removeLegacyGroupChats(directory); + const path = join(directory, "store.sqlite"); + const files = rows( + path, + "SELECT id, agent_id, name, mime_type, size, hash, text, description, created_at FROM library_files", + ); + const tombstones = rows( + path, + "SELECT id, agent_id, name FROM deleted_library_files", + ); + await Effect.runPromise(migrateFile(path, migrationsFolder("store"))); + expect(rows(path, "SELECT * FROM library_files")).toEqual(files); + expect(rows(path, "SELECT * FROM deleted_library_files")).toEqual(tombstones); + expect( + rows( + path, + "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'group_%'", + ), + ).toEqual([]); + expect(rows(path, "PRAGMA foreign_key_check")).toEqual([]); + expect( + rows( + path, + "SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'library_files_%'", + ), + ).toEqual([{ name: "library_files_bot_hash" }]); + for (const suffix of ["", ".txt", ".pdf.txt"]) + expect( + readFileSync(join(directory, "files", `${shared}${suffix}`), "utf8"), + ).toBe(`${shared}${suffix} sentinel`); + for (const name of ["member", "former", "deleted"]) { + const db = new Database(join(directory, "agents", `${name}.sqlite`)); + db.run("UPDATE durable_schema SET version = 99"); + db.close(); + } + await removeLegacyGroupChats(directory); +}); + +test("manifest replay refuses root and store-designated direct conversations before any deletion", async () => { + for (const conversation of [1, 22]) { + const directory = temporary(); + const path = await privateHistory(directory, "bot"); + const store = new Database(join(directory, "store.sqlite")); + store.run( + "CREATE TABLE conversations (id TEXT, chat INTEGER); INSERT INTO conversations VALUES ('bot:22', 1)", + ); + store.close(); + writeFileSync( + join(directory, "group-chat-removal.json"), + JSON.stringify({ + version: 1, + privateHistories: [ + { + agentId: "bot", + conversations: [conversation], + tasks: [], + entries: [], + submissions: [], + documents: [], + }, + ], + conversations: [], + executions: [], + hashes: [], + groupFiles: [], + }), + ); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow( + conversation === 1 + ? "root/direct conversation" + : "direct conversation bot:22", + ); + expect(rows(path, "SELECT id FROM conversations")).toHaveLength(5); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(true); + } +}); + +test("older partial installations skip absent group tables and owner columns", async () => { + const directory = temporary(); + const db = new Database(join(directory, "store.sqlite")); + db.run( + "CREATE TABLE library_files (id TEXT, agent_id TEXT, hash TEXT); INSERT INTO library_files VALUES ('direct-file', 'bot', 'sentinel'); CREATE TABLE memories (id TEXT, content TEXT); INSERT INTO memories VALUES ('direct-memory', 'sentinel')", + ); + db.close(); + await removeLegacyGroupChats(directory); + expect( + rows(join(directory, "store.sqlite"), "SELECT * FROM library_files"), + ).toEqual([{ id: "direct-file", agent_id: "bot", hash: "sentinel" }]); + expect( + rows(join(directory, "store.sqlite"), "SELECT * FROM memories"), + ).toEqual([{ id: "direct-memory", content: "sentinel" }]); + expect(readdirSync(directory)).toEqual(["store.sqlite"]); +}); + +test("fresh and absent directories do not create legacy databases", async () => { + const directory = temporary(); + await removeLegacyGroupChats(join(directory, "absent")); + await removeLegacyGroupChats(directory); + await removeLegacyGroupChats(directory); + expect(readdirSync(directory)).toEqual([]); +}); + +test("purges archived former/deleted-group private histories without changing direct chats, reviews, calls, counters or session documents", async () => { + const { directory, shared, exclusive } = await fixture(); + const retained = ["member", "former", "deleted"].map((agent) => { + const path = join(directory, "agents", `${agent}.sqlite`); + return [ + rows(path, "SELECT * FROM durable_metadata"), + rows(path, "SELECT * FROM entries WHERE id >= 20"), + rows(path, "SELECT * FROM document_revisions WHERE document_id >= 27"), + rows(path, "SELECT * FROM durable_schema"), + ]; + }); + await removeLegacyGroupChats(directory); + for (const [index, agent] of ["member", "former", "deleted"].entries()) { + const path = join(directory, "agents", `${agent}.sqlite`); + expect(rows(path, "SELECT id FROM conversations ORDER BY id")).toEqual([ + { id: 1 }, + { id: 22 }, + { id: 25 }, + ]); + expect(rows(path, "SELECT id FROM tasks ORDER BY id")).toEqual([ + { id: 21 }, + { id: 24 }, + ]); + expect(rows(path, "SELECT id FROM submissions")).toEqual([]); + expect( + rows(path, "SELECT id FROM record_ids WHERE id < 20 AND id != 1"), + ).toEqual([]); + expect([ + rows(path, "SELECT * FROM durable_metadata"), + rows(path, "SELECT * FROM entries WHERE id >= 20"), + rows(path, "SELECT * FROM document_revisions WHERE document_id >= 27"), + rows(path, "SELECT * FROM durable_schema"), + ]).toEqual(retained[index]!); + } + const store = join(directory, "store.sqlite"); + for (const table of ["group_chats", "group_members", "group_turns"]) + expect(rows(store, `SELECT * FROM ${table}`)).toEqual([]); + expect( + rows( + store, + "SELECT id FROM conversations WHERE id LIKE '%:3' OR id LIKE '%:7'", + ), + ).toEqual([]); + expect(rows(store, "SELECT id FROM agents ORDER BY id")).toEqual([ + { id: "deleted" }, + { id: "former" }, + { id: "member" }, + ]); + expect(rows(store, "SELECT id FROM executions")).toHaveLength(9); + expect(rows(store, "SELECT * FROM pending_reviews")).toHaveLength(9); + expect(rows(store, "SELECT * FROM review_results")).toHaveLength(9); + expect(rows(store, "SELECT id FROM library_files")).toEqual([ + { id: "bot-shared" }, + ]); + expect(rows(store, "SELECT id FROM deleted_library_files")).toEqual([ + { id: "bot-tombstone" }, + ]); + for (const suffix of ["", ".txt", ".pdf.txt"]) { + expect(existsSync(join(directory, "files", `${exclusive}${suffix}`))).toBe( + false, + ); + expect( + readFileSync(join(directory, "files", `${shared}${suffix}`), "utf8"), + ).toBe(`${shared}${suffix} sentinel`); + } + expect(readdirSync(join(directory, "groups"))).toEqual([]); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(false); + await removeLegacyGroupChats(directory); +}); + +test("keeps memories, skill snapshots and revert chains readable and reversible after normalizing provenance", async () => { + const { directory } = await fixture(); + await removeLegacyGroupChats(directory); + const store = new Store(directory); + try { + expect(store.getMemory("retained-memory")?.source).toBeNull(); + expect(store.getSkill("retained-skill")?.sourceExecutionId).toBeNull(); + const change = store.getChange("memory-change")!; + expect(change.source).toEqual({}); + expect(change.actor).toBe("bot"); + expect(change.before).toMatchObject({ content: "before", source: null }); + expect(change.after).toMatchObject({ content: "after", source: null }); + expect(store.getChange("older-revert")?.revertsId).toBe("older-change"); + expect( + store.listChanges("former").find((row) => row.target === "skill")?.after, + ).toMatchObject({ + sourceExecutionId: null, + instructions: "Keep these instructions", + }); + expect( + store.revertChange("memory-change", { actor: "owner" })?.revertsId, + ).toBe("memory-change"); + expect(store.getMemory("retained-memory")?.content).toBe("before"); + expect(store.getMemory("retained-memory")?.source).toBeNull(); + } finally { + store.close(); + } +}); + +test("removes queued group push deliveries but preserves bot notifications, devices and credentials", async () => { + const { directory } = await fixture(); + const path = join(directory, "push.sqlite"); + const device = rows(path, "SELECT * FROM push_devices"); + const settings = rows(path, "SELECT * FROM push_settings"); + await removeLegacyGroupChats(directory); + expect(rows(path, "SELECT id FROM push_outbox")).toEqual([{ id: "bot" }]); + expect(rows(path, "SELECT outbox_id FROM push_delivery")).toEqual([ + { outbox_id: "bot" }, + ]); + expect(rows(path, "SELECT * FROM push_devices")).toEqual(device); + expect(rows(path, "SELECT * FROM push_settings")).toEqual(settings); + expect( + rows(path, "SELECT * FROM chat_views WHERE chat_kind = 'group'"), + ).toEqual([]); + expect( + rows(path, "SELECT * FROM reply_associations WHERE chat_kind = 'group'"), + ).toEqual([]); + expect( + rows( + path, + "SELECT event_id FROM reply_associations WHERE event_id = 'bot'", + ), + ).toEqual([{ event_id: "bot" }]); +}); + +test("reuses an inventory after private data is purged and a file deletion interrupts cleanup", async () => { + const { directory, exclusive } = await fixture(); + const blocked = join(directory, "files", `${exclusive}.pdf.txt`); + rmSync(blocked); + mkdirSync(blocked); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow(); + const manifest = readFileSync( + join(directory, "group-chat-removal.json"), + "utf8", + ); + expect(manifest).toContain("former-execution-3"); + expect(manifest).not.toContain("private group transcript"); + expect( + rows( + join(directory, "agents", "former.sqlite"), + "SELECT id FROM tasks WHERE kind = json_quote('crumble.group-anchor')", + ), + ).toEqual([]); + expect( + rows( + join(directory, "store.sqlite"), + "SELECT id FROM library_files WHERE group_id IS NOT NULL", + ), + ).toHaveLength(2); + rmSync(blocked, { recursive: true }); + await removeLegacyGroupChats(directory); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(false); + expect( + rows( + join(directory, "store.sqlite"), + "SELECT id FROM executions WHERE id LIKE '%-3'", + ), + ).toEqual([]); + expect( + rows(join(directory, "store.sqlite"), "SELECT source FROM memories"), + ).toEqual([{ source: null }]); +}); + +test("rejects unsupported Pi versions and physical shapes before deleting anything", async () => { + for (const change of [ + "UPDATE durable_schema SET version = 99", + "ALTER TABLE tasks ADD COLUMN unknown TEXT", + ]) { + const directory = temporary(); + const path = await privateHistory(directory, "bot"); + const db = new Database(path); + db.run(change); + db.close(); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow( + "Unsupported Pi", + ); + expect(rows(path, "SELECT id FROM conversations WHERE id = 3")).toEqual([ + { id: 3 }, + ]); + expect(existsSync(join(directory, "group-chat-removal.json"))).toBe(false); + } +}); + +test("refuses retained conversations inheriting group history without following group parents upward", async () => { + const directory = temporary(); + const path = await privateHistory(directory, "bot"); + const db = new Database(path); + db.run( + "UPDATE conversations SET record = json_set(record, '$.parent', json_object('conversationId', 1, 'at', 20)) WHERE id = 3", + ); + db.run( + "UPDATE conversations SET record = json_set(record, '$.parent', json_object('conversationId', 3, 'at', 4)) WHERE id = 22", + ); + db.close(); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow( + "retained Pi conversation 22 inherits", + ); + expect(rows(path, "SELECT id FROM conversations")).toHaveLength(5); + const repaired = new Database(path); + repaired.run( + "UPDATE conversations SET record = json_remove(record, '$.parent') WHERE id = 22", + ); + repaired.close(); + await removeLegacyGroupChats(directory); + expect(rows(path, "SELECT id FROM conversations WHERE id = 1")).toEqual([ + { id: 1 }, + ]); +}); + +test("refuses symlinked databases, sidecars and blob paths, and rejects traversal in a restart manifest", async () => { + for (const parts of [ + ["agents"], + ["groups"], + ["store.sqlite"], + ["store.sqlite-wal"], + ]) { + const directory = temporary(); + if (parts[0] === "store.sqlite-wal") + new Database(join(directory, "store.sqlite")).close(); + symlinkSync(join(directory, "outside"), join(directory, ...parts)); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow("symlink"); + } + const { directory, exclusive } = await fixture(); + const blob = join(directory, "files", exclusive); + rmSync(blob); + symlinkSync(join(directory, "outside"), blob); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow("symlink"); + expect( + rows( + join(directory, "store.sqlite"), + "SELECT id FROM library_files WHERE group_id IS NOT NULL", + ), + ).toHaveLength(2); + writeFileSync( + join(directory, "group-chat-removal.json"), + JSON.stringify({ + version: 1, + privateHistories: [], + conversations: [], + executions: [], + hashes: [], + groupFiles: ["../outside.sqlite"], + }), + ); + await expect(removeLegacyGroupChats(directory)).rejects.toThrow(); +}); diff --git a/apps/server/src/app/group-chat-upgrade.ts b/apps/server/src/app/group-chat-upgrade.ts new file mode 100644 index 00000000..4eabf8b3 --- /dev/null +++ b/apps/server/src/app/group-chat-upgrade.ts @@ -0,0 +1,817 @@ +import { Database } from "bun:sqlite"; +import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; +import type { DocumentId } from "@earendil-works/pi-durable"; +import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node"; +import { + closeSync, + fsyncSync, + lstatSync, + openSync, + readdirSync, + readFileSync, + renameSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import { join, resolve } from "node:path"; +import { Schema } from "effect"; +import { + CURRENT_SQLITE_SCHEMA_VERSION, + SQLITE_MIGRATIONS, +} from "@earendil-works/pi-durable/storage/sqlite"; +import { formatEntryId } from "../shared/entry-ids"; + +const LocalId = Schema.Number.check( + Schema.isInt(), + Schema.isBetween({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }), +); + +const Segment = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]+$/)); +const Hash = Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/)); + +const PrivateHistory = Schema.Struct({ + agentId: Segment, + conversations: Schema.Array(LocalId), + tasks: Schema.Array(LocalId), + entries: Schema.Array(LocalId), + submissions: Schema.Array(LocalId), + documents: Schema.Array(LocalId), +}); + +const Manifest = Schema.Struct({ + version: Schema.Literal(1), + privateHistories: Schema.Array(PrivateHistory), + conversations: Schema.Array(Schema.String), + executions: Schema.Array(Schema.String), + hashes: Schema.Array(Hash), + groupFiles: Schema.Array( + Schema.String.check(Schema.isPattern(/^[^/\\]+\.sqlite(?:-(?:wal|shm))?$/)), + ), +}); + +type Manifest = typeof Manifest.Type; + +type PrivateHistory = typeof PrivateHistory.Type; + +function safePath(root: string, ...parts: string[]) { + let path = root; + + for (const part of ["", ...parts]) { + path = join(path, part); + const stat = lstatSync(path, { throwIfNoEntry: false }); + + if (stat?.isSymbolicLink()) + throw new Error(`Group chat cleanup refuses symlink: ${path}`); + } + + return path; +} + +function existingDatabase(root: string, parts: string[], readonly: boolean) { + const path = safePath(root, ...parts); + + if (!lstatSync(path, { throwIfNoEntry: false })) return; + safePath(root, ...parts.slice(0, -1), `${parts.at(-1)}-wal`); + safePath(root, ...parts.slice(0, -1), `${parts.at(-1)}-shm`); + // Cold WAL databases may need writable sidecars even for an inventory-only connection. + const db = new Database(path, { create: false, strict: true }); + db.run(readonly ? "PRAGMA query_only = ON" : "PRAGMA foreign_keys = ON"); + + return db; +} + +function hasColumns(db: Database, table: string, ...columns: string[]) { + const found = db + .query<{ name: string }, []>(`PRAGMA table_info(${table})`) + .all(); + + if (!found.length) return false; + + return columns.every((column) => found.some((row) => row.name === column)); +} + +function ids(db: Database, sql: string): number[] { + return db + .query<{ id: number }, []>(sql) + .all() + .map((row) => row.id); +} + +function validatePi(db: Database) { + if ( + CURRENT_SQLITE_SCHEMA_VERSION !== 2 || + !hasColumns(db, "durable_schema", "version") + ) + throw new Error( + "Unsupported Pi schema for group chat cleanup (expected Pi Durable 1.4.0 / schema 2)", + ); + + const version = db + .query<{ version: number }, []>( + "SELECT max(version) AS version FROM durable_schema", + ) + .get(); + + if (version?.version !== 2) + throw new Error( + "Unsupported Pi schema for group chat cleanup (expected schema 2); upgrade with a compatible server", + ); + const expected = new Database(":memory:"); + + try { + for (const migration of SQLITE_MIGRATIONS) + for (const statement of migration.statements) expected.run(statement); + + for (const table of [ + "durable_metadata", + "record_ids", + "conversations", + "tasks", + "entries", + "submissions", + "documents", + "document_revisions", + ]) { + const sql = `PRAGMA table_info(${table})`; + + const definition = (database: Database) => + database + .query<{ sql: string }, [string]>( + "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", + ) + .get(table) + ?.sql.replaceAll(/\s+/g, " ") + .trim(); + + if ( + JSON.stringify(db.query(sql).all()) !== + JSON.stringify(expected.query(sql).all()) || + definition(db) !== definition(expected) + ) + throw new Error(`Unsupported Pi ${table} shape for group chat cleanup`); + } + + const tables = db + .query<{ name: string }, []>( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'durable_schema' ORDER BY name", + ) + .all(); + + if ( + JSON.stringify(tables) !== + JSON.stringify( + expected + .query( + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", + ) + .all(), + ) + ) + throw new Error("Unsupported Pi tables for group chat cleanup"); + + if (db.query("SELECT 1 FROM sqlite_master WHERE type = 'trigger'").get()) + throw new Error("Unsupported Pi triggers for group chat cleanup"); + } finally { + expected.close(); + } +} + +function guardInheritance(db: Database, selected: ReadonlySet) { + const rows = db + .query<{ id: number; parent: number | null }, []>( + "SELECT id, json_extract(record, '$.parent.conversationId') AS parent FROM conversations", + ) + .all(); + + for (const row of rows) + if ( + !selected.has(row.id) && + row.parent !== null && + selected.has(row.parent) + ) + throw new Error( + `Cannot remove group history: retained Pi conversation ${row.id} inherits from group conversation ${row.parent}. Restore a backup and resolve the inherited history before upgrading.`, + ); +} + +type ReviewInventory = { + path: string; + executions: ReadonlySet; + pending: ReadonlySet; +}; + +async function inventoryReviewConversations( + db: Database, + agentId: string, + reviews: ReviewInventory, +) { + const selected = new Set(reviews.pending); + + const documents = ids( + db, + "SELECT id FROM documents WHERE kind = json_quote('crumble.review-conversation')", + ); + + if (!documents.length) return selected; + + const storage = await openNodeSqliteStorage(reviews.path); + + try { + for (const id of documents) { + // SAFETY: IDs come from the documents table after validating the installed Pi schema. + const document = await storage.document( + id as DocumentId, + "current", + BACKGROUND_CONTEXT, + ); + + if (document?.record.scope.kind !== "conversation") continue; + + const review = Schema.decodeUnknownSync( + Schema.Struct({ + executionId: Schema.NullOr(Schema.String), + groupId: Schema.optionalKey(Schema.NullOr(Schema.String)), + }), + )(document.value); + + if ( + (review.executionId !== null && + reviews.executions.has(review.executionId)) || + review.groupId != null + ) + selected.add( + formatEntryId(agentId, document.record.scope.conversationId), + ); + } + } finally { + await storage.close(BACKGROUND_CONTEXT); + } + + return selected; +} + +async function inventoryPi( + db: Database, + agentId: string, + reviews?: ReviewInventory, +): Promise { + validatePi(db); + + const tasks = new Set( + ids( + db, + "SELECT id FROM tasks WHERE kind = json_quote('crumble.group-anchor')", + ), + ); + + const conversations = new Set(); + + if (reviews) { + const selected = await inventoryReviewConversations(db, agentId, reviews); + + for (const row of db + .query<{ id: number; anchor: number | null }, []>( + "SELECT c.id, t.id AS anchor FROM conversations c LEFT JOIN tasks t ON t.id = c.owner_task_id AND t.kind = json_quote('crumble.review-anchor')", + ) + .all() + .filter((row) => selected.has(formatEntryId(agentId, row.id)))) { + conversations.add(row.id); + + if (row.anchor !== null) tasks.add(row.anchor); + } + } + + const taskRows = db + .query<{ id: number; conversation_id: number; owner: number | null }, []>( + "SELECT id, conversation_id, json_extract(record, '$.owner') AS owner FROM tasks", + ) + .all(); + + const conversationRows = db + .query< + { + id: number; + owner_task_id: number | null; + owner_conversation_id: number | null; + }, + [] + >("SELECT id, owner_task_id, owner_conversation_id FROM conversations") + .all(); + + let changed = true; + + while (changed) { + const size = tasks.size + conversations.size; + + for (const row of conversationRows) + if ( + (row.owner_task_id !== null && tasks.has(row.owner_task_id)) || + (row.owner_conversation_id !== null && + conversations.has(row.owner_conversation_id)) + ) + conversations.add(row.id); + + for (const row of taskRows) + if ( + conversations.has(row.conversation_id) || + (row.owner !== null && tasks.has(row.owner)) + ) + tasks.add(row.id); + changed = tasks.size + conversations.size !== size; + } + + if (conversations.has(1)) + throw new Error( + "Group chat cleanup refuses to remove the Pi root conversation", + ); + guardInheritance(db, conversations); + + const selectedRows = (table: string) => + db + .query<{ id: number; conversation_id: number }, []>( + `SELECT id, conversation_id FROM ${table}`, + ) + .all() + .filter((row) => conversations.has(row.conversation_id)) + .map((row) => row.id); + + const documents = db + .query<{ id: number; scope_kind: string; owner_id: number }, []>( + "SELECT id, scope_kind, owner_id FROM documents", + ) + .all() + .filter( + (row) => + (row.scope_kind === "conversation" && + conversations.has(row.owner_id)) || + (row.scope_kind === "task" && tasks.has(row.owner_id)), + ) + .map((row) => row.id); + + return { + agentId, + conversations: [...conversations], + tasks: [...tasks], + entries: selectedRows("entries"), + submissions: selectedRows("submissions"), + documents, + }; +} + +function inventoryReviewIds( + store: Database, + conversations: Set, + executions: Set, +) { + if (hasColumns(store, "pending_reviews", "execution_id", "conversation_id")) + for (const row of store + .query<{ execution_id: string; conversation_id: string }, []>( + "SELECT execution_id, conversation_id FROM pending_reviews", + ) + .all()) + if (conversations.has(row.conversation_id)) + executions.add(row.execution_id); + + if (hasColumns(store, "review_results", "execution_id")) + for (const row of store + .query<{ execution_id: string }, []>( + "SELECT execution_id FROM review_results", + ) + .all()) { + const parts = row.execution_id.split(":"); + + if ( + parts.length === 4 && + parts[0]!.endsWith("-job") && + conversations.has(`${parts[1]}:${parts[2]}`) + ) + executions.add(row.execution_id); + } +} + +function inventoryStore(store: Database, conversations: Set) { + const executions = new Set(); + const hashes: string[] = []; + + if (hasColumns(store, "group_members", "conversation_id")) + for (const row of store + .query<{ conversation_id: string | null }, []>( + "SELECT conversation_id FROM group_members", + ) + .all()) + if (row.conversation_id) conversations.add(row.conversation_id); + + if (hasColumns(store, "group_turns", "execution_id")) + for (const row of store + .query<{ execution_id: string }, []>( + "SELECT execution_id FROM group_turns", + ) + .all()) + executions.add(row.execution_id); + + if (hasColumns(store, "executions", "id", "conversation_id")) + for (const row of store + .query<{ id: string; conversation_id: string }, []>( + "SELECT id, conversation_id FROM executions", + ) + .all()) + if (conversations.has(row.conversation_id)) executions.add(row.id); + + inventoryReviewIds(store, conversations, executions); + + if (hasColumns(store, "library_files", "hash", "group_id", "agent_id")) + for (const row of store + .query<{ hash: string }, []>( + "SELECT DISTINCT hash FROM library_files WHERE group_id IS NOT NULL", + ) + .all()) + hashes.push(Schema.decodeUnknownSync(Hash)(row.hash)); + + const reviews = hasColumns( + store, + "pending_reviews", + "execution_id", + "agent_id", + "conversation_id", + ) + ? store + .query< + { agent_id: string; conversation_id: string; execution_id: string }, + [] + >("SELECT agent_id, conversation_id, execution_id FROM pending_reviews") + .all() + .filter((row) => executions.has(row.execution_id)) + : []; + + return { executions: [...executions], hashes, reviews }; +} + +async function inventory(root: string): Promise { + const privateHistories: PrivateHistory[] = []; + const agents = safePath(root, "agents"); + + if (lstatSync(agents, { throwIfNoEntry: false })) { + for (const file of readdirSync(agents)) { + if (!file.endsWith(".sqlite")) continue; + const agentId = Schema.decodeUnknownSync(Segment)(file.slice(0, -7)); + const db = existingDatabase(root, ["agents", file], true)!; + + try { + privateHistories.push(await inventoryPi(db, agentId)); + } finally { + db.close(); + } + } + } + + const conversations = new Set( + privateHistories.flatMap((history) => + history.conversations.map((id) => formatEntryId(history.agentId, id)), + ), + ); + + const store = existingDatabase(root, ["store.sqlite"], true); + + let stored: ReturnType = { + executions: [], + hashes: [], + reviews: [], + }; + + try { + if (store) stored = inventoryStore(store, conversations); + } finally { + store?.close(); + } + + for (const [index, history] of privateHistories.entries()) { + const path = safePath(root, "agents", `${history.agentId}.sqlite`); + + const db = existingDatabase( + root, + ["agents", `${history.agentId}.sqlite`], + true, + )!; + + try { + privateHistories[index] = await inventoryPi(db, history.agentId, { + path, + executions: new Set(stored.executions), + pending: new Set( + stored.reviews + .filter((row) => row.agent_id === history.agentId) + .map((row) => row.conversation_id), + ), + }); + + for (const id of privateHistories[index].conversations) + conversations.add(formatEntryId(history.agentId, id)); + } finally { + db.close(); + } + } + + // Reviews can have their own executions and pending rows, too. + const expandedStore = existingDatabase(root, ["store.sqlite"], true); + + try { + if (expandedStore) stored = inventoryStore(expandedStore, conversations); + } finally { + expandedStore?.close(); + } + + const groups = safePath(root, "groups"); + + const groupFiles = lstatSync(groups, { throwIfNoEntry: false }) + ? readdirSync(groups).filter((file) => + /\.sqlite(?:-(?:wal|shm))?$/.test(file), + ) + : []; + + for (const file of groupFiles) safePath(root, "groups", file); + + return Schema.decodeUnknownSync(Manifest)({ + version: 1, + privateHistories, + conversations: [...conversations], + executions: stored.executions, + hashes: stored.hashes, + groupFiles, + }); +} + +function persist(root: string, manifest: Manifest) { + const temporary = safePath(root, "group-chat-removal.json.tmp"); + const file = openSync(temporary, "w", 0o600); + + try { + writeFileSync(file, JSON.stringify(manifest)); + fsyncSync(file); + } finally { + closeSync(file); + } + + renameSync(temporary, safePath(root, "group-chat-removal.json")); + const directory = openSync(root, "r"); + + try { + fsyncSync(directory); + } finally { + closeSync(directory); + } +} + +function removeFile(root: string, ...parts: string[]) { + const path = safePath(root, ...parts); + + if (lstatSync(path, { throwIfNoEntry: false })) unlinkSync(path); +} + +function deleteIds( + db: Database, + table: string, + column: string, + selected: readonly (string | number)[], +) { + if (!hasColumns(db, table, column)) return; + const statement = db.query(`DELETE FROM ${table} WHERE ${column} = ?`); + + for (const id of selected) statement.run(id); +} + +function purgePi(root: string, history: PrivateHistory) { + if (history.conversations.includes(1)) + throw new Error( + "Group chat cleanup refuses to remove the Pi root/direct conversation, including on manifest replay", + ); + + const db = existingDatabase( + root, + ["agents", `${history.agentId}.sqlite`], + false, + ); + + if (!db) return; + + try { + validatePi(db); + guardInheritance(db, new Set(history.conversations)); + db.transaction(() => { + deleteIds(db, "document_revisions", "document_id", history.documents); + + for (const [table, selected] of [ + ["documents", history.documents], + ["entries", history.entries], + ["submissions", history.submissions], + ["tasks", history.tasks], + ["conversations", history.conversations], + ] as const) { + deleteIds(db, table, "id", selected); + deleteIds(db, "record_ids", "id", selected); + } + })(); + } finally { + db.close(); + } +} + +function purgePush(root: string) { + const db = existingDatabase(root, ["push.sqlite"], false); + + if (!db) return; + + try { + db.transaction(() => { + const events = new Set(); + + if (hasColumns(db, "reply_associations", "event_id", "chat_kind")) + for (const row of db + .query<{ event_id: string }, []>( + "SELECT event_id FROM reply_associations WHERE chat_kind = 'group'", + ) + .all()) + events.add(row.event_id); + + if (hasColumns(db, "push_outbox", "id", "event_id", "event_json")) { + for (const row of db + .query<{ id: string; event_id: string; group_event: number }, []>( + `SELECT id, event_id, EXISTS (SELECT 1 FROM json_tree(event_json) WHERE (key = 'groupId' AND type != 'null') OR (key IN ('origin', 'kind') AND value = 'group')) AS group_event FROM push_outbox`, + ) + .all()) { + if (!events.has(row.event_id) && !row.group_event) continue; + deleteIds(db, "reply_associations", "event_id", [row.event_id]); + deleteIds(db, "push_delivery", "outbox_id", [row.id]); + deleteIds(db, "push_outbox", "id", [row.id]); + } + } + + for (const table of ["chat_views", "reply_associations"]) + if (hasColumns(db, table, "chat_kind")) + db.run(`DELETE FROM ${table} WHERE chat_kind = 'group'`); + })(); + } finally { + db.close(); + } +} + +function normalizeProvenance(db: Database, manifest: Manifest) { + if (hasColumns(db, "memories", "source")) + db.run( + "UPDATE memories SET source = NULL WHERE json_extract(source, '$.kind') = 'group'", + ); + + if (hasColumns(db, "skills", "source_execution_id")) + for (const id of manifest.executions) + db.query( + "UPDATE skills SET source_execution_id = NULL WHERE source_execution_id = ?", + ).run(id); + + if ( + !hasColumns(db, "learned_changes", "source", "before_state", "after_state") + ) + return; + db.run( + "UPDATE learned_changes SET source = json_remove(source, '$.groupId') WHERE source IS NOT NULL", + ); + + for (const [key, selected] of [ + ["executionId", manifest.executions], + ["conversationId", manifest.conversations], + ] as const) + for (const id of selected) + db.query( + `UPDATE learned_changes SET source = json_remove(source, '$.${key}') WHERE json_extract(source, '$.${key}') = ?`, + ).run(id); + + for (const column of ["before_state", "after_state"]) { + db.run( + `UPDATE learned_changes SET ${column} = json_set(${column}, '$.source', NULL) WHERE target = 'memory' AND json_extract(${column}, '$.source.kind') = 'group'`, + ); + + for (const id of manifest.executions) + db.query( + `UPDATE learned_changes SET ${column} = json_set(${column}, '$.sourceExecutionId', NULL) WHERE target = 'skill' AND json_extract(${column}, '$.sourceExecutionId') = ?`, + ).run(id); + } +} + +function purgeStore(root: string, manifest: Manifest) { + const db = existingDatabase(root, ["store.sqlite"], false); + + if (!db) return; + + try { + if (hasColumns(db, "library_files", "group_id", "agent_id", "hash")) { + for (const hash of manifest.hashes) { + if ( + db + .query( + "SELECT 1 FROM library_files WHERE agent_id IS NOT NULL AND hash = ?", + ) + .get(hash) + ) + continue; + + for (const suffix of ["", ".txt", ".pdf.txt"]) + removeFile(root, "files", `${hash}${suffix}`); + } + } + + db.transaction(() => { + normalizeProvenance(db, manifest); + + for (const table of ["library_files", "deleted_library_files"]) + if (hasColumns(db, table, "group_id")) + db.run(`DELETE FROM ${table} WHERE group_id IS NOT NULL`); + + for (const table of ["group_turns", "group_members", "group_chats"]) + if (hasColumns(db, table)) db.run(`DELETE FROM ${table}`); + + for (const table of ["pending_reviews", "review_results"]) + deleteIds(db, table, "execution_id", manifest.executions); + deleteIds( + db, + "pending_reviews", + "conversation_id", + manifest.conversations, + ); + deleteIds(db, "executions", "id", manifest.executions); + deleteIds(db, "conversations", "id", manifest.conversations); + })(); + } finally { + db.close(); + } +} + +function completedUpgrade(root: string) { + const store = existingDatabase(root, ["store.sqlite"], true); + + if (!store) return false; + + try { + return ( + hasColumns(store, "__drizzle_migrations", "name") && + !!store + .query("SELECT 1 FROM __drizzle_migrations WHERE name = ?") + .get("20261122205418_remove_group_chats") + ); + } finally { + store.close(); + } +} + +export async function removeLegacyGroupChats( + accountDirectory: string, +): Promise { + const root = resolve(accountDirectory); + + if (!lstatSync(safePath(root), { throwIfNoEntry: false })) return; + const path = safePath(root, "group-chat-removal.json"); + + if (!lstatSync(path, { throwIfNoEntry: false }) && completedUpgrade(root)) + return; + + const manifest = lstatSync(path, { throwIfNoEntry: false }) + ? Schema.decodeUnknownSync(Schema.fromJsonString(Manifest))( + readFileSync(path, "utf8"), + ) + : await inventory(root); + + const store = existingDatabase(root, ["store.sqlite"], true); + + try { + if (store && hasColumns(store, "conversations", "id", "chat")) + for (const id of new Set([ + ...manifest.conversations, + ...manifest.privateHistories.flatMap((history) => + history.conversations.map((local) => + formatEntryId(history.agentId, local), + ), + ), + ])) + if ( + store + .query("SELECT 1 FROM conversations WHERE id = ? AND chat = 1") + .get(id) + ) + throw new Error( + `Group chat cleanup refuses to remove direct conversation ${id}`, + ); + } finally { + store?.close(); + } + + for (const history of manifest.privateHistories) + if (history.conversations.includes(1)) + throw new Error( + "Group chat cleanup refuses to remove the Pi root/direct conversation, including on manifest replay", + ); + persist(root, manifest); + + for (const history of manifest.privateHistories) purgePi(root, history); + + for (const file of manifest.groupFiles) removeFile(root, "groups", file); + purgePush(root); + purgeStore(root, manifest); + removeFile(root, "group-chat-removal.json"); +} diff --git a/apps/server/src/app/product-layer.ts b/apps/server/src/app/product-layer.ts index 843bf07f..22b82af1 100644 --- a/apps/server/src/app/product-layer.ts +++ b/apps/server/src/app/product-layer.ts @@ -10,7 +10,6 @@ import { ConversationRepository } from "../bot-store/conversation-repository"; import { ExecutionRepository } from "../bot-store/execution-repository"; import { AgentCredentialRepository } from "../credentials/agent-credential-repository"; import { SecretRepository } from "../secrets/secret-repository"; -import { GroupChatRepository } from "../group-chats/group-chat-repository"; import { McpServerRepository } from "../integrations/mcp-server-repository"; import { MemoryRepository } from "../memory/memory-repository"; import { PasswordManagerRepository } from "../password-managers/password-manager-repository"; @@ -68,7 +67,6 @@ export const productLayer = (dataDir: string) => { DesktopControlRepository.layer, ConversationRepository.layer, ExecutionRepository.layer, - GroupChatRepository.layer, LibraryRepository.layer, ).pipe(Layer.provideMerge(database)); diff --git a/apps/server/src/app/server.test.ts b/apps/server/src/app/server.test.ts index 386f4524..b6fe81e8 100644 --- a/apps/server/src/app/server.test.ts +++ b/apps/server/src/app/server.test.ts @@ -7,12 +7,16 @@ import { scheduleInput } from "../contract/schedules"; import { ScriptRunRepository } from "../automations/script-run-repository"; import { DEFAULT_SERVER_SETTINGS } from "./server-settings"; import { createTenant } from "./tenant"; +import { createAuth } from "./auth"; +import { Database } from "bun:sqlite"; import { CLIENT_DOCUMENT_PATH } from "../integrations/mcp-oauth"; import { ownerRecord } from "./data-lock"; import { + existsSync, mkdirSync, mkdtempSync, readdirSync, + readFileSync, rmSync, writeFileSync, } from "node:fs"; @@ -20,7 +24,6 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { agentResponse, - groupChatResponse, historyResponse, modelResponse, providerResponse, @@ -331,66 +334,215 @@ test.serial( }, ); -test.serial("serves group chats and keeps them across restarts", async () => { - const dataDir = mkdtempSync(join(tmpdir(), "crumble-server-groups-")); - +async function upgradeAccounts(dataDir: string) { + const accounts = await createAuth(dataDir, "http://localhost:7337"); + const paths: string[] = []; try { - const running = await startServer({ dataDir, port: 0 }); - const headers = await signUp(running); - const memberIds: string[] = []; + for (const name of ["first", "second"]) { + const { user } = await accounts.auth.api.signUpEmail({ + body: { + name, + email: `${name}@example.test`, + password: "correct horse battery staple", + }, + headers: new Headers(), + }); + const path = join(dataDir, "users", user.id); + mkdirSync(join(path, "groups"), { recursive: true }); + writeFileSync( + join(path, "groups", "orphan.sqlite-wal"), + "legacy transcript", + ); + paths.push(path); + } + } finally { + accounts.close(); + } + return paths; +} - for (const name of ["Planner", "Researcher"]) { - const response = await fetch(new URL("/v1/agents", running.server.url), { - method: "POST", - headers: json(headers), - body: JSON.stringify({ name }), +test.serial( + "all accounts finish offline cleanup before the first worker starts", + async () => { + const dataDir = mkdtempSync(join(tmpdir(), "crumble-upgrade-barrier-")); + let running: Running | undefined; + try { + const paths = await upgradeAccounts(dataDir); + let started = 0; + running = await startServer({ + dataDir, + port: 0, + workspaces: () => + Effect.sync(() => { + for (const path of paths) { + expect( + existsSync(join(path, "groups", "orphan.sqlite-wal")), + ).toBe(false); + expect(existsSync(join(path, "group-chat-removal.json"))).toBe( + false, + ); + } + started++; + return undefined; + }), }); + expect(started).toBe(2); + } finally { + await running?.close(); + rmSync(dataDir, { recursive: true, force: true }); + } + }, +); - expect(response.status).toBe(201); - memberIds.push(agentResponse.parse(await response.json()).id); +test.serial( + "failed cleanup in any account prevents every tenant and push database from starting", + async () => { + const dataDir = mkdtempSync(join(tmpdir(), "crumble-upgrade-failed-")); + try { + const paths = await upgradeAccounts(dataDir); + const last = [...paths].sort().at(-1)!; + writeFileSync( + join(last, "group-chat-removal.json"), + "interrupted invalid manifest", + ); + let started = 0; + await expect( + startServer({ + dataDir, + port: 0, + workspaces: () => + Effect.sync(() => { + started++; + return undefined; + }), + }), + ).rejects.toThrow(); + expect(started).toBe(0); + for (const path of paths) { + expect(existsSync(join(path, "store.sqlite"))).toBe(false); + expect(existsSync(join(path, "push.sqlite"))).toBe(false); + } + } finally { + rmSync(dataDir, { recursive: true, force: true }); } + }, +); - const created = await fetch( - new URL("/v1/group-chats", running.server.url), - { - method: "POST", - headers: json(headers), - body: JSON.stringify({ name: "Trip", memberIds }), - }, +test.serial( + "direct tenant initialization fails before migrations or workers on unsafe legacy data", + async () => { + const dataDir = mkdtempSync( + join(tmpdir(), "crumble-tenant-upgrade-failed-"), ); + let started = 0; + try { + mkdirSync(join(dataDir, "agents")); + const unsupported = new Database(join(dataDir, "agents", "bot.sqlite")); + unsupported.run( + "CREATE TABLE durable_schema (version INTEGER); INSERT INTO durable_schema VALUES (99)", + ); + unsupported.close(); + await expect( + createTenant({ + dataDir, + tenantId: "test", + workspaceEnv: {}, + serverSettings: () => DEFAULT_SERVER_SETTINGS, + workspaces: Effect.sync(() => { + started++; + return undefined; + }), + }), + ).rejects.toThrow("Unsupported Pi"); + expect(started).toBe(0); + expect(existsSync(join(dataDir, "store.sqlite"))).toBe(false); + expect(existsSync(join(dataDir, "push.sqlite"))).toBe(false); + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }, +); - expect(created.status).toBe(201); - const group = groupChatResponse.parse(await created.json()); +test.serial( + "restart deletes legacy groups but preserves their member bots", + async () => { + const dataDir = mkdtempSync(join(tmpdir(), "crumble-server-groups-")); - const message = await fetch( - new URL(`/v1/group-chats/${group.id}/messages`, running.server.url), - { - method: "POST", - headers: json(headers), - body: JSON.stringify({ - content: "Hello", - requestId: crypto.randomUUID(), - }), - }, - ); + try { + const running = await startServer({ dataDir, port: 0 }); + const headers = await signUp(running); + const memberIds: string[] = []; - expect(message.status).toBe(201); - await running.close(); - const reopened = await startServer({ dataDir, port: 0 }); + for (const name of ["Planner", "Researcher"]) { + const response = await fetch( + new URL("/v1/agents", running.server.url), + { + method: "POST", + headers: json(headers), + body: JSON.stringify({ name }), + }, + ); - const history = await fetch( - new URL(`/v1/group-chats/${group.id}/history`, reopened.server.url), - { headers }, - ); + expect(response.status).toBe(201); + memberIds.push(agentResponse.parse(await response.json()).id); + } - expect(historyResponse.parse(await history.json()).messages).toMatchObject([ - { content: "Hello" }, - ]); - await reopened.close(); - } finally { - rmSync(dataDir, { recursive: true, force: true }); - } -}); + await running.close(); + const account = readdirSync(join(dataDir, "users"))[0]!; + const accountPath = join(dataDir, "users", account); + const legacy = readFileSync( + new URL("../../test/fixtures/legacy-store-schema.sql", import.meta.url), + "utf8", + ); + const database = new Database(join(accountPath, "store.sqlite")); + for (const table of ["group_chats", "group_members", "group_turns"]) + database.run( + legacy + .split("\n") + .find((line) => line.startsWith(`CREATE TABLE ${table} `))!, + ); + database.run( + "DELETE FROM __drizzle_migrations WHERE name = '20261122205418_remove_group_chats'; INSERT INTO group_chats (id, name, created_at, updated_at) VALUES ('legacy', 'Trip', 'now', 'now')", + ); + database.close(); + mkdirSync(join(accountPath, "groups"), { recursive: true }); + writeFileSync( + join(accountPath, "groups", "legacy.sqlite"), + "legacy shared transcript", + ); + const reopened = await startServer({ dataDir, port: 0 }); + + const history = await fetch( + new URL("/v1/group-chats/legacy/history", reopened.server.url), + { headers }, + ); + + try { + expect(history.status).toBe(404); + const groups = await fetch( + new URL("/v1/group-chats", reopened.server.url), + { headers }, + ); + expect(groups.status).toBe(404); + expect(existsSync(join(accountPath, "groups", "legacy.sqlite"))).toBe( + false, + ); + for (const id of memberIds) { + const bot = await fetch( + new URL(`/v1/agents/${id}`, reopened.server.url), + { headers }, + ); + expect(bot.status).toBe(200); + expect(agentResponse.parse(await bot.json()).id).toBe(id); + } + } finally { + await reopened.close(); + } + } finally { + rmSync(dataDir, { recursive: true, force: true }); + } + }, +); test.serial( "a desktop viewer link opens without the owner's session", diff --git a/apps/server/src/app/server.ts b/apps/server/src/app/server.ts index de8f63ee..75da9845 100644 --- a/apps/server/src/app/server.ts +++ b/apps/server/src/app/server.ts @@ -18,6 +18,7 @@ import { viewerPathOwner, } from "../bot-desktop/desktop-viewer"; import { createTenant } from "./tenant"; +import { removeLegacyGroupChats } from "./group-chat-upgrade"; import { emulateDirectoriesOverlap, type EmulateProfile, @@ -206,10 +207,14 @@ async function restoreTenants( if (!existsSync(usersDir)) return; - for (const entry of readdirSync(usersDir, { withFileTypes: true })) { - if (entry.isDirectory() && accounts.hasUser(entry.name)) - await tenant(entry.name); - } + const accountsToRestore = readdirSync(usersDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && accounts.hasUser(entry.name)) + .map((entry) => entry.name); + + for (const id of accountsToRestore) + await removeLegacyGroupChats(accountDir(dataDir, id)); + + for (const id of accountsToRestore) await tenant(id); } const outdatedWorkspaces = async (tenants: Map>) => diff --git a/apps/server/src/app/tenant.ts b/apps/server/src/app/tenant.ts index a319543e..eb2d67e7 100644 --- a/apps/server/src/app/tenant.ts +++ b/apps/server/src/app/tenant.ts @@ -6,7 +6,6 @@ import { BotRuntime } from "../bots/runtime"; import { Bots, botsAccess } from "../bots/bots"; import { BotMessaging } from "../bot-messaging/bot-messaging"; import { BotActivity } from "../bots/bot-activity"; -import { groupConversations } from "../group-chats/group-turns"; import { reviewConversations } from "../learning/review-kind"; import { BotExtensions } from "../bot-ports/bot-extensions"; import { reactionTools } from "../bots/reaction"; @@ -22,9 +21,6 @@ import { Automations } from "../automations/automations"; import { AutomationDispatch } from "../automations/automation-dispatch"; import { ScriptRuns, scriptRunRetention } from "../automations/script-runs"; import { createAPI, type ApiServices } from "./api"; -import { GroupChats, GroupTranscriptStore } from "../group-chats/group-chats"; -import { groupLookupTools } from "../group-chats/group-lookup"; -import { GroupTranscripts } from "../group-chats/group-transcripts"; import { historyTools } from "../history/history-tools"; import { BotSkills } from "../skills/skills"; import { LearningReview, learningReviews } from "../learning/learning-review"; @@ -100,6 +96,7 @@ import { eventPayloadTools } from "../automations/event-tools"; import { usesDesktop } from "../contract/tools"; import type { ServerSettings } from "./server-settings"; import type { EmulateProfile } from "../providers/emulate-profile"; +import { removeLegacyGroupChats } from "./group-chat-upgrade"; export type TenantOptions = { emulate?: EmulateProfile | undefined; @@ -235,11 +232,7 @@ function accountLayer(options: TenantOptions, dataDir: string) { return BotRuntime.layer(join(dataDir, "agents"), { jobExtensions: (agent) => jobExtensions(jobKinds, agent).job, - conversationKinds: () => [ - groupConversations(), - reviewConversations(), - callConversations(), - ], + conversationKinds: () => [reviewConversations(), callConversations()], env: (agent, target, context) => conversationEnv(jobKinds, agent, target, context), }); @@ -272,14 +265,6 @@ function accountLayer(options: TenantOptions, dataDir: string) { const scheduler = Scheduler.layer.pipe(Layer.provide(automations)); - const groups = GroupChats.layer.pipe( - Layer.provide( - GroupTranscriptStore.layer( - () => new GroupTranscripts(join(dataDir, "groups")), - ), - ), - ); - const schedules = BotSchedules.layer; const botRequests = BotRequests.layer; @@ -315,7 +300,6 @@ function accountLayer(options: TenantOptions, dataDir: string) { scheduleTools, eventPayloadTools, botRequestTools, - groupLookupTools, historyTools, desktopKeepAwake, desktopScreenshotTools, @@ -336,7 +320,7 @@ function accountLayer(options: TenantOptions, dataDir: string) { botSecretUseRetention, ); - const conversations = Layer.mergeAll(scheduler, groups, activity); + const conversations = Layer.mergeAll(scheduler, activity); /** Tools whose sandboxes must close after the bot runtime that uses them. */ const sandboxedTools = Layer.mergeAll( @@ -401,7 +385,6 @@ const removeAccountWorkspaces = Effect.fnUntraced(function* ( const resumeAccount = Effect.fnUntraced(function* (scheduler: SchedulerAccess) { yield* (yield* Bots).recover; yield* (yield* ScriptRuns).recover; - yield* (yield* GroupChats).recover; yield* (yield* MessageGateway).start; yield* (yield* EventRelay).start; yield* (yield* EventDispatcher).start; @@ -417,6 +400,8 @@ export async function createTenant( mkdirSync(dataDir, { recursive: true, mode: 0o700 }); chmodSync(dataDir, 0o700); + await removeLegacyGroupChats(dataDir); + const account = ManagedRuntime.make(accountLayer(options, dataDir)); try { diff --git a/apps/server/src/bot-desktop/desktop-screenshot.ts b/apps/server/src/bot-desktop/desktop-screenshot.ts index 1d6da06f..2197ebc9 100644 --- a/apps/server/src/bot-desktop/desktop-screenshot.ts +++ b/apps/server/src/bot-desktop/desktop-screenshot.ts @@ -9,7 +9,6 @@ import { import { defineExtension, defineTool } from "@earendil-works/pi-durable"; import { Effect, Layer } from "effect"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; -import { chatOnly } from "../shared/chat-only"; import { BotWorkspaces, type Workspaces } from "../workspaces/workspace"; import type { DesktopShell } from "./computer-use"; import { @@ -161,10 +160,7 @@ export function desktopScreenshotExtension( }, }); - // A group's transcript can't show the image. - return chatOnly( - defineExtension({ name: "desktop-screenshot", tools: [screenshot] }), - ); + return defineExtension({ name: "desktop-screenshot", tools: [screenshot] }); } export const desktopScreenshotTools = Layer.effectDiscard( diff --git a/apps/server/src/bot-messaging/bot-messaging.test.ts b/apps/server/src/bot-messaging/bot-messaging.test.ts index d1e5de7a..ac2cdaf4 100644 --- a/apps/server/src/bot-messaging/bot-messaging.test.ts +++ b/apps/server/src/bot-messaging/bot-messaging.test.ts @@ -132,11 +132,11 @@ test("rejects disabled and ambiguous name recipients", async () => { store.close(); }); -test("send resolves IDs, exact names, and @mentions and deduplicates task requests", async () => { +test("send resolves IDs, normalized names, and @mentions and deduplicates task requests", async () => { const { messaging, store } = setup(); const first = await messaging.send(ids.source, { - recipient: "@Bot2", + recipient: "@Bot2", message: "How do you feel?", requestId: "ask-1", }); diff --git a/apps/server/src/bot-messaging/bot-messaging.ts b/apps/server/src/bot-messaging/bot-messaging.ts index 0ebf7bb5..b474494c 100644 --- a/apps/server/src/bot-messaging/bot-messaging.ts +++ b/apps/server/src/bot-messaging/bot-messaging.ts @@ -26,7 +26,6 @@ import { type AppError, } from "../shared/errors"; import { BOT_TOOL } from "../contract/tools"; -import { normalize } from "../group-chats/group-mentions"; import { MAX_MESSAGE_CHARS, MAX_WAIT_SECONDS } from "../shared/limits"; import { delegationStore } from "./delegation-store"; @@ -43,6 +42,8 @@ type JobQuestionAnswered = { agentId: string; agent: string; job: string }; const JOB_POLL_MS = 500; +const normalize = (text: string) => text.normalize("NFKC").toLowerCase(); + const addressed = (recipient: string) => recipient.trim().replace(/^@/, ""); /** Throws the abort reason once the tool call is cancelled, as Pi tools do. */ diff --git a/apps/server/src/bot-messaging/coordination.ts b/apps/server/src/bot-messaging/coordination.ts index b286b956..d8feee97 100644 --- a/apps/server/src/bot-messaging/coordination.ts +++ b/apps/server/src/bot-messaging/coordination.ts @@ -4,7 +4,6 @@ import { EXECUTION_STATUSES } from "../shared/domain"; import { type Agent } from "../contract/agents"; import { Effect, Layer } from "effect"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; -import { chatOnly } from "../shared/chat-only"; import { BotMessaging } from "./bot-messaging"; import { toolOutput } from "../shared/tool-output"; import { BOT_TOOL } from "../contract/tools"; @@ -165,12 +164,10 @@ export function coordinationExtension(agent: Agent, messaging: Messaging) { answerJobQuestionTool(agent, messaging), ]; - return chatOnly( - defineExtension({ - name: "coordination", - tools: agent.tools.includes(BOT_TOOL.delegate) ? tools : [], - }), - ); + return defineExtension({ + name: "coordination", + tools: agent.tools.includes(BOT_TOOL.delegate) ? tools : [], + }); } export const coordinationTools = Layer.effectDiscard( diff --git a/apps/server/src/bot-ports/bot-extensions.ts b/apps/server/src/bot-ports/bot-extensions.ts index 3d6e41fb..e6e698f6 100644 --- a/apps/server/src/bot-ports/bot-extensions.ts +++ b/apps/server/src/bot-ports/bot-extensions.ts @@ -53,7 +53,6 @@ export class BotExtensions extends Context.Service< export const ExtensionPosition = { integrations: 10, coordination: 20, - groupLookup: 30, historyTools: 40, schedules: 50, eventPayload: 55, diff --git a/apps/server/src/bots/bots-admission.ts b/apps/server/src/bots/bots-admission.ts index 77109bfa..2823f325 100644 --- a/apps/server/src/bots/bots-admission.ts +++ b/apps/server/src/bots/bots-admission.ts @@ -3,7 +3,7 @@ import { Cause, Effect, FiberMap, Option } from "effect"; import type { Agent } from "../contract/agents"; import type { Execution } from "../shared/domain"; import { errorText } from "../shared/errors"; -import { groupTurnScope, parseRequestId } from "../shared/request-ids"; +import { parseRequestId } from "../shared/request-ids"; import type { InputOrigin } from "../transcript/origins"; import { frameInput } from "./input-framing"; import { isChatTurn, type BotsContext } from "./bots-context"; @@ -68,11 +68,7 @@ export const botsAdmission = (context: BotsContext, deps: AdmissionDeps) => { const files = attachments.kind === "files" && attachments.ids.length - ? yield* runtime.resolveFiles( - owner.id, - attachments.ids, - groupTurnScope(execution.requestId, owner.id), - ) + ? yield* runtime.resolveFiles(owner.id, attachments.ids) : []; const event = yield* eventInput(execution); diff --git a/apps/server/src/bots/bots-context.ts b/apps/server/src/bots/bots-context.ts index 6ecbf997..da943d88 100644 --- a/apps/server/src/bots/bots-context.ts +++ b/apps/server/src/bots/bots-context.ts @@ -21,16 +21,12 @@ import { BotRuntime } from "./runtime"; import { Library } from "../files/library"; import { ChatAttention } from "../push/chat-attention"; -export const isGroupTurn = (execution: Execution) => - parseRequestId(execution.requestId).kind === "group-turn"; - /** A turn in an outside call's conversation: what the callee said. */ export const isCallTurn = (execution: Pick) => parseRequestId(execution.requestId).kind === "outside-call"; -/** A bot chat turn, whose previews and replies reach the owner's activity; group and call turns are not. */ -export const isChatTurn = (execution: Execution) => - !isGroupTurn(execution) && !isCallTurn(execution); +/** A bot chat turn, whose previews and replies reach the owner's activity; call turns are not. */ +export const isChatTurn = (execution: Execution) => !isCallTurn(execution); export type BotsContext = { readonly attention: ChatAttention["Service"]; diff --git a/apps/server/src/bots/bots-submissions.ts b/apps/server/src/bots/bots-submissions.ts index ba416bfd..72744b4c 100644 --- a/apps/server/src/bots/bots-submissions.ts +++ b/apps/server/src/bots/bots-submissions.ts @@ -3,7 +3,6 @@ import type { Agent } from "../contract/agents"; import { pi } from "../shared/app-errors"; import { MAX_IMAGE_BYTES, attachmentKind } from "../shared/attachment-rules"; import { fileIdDigest } from "../shared/attachments"; -import { groupTurnScope } from "../shared/request-ids"; import { validTimezone } from "../contract/cron"; import type { Execution } from "../shared/domain"; import { @@ -100,7 +99,7 @@ export const botsSubmissions = (context: BotsContext, deps: SubmissionDeps) => { if (existing && differsFrom(existing, content, replyTo, attachmentsDigest)) return yield* conflict(REQUEST_ID_REUSED); - if (!existing && files.length && !groupTurnScope(requestId, owner.id)) { + if (!existing && files.length) { yield* runtime.validateFiles(owner.id, files); yield* refuseUnreadableImages(owner, files); } diff --git a/apps/server/src/bots/chat.test.ts b/apps/server/src/bots/chat.test.ts index c0aa2b5d..294b8b8a 100644 --- a/apps/server/src/bots/chat.test.ts +++ b/apps/server/src/bots/chat.test.ts @@ -1,5 +1,4 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { openGroupConversation } from "../group-chats/group-turns"; import { mkdtempSync, rmSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; @@ -167,92 +166,72 @@ async function settle( return status(); } -for (const groupTurn of [false, true]) { - test(`library tool reads only allowed files in a ${groupTurn ? "group turn" : "bot chat"}`, async () => { - const seen: string[] = []; - let selected = ""; - const { service, agent, store, library } = setup([ - () => - fauxAssistantMessage(fauxToolCall("library", { action: "list" }), { - stopReason: "toolUse", - }), - (context) => { - seen.push(JSON.stringify(context.messages.at(-1)?.content)); - return fauxAssistantMessage( - fauxToolCall("library", { action: "read", id: selected }), - { stopReason: "toolUse" }, - ); +test("library tool reads only the bot chat library", async () => { + const seen: string[] = []; + let selected = ""; + const { service, agent, store, library } = setup([ + () => + fauxAssistantMessage(fauxToolCall("library", { action: "list" }), { + stopReason: "toolUse", + }), + (context) => { + seen.push(JSON.stringify(context.messages.at(-1)?.content)); + return fauxAssistantMessage( + fauxToolCall("library", { action: "read", id: selected }), + { stopReason: "toolUse" }, + ); + }, + (context) => { + seen.push(JSON.stringify(context.messages.at(-1)?.content)); + return fauxAssistantMessage("Read it."); + }, + ]); + const other = store.createAgent({ + name: "Other", + description: "", + instructions: "", + provider: "faux", + model: "chat", + enabled: true, + tools: [], + skills: [], + mcpServers: [], + delegates: [], + }); + const own = await Effect.runPromise( + library.upload( + { kind: "bot", agentId: agent.id }, + { + name: "own-notes.txt", + mimeType: "text/plain", + body: new Blob(["own secret"]).stream(), }, - (context) => { - seen.push(JSON.stringify(context.messages.at(-1)?.content)); - return fauxAssistantMessage("Read it."); + ), + ); + await Effect.runPromise( + library.upload( + { kind: "bot", agentId: other.id }, + { + name: "foreign-notes.txt", + mimeType: "text/plain", + body: new Blob(["foreign secret"]).stream(), }, - ]); - const other = store.createAgent({ - name: "Other", - description: "", - instructions: "", - provider: "faux", - model: "chat", - enabled: true, - tools: [], - skills: [], - mcpServers: [], - delegates: [], - }); - const group = store.createGroupChat({ - name: "Shared", - memberIds: [agent.id, other.id], - }); - const own = await Effect.runPromise( - library.upload( - { kind: "bot", agentId: agent.id }, - { - name: "own-notes.txt", - mimeType: "text/plain", - body: new Blob(["own secret"]).stream(), - }, - ), - ); - const shared = await Effect.runPromise( - library.upload( - { kind: "group", groupId: group.id }, - { - name: "group-notes.txt", - mimeType: "text/plain", - body: new Blob(["group secret"]).stream(), - }, - ), - ); - await Effect.runPromise( - library.upload( - { kind: "bot", agentId: other.id }, - { - name: "foreign-notes.txt", - mimeType: "text/plain", - body: new Blob(["foreign secret"]).stream(), - }, - ), - ); - selected = groupTurn ? shared.file.id : own.file.id; - const chat = groupTurn - ? await openGroupConversation(service.runtime, agent, group.id) - : (await service.chat(agent.id)).id; - const submission = await service.runtime.submit( - agent, - chat, - "Read my file", - crypto.randomUUID(), - ); - expect((await service.runtime.wait(submission, agent)).status).toBe("done"); - expect(seen[0]).toContain("own-notes.txt"); - expect(seen[0]).not.toContain("foreign-notes.txt"); - if (groupTurn) expect(seen[0]).toContain("group-notes.txt"); - else expect(seen[0]).not.toContain("group-notes.txt"); - expect(seen[1]).toContain(groupTurn ? "group secret" : "own secret"); - await service.close(); - }); -} + ), + ); + selected = own.file.id; + const chat = (await service.chat(agent.id)).id; + const submission = await service.runtime.submit( + agent, + chat, + "Read my file", + crypto.randomUUID(), + ); + expect((await service.runtime.wait(submission, agent)).status).toBe("done"); + expect(seen[0]).toContain("own-notes.txt"); + expect(seen[0]).not.toContain("foreign-notes.txt"); + expect(seen[1]).toContain("own secret"); + await service.close(); +}); describe("continuous bot chat", () => { test("keeps the full transcript visible after compaction", async () => { @@ -665,60 +644,6 @@ describe("activity", () => { }); }); -describe("group turns", () => { - test("announce nothing and report when they settle", async () => { - const { service, store, agent } = setup([ - fauxAssistantMessage("For the group."), - ]); - - const reference = await openGroupConversation( - service.runtime, - agent, - "group-1", - ); - - store.createConversation({ agentId: agent.id, title: "Group" }, reference); - const events: unknown[] = []; - const settled: string[] = []; - service.onActivity((event) => events.push(event)); - service.onSettled((execution) => { - settled.push(execution.status); - }); - - const execution = await service.send(reference, "hello", "group-turn:1"); - - expect(await settle(service, execution.id)).toBe("done"); - - await until(() => settled.length > 0); - expect(settled).toEqual(["done"]); - expect(events).toEqual([]); - await service.close(); - }); - - test("report a cancelled execution as settled", async () => { - const { service, store, agent } = setup([() => new Promise(() => {})]); - - const reference = await openGroupConversation( - service.runtime, - agent, - "group-1", - ); - - store.createConversation({ agentId: agent.id, title: "Group" }, reference); - const settled: string[] = []; - service.onSettled((execution) => { - settled.push(execution.status); - }); - - const execution = await service.send(reference, "hello", "group-turn:1"); - - await service.abort(reference); - expect(store.getExecution(execution.id)?.status).toBe("cancelled"); - await service.close(); - expect(settled).toEqual(["cancelled"]); - }); -}); - describe("message gateways", () => { test("a gateway message keeps owner authority and names its gateway", async () => { const seen: unknown[] = []; diff --git a/apps/server/src/bots/runtime-behavior.test.ts b/apps/server/src/bots/runtime-behavior.test.ts index da0c628c..197ced31 100644 --- a/apps/server/src/bots/runtime-behavior.test.ts +++ b/apps/server/src/bots/runtime-behavior.test.ts @@ -1,5 +1,5 @@ import { Effect } from "effect"; -import { openGroupConversation } from "../group-chats/group-turns"; +import { defineAnchorTask } from "../shared/anchor-task"; import { afterEach, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -714,15 +714,19 @@ test("a turn running in another conversation leaves the chat's answers in its hi const a = makeAgent(); const chat = await runtime.openChat(a); - const group = await openGroupConversation(runtime, a, "group-1"); + const other = await runtime.openAnchored( + a, + defineAnchorTask("test.concurrent-anchor"), + async () => {}, + ); faux.setResponses([ fauxAssistantMessage([fauxToolCall("blocked", {})], { stopReason: "toolUse", }), fauxAssistantMessage("The chat's answer."), - fauxAssistantMessage("The group turn's answer."), + fauxAssistantMessage("The private turn's answer."), ]); - const turn = await runtime.submit(a, group, "group turn", "group-input"); + const turn = await runtime.submit(a, other, "private turn", "private-input"); await started; const asked = await runtime.submit(a, chat, "chat turn", "chat-input"); diff --git a/apps/server/src/bots/runtime.ts b/apps/server/src/bots/runtime.ts index ffca2996..6d7f3c57 100644 --- a/apps/server/src/bots/runtime.ts +++ b/apps/server/src/bots/runtime.ts @@ -67,7 +67,6 @@ import { import { SkillReads, skillTool } from "../skills/skill-library"; import { BotSkills } from "../skills/skills"; import { skillManageTool } from "../skills/skill-manage"; -import type { LibraryRef } from "../files/library-repository"; import { FileStore } from "../files/file-store"; import { Library } from "../files/library"; import { libraryExtension } from "../files/library-tool"; @@ -113,7 +112,6 @@ export type RuntimeCallbacks = MemoryStore & { resolveFiles: ( agentId: string, ids: readonly string[], - library?: LibraryRef, ) => Effect.Effect; existingFiles: ( agentId: string, @@ -395,8 +393,8 @@ export class AgentRuntime { return this.callbacks.validateFiles(agentId, ids); } - resolveFiles(agentId: string, ids: readonly string[], library?: LibraryRef) { - return this.callbacks.resolveFiles(agentId, ids, library); + resolveFiles(agentId: string, ids: readonly string[]) { + return this.callbacks.resolveFiles(agentId, ids); } private async currentFiles(agentId: string, messages: TranscriptMessage[]) { @@ -478,17 +476,11 @@ export class AgentRuntime { return { next, installed }; } - private libraryTools(agent: Agent, ownOnly = false) { + private libraryTools(agent: Agent) { return libraryExtension({ agent, library: this.callbacks.library, - libraries: ({ groupId }) => - groupId && !ownOnly - ? [ - { kind: "group", groupId }, - { kind: "bot", agentId: agent.id }, - ] - : [{ kind: "bot", agentId: agent.id }], + libraries: () => [{ kind: "bot", agentId: agent.id }], workspace: agent.tools.includes(BOT_TOOL.coding) || agent.tools.includes(BOT_TOOL.desktop), @@ -537,7 +529,7 @@ export class AgentRuntime { ) { return defineExtension({ name: JOB_KNOWLEDGE_EXTENSION, - tools: [skill, ...(this.libraryTools(choices.agent, true).tools ?? [])], + tools: [skill, ...(this.libraryTools(choices.agent).tools ?? [])], sections: [ { key: "bot_knowledge", @@ -1281,11 +1273,11 @@ export class BotRuntime extends Context.Service()( library, validateFiles: (agentId, ids) => library.validate({ kind: "bot", agentId }, ids), - resolveFiles: (agentId, ids, ref) => + resolveFiles: (agentId, ids) => resolveMessageFiles( library, fileStore, - ref ?? { kind: "bot", agentId }, + { kind: "bot", agentId }, ids, ), existingFiles: (agentId, ids) => diff --git a/apps/server/src/contract/api-contract.ts b/apps/server/src/contract/api-contract.ts index fb19bd31..e120543d 100644 --- a/apps/server/src/contract/api-contract.ts +++ b/apps/server/src/contract/api-contract.ts @@ -13,7 +13,6 @@ import { secretInput, } from "./secrets"; import { reasoningPreviewInput, reasoningPreviewResponse } from "./reasoning"; -import { groupChatInput } from "./group-chats"; import { scheduleInput } from "./schedules"; import { schedulePreviewInput, @@ -168,14 +167,6 @@ export const messageInput = messageFields path: ["content"], }); -/** `replyTo` names a message in the same group; replying to a bot's message also wakes that bot. */ -export const groupMessageInput = messageFields - .strict() - .refine((value) => value.content || value.files.length, { - message: "Write a message or attach a file", - path: ["content"], - }); - export const credentialUsesInput = z.object({ limit: z.coerce.number().int().min(1).max(200).default(50), before: z.string().min(1).max(200).optional(), @@ -885,34 +876,6 @@ export const routes = { request: { params: id.extend({ fileId: z.uuid() }) }, responses: { 204: empty }, }), - uploadGroupFile: define({ - method: "post", - path: "/v1/group-chats/{id}/files", - operationId: "uploadGroupFile", - request: { params: id, headers: fileHeaders, body: rawFileBody }, - responses: { 201: json(response.uploadFileResponse) }, - }), - listGroupFiles: define({ - method: "get", - path: "/v1/group-chats/{id}/files", - operationId: "listGroupFiles", - request: { params: id, query: filePageInput }, - responses: { 200: json(z.array(response.libraryFileResponse)) }, - }), - getGroupFile: define({ - method: "get", - path: "/v1/group-chats/{id}/files/{fileId}", - operationId: "getGroupFile", - request: { params: id.extend({ fileId: z.uuid() }) }, - responses: { 200: fileBytes }, - }), - deleteGroupFile: define({ - method: "delete", - path: "/v1/group-chats/{id}/files/{fileId}", - operationId: "deleteGroupFile", - request: { params: id.extend({ fileId: z.uuid() }) }, - responses: { 204: empty }, - }), attachment: define({ method: "get", path: "/v1/agents/{id}/attachments/{entryId}/{index}", @@ -997,88 +960,6 @@ export const routes = { }, }, }), - listGroupChats: define({ - method: "get", - path: "/v1/group-chats", - operationId: "listGroupChats", - responses: { 200: json(z.array(response.groupChatResponse)) }, - }), - createGroupChat: define({ - method: "post", - path: "/v1/group-chats", - operationId: "createGroupChat", - request: { body: body(groupChatInput) }, - responses: { 201: json(response.groupChatResponse) }, - }), - getGroupChat: define({ - method: "get", - path: "/v1/group-chats/{id}", - operationId: "getGroupChat", - request: { params: id }, - responses: { 200: json(response.groupChatResponse) }, - }), - updateGroupChat: define({ - method: "patch", - path: "/v1/group-chats/{id}", - operationId: "updateGroupChat", - request: { params: id, body: body(patchInput(groupChatInput)) }, - responses: { 200: json(response.groupChatResponse) }, - }), - deleteGroupChat: define({ - method: "delete", - path: "/v1/group-chats/{id}", - operationId: "deleteGroupChat", - request: { params: id }, - responses: { 204: empty }, - }), - groupChatSnapshot: define({ - method: "get", - path: "/v1/group-chats/{id}/chat", - operationId: "getGroupChatSnapshot", - request: { params: id, query: snapshotInput }, - responses: { 200: json(response.groupChatSnapshotResponse) }, - }), - groupChatHistory: define({ - method: "get", - path: "/v1/group-chats/{id}/history", - operationId: "getGroupChatHistory", - request: { params: id, query: historyInput }, - responses: { 200: json(response.historyResponse) }, - }), - sendGroupMessage: define({ - method: "post", - path: "/v1/group-chats/{id}/messages", - operationId: "sendGroupMessage", - request: { params: id, body: body(groupMessageInput) }, - responses: { 201: json(response.groupMessageReceiptResponse) }, - }), - stopGroupChat: define({ - method: "post", - path: "/v1/group-chats/{id}/stop", - operationId: "stopGroupChat", - description: - "Ends every running bot turn in the group and drops the queued ones. The group is not paused; the next message starts turns again.", - request: { params: id }, - responses: { 204: empty }, - }), - groupChatEvents: define({ - method: "get", - path: "/v1/group-chats/{id}/events", - operationId: "streamGroupChatEvents", - "x-sse-events": { - snapshot: { $ref: "#/components/schemas/GroupChatSnapshot" }, - heartbeat: { $ref: "#/components/schemas/HeartbeatEvent" }, - }, - description: - "Server-sent events. Each snapshot event carries a GroupChatSnapshot JSON object in data, sent on connection and after every change. Heartbeat events carry {} every 15 seconds. Authenticate with the Authorization header. Reconnect by fetching the current snapshot; there is no Last-Event-ID replay.", - request: { params: id, query: snapshotInput }, - responses: { - 200: { - description: "SSE stream, not a JSON array", - content: { "text/event-stream": { schema: z.string() } }, - }, - }, - }), agentCredentials: define({ method: "get", path: "/v1/agents/{id}/credentials", diff --git a/apps/server/src/contract/api-responses.ts b/apps/server/src/contract/api-responses.ts index 21053b7d..9ec0ecff 100644 --- a/apps/server/src/contract/api-responses.ts +++ b/apps/server/src/contract/api-responses.ts @@ -171,7 +171,7 @@ const origin = z .object({ kind: z.string().openapi({ description: - "Where the message came from: owner, task, event (an event automation's prompt), script (a script task's result), credential, bot, group, call (a voice gateway call ended, which starts a bot turn), call_request (the owner declined a call request), or callee (what the callee of an outside call said, in that call's conversation only). Clients may receive other values later.", + "Where the message came from: owner, task, event (an event automation's prompt), script (a script task's result), credential, bot, call (a voice gateway call ended, which starts a bot turn), call_request (the owner declined a call request), or callee (what the callee of an outside call said, in that call's conversation only). Clients may receive other values later.", }), name: z.string().optional(), agentId: z.string().optional(), @@ -316,13 +316,6 @@ const message = z "Provider-specific tool details, including nested code-mode calls. A successful `desktop_screenshot` result has `{ mimeType, size }`; read its image from `GET /v1/agents/{id}/attachments/{entryId}/0`.", }), presentation: messagePresentation.optional(), - sources: z - .array(z.object({ url: z.string(), title: z.string() })) - .optional() - .openapi({ - description: - "In a group chat, the pages the sending bot searched or read in the turn that wrote the message.", - }), }) .openapi("TranscriptMessage"); @@ -481,53 +474,6 @@ export const chatSnapshotResponse = historyResponse }) .openapi("ChatSnapshot"); -export const groupChatResponse = z - .object({ - id: z.string(), - name: z.string(), - memberIds: strings.openapi({ - description: "Member bots in the order they joined.", - }), - createdAt: z.string(), - updatedAt: z.string(), - }) - .openapi("GroupChat"); - -export const groupActivityResponse = z - .object({ - paused: z.boolean().openapi({ - description: - "Bot-started turns used up the turn budget; the owner's next message resumes the group.", - }), - botTurns: z.number().openapi({ - description: "Bot-started turns since the owner's last message.", - }), - members: z.array( - z - .object({ - agentId: z.string(), - status: z.enum(["idle", "queued", "running", "disabled"]), - error: z.string().nullable().openapi({ - description: "Why the member's latest turn failed.", - }), - }) - .openapi("GroupMemberActivity"), - ), - }) - .openapi("GroupActivity"); - -export const groupChatSnapshotResponse = historyResponse - .extend({ - groupChat: groupChatResponse, - activity: groupActivityResponse, - updatedAt: z.number(), - }) - .openapi("GroupChatSnapshot"); - -export const groupMessageReceiptResponse = z - .object({ requestId: z.string(), entryId: z.string() }) - .openapi("GroupMessageReceipt"); - export const executionResponse = z .object({ id: z.string(), @@ -586,16 +532,14 @@ const memorySourceResponse = z .object({ kind: z.enum(MEMORY_SOURCE_KINDS), name: z.string().optional().openapi({ - description: - "The task, bot, or group chat, as named when the memory was saved.", + description: "The task or bot, as named when the memory was saved.", }), scheduleId: z.string().optional().openapi({ description: "For `task`." }), agentId: z.string().optional().openapi({ description: "For `bot`." }), - groupId: z.string().optional().openapi({ description: "For `group`." }), }) .openapi("MemorySource", { description: - "Where the memory was saved: the owner's bot chat, the owner directly, a scheduled task, another bot's request, or a group chat.", + "Where the memory was saved: the owner's bot chat, the owner directly, a scheduled task, or another bot's request.", }); export const credentialResponse = z @@ -756,7 +700,7 @@ export const visionModelResponse = z .nullable() .openapi({ description: - "The model that describes images for bots whose model can't read them. Null when off: such bots refuse images in their chat and get only an image's name in group chats.", + "The model that describes images for bots whose model can't read them. Null when off: such bots refuse images in their chat.", }), choices: z.array(visionChoice).openapi({ description: @@ -901,7 +845,6 @@ const changeSourceResponse = z .object({ executionId: z.string().nullable().optional(), conversationId: z.string().nullable().optional(), - groupId: z.string().nullable().optional(), }) .openapi("ChangeSource"); @@ -1290,10 +1233,6 @@ export const eventSchemas: { artifact: "pins-event.schema.json", }, { schema: chatSnapshotResponse, artifact: "chat-snapshot.schema.json" }, - { - schema: groupChatSnapshotResponse, - artifact: "group-chat-snapshot.schema.json", - }, { schema: desktopControlResponse, artifact: "desktop-control.schema.json" }, { schema: voiceGatewayConfigEvent, diff --git a/apps/server/src/contract/group-chats.ts b/apps/server/src/contract/group-chats.ts deleted file mode 100644 index 64695dd5..00000000 --- a/apps/server/src/contract/group-chats.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { z } from "zod"; -import { - MAX_GROUP_MEMBERS, - MAX_GROUP_NAME_CHARS, - MIN_GROUP_MEMBERS, -} from "../shared/limits"; - -export const groupChatInput = z.object({ - name: z.string().trim().min(1).max(MAX_GROUP_NAME_CHARS), - memberIds: z - .array(z.uuid()) - .min(MIN_GROUP_MEMBERS) - .max(MAX_GROUP_MEMBERS) - .refine((ids) => new Set(ids).size === ids.length, "List each bot once"), -}); diff --git a/apps/server/src/contract/limits.ts b/apps/server/src/contract/limits.ts index d5a75c21..d3865343 100644 --- a/apps/server/src/contract/limits.ts +++ b/apps/server/src/contract/limits.ts @@ -16,8 +16,6 @@ export const { MAX_BOT_DESCRIPTION_CHARS, MAX_BOT_NAME_CHARS, MAX_CRON_CHARS, - MAX_GROUP_MEMBERS, - MAX_GROUP_NAME_CHARS, MAX_INSTRUCTIONS_CHARS, MAX_MEMORY_CHARS, MAX_MESSAGE_CHARS, @@ -25,7 +23,6 @@ export const { MAX_SCHEDULE_NAME_CHARS, MAX_SCHEDULE_TIMEOUT_SECONDS, MAX_SKILL_NAME_CHARS, - MIN_GROUP_MEMBERS, } = limits; export const MAX_MCP_SERVER_NAME_CHARS = 100; diff --git a/apps/server/src/contract/message-files.test.ts b/apps/server/src/contract/message-files.test.ts index 55a69828..f23b0ae9 100644 --- a/apps/server/src/contract/message-files.test.ts +++ b/apps/server/src/contract/message-files.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; -import { groupMessageInput, messageInput } from "./api-contract"; +import { messageInput } from "./api-contract"; -test("bot and group messages accept file IDs and reject base64 attachments", () => { +test("bot messages accept file IDs and reject base64 attachments", () => { const requestId = crypto.randomUUID(); const fileId = crypto.randomUUID(); expect( @@ -12,11 +12,7 @@ test("bot and group messages accept file IDs and reject base64 attachments", () .success, ).toBe(false); expect( - groupMessageInput.safeParse({ requestId, content: "", files: [fileId] }) - .success, - ).toBe(true); - expect( - groupMessageInput.safeParse({ + messageInput.safeParse({ requestId, content: "", attachments: [{ name: "a.txt", mimeType: "text/plain", data: "YQ==" }], diff --git a/apps/server/src/contract/push.ts b/apps/server/src/contract/push.ts index 429b9a4f..be45fb9b 100644 --- a/apps/server/src/contract/push.ts +++ b/apps/server/src/contract/push.ts @@ -7,7 +7,7 @@ import { import { body, define, empty, json } from "./route"; export const chatReference = z.object({ - kind: z.enum(["bot", "group"]), + kind: z.literal("bot"), id: z.string().min(1), }); diff --git a/apps/server/src/contract/reply-event.ts b/apps/server/src/contract/reply-event.ts index a35cb988..edcf6963 100644 --- a/apps/server/src/contract/reply-event.ts +++ b/apps/server/src/contract/reply-event.ts @@ -4,7 +4,6 @@ import { WAITING_FOR } from "../shared/domain"; /** Reply origins that name neither a job kind nor a message's origin; the rest are stored kinds, never renamed. */ export const REPLY_ORIGIN = { bot: "bot", - group: "group", } as const; export const replyEvent = z @@ -17,7 +16,7 @@ export const replyEvent = z entryId: z.string().nullable(), origin: z.string().openapi({ description: - "What the bot answered: owner (a message from the owner), task (a scheduled task), script (a script task's result), bot (another bot's request), group (a group chat turn), or coding or desktop (a job's report; jobName names the job). Clients may receive other values later.", + "What the bot answered: owner (a message from the owner), task (a scheduled task), script (a script task's result), bot (another bot's request), or coding or desktop (a job's report; jobName names the job). Clients may receive other values later.", }), preview: z.string(), createdAt: z.string(), @@ -26,11 +25,6 @@ export const replyEvent = z description: "The job whose report the bot answered, for origin coding or desktop. A desktop job's report often asks for the owner; clients may open the bot desktop.", }), - groupId: z.string().optional().openapi({ - description: - "Set when a bot answered in a group chat; open the group rather than the bot chat.", - }), - groupName: z.string().optional(), waitingFor: z.enum(WAITING_FOR).optional().openapi({ description: "Set when the bot waits for the owner's answer: approval (a desktop job action held by an intent check, or a call request), credential, or login (a request the owner saves or declines). Clients may receive other values later.", @@ -51,11 +45,8 @@ export type ReplyActivity = { origin: string; preview: string; createdAt: string; - /** Set for a bot's answer in a group chat; clients open the group instead of the bot chat. */ - groupId?: string; /** Set for a bot's answer to a coding or desktop job's report (origin `coding` or `desktop`): the job's name. */ jobName?: string; - groupName?: string; /** Set when the reply waits for the owner's answer: a held desktop action or call request, or a credential or login request. */ waitingFor?: WaitingFor; }; @@ -65,8 +56,6 @@ export function canonicalReplyEvent( serverId: string, ): ReplyEvent { return { - ...(activity.groupId && { groupId: activity.groupId }), - ...(activity.groupName && { groupName: activity.groupName }), ...(activity.jobName && { jobName: activity.jobName }), ...(activity.waitingFor && { waitingFor: activity.waitingFor }), type: "reply", diff --git a/apps/server/src/contract/user-preferences.ts b/apps/server/src/contract/user-preferences.ts index 1af100dc..dc6684fc 100644 --- a/apps/server/src/contract/user-preferences.ts +++ b/apps/server/src/contract/user-preferences.ts @@ -8,8 +8,8 @@ export type Theme = (typeof THEMES)[number]; /** Messages allows nine pins: three rows of three. */ export const MAX_PINS = 9; -/** A pinned conversation: `agent:` or `group:`. */ -export const pinKey = z.string().regex(/^(agent|group):\S+$/); +/** A pinned bot chat: `agent:`. */ +export const pinKey = z.string().regex(/^agent:\S+$/); /** The pinned conversations in order, first pin first. */ export const pinnedConversations = z diff --git a/apps/server/src/files/files-api.test.ts b/apps/server/src/files/files-api.test.ts index ef8d0c64..78d50845 100644 --- a/apps/server/src/files/files-api.test.ts +++ b/apps/server/src/files/files-api.test.ts @@ -47,7 +47,6 @@ function setup() { delegates: [], }); - const group = store.createGroupChat({ name: "G", memberIds: [agent.id] }); const scope = Scope.makeUnsafe(); const core = store.runtime.runSync(Effect.context()); @@ -67,13 +66,11 @@ function setup() { () => Effect.runSync(Scope.close(scope, Exit.void)), ); - const describe = (kind: "bot" | "group", id: string) => + const describe = (_kind: "bot", id: string) => Effect.runPromise( Library.use((library) => library.describe( - kind === "bot" - ? { kind: "bot", agentId: agent.id } - : { kind: "group", groupId: group.id }, + { kind: "bot", agentId: agent.id }, id, "Bot-only description", ), @@ -85,11 +82,10 @@ function setup() { bot: `/v1/agents/${agent.id}/files`, describe, other: `/v1/agents/${other.id}/files`, - group: `/v1/group-chats/${group.id}/files`, }; } -for (const kind of ["bot", "group"] as const) { +for (const kind of ["bot"] as const) { test(`${kind} file routes stream, deduplicate, isolate and delete`, async () => { const env = setup(); const path = env[kind]; diff --git a/apps/server/src/files/files-api.ts b/apps/server/src/files/files-api.ts index 64d0cdb1..d3950a56 100644 --- a/apps/server/src/files/files-api.ts +++ b/apps/server/src/files/files-api.ts @@ -140,39 +140,6 @@ export function registerFileRoutes({ c.req.param("fileId"), ); - return c.body(null, 204); - }); - register( - routes.uploadGroupFile, - function* (c) { - return c.json( - yield* upload({ kind: "group", groupId: c.req.param("id") }, c.req.raw), - 201, - ); - }, - { parsesBody: true }, - ); - register(routes.listGroupFiles, function* (c) { - return c.json( - yield* list( - { kind: "group", groupId: c.req.param("id") }, - c.req.valid("query"), - ), - 200, - ); - }); - register(routes.getGroupFile, function* (c) { - return yield* download( - { kind: "group", groupId: c.req.param("id") }, - c.req.param("fileId"), - ); - }); - register(routes.deleteGroupFile, function* (c) { - yield* remove( - { kind: "group", groupId: c.req.param("id") }, - c.req.param("fileId"), - ); - return c.body(null, 204); }); } diff --git a/apps/server/src/files/library-cleanup.test.ts b/apps/server/src/files/library-cleanup.test.ts index 1a9c5a3d..c6894806 100644 --- a/apps/server/src/files/library-cleanup.test.ts +++ b/apps/server/src/files/library-cleanup.test.ts @@ -7,8 +7,6 @@ import { Store } from "../../test/support/store"; import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; import { AgentRuntime } from "../bots/runtime"; import { standaloneBots } from "../bots/bots-test-support"; -import { standaloneGroupChats } from "../group-chats/group-chats-test-support"; -import { GroupTranscripts } from "../group-chats/group-transcripts"; import { Library } from "./library"; import { FileStore } from "./file-store"; import { AgentRepository } from "../bot-store/agent-repository"; @@ -23,12 +21,8 @@ function setup() { const store = new Store(dir); const runtime = new AgentRuntime(join(dir, "agents"), runtimeCallbacks()); const bots = standaloneBots(store, runtime); - const transcripts = new GroupTranscripts(join(dir, "groups")); - const groups = standaloneGroupChats(bots, transcripts); cleanups.push(() => rmSync(dir, { recursive: true, force: true })); cleanups.push(() => bots.close()); - cleanups.push(() => transcripts.close()); - cleanups.push(() => groups.close()); const agent = store.createAgent({ name: "Ada", description: "", @@ -41,11 +35,11 @@ function setup() { mcpServers: [], delegates: [], }); - const group = store.createGroupChat({ name: "Group", memberIds: [agent.id] }); + const otherBot = store.duplicateAgent(agent.id, "Grace")!; const library = store.run(Library); const files = store.run(FileStore); const bot: LibraryRef = { kind: "bot", agentId: agent.id }; - const shared: LibraryRef = { kind: "group", groupId: group.id }; + const shared: LibraryRef = { kind: "bot", agentId: otherBot.id }; const upload = (ref: LibraryRef) => Effect.runPromise( library.upload(ref, { @@ -57,14 +51,12 @@ function setup() { return { store, bots, - groups, library, files, bot, shared, upload, agent, - group, }; } @@ -108,7 +100,7 @@ test("owner deletion holds the lock until new uploads can no longer create entri expect((await next)._tag).toBe("NotFound"); }); -for (const kind of ["bot", "group"] as const) { +for (const kind of ["bot"] as const) { test(`deleting a ${kind} removes its library and unshared bytes`, async () => { const fixture = setup(); const ref = kind === "bot" ? fixture.bot : fixture.shared; @@ -116,8 +108,7 @@ for (const kind of ["bot", "group"] as const) { const entry = ( await Effect.runPromise(fixture.library.entries(ref, [uploaded.file.id])) ).get(uploaded.file.id)!; - if (kind === "bot") await fixture.bots.deleteAgent(fixture.agent.id); - else await fixture.groups.delete(fixture.group.id); + await fixture.bots.deleteAgent(fixture.agent.id); expect( (await Effect.runPromise(fixture.library.entries(ref, [entry.id]))).size, ).toBe(0); @@ -137,8 +128,7 @@ for (const kind of ["bot", "group"] as const) { const other = kind === "bot" ? fixture.shared : fixture.bot; await fixture.upload(own); const retained = await fixture.upload(other); - if (kind === "bot") await fixture.bots.deleteAgent(fixture.agent.id); - else await fixture.groups.delete(fixture.group.id); + await fixture.bots.deleteAgent(fixture.agent.id); const download = await Effect.runPromise( fixture.library.download(other, retained.file.id), ); diff --git a/apps/server/src/files/library-repository.test.ts b/apps/server/src/files/library-repository.test.ts index ef170bf5..3f22867c 100644 --- a/apps/server/src/files/library-repository.test.ts +++ b/apps/server/src/files/library-repository.test.ts @@ -74,15 +74,12 @@ test("add with the same hash in one library twice returns existed: true and keep ).toEqual([first.entry]); }); -test("removeUnreferenced preserves bytes shared between bot and group libraries", async () => { +test("removeUnreferenced preserves bytes shared between bot libraries", async () => { const { runtime, library, store, agent } = setup(); - const group = store.createGroupChat({ - name: "Shared", - memberIds: [agent.id], - }); + const otherBot = store.duplicateAgent(agent.id, "Grace")!; - const groupLibrary: LibraryRef = { kind: "group", groupId: group.id }; + const otherLibrary: LibraryRef = { kind: "bot", agentId: otherBot.id }; await runtime.runPromise( Effect.gen(function* () { const files = yield* FileStore; @@ -106,9 +103,9 @@ test("removeUnreferenced preserves bytes shared between bot and group libraries" const botEntry = yield* repo.add({ ...input, library }); - const groupEntry = yield* repo.add({ + const otherEntry = yield* repo.add({ ...input, - library: groupLibrary, + library: otherLibrary, }); yield* repo.remove(library, botEntry.entry.id); @@ -118,7 +115,7 @@ test("removeUnreferenced preserves bytes shared between bot and group libraries" "shared bytes", ); expect(yield* files.text(hash)).toBe("extracted text"); - yield* repo.remove(groupLibrary, groupEntry.entry.id); + yield* repo.remove(otherLibrary, otherEntry.entry.id); yield* files.removeUnreferenced(hash); expect((yield* files.bytes(hash).pipe(Effect.flip))._tag).toBe( "NotFound", diff --git a/apps/server/src/files/library-repository.ts b/apps/server/src/files/library-repository.ts index 3d442ff6..8170d367 100644 --- a/apps/server/src/files/library-repository.ts +++ b/apps/server/src/files/library-repository.ts @@ -5,9 +5,7 @@ import { nowIso } from "../shared/time"; import { newFileId } from "./ids"; import { deletedLibraryFiles, libraryFiles } from "./schema"; -export type LibraryRef = - | { kind: "bot"; agentId: string } - | { kind: "group"; groupId: string }; +export type LibraryRef = { kind: "bot"; agentId: string }; export type LibraryEntry = { id: string; @@ -22,16 +20,11 @@ export type LibraryEntry = { }; const owner = (library: LibraryRef) => - library.kind === "bot" - ? eq(libraryFiles.agentId, library.agentId) - : eq(libraryFiles.groupId, library.groupId); + eq(libraryFiles.agentId, library.agentId); const entryOf = (row: typeof libraryFiles.$inferSelect): LibraryEntry => ({ id: row.id, - library: - row.agentId !== null - ? { kind: "bot", agentId: row.agentId } - : { kind: "group", groupId: row.groupId! }, + library: { kind: "bot", agentId: row.agentId }, name: row.name, mimeType: row.mimeType, size: row.size, @@ -100,10 +93,7 @@ export class LibraryRepository extends Context.Service< .insert(libraryFiles) .values({ id: newFileId(), - agentId: - input.library.kind === "bot" ? input.library.agentId : null, - groupId: - input.library.kind === "group" ? input.library.groupId : null, + agentId: input.library.agentId, name: input.name, mimeType: input.mimeType, size: input.size, @@ -175,7 +165,6 @@ export class LibraryRepository extends Context.Service< yield* db.insert(deletedLibraryFiles).values({ id: row.id, agentId: row.agentId, - groupId: row.groupId, name: row.name, }); @@ -209,9 +198,7 @@ export class LibraryRepository extends Context.Service< .where( and( eq(deletedLibraryFiles.id, id), - library.kind === "bot" - ? eq(deletedLibraryFiles.agentId, library.agentId) - : eq(deletedLibraryFiles.groupId, library.groupId), + eq(deletedLibraryFiles.agentId, library.agentId), ), ); diff --git a/apps/server/src/files/library-tool.test.ts b/apps/server/src/files/library-tool.test.ts index a2295ced..92ec3ce9 100644 --- a/apps/server/src/files/library-tool.test.ts +++ b/apps/server/src/files/library-tool.test.ts @@ -41,14 +41,11 @@ function setup() { }); const agent = make("Ada"); const other = make("Grace"); - const group = store.createGroupChat({ - name: "Group", - memberIds: [agent.id, other.id], - }); + const sharedOwner = make("Hopper"); const library = store.run(Library.use(Effect.succeed)); const bot: LibraryRef = { kind: "bot", agentId: agent.id }; const ownOther: LibraryRef = { kind: "bot", agentId: other.id }; - const shared: LibraryRef = { kind: "group", groupId: group.id }; + const shared: LibraryRef = { kind: "bot", agentId: sharedOwner.id }; const scope = (libraries: LibraryRef[] = [bot], workspace = false) => ({ library, libraries, @@ -159,10 +156,10 @@ test("search bounds matches and returns continuation offsets", async () => { expect(next.matches[0]?.offset).toBe(parsed.nextOffset); }); -test("bot and group scopes expose only the allowed libraries with labels", async () => { +test("bot scopes expose only the allowed libraries with labels", async () => { const { bot, ownOther, shared, scope, upload } = setup(); const own = await upload(bot, "own.txt", "own"); - const group = await upload(shared, "group.txt", "group"); + const sharedFile = await upload(shared, "shared.txt", "shared"); const foreign = await upload(ownOther, "foreign.txt", "foreign"); expect( listSchema @@ -173,11 +170,11 @@ test("bot and group scopes expose only the allowed libraries with labels", async await libraryAction(scope([bot, shared]), { action: "list" }), ); expect(combined.files.map((file) => file.id)).toEqual([ - group.file.id, + sharedFile.file.id, own.file.id, ]); expect(combined.files.map((file) => file.library.kind)).toEqual([ - "group", + "bot", "bot", ]); await expect( @@ -447,7 +444,9 @@ test("listing two interleaved libraries returns every file exactly once", async ids.push((await upload(bot, `own-${i}.txt`, `own ${i}`)).file.id); if (i % 3 === 0) - ids.push((await upload(shared, `group-${i}.txt`, `group ${i}`)).file.id); + ids.push( + (await upload(shared, `shared-${i}.txt`, `shared ${i}`)).file.id, + ); } const seen: string[] = []; diff --git a/apps/server/src/files/library-tool.ts b/apps/server/src/files/library-tool.ts index eb92f2fb..07b91bb7 100644 --- a/apps/server/src/files/library-tool.ts +++ b/apps/server/src/files/library-tool.ts @@ -5,7 +5,6 @@ import type { Context, JsonValue } from "@earendil-works/chord"; import { getOrThrow, type ExecutionEnv } from "@earendil-works/pi-durable/env"; import { Effect } from "effect"; import type { Agent } from "../contract/agents"; -import { groupOf } from "../group-chats/group-conversation"; import { toolOutput } from "../shared/tool-output"; import { WORKSPACE_PATH } from "../../workspace-image/guest"; import type { Library } from "./library"; @@ -473,7 +472,7 @@ export async function libraryAction( export function libraryExtension(options: { agent: Agent; library: Library["Service"]; - libraries: (context: { groupId: string | null }) => LibraryRef[]; + libraries: () => LibraryRef[]; workspace: boolean; }) { const actions = options.workspace @@ -498,7 +497,6 @@ export function libraryExtension(options: { }), replay: "unsafe", execute: async (args, api, context) => { - const groupId = await groupOf(api, api.conversationId, context); let environment: Environment | undefined; if (api.env) environment = { env: api.env, context }; @@ -507,7 +505,7 @@ export function libraryExtension(options: { await libraryAction( { library: options.library, - libraries: options.libraries({ groupId: groupId ?? null }), + libraries: options.libraries(), workspace: options.workspace, }, args, diff --git a/apps/server/src/files/library.test.ts b/apps/server/src/files/library.test.ts index 98224030..2df6170e 100644 --- a/apps/server/src/files/library.test.ts +++ b/apps/server/src/files/library.test.ts @@ -32,7 +32,7 @@ test("deleted names survive reopening and remain scoped to the library", async ( }); const library: LibraryRef = { kind: "bot", agentId: bot.id }; - const group = store.createGroupChat({ name: "Group", memberIds: [bot.id] }); + const otherBot = store.duplicateAgent(bot.id, "Grace")!; const uploaded = await store.runtime.runPromise( Library.use((service) => @@ -61,7 +61,7 @@ test("deleted names survive reopening and remain scoped to the library", async ( const foreign = await reopened.runtime.runPromise( Library.use((service) => - service.validate({ kind: "group", groupId: group.id }, [ + service.validate({ kind: "bot", agentId: otherBot.id }, [ uploaded.file.id, ]), ).pipe(Effect.flip), @@ -90,12 +90,12 @@ for (const sameLibrary of [true, false]) { delegates: [], }); - const group = store.createGroupChat({ name: "Group", memberIds: [bot.id] }); + const otherBot = store.duplicateAgent(bot.id, "Grace")!; const library: LibraryRef = { kind: "bot", agentId: bot.id }; const other: LibraryRef = sameLibrary ? library - : { kind: "group", groupId: group.id }; + : { kind: "bot", agentId: otherBot.id }; const bytes = await Bun.file( new URL("../../test/fixtures/text.pdf", import.meta.url), diff --git a/apps/server/src/files/library.ts b/apps/server/src/files/library.ts index 5523441b..fce572ce 100644 --- a/apps/server/src/files/library.ts +++ b/apps/server/src/files/library.ts @@ -1,6 +1,5 @@ import { Context, Effect, Layer } from "effect"; import { AgentRepository } from "../bot-store/agent-repository"; -import { GroupChatRepository } from "../group-chats/group-chat-repository"; import { attachmentKind } from "../shared/attachment-rules"; import { InvalidInput, NotFound } from "../shared/errors"; import { FileStore, type FileTooLarge } from "./file-store"; @@ -98,13 +97,9 @@ export class Library extends Context.Service< const files = yield* FileStore; const repository = yield* LibraryRepository; const agents = yield* AgentRepository; - const groups = yield* GroupChatRepository; const exists = Effect.fnUntraced(function* (library: LibraryRef) { - const owner = - library.kind === "bot" - ? yield* agents.get(library.agentId) - : yield* groups.get(library.groupId); + const owner = yield* agents.get(library.agentId); if (!owner) return yield* new NotFound({ message: "Library not found" }); diff --git a/apps/server/src/files/schema.ts b/apps/server/src/files/schema.ts index 32e5bb10..33e89ae0 100644 --- a/apps/server/src/files/schema.ts +++ b/apps/server/src/files/schema.ts @@ -1,44 +1,26 @@ -import { sql } from "drizzle-orm"; import { - check, integer, sqliteTable, text, uniqueIndex, } from "drizzle-orm/sqlite-core"; import { agents } from "../bot-store/schema"; -import { groupChats } from "../group-chats/schema"; -export const deletedLibraryFiles = sqliteTable( - "deleted_library_files", - { - id: text("id").primaryKey(), - agentId: text("agent_id").references(() => agents.id, { - onDelete: "cascade", - }), - groupId: text("group_id").references(() => groupChats.id, { - onDelete: "cascade", - }), - name: text("name").notNull(), - }, - (table) => [ - check( - "deleted_library_files_one_owner", - sql`(${table.agentId} IS NOT NULL) != (${table.groupId} IS NOT NULL)`, - ), - ], -); +export const deletedLibraryFiles = sqliteTable("deleted_library_files", { + id: text("id").primaryKey(), + agentId: text("agent_id") + .notNull() + .references(() => agents.id, { onDelete: "cascade" }), + name: text("name").notNull(), +}); export const libraryFiles = sqliteTable( "library_files", { id: text("id").primaryKey(), - agentId: text("agent_id").references(() => agents.id, { - onDelete: "cascade", - }), - groupId: text("group_id").references(() => groupChats.id, { - onDelete: "cascade", - }), + agentId: text("agent_id") + .notNull() + .references(() => agents.id, { onDelete: "cascade" }), name: text("name").notNull(), mimeType: text("mime_type").notNull(), size: integer("size").notNull(), @@ -48,11 +30,6 @@ export const libraryFiles = sqliteTable( createdAt: text("created_at").notNull(), }, (table) => [ - check( - "library_files_one_owner", - sql`(${table.agentId} IS NOT NULL) != (${table.groupId} IS NOT NULL)`, - ), uniqueIndex("library_files_bot_hash").on(table.agentId, table.hash), - uniqueIndex("library_files_group_hash").on(table.groupId, table.hash), ], ); diff --git a/apps/server/src/group-chats/group-chat-context.ts b/apps/server/src/group-chats/group-chat-context.ts deleted file mode 100644 index b55468ed..00000000 --- a/apps/server/src/group-chats/group-chat-context.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { Effect, FiberSet, Semaphore, type Fiber, type Scope } from "effect"; -import { - keyedListeners, - keyedLocks, - type KeyedListeners, -} from "../shared/keyed"; -import type { AgentRepository } from "../bot-store/agent-repository"; -import type { Bots } from "../bots/bots"; -import type { ConversationRepository } from "../bot-store/conversation-repository"; -import type { ExecutionRepository } from "../bot-store/execution-repository"; -import type { BotRuntime } from "../bots/runtime"; -import type { GroupChat } from "./group-chat-repository"; -import { InvalidInput, NotFound, type AppError } from "../shared/errors"; -import type { GroupChatRepository } from "./group-chat-repository"; -import type { GroupTranscripts } from "./group-transcripts"; -import type { Library } from "../files/library"; -import type { ChatAttention } from "../push/chat-attention"; - -export type GroupChatServices = { - readonly attention: ChatAttention["Service"]; - readonly groups: GroupChatRepository["Service"]; - readonly agents: AgentRepository["Service"]; - readonly executions: ExecutionRepository["Service"]; - readonly conversations: ConversationRepository["Service"]; - readonly transcripts: GroupTranscripts; - readonly bots: Bots["Service"]; - readonly runtime: BotRuntime["Service"]; - readonly library: Library["Service"]; -}; - -export type GroupChatFork = ( - effect: Effect.Effect, -) => Fiber.Fiber; - -export type GroupChatState = { - readonly listeners: KeyedListeners; - readonly summarizing: Set; - // Bumped by each queueing, by `memberKey`, so a turn that was starting meanwhile leaves the new follow-up queued. - readonly pendingVersions: Map; - // Turn state changes run one at a time per group, so a member never gets two turns. - readonly locks: ReturnType; - // Held only across store writes: posting takes this one, as a turn's startup can hold `locks` while it submits. - readonly queueLocks: ReturnType; - readonly fork: GroupChatFork; -}; - -export type GroupChatContext = GroupChatServices & { - readonly state: GroupChatState; - readonly serial: ( - groupId: string, - work: Effect.Effect, - ) => Effect.Effect; - /** Guards a group's queue and budget records. Taken inside `serial`, never around it; only store writes inside. */ - readonly queueing: ( - groupId: string, - work: Effect.Effect, - ) => Effect.Effect; - readonly changed: (groupId: string) => Effect.Effect; - readonly get: (groupId: string) => Effect.Effect; - readonly enabled: (agentId: string) => Effect.Effect; - readonly checkMembers: (memberIds: string[]) => Effect.Effect; -}; - -export const memberKey = (groupId: string, agentId: string) => - `${groupId}:${agentId}`; - -export const groupChatState: Effect.Effect = - Effect.gen(function* () { - // Closing interrupts background work between steps; the step in progress finishes, and recovery resumes the rest. - const background = yield* FiberSet.make(); - const fork = yield* FiberSet.runtime(background)(); - - return { - listeners: keyedListeners(), - summarizing: new Set(), - pendingVersions: new Map(), - locks: keyedLocks(), - queueLocks: keyedLocks(), - fork, - }; - }); - -export const groupChatContext = ( - services: GroupChatServices, - state: GroupChatState, -): GroupChatContext => { - const { groups, agents } = services; - - const locked = - (lockOf: ReturnType) => - (groupId: string, work: Effect.Effect) => - Semaphore.withPermit(lockOf(groupId), Effect.uninterruptible(work)); - - const changed = (groupId: string) => - Effect.sync(() => state.listeners.notify(groupId)); - - const get = Effect.fn("GroupChats.get")(function* (groupId: string) { - const group = yield* groups.get(groupId); - - if (!group) - return yield* Effect.fail( - new NotFound({ message: "Group chat not found" }), - ); - - return group; - }); - - const enabled = (agentId: string) => - agents.get(agentId).pipe(Effect.map((agent) => agent?.enabled === true)); - - const checkMembers = Effect.fnUntraced(function* (memberIds: string[]) { - for (const agentId of memberIds) - if (!(yield* agents.get(agentId))) - return yield* Effect.fail( - new InvalidInput({ message: "Choose existing bots as members" }), - ); - }); - - return { - ...services, - state, - serial: locked(state.locks), - queueing: locked(state.queueLocks), - changed, - get, - enabled, - checkMembers, - }; -}; diff --git a/apps/server/src/group-chats/group-chat-members.ts b/apps/server/src/group-chats/group-chat-members.ts deleted file mode 100644 index f554df81..00000000 --- a/apps/server/src/group-chats/group-chat-members.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { activeExecution } from "../shared/domain"; -import { pi } from "../shared/app-errors"; -import { Effect } from "effect"; -import type { GroupChat } from "./group-chat-repository"; -import { type GroupChatContext } from "./group-chat-context"; -import { mentionedMembers } from "./group-mentions"; -import { openGroupConversation } from "./group-turns"; -import type { GroupEntry } from "./group-transcripts"; - -export const groupChatMembers = (context: GroupChatContext) => { - const { agents, bots, conversations, executions, groups, runtime } = context; - - const mentions = Effect.fnUntraced(function* ( - group: GroupChat, - text: string, - senderId: string | undefined, - replyTarget?: GroupEntry, - ) { - const members = (yield* Effect.forEach(group.memberIds, (agentId) => - agents.get(agentId), - )).flatMap((agent) => (agent ? [{ id: agent.id, name: agent.name }] : [])); - - const found = mentionedMembers(text, members, senderId); - const repliedTo = replyTarget?.sender.agentId; - - if ( - repliedTo && - repliedTo !== senderId && - group.memberIds.includes(repliedTo) && - !found.includes(repliedTo) - ) - found.unshift(repliedTo); - - return found; - }); - - const openConversation = Effect.fnUntraced(function* ( - group: GroupChat, - agentId: string, - ) { - const agent = yield* bots.agent(agentId); - - const conversationId = yield* pi(() => - openGroupConversation(runtime, agent, group.id), - ); - - yield* conversations.create({ agentId, title: group.name }, conversationId); - yield* groups.setMember(group.id, agentId, { conversationId }); - - return conversationId; - }); - - const abortTurn = Effect.fnUntraced(function* ( - groupId: string, - agentId: string, - ) { - const member = yield* groups.member(groupId, agentId); - const queued = member?.pending === true; - - if (queued) yield* groups.setMember(groupId, agentId, { pending: false }); - const turn = yield* groups.activeTurn(groupId, agentId); - const execution = turn ? yield* executions.get(turn.executionId) : null; - - if (!execution || !activeExecution(execution)) return queued; - yield* bots.abort(execution.conversationId); - - return true; - }); - - return { mentions, openConversation, abortTurn }; -}; - -export type GroupChatMembers = ReturnType; diff --git a/apps/server/src/group-chats/group-chat-post.ts b/apps/server/src/group-chats/group-chat-post.ts deleted file mode 100644 index e21dde83..00000000 --- a/apps/server/src/group-chats/group-chat-post.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { logged, pi } from "../shared/app-errors"; -import { Effect } from "effect"; -import type { MessageFile } from "../files/message-files"; -import { InvalidInput, type AppError } from "../shared/errors"; -import type { GroupChatContext } from "./group-chat-context"; -import type { GroupChatMembers } from "./group-chat-members"; -import type { GroupMessageReceipt } from "./group-chat-types"; -import type { GroupEntry } from "./group-transcripts"; -import type { GroupTurnEngine } from "./group-turn-engine"; -import { MESSAGE_PREVIEW_CHARS } from "../shared/limits"; - -export type GroupChatPostOptions = { - replyTo?: string | undefined; - files?: string[] | undefined; -}; - -export type GroupChatPost = ( - groupId: string, - content: string, - requestId: string, - options?: GroupChatPostOptions, -) => Effect.Effect; - -export type GroupChatPostDeps = { - readonly context: GroupChatContext; - readonly members: GroupChatMembers; - readonly turns: GroupTurnEngine; -}; - -type OwnerPost = { - content: string; - files: MessageFile[]; - target: GroupEntry | undefined; -}; - -export const groupChatPost = ({ - context, - members, - turns, -}: GroupChatPostDeps): GroupChatPost => { - const writeOwnerMessage = Effect.fnUntraced(function* ( - groupId: string, - requestId: string, - message: OwnerPost, - ) { - const { content, files, target } = message; - - return yield* pi(() => - context.transcripts.write( - groupId, - { - text: content, - sender: { kind: "owner" }, - ...(files.length && { files }), - ...(target && { - replyTo: target.entryId, - replyPreview: target.text.slice(0, MESSAGE_PREVIEW_CHARS), - }), - }, - requestId, - ), - ); - }); - - return Effect.fn("GroupChats.post")(function* ( - groupId: string, - content: string, - requestId: string, - options: GroupChatPostOptions = {}, - ) { - yield* context.get(groupId); - - const ids = options.files ?? []; - const ref = { kind: "group" as const, groupId }; - - const previous = yield* pi(() => - context.transcripts.byRequest(groupId, requestId), - ); - - if (!previous && ids.length) yield* context.library.validate(ref, ids); - - const entries = yield* context.library.entries(ref, ids); - - const files: MessageFile[] = ids.map((id) => { - const old = previous?.files?.find((file) => file.id === id); - - if (old) return old; - - const entry = entries.get(id); - - return entry - ? { id, name: entry.name, mimeType: entry.mimeType, size: entry.size } - : { id, deleted: true }; - }); - - const replyTo = options.replyTo; - - const target = replyTo - ? yield* pi(() => context.transcripts.message(groupId, replyTo)) - : undefined; - - if (replyTo && !target) - return yield* Effect.fail( - new InvalidInput({ - message: "Reply to a message in this group chat", - }), - ); - - const { entry, entryId, created } = yield* writeOwnerMessage( - groupId, - requestId, - { content, files, target }, - ); - - const group = yield* context.get(groupId); - - const mentioned = yield* members.mentions( - group, - content, - undefined, - target, - ); - - const woken = mentioned.length ? mentioned : group.memberIds; - - yield* turns.queue(groupId, { entry, woken, created }); - yield* context.changed(groupId); - - context.state.fork( - turns - .startQueued(groupId, woken) - .pipe(logged("Group turns could not start", groupId)), - ); - - return { requestId, entryId }; - }); -}; diff --git a/apps/server/src/group-chats/group-chat-repository.ts b/apps/server/src/group-chats/group-chat-repository.ts deleted file mode 100644 index 190fb7ab..00000000 --- a/apps/server/src/group-chats/group-chat-repository.ts +++ /dev/null @@ -1,434 +0,0 @@ -import type { groupChatInput } from "../contract/group-chats"; -import { and, asc, desc, eq, ne, sql } from "drizzle-orm"; -import { Context, Effect, Layer } from "effect"; -import { z } from "zod"; -import { ProductDatabase } from "../shared/product-database"; -import { nowIso } from "../shared/time"; -import { groupChats, groupMembers, groupTurns } from "./schema"; - -export type GroupChatInput = z.infer; - -export type GroupChat = GroupChatInput & { - id: string; - createdAt: string; - updatedAt: string; -}; - -export const GROUP_TURN_BUDGET = 8; - -export type GroupMember = { - groupId: string; - agentId: string; - conversationId: string | null; - cursor: number; - pending: boolean; - pendingBotStarted: boolean; - summary: string | null; - joinedAt: string; -}; - -export type GroupTurnStatus = "running" | "posting" | "settled"; - -export type GroupTurn = { - executionId: string; - groupId: string; - agentId: string; - through: number; - botStarted: boolean; - status: GroupTurnStatus; - createdAt: string; -}; - -const awaitingAnswers = z.record(z.string(), z.array(z.string())); - -export type GroupProgress = { - botTurns: number; - paused: boolean; - awaitingAnswers: Record; -}; - -export type GroupMemberChange = Partial< - Pick< - GroupMember, - "conversationId" | "cursor" | "pending" | "pendingBotStarted" | "summary" - > ->; - -const turnOf = (row: typeof groupTurns.$inferSelect): GroupTurn => ({ - executionId: row.executionId, - groupId: row.groupId, - agentId: row.agentId, - through: row.through, - botStarted: row.botStarted, - status: row.status, - createdAt: row.createdAt, -}); - -export class GroupChatRepository extends Context.Service< - GroupChatRepository, - { - /** Oldest first. */ - readonly list: Effect.Effect; - readonly get: (groupId: string) => Effect.Effect; - readonly create: ( - input: GroupChatInput, - groupId?: string, - ) => Effect.Effect; - /** Replaces name and members; members that stay keep their place in the join order. */ - readonly update: ( - groupId: string, - input: GroupChatInput, - ) => Effect.Effect; - readonly delete: (groupId: string) => Effect.Effect; - readonly member: ( - groupId: string, - agentId: string, - ) => Effect.Effect; - readonly setMember: ( - groupId: string, - agentId: string, - change: GroupMemberChange, - ) => Effect.Effect; - readonly activity: (groupId: string) => Effect.Effect; - readonly setActivity: ( - groupId: string, - change: Partial, - ) => Effect.Effect; - readonly createTurn: ( - turn: Omit, - ) => Effect.Effect; - readonly getTurn: ( - executionId: string, - ) => Effect.Effect; - readonly updateTurn: ( - executionId: string, - change: { status: GroupTurnStatus }, - ) => Effect.Effect; - /** The member's unsettled turn in the group; there is at most one. */ - readonly activeTurn: ( - groupId: string, - agentId: string, - ) => Effect.Effect; - /** Oldest first, optionally in one group or with some statuses. */ - readonly listTurns: (filter?: { - groupId?: string; - status?: GroupTurnStatus[]; - }) => Effect.Effect; - } ->()("crumble/group-chats/GroupChatRepository") { - static readonly layer = Layer.effect( - GroupChatRepository, - Effect.gen(function* () { - const db = yield* ProductDatabase; - - const groupOf = Effect.fnUntraced(function* ( - row: typeof groupChats.$inferSelect, - ) { - const members = yield* db - .select({ agentId: groupMembers.agentId }) - .from(groupMembers) - .where(eq(groupMembers.groupId, row.id)) - .orderBy(asc(groupMembers.joinedAt), sql`rowid`); - - const group: GroupChat = { - id: row.id, - name: row.name, - memberIds: members.map((member) => member.agentId), - createdAt: row.createdAt, - updatedAt: row.updatedAt, - }; - - return group; - }); - - const list = Effect.gen(function* () { - const rows = yield* db - .select() - .from(groupChats) - .orderBy(asc(groupChats.createdAt), sql`rowid`); - - return yield* Effect.forEach(rows, groupOf); - }).pipe(Effect.orDie, Effect.withSpan("GroupChatRepository.list")); - - const get = Effect.fn("GroupChatRepository.get")(function* ( - groupId: string, - ) { - const [row] = yield* db - .select() - .from(groupChats) - .where(eq(groupChats.id, groupId)); - - return row ? yield* groupOf(row) : null; - }, Effect.orDie); - - const insertMembers = Effect.fnUntraced(function* ( - groupId: string, - agentIds: ReadonlyArray, - joinedAt: string, - ) { - if (agentIds.length) - yield* db - .insert(groupMembers) - .values( - agentIds.map((agentId) => ({ groupId, agentId, joinedAt })), - ); - }); - - const create = Effect.fn("GroupChatRepository.create")(function* ( - input: GroupChatInput, - groupId: string = crypto.randomUUID(), - ) { - const at = yield* nowIso; - - yield* db.transaction(() => - Effect.gen(function* () { - yield* db.insert(groupChats).values({ - id: groupId, - name: input.name, - createdAt: at, - updatedAt: at, - }); - yield* insertMembers(groupId, input.memberIds, at); - }), - ); - - return (yield* get(groupId))!; - }, Effect.orDie); - - const update = Effect.fn("GroupChatRepository.update")(function* ( - groupId: string, - input: GroupChatInput, - ) { - const current = yield* get(groupId); - - if (!current) return null; - const at = yield* nowIso; - const kept = new Set(input.memberIds); - const currentMembers = new Set(current.memberIds); - - yield* db.transaction(() => - Effect.gen(function* () { - yield* db - .update(groupChats) - .set({ name: input.name, updatedAt: at }) - .where(eq(groupChats.id, groupId)); - - for (const agentId of current.memberIds) - if (!kept.has(agentId)) - yield* db - .delete(groupMembers) - .where( - and( - eq(groupMembers.groupId, groupId), - eq(groupMembers.agentId, agentId), - ), - ); - - yield* insertMembers( - groupId, - input.memberIds.filter((agentId) => !currentMembers.has(agentId)), - at, - ); - }), - ); - - return yield* get(groupId); - }, Effect.orDie); - - const remove = Effect.fn("GroupChatRepository.delete")(function* ( - groupId: string, - ) { - const deleted = yield* db - .delete(groupChats) - .where(eq(groupChats.id, groupId)) - .returning({ id: groupChats.id }); - - return deleted.length > 0; - }, Effect.orDie); - - const membership = (groupId: string, agentId: string) => - and( - eq(groupMembers.groupId, groupId), - eq(groupMembers.agentId, agentId), - ); - - const member = Effect.fn("GroupChatRepository.member")(function* ( - groupId: string, - agentId: string, - ) { - const [row] = yield* db - .select() - .from(groupMembers) - .where(membership(groupId, agentId)); - - if (!row) return; - - const state: GroupMember = { - groupId: row.groupId, - agentId: row.agentId, - conversationId: row.conversationId, - cursor: row.cursor, - pending: row.pending, - pendingBotStarted: row.pendingBotStarted, - summary: row.summary, - joinedAt: row.joinedAt, - }; - - return state; - }, Effect.orDie); - - const setMember = Effect.fn("GroupChatRepository.setMember")(function* ( - groupId: string, - agentId: string, - change: GroupMemberChange, - ) { - const current = yield* member(groupId, agentId); - - if (!current) return; - const next = { ...current, ...change }; - - yield* db - .update(groupMembers) - .set({ - conversationId: next.conversationId, - cursor: next.cursor, - pending: next.pending, - pendingBotStarted: next.pendingBotStarted, - summary: next.summary, - }) - .where(membership(groupId, agentId)); - }, Effect.orDie); - - const activity = Effect.fn("GroupChatRepository.activity")(function* ( - groupId: string, - ) { - const [row] = yield* db - .select({ - botTurns: groupChats.botTurns, - paused: groupChats.paused, - awaitingAnswers: groupChats.awaitingAnswers, - }) - .from(groupChats) - .where(eq(groupChats.id, groupId)); - - const state: GroupProgress = { - botTurns: row?.botTurns ?? 0, - paused: row?.paused ?? false, - awaitingAnswers: - awaitingAnswers.safeParse(JSON.parse(row?.awaitingAnswers ?? "{}")) - .data ?? {}, - }; - - return state; - }, Effect.orDie); - - const setActivity = Effect.fn("GroupChatRepository.setActivity")( - function* (groupId: string, change: Partial) { - const next = { ...(yield* activity(groupId)), ...change }; - - yield* db - .update(groupChats) - .set({ - botTurns: next.botTurns, - paused: next.paused, - awaitingAnswers: JSON.stringify(next.awaitingAnswers), - }) - .where(eq(groupChats.id, groupId)); - }, - Effect.orDie, - ); - - const getTurn = Effect.fn("GroupChatRepository.getTurn")(function* ( - executionId: string, - ) { - const [row] = yield* db - .select() - .from(groupTurns) - .where(eq(groupTurns.executionId, executionId)); - - return row ? turnOf(row) : undefined; - }, Effect.orDie); - - const createTurn = Effect.fn("GroupChatRepository.createTurn")(function* ( - turn: Omit, - ) { - yield* db.insert(groupTurns).values({ - executionId: turn.executionId, - groupId: turn.groupId, - agentId: turn.agentId, - through: turn.through, - botStarted: turn.botStarted, - status: turn.status, - createdAt: yield* nowIso, - }); - - return (yield* getTurn(turn.executionId))!; - }, Effect.orDie); - - const updateTurn = Effect.fn("GroupChatRepository.updateTurn")(function* ( - executionId: string, - change: { status: GroupTurnStatus }, - ) { - yield* db - .update(groupTurns) - .set({ status: change.status }) - .where(eq(groupTurns.executionId, executionId)); - }, Effect.orDie); - - const activeTurn = Effect.fn("GroupChatRepository.activeTurn")(function* ( - groupId: string, - agentId: string, - ) { - const [row] = yield* db - .select() - .from(groupTurns) - .where( - and( - eq(groupTurns.groupId, groupId), - eq(groupTurns.agentId, agentId), - ne(groupTurns.status, "settled"), - ), - ) - .orderBy(desc(groupTurns.createdAt), sql`rowid DESC`) - .limit(1); - - return row ? turnOf(row) : undefined; - }, Effect.orDie); - - const listTurns = Effect.fn("GroupChatRepository.listTurns")( - function* (filter: { groupId?: string; status?: GroupTurnStatus[] }) { - const rows = yield* db - .select() - .from(groupTurns) - .orderBy(asc(groupTurns.createdAt), sql`rowid`); - - return rows - .map(turnOf) - .filter( - (turn) => - (!filter.groupId || turn.groupId === filter.groupId) && - (!filter.status || filter.status.includes(turn.status)), - ); - }, - Effect.orDie, - ); - - return GroupChatRepository.of({ - list, - get, - create, - update, - delete: remove, - member, - setMember, - activity, - setActivity, - createTurn, - getTurn, - updateTurn, - activeTurn, - listTurns: (filter = {}) => listTurns(filter), - }); - }), - ); -} diff --git a/apps/server/src/group-chats/group-chat-service.ts b/apps/server/src/group-chats/group-chat-service.ts deleted file mode 100644 index e160eb2a..00000000 --- a/apps/server/src/group-chats/group-chat-service.ts +++ /dev/null @@ -1,313 +0,0 @@ -import { activeExecution } from "../shared/domain"; -import { pi } from "../shared/app-errors"; -import { Effect } from "effect"; -import type { GroupChatInput } from "./group-chat-repository"; -import { NotFound, type AppError } from "../shared/errors"; -import { type GroupChatContext } from "./group-chat-context"; -import type { GroupChatMembers } from "./group-chat-members"; -import { groupChatPost } from "./group-chat-post"; -import type { PageOptions, TranscriptPage } from "../transcript/transcript"; -import type { GroupMemberActivity } from "./group-chat-types"; -import type { GroupTurnEngine } from "./group-turn-engine"; - -export const groupChatsService = ( - context: GroupChatContext, - members: GroupChatMembers, - engine: GroupTurnEngine, -) => { - const create = Effect.fn("GroupChats.create")(function* ( - input: GroupChatInput, - ) { - yield* context.checkMembers(input.memberIds); - - return yield* context.groups.create(input); - }); - - const update = Effect.fn("GroupChats.update")(function* ( - groupId: string, - input: GroupChatInput, - ) { - const current = yield* context.get(groupId); - yield* context.checkMembers(input.memberIds); - - return yield* context.serial( - groupId, - Effect.gen(function* () { - const latest = yield* pi(() => context.transcripts.latest(groupId)); - const group = (yield* context.groups.update(groupId, input))!; - - for (const agentId of input.memberIds) - if (!current.memberIds.includes(agentId)) - yield* context.groups.setMember(groupId, agentId, { - cursor: latest, - }); - - for (const agentId of current.memberIds) - if (!input.memberIds.includes(agentId)) - yield* members.abortTurn(groupId, agentId); - yield* context.changed(groupId); - - return group; - }), - ); - }); - - const remove = Effect.fn("GroupChats.delete")(function* (groupId: string) { - const group = yield* context.get(groupId); - yield* stop(groupId); - - // Queued behind the stop and the settling of the turns it stopped, so no turn posts into a deleted group. - yield* context.serial( - groupId, - Effect.gen(function* () { - // Remove the transcript first: a failure then leaves a group with an empty transcript, not an orphaned file. - yield* pi(() => context.transcripts.delete(groupId)); - - for (const agentId of group.memberIds) { - const conversationId = (yield* context.groups.member( - groupId, - agentId, - ))?.conversationId; - - if (conversationId) - yield* context.conversations.setArchived(conversationId, true); - } - - yield* context.library.removeLibrary( - { kind: "group", groupId }, - context.groups.delete(groupId), - ); - yield* context.attention.removeChat({ kind: "group", id: groupId }); - yield* context.changed(groupId); - }), - ); - }); - - const stop = Effect.fn("GroupChats.stop")(function* (groupId: string) { - const group = yield* context.get(groupId); - - yield* context.serial( - groupId, - Effect.gen(function* () { - let stopped = false; - - for (const agentId of group.memberIds) - stopped = (yield* members.abortTurn(groupId, agentId)) || stopped; - - if (stopped) yield* context.changed(groupId); - }), - ); - }); - - const activity = Effect.fn("GroupChats.activity")(function* ( - groupId: string, - ) { - const group = yield* context.get(groupId); - const { botTurns, paused } = yield* context.groups.activity(groupId); - const turns = yield* context.groups.listTurns({ groupId }); - - return { - paused, - botTurns, - members: yield* Effect.forEach( - group.memberIds, - Effect.fnUntraced(function* (agentId) { - const member = yield* context.groups.member(groupId, agentId); - const latest = turns.findLast((turn) => turn.agentId === agentId); - - const execution = latest - ? yield* context.executions.get(latest.executionId) - : null; - - const statusOf = Effect.fnUntraced(function* () { - if (!(yield* context.enabled(agentId))) return "disabled" as const; - - if (yield* context.groups.activeTurn(groupId, agentId)) - return "running" as const; - - return member?.pending ? ("queued" as const) : ("idle" as const); - }); - - const status: GroupMemberActivity["status"] = yield* statusOf(); - - return { - agentId, - status, - error: execution?.status === "failed" ? execution.error : null, - }; - }), - ), - }; - }); - - const currentFiles = Effect.fnUntraced(function* ( - groupId: string, - page: TranscriptPage, - ) { - const ids = page.messages.flatMap((message) => - (message.files ?? []).map((file) => file.id), - ); - - const entries = yield* context.library.entries( - { kind: "group", groupId }, - ids, - ); - - return { - ...page, - messages: page.messages.map((message) => - message.files - ? { - ...message, - files: message.files.map((file) => - "deleted" in file || entries.has(file.id) - ? file - : { id: file.id, deleted: true as const }, - ), - } - : message, - ), - }; - }); - - const withReferences = Effect.fnUntraced(function* ( - groupId: string, - page: TranscriptPage, - ) { - const references = yield* context.attention.references( - { kind: "group", id: groupId }, - page.messages.map((message) => message.id), - ); - - return { - ...page, - messages: page.messages.map((message) => ({ - ...message, - replyReferences: [...(references.get(message.id) ?? [])], - })), - }; - }); - - const forMember = Effect.fn("GroupChats.forMember")(function* ( - agentId: string, - ) { - return yield* Effect.forEach( - (yield* context.groups.list).filter((group) => - group.memberIds.includes(agentId), - ), - Effect.fnUntraced(function* (group) { - const [latest] = (yield* Effect.promise(() => - context.transcripts.history(group.id, { limit: 1 }), - )).messages; - - const members = yield* Effect.forEach(group.memberIds, (id) => - context.agents - .get(id) - .pipe(Effect.map((agent) => agent?.name ?? "A deleted bot")), - ); - - return { - id: group.id, - name: group.name, - members, - latestAt: latest?.timestamp - ? new Date(latest.timestamp).toISOString() - : null, - }; - }), - { concurrency: "unbounded" }, - ); - }); - - const readAsMember = Effect.fn("GroupChats.readAsMember")(function* ( - agentId: string, - groupId: string, - options: PageOptions, - ) { - const group = yield* context.groups.get(groupId); - - if (!group?.memberIds.includes(agentId)) - return yield* Effect.fail( - new NotFound({ message: "Group chat not found" }), - ); - - return yield* currentFiles( - groupId, - yield* pi(() => context.transcripts.history(groupId, options)), - ); - }); - - const history = Effect.fn("GroupChats.history")(function* ( - groupId: string, - options: PageOptions, - ) { - yield* context.get(groupId); - - return yield* withReferences( - groupId, - yield* currentFiles( - groupId, - yield* pi(() => context.transcripts.history(groupId, options)), - ), - ); - }); - - const snapshot = Effect.fn("GroupChats.snapshot")(function* ( - groupId: string, - options: { limit?: number | undefined }, - ) { - const groupChat = yield* context.get(groupId); - - const page = yield* withReferences( - groupId, - yield* currentFiles( - groupId, - yield* pi(() => context.transcripts.history(groupId, options)), - ), - ); - - return { - ...page, - groupChat, - activity: yield* activity(groupId), - updatedAt: Date.now(), - }; - }); - - const subscribe = (groupId: string, callback: () => void) => - context.state.listeners.add(groupId, callback); - - /** Finishes turns a restart interrupted, then starts the turns that were waiting. Run after the bots recover. */ - const recover: Effect.Effect = Effect.gen(function* () { - for (const turn of yield* context.groups.listTurns({ - status: ["running", "posting"], - })) { - const execution = yield* context.executions.get(turn.executionId); - - if (execution && !activeExecution(execution)) - yield* engine.settled(execution); - } - - for (const group of yield* context.groups.list) - yield* engine.startQueued(group.id, group.memberIds); - }); - - return { - list: context.groups.list, - get: context.get, - create, - update, - delete: remove, - post: groupChatPost({ context, members, turns: engine }), - stop, - activity, - forMember, - readAsMember, - history, - snapshot, - subscribe, - recover, - }; -}; - -export type GroupChatsService = ReturnType; diff --git a/apps/server/src/group-chats/group-chat-types.ts b/apps/server/src/group-chats/group-chat-types.ts deleted file mode 100644 index f8f69d43..00000000 --- a/apps/server/src/group-chats/group-chat-types.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { z } from "zod"; -import type { groupActivityResponse } from "../contract/api-responses"; -import type { TranscriptPage } from "../transcript/transcript"; -import type { GroupChat } from "./group-chat-repository"; - -export type GroupActivity = z.output; - -export type GroupMemberActivity = GroupActivity["members"][number]; - -export type GroupChatSnapshot = TranscriptPage & { - groupChat: GroupChat; - activity: GroupActivity; - updatedAt: number; -}; - -export type GroupMessageReceipt = { requestId: string; entryId: string }; diff --git a/apps/server/src/group-chats/group-chats-api.test.ts b/apps/server/src/group-chats/group-chats-api.test.ts deleted file mode 100644 index ff5c74c3..00000000 --- a/apps/server/src/group-chats/group-chats-api.test.ts +++ /dev/null @@ -1,464 +0,0 @@ -import { afterEach, describe, expect, test } from "bun:test"; -import type { JsonValue } from "@earendil-works/chord"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { testAPI } from "../../test/support/api"; -import { - activityEvent, - groupChatResponse, - groupChatSnapshotResponse, - groupMessageReceiptResponse, - historyResponse, -} from "../contract/api-responses"; -import { standaloneGroupChats } from "./group-chats-test-support"; -import { GroupTranscripts } from "./group-transcripts"; -import { AgentRuntime } from "../bots/runtime"; -import { standaloneScheduler } from "../automations/scheduler-test-support"; -import { standaloneBots } from "../bots/bots-test-support"; -import { Store } from "../../test/support/store"; -import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; - -type TestRequestInit = Omit & { - headers?: Record; -}; - -const token = "t".repeat(40); -const dirs: string[] = []; - -afterEach(() => { - while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); -}); - -function setup() { - const dir = mkdtempSync(join(tmpdir(), "bot-group-api-")); - dirs.push(dir); - const store = new Store(dir); - - const service = standaloneBots( - store, - new AgentRuntime(join(dir, "agents"), runtimeCallbacks()), - ); - - const scheduler = standaloneScheduler(store.runtime, (a, p, r, s) => - service.dispatch(a, p, r, s), - ); - - const transcripts = new GroupTranscripts(join(dir, "groups")); - - const groupChats = standaloneGroupChats(service, transcripts); - - const app = testAPI(service, token, { scheduler, groupChats }); - - const bots = ["Planner", "Researcher", "Critic"].map((name) => - store.createAgent({ - name, - description: "", - instructions: "Answer", - provider: "openai", - model: "gpt-4.1", - enabled: false, - tools: [], - skills: [], - mcpServers: [], - delegates: [], - }), - ); - - return { - app, - service, - transcripts, - ids: bots.map((bot) => bot.id), - close: async () => { - await groupChats.close(); - await service.close(); - }, - }; -} - -const req = ( - app: ReturnType, - path: string, - init: TestRequestInit = {}, -) => - app.request(path, { - ...init, - headers: { - authorization: `Bearer ${token}`, - "content-type": "application/json", - ...init.headers, - }, - }); - -const post = ( - app: ReturnType, - path: string, - body: Record, -) => req(app, path, { method: "POST", body: JSON.stringify(body) }); - -describe("group chat API", () => { - test("group messages use library files and the old attachment route is gone", async () => { - const { app, ids, close } = setup(); - try { - const group = groupChatResponse.parse( - await ( - await post(app, "/v1/group-chats", { - name: "Trip", - memberIds: [ids[0]!, ids[1]!], - }) - ).json(), - ); - const upload = await req(app, `/v1/group-chats/${group.id}/files`, { - method: "POST", - headers: { "content-type": "text/plain", "x-file-name": "notes.txt" }, - body: "notes", - }); - expect(upload.status).toBe(201); - const { file } = await upload.json(); - const requestId = crypto.randomUUID(); - const unknown = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Read", - requestId: crypto.randomUUID(), - files: [crypto.randomUUID()], - }); - expect(unknown.status).toBe(400); - const sent = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Read", - requestId, - files: [file.id], - }); - expect(sent.status).toBe(201); - const receipt = groupMessageReceiptResponse.parse(await sent.json()); - const history = historyResponse.parse( - await (await req(app, `/v1/group-chats/${group.id}/history`)).json(), - ); - expect(history.messages[0]?.files).toEqual([ - { id: file.id, name: "notes.txt", mimeType: "text/plain", size: 5 }, - ]); - expect( - ( - await req( - app, - `/v1/group-chats/${group.id}/attachments/${receipt.entryId}/0`, - ) - ).status, - ).toBe(404); - expect( - ( - await req(app, `/v1/group-chats/${group.id}/files/${file.id}`, { - method: "DELETE", - }) - ).status, - ).toBe(204); - const deleted = historyResponse.parse( - await (await req(app, `/v1/group-chats/${group.id}/history`)).json(), - ); - expect(deleted.messages[0]?.files).toEqual([ - { id: file.id, deleted: true }, - ]); - expect( - ( - await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Read", - requestId, - files: [file.id], - }) - ).status, - ).toBe(201); - const rejected = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Read", - requestId: crypto.randomUUID(), - files: [file.id], - }); - expect(rejected.status).toBe(400); - expect(JSON.stringify(await rejected.json())).toContain( - "notes.txt was deleted from the library", - ); - const conflict = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Changed", - requestId, - files: [file.id], - }); - expect(conflict.status).toBe(409); - } finally { - await close(); - } - }); - test("creates, lists, renames, and deletes group chats", async () => { - const { app, ids, close } = setup(); - - try { - const tooSmall = await post(app, "/v1/group-chats", { - name: "Solo", - memberIds: [ids[0]!], - }); - - expect(tooSmall.status).toBe(400); - - const created = await post(app, "/v1/group-chats", { - name: "Trip", - memberIds: [ids[0]!, ids[1]!], - }); - - expect(created.status).toBe(201); - const group = groupChatResponse.parse(await created.json()); - - expect(group).toMatchObject({ - name: "Trip", - memberIds: [ids[0], ids[1]], - }); - expect( - groupChatResponse - .array() - .parse(await (await req(app, "/v1/group-chats")).json()), - ).toEqual([group]); - - const renamed = await req(app, `/v1/group-chats/${group.id}`, { - method: "PATCH", - body: JSON.stringify({ name: "Holiday" }), - }); - - expect(groupChatResponse.parse(await renamed.json())).toEqual({ - ...group, - name: "Holiday", - updatedAt: expect.any(String), - }); - - const deleted = await req(app, `/v1/group-chats/${group.id}`, { - method: "DELETE", - }); - - expect(deleted.status).toBe(204); - expect((await req(app, `/v1/group-chats/${group.id}`)).status).toBe(404); - } finally { - await close(); - } - }); - - test("posts messages and serves history, snapshots, and events", async () => { - const { app, ids, close } = setup(); - - try { - const group = groupChatResponse.parse( - await ( - await post(app, "/v1/group-chats", { - name: "Trip", - memberIds: [ids[0]!, ids[1]!, ids[2]!], - }) - ).json(), - ); - - const events: Response = await req( - app, - `/v1/group-chats/${group.id}/events`, - ); - - expect(events.headers.get("content-type")).toContain("text/event-stream"); - const reader = events.body!.getReader(); - const first = new TextDecoder().decode((await reader.read()).value); - - expect(first).toContain("event: snapshot"); - expect(first).toContain(`"id":"${group.id}"`); - - const requestId = crypto.randomUUID(); - - const sent = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Where should we go?", - requestId, - }); - - expect(sent.status).toBe(201); - const receipt = groupMessageReceiptResponse.parse(await sent.json()); - - expect(receipt.requestId).toBe(requestId); - - const update = new TextDecoder().decode((await reader.read()).value); - - expect(update).toContain("Where should we go?"); - await reader.cancel(); - - const history = historyResponse.parse( - await (await req(app, `/v1/group-chats/${group.id}/history`)).json(), - ); - - expect(history.messages).toMatchObject([ - { - entryId: receipt.entryId, - role: "user", - content: "Where should we go?", - origin: { kind: "owner" }, - }, - ]); - - const snapshot = groupChatSnapshotResponse.parse( - await ( - await req(app, `/v1/group-chats/${group.id}/chat?limit=10`) - ).json(), - ); - - expect(snapshot.groupChat.id).toBe(group.id); - expect(snapshot.messages).toHaveLength(1); - } finally { - await close(); - } - }); - - test("stops a group, rejects foreign replies, and reports activity and reactions", async () => { - const { app, ids, transcripts, close } = setup(); - - try { - const group = groupChatResponse.parse( - await ( - await post(app, "/v1/group-chats", { - name: "Trip", - memberIds: [ids[0]!, ids[1]!], - }) - ).json(), - ); - - const stopped = await req(app, `/v1/group-chats/${group.id}/stop`, { - method: "POST", - }); - - expect(stopped.status).toBe(204); - expect( - ( - await req(app, `/v1/group-chats/${crypto.randomUUID()}/stop`, { - method: "POST", - }) - ).status, - ).toBe(404); - - const foreign = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Me too", - requestId: crypto.randomUUID(), - replyTo: `${crypto.randomUUID()}:1`, - }); - - expect(foreign.status).toBe(400); - - const receipt = groupMessageReceiptResponse.parse( - await ( - await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "Pack light", - requestId: crypto.randomUUID(), - }) - ).json(), - ); - - await transcripts.post( - group.id, - { - text: "", - sender: { kind: "bot", agentId: ids[0]!, name: "Planner" }, - reaction: "👍", - replyTo: receipt.entryId, - }, - "reaction-1", - ); - - const snapshot = groupChatSnapshotResponse.parse( - await (await req(app, `/v1/group-chats/${group.id}/chat`)).json(), - ); - - expect(snapshot.activity).toEqual({ - paused: false, - botTurns: 0, - members: [ - { agentId: ids[0]!, status: "disabled", error: null }, - { agentId: ids[1]!, status: "disabled", error: null }, - ], - }); - expect(snapshot.messages.at(-1)).toMatchObject({ - role: "toolResult", - toolName: "react", - toolDetails: { emoji: "👍" }, - replyTo: receipt.entryId, - origin: { kind: "bot", agentId: ids[0] }, - }); - } finally { - await close(); - } - }); - - test("rejects legacy base64 attachments and empty messages", async () => { - const { app, ids, close } = setup(); - - const png = - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; - - try { - const group = groupChatResponse.parse( - await ( - await post(app, "/v1/group-chats", { - name: "Trip", - memberIds: [ids[0]!, ids[1]!], - }) - ).json(), - ); - - const sent = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: "", - requestId: crypto.randomUUID(), - attachments: [{ name: "map.png", mimeType: "image/png", data: png }], - }); - - expect(sent.status).toBe(400); - - const empty = await post(app, `/v1/group-chats/${group.id}/messages`, { - content: " ", - requestId: crypto.randomUUID(), - }); - - expect(empty.status).toBe(400); - } finally { - await close(); - } - }); - - test("streams group answers as reply events", async () => { - const { app, service, close } = setup(); - - try { - const events = await req(app, "/v1/events"); - const reader = events.body!.getReader(); - - const reply = { - type: "reply" as const, - executionId: "execution-1", - agentId: "agent-1", - agentName: "Planner", - entryId: "group-1:3", - origin: "group" as const, - preview: "Booked.", - createdAt: "2026-11-02T10:00:00.000Z", - groupId: "group-1", - groupName: "Trip", - }; - - service.announce(reply); - - let text = ""; - - while (!text.includes("Booked.")) - text += new TextDecoder().decode((await reader.read()).value); - await reader.cancel(); - - const data = text - .split("\n") - .find((line) => line.startsWith("data: ") && line.includes("Booked.")) - ?.slice("data: ".length); - - const { executionId, ...shown } = reply; - - expect(activityEvent.parse(JSON.parse(data!))).toEqual({ - ...shown, - eventId: executionId, - serverId: "", - }); - } finally { - await close(); - } - }); -}); diff --git a/apps/server/src/group-chats/group-chats-api.ts b/apps/server/src/group-chats/group-chats-api.ts deleted file mode 100644 index 767ddcf6..00000000 --- a/apps/server/src/group-chats/group-chats-api.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { routes } from "../contract/api-contract"; -import type { Register } from "../contract/route"; -import { snapshotSender, streamEvents } from "../shared/event-stream"; -import { groupChatInput } from "../contract/group-chats"; -import type { GroupChatsAccess } from "./group-chats"; - -type GroupChatRoutesOptions = { - register: Register; - groupChats: GroupChatsAccess; -}; - -const registerGroupChatDefinitionRoutes = (options: GroupChatRoutesOptions) => { - const { register, groupChats } = options; - - register.plain(routes.listGroupChats, (c) => c.json(groupChats.list(), 200)); - register.plain(routes.createGroupChat, (c) => - c.json(groupChats.create(c.req.valid("json")), 201), - ); - register.plain(routes.getGroupChat, (c) => - c.json(groupChats.get(c.req.param("id")), 200), - ); - register.plain( - routes.updateGroupChat, - async (c) => { - const current = groupChats.get(c.req.param("id")); - - const input = groupChatInput.parse({ - name: current.name, - memberIds: current.memberIds, - ...(await c.req.json()), - }); - - return c.json(await groupChats.update(current.id, input), 200); - }, - { parsesBody: true }, - ); - register.plain(routes.deleteGroupChat, async (c) => { - await groupChats.delete(c.req.param("id")); - - return c.body(null, 204); - }); - register.plain(routes.groupChatSnapshot, async (c) => - c.json( - await groupChats.snapshot(c.req.param("id"), c.req.valid("query")), - 200, - ), - ); - register.plain(routes.groupChatHistory, async (c) => - c.json( - await groupChats.history(c.req.param("id"), c.req.valid("query")), - 200, - ), - ); -}; - -const registerGroupMessageRoutes = (options: GroupChatRoutesOptions) => { - const { register, groupChats } = options; - - register.plain(routes.sendGroupMessage, async (c) => { - const input = c.req.valid("json"); - - return c.json( - await groupChats.post(c.req.param("id"), input.content, input.requestId, { - replyTo: input.replyTo, - files: input.files, - }), - 201, - ); - }); - register.plain(routes.stopGroupChat, async (c) => { - await groupChats.stop(c.req.param("id")); - - return c.body(null, 204); - }); - register.plain(routes.groupChatEvents, (c) => { - const query = c.req.valid("query"); - const groupId = groupChats.get(c.req.param("id")).id; - - return streamEvents(c, async ({ stream, close, onClose }) => { - const sendSnapshot = snapshotSender(stream, () => - groupChats.snapshot(groupId, query), - ); - - onClose( - groupChats.subscribe(groupId, () => { - void sendSnapshot().catch(close); - }), - ); - - await sendSnapshot(); - }); - }); -}; - -export function registerGroupChatRoutes(options: GroupChatRoutesOptions) { - registerGroupChatDefinitionRoutes(options); - registerGroupMessageRoutes(options); -} diff --git a/apps/server/src/group-chats/group-chats-test-support.ts b/apps/server/src/group-chats/group-chats-test-support.ts deleted file mode 100644 index 62db0e35..00000000 --- a/apps/server/src/group-chats/group-chats-test-support.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Effect, Layer, ManagedRuntime } from "effect"; -import type { AgentRepository } from "../bot-store/agent-repository"; -import type { Bots } from "../bots/bots"; -import type { ConversationRepository } from "../bot-store/conversation-repository"; -import type { ExecutionRepository } from "../bot-store/execution-repository"; -import type { BotRuntime } from "../bots/runtime"; -import type { Library } from "../files/library"; -import type { ChatAttention } from "../push/chat-attention"; -import { layerOfRunner, type Runner } from "../shared/runner"; -import type { GroupChatRepository } from "./group-chat-repository"; -import { - GroupChats, - groupChatsAccess, - GroupTranscriptStore, - type GroupChatsAccess, -} from "./group-chats"; -import type { GroupTranscripts } from "./group-transcripts"; - -export function standaloneGroupChats( - bots: { - effects: Runner< - | Bots - | BotRuntime - | AgentRepository - | ExecutionRepository - | ConversationRepository - | ChatAttention - >; - store: { runtime: Runner }; - }, - transcripts: GroupTranscripts, -): GroupChatsAccess & { - service: GroupChats["Service"]; - close(): Promise; -} { - const chats = ManagedRuntime.make( - GroupChats.layer.pipe( - Layer.provide(GroupTranscriptStore.layer(() => transcripts)), - Layer.provide(layerOfRunner(bots.effects)), - Layer.provide(layerOfRunner(bots.store.runtime)), - ), - ); - - const service = chats.runSync(GroupChats.use(Effect.succeed)); - - return { - ...groupChatsAccess(service), - service, - close: () => chats.dispose(), - }; -} diff --git a/apps/server/src/group-chats/group-chats.test.ts b/apps/server/src/group-chats/group-chats.test.ts deleted file mode 100644 index fbd37800..00000000 --- a/apps/server/src/group-chats/group-chats.test.ts +++ /dev/null @@ -1,1134 +0,0 @@ -import { afterEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { - createModels, - type AssistantMessage, - type Message, -} from "@earendil-works/pi-ai"; -import { - fauxAssistantMessage, - fauxProvider, - fauxText, - fauxToolCall, - type FauxResponseFactory, -} from "@earendil-works/pi-ai/providers/faux"; -import { GROUP_TURN_BUDGET } from "./group-chat-repository"; -import type { GroupChatsAccess } from "./group-chats"; -import { standaloneGroupChats } from "./group-chats-test-support"; -import { GroupTranscripts } from "./group-transcripts"; -import { reactionExtension } from "../bots/reaction"; -import { AgentRuntime } from "../bots/runtime"; -import { standaloneBots } from "../bots/bots-test-support"; -import { Store } from "../../test/support/store"; -import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; -import { Effect } from "effect"; -import { Library } from "../files/library"; -import { FileStore } from "../files/file-store"; -import { DESCRIPTION_HINT, resolveMessageFiles } from "../files/message-files"; -import { until } from "../../test/support/until"; - -const cleanups: (() => void | Promise)[] = []; - -afterEach(async () => { - while (cleanups.length) await cleanups.pop()!(); -}); - -const textOf = (message: Message) => - (Array.isArray(message.content) - ? message.content - : [{ type: "text" as const, text: message.content }] - ) - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join(""); - -type Bot = ( - input: string, - signal: AbortSignal | undefined, -) => AssistantMessage | Promise; - -const hang: Bot = (_input, signal) => - new Promise((_resolve, reject) => - signal?.addEventListener("abort", () => reject(new Error("aborted"))), - ); - -const say = (text: string) => fauxAssistantMessage([fauxText(text)]); - -const call = (name: string, args: Record = {}) => - fauxAssistantMessage(fauxToolCall(name, args), { stopReason: "toolUse" }); - -function script( - bots: Record, - inputs: Map, - contents: Map, -): FauxResponseFactory { - return async (context, options) => { - const system = context.messages - .filter((message) => message.role === "system") - .map((message) => JSON.stringify(message)) - .join("\n"); - - const name = system.includes("Summarize this group chat") - ? "summary" - : (/You are (.+?), a bot on Crumble/.exec(system)?.[1] ?? ""); - - const last = context.messages.findLast( - (message) => message.role !== "system", - )!; - - if (last.role === "toolResult") return say("Done."); - const input = textOf(last); - inputs.set(name, [...(inputs.get(name) ?? []), input]); - contents.set(name, [...(contents.get(name) ?? []), last.content]); - - return (bots[name] ?? (() => call("pass")))(input, options?.signal); - }; -} - -const bot = (name: string, enabled = true, model = "chat") => ({ - name, - description: "", - instructions: "Answer", - provider: "faux", - model, - enabled, - tools: [], - skills: [], - mcpServers: [], - delegates: [], -}); - -type VisionAnswers = string[]; - -function open(dir: string, bots: Record, vision?: VisionAnswers) { - const inputs = new Map(); - const contents = new Map(); - - const faux = fauxProvider({ - provider: "faux", - models: [ - { id: "chat", input: ["text", "image"] }, - { id: "text", input: ["text"] }, - ], - }); - - faux.setResponses( - Array.from({ length: 200 }, () => script(bots, inputs, contents)), - ); - const models = createModels(); - models.setProvider(faux.provider); - - if (vision) { - const eye = fauxProvider({ - provider: "eye", - models: [{ id: "vision", input: ["text", "image"] }], - }); - - eye.setResponses(vision.map((text) => say(text))); - models.setProvider(eye.provider); - } - - const store = new Store(dir); - const library = store.run(Library.use(Effect.succeed)); - const fileStore = store.run(FileStore.use(Effect.succeed)); - - const service = standaloneBots( - store, - new AgentRuntime( - join(dir, "agents"), - runtimeCallbacks({ - models, - library, - resolveFiles: (agentId, ids, ref) => - resolveMessageFiles( - library, - fileStore, - ref ?? { kind: "bot", agentId }, - ids, - ), - extensions: () => [reactionExtension()], - ...(vision && { - visionModel: () => ({ provider: "eye", model: "vision" }), - }), - }), - ), - ); - - const transcripts = new GroupTranscripts(join(dir, "groups")); - const groups = standaloneGroupChats(service, transcripts); - - let closed = false; - - const close = async () => { - if (closed) return; - closed = true; - await groups.close(); - await service.close(); - }; - - cleanups.push(close); - - return { - store, - library, - service, - groups, - transcripts, - inputs, - contents, - close, - }; -} - -function setup( - bots: Record = {}, - names = ["Ada", "Grace"], - vision?: VisionAnswers, -) { - const dir = mkdtempSync(join(tmpdir(), "bot-group-chats-")); - cleanups.push(() => rmSync(dir, { recursive: true, force: true })); - const opened = open(dir, bots, vision); - const agents = names.map((name) => opened.store.createAgent(bot(name))); - - const group = opened.groups.create({ - name: "Trip", - memberIds: agents.map((agent) => agent.id), - }); - - return { ...opened, dir, agents, group }; -} - -const quiet = (groups: GroupChatsAccess, groupId: string) => - until(() => - groups - .activity(groupId) - .members.every((member) => ["idle", "disabled"].includes(member.status)), - ); - -const botMessages = async (groups: GroupChatsAccess, groupId: string) => - (await groups.snapshot(groupId, { limit: 200 })).messages.filter( - (message) => message.origin?.kind === "bot", - ); - -function gate() { - let open!: () => void; - const opened = new Promise((resolve) => (open = resolve)); - - return { open, opened }; -} - -describe("group chat membership and transcript", () => { - test("rejects members that are not bots", () => { - const { groups, agents } = setup(); - - expect(() => - groups.create({ - name: "Trip", - memberIds: [agents[0]!.id, crypto.randomUUID()], - }), - ).toThrow("Choose existing bots as members"); - }); - - test("posts owner messages, notifies subscribers, and serves snapshots", async () => { - const { groups, group } = setup(); - let calls = 0; - const unsubscribe = groups.subscribe(group.id, () => calls++); - const receipt = await groups.post(group.id, "Plan it", "r-1"); - - expect(receipt.requestId).toBe("r-1"); - expect(receipt.entryId.startsWith(`${group.id}:`)).toBe(true); - expect(calls).toBeGreaterThan(0); - - const snapshot = await groups.snapshot(group.id, {}); - - expect(snapshot.groupChat).toEqual(group); - expect(snapshot.messages.map((message) => message.content)).toEqual([ - "Plan it", - ]); - unsubscribe(); - await quiet(groups, group.id); - }); - - test("renames and deletes a group with its transcript", async () => { - const { groups, group, agents } = setup(); - const [a, b] = agents.map((agent) => agent.id); - - expect( - await groups.update(group.id, { name: "Holiday", memberIds: [b!, a!] }), - ).toEqual({ - ...group, - name: "Holiday", - memberIds: [a!, b!], - updatedAt: expect.any(String), - }); - await groups.post(group.id, "Hello", "r-1"); - await groups.delete(group.id); - expect(() => groups.get(group.id)).toThrow("Group chat not found"); - await expect(groups.post(group.id, "Late", "r-2")).rejects.toThrow( - "Group chat not found", - ); - }); -}); - -describe("group turns", () => { - test("confirms stored messages while a member's turn is still starting", async () => { - const { groups, group, service, inputs } = setup({ - Ada: hang, - Grace: hang, - }); - - const starting = gate(); - const release = gate(); - const submit = service.runtime.submit.bind(service.runtime); - service.runtime.submit = async (...args) => { - starting.open(); - await release.opened; - - return submit(...args); - }; - - let accepted = false; - - const first = groups.post(group.id, "@Ada first", "r-1").then((receipt) => { - accepted = true; - - return receipt; - }); - - await starting.opened; - - try { - await until(() => accepted); - expect((await first).requestId).toBe("r-1"); - const second = await groups.post(group.id, "@Grace second", "r-2"); - expect(second.requestId).toBe("r-2"); - expect((await groups.snapshot(group.id, {})).messages).toHaveLength(2); - } finally { - release.open(); - await first; - } - - await until(() => inputs.has("Ada") && inputs.has("Grace")); - await groups.stop(group.id); - }); - - test("messages accepted during startup get one follow-up and retries add none", async () => { - const response = gate(); - const starting = gate(); - const release = gate(); - let calls = 0; - - const { groups, group, service, inputs } = setup({ - Ada: async () => { - if (++calls === 1) await response.opened; - - return say("Reply."); - }, - }); - - const submit = service.runtime.submit.bind(service.runtime); - service.runtime.submit = async (...args) => { - starting.open(); - await release.opened; - - return submit(...args); - }; - - try { - const first = await groups.post(group.id, "@Ada first", "r-1"); - await starting.opened; - expect(await groups.post(group.id, "@Ada first", "r-1")).toEqual(first); - await groups.post(group.id, "@Ada second", "r-2"); - release.open(); - await until(() => inputs.has("Ada")); - response.open(); - await quiet(groups, group.id); - expect(inputs.get("Ada")).toHaveLength(2); - expect(inputs.get("Ada")![1]).toContain("@Ada second"); - expect(inputs.get("Ada")![1]).not.toContain("@Ada first"); - } finally { - release.open(); - response.open(); - } - }); - - test("an unmentioned owner message reaches every member", async () => { - const { groups, group, inputs } = setup({ - Ada: () => say("Ada here."), - Grace: () => say("Grace here."), - }); - - await groups.post(group.id, "Who is around?", "r-1"); - await quiet(groups, group.id); - - expect( - (await botMessages(groups, group.id)) - .map((message) => message.content) - .toSorted(), - ).toEqual(["Ada here.", "Grace here."]); - expect(inputs.get("Ada")?.[0]).toContain("Owner: Who is around?"); - }); - - test("a mention or a reply reaches only that bot", async () => { - const { groups, group, inputs } = setup({ - Ada: () => say("On it."), - Grace: () => say("Grace answers."), - }); - - await groups.post(group.id, "@Ada pack the tent", "r-1"); - await quiet(groups, group.id); - expect(inputs.has("Grace")).toBe(false); - - const answer = (await botMessages(groups, group.id))[0]!; - await groups.post(group.id, "Thanks, and the stove?", "r-2", { - replyTo: answer.entryId, - }); - await quiet(groups, group.id); - expect(inputs.get("Ada")).toHaveLength(2); - expect(inputs.has("Grace")).toBe(false); - }); - - test("a bot message wakes only the bots it mentions", async () => { - const { groups, group, inputs } = setup({ - Ada: (input) => - input.includes("ask Grace") - ? say("@Grace what do you think?") - : say("Noted."), - Grace: () => say("Sounds good."), - }); - - await groups.post(group.id, "@Ada note this", "r-1"); - await quiet(groups, group.id); - expect(inputs.has("Grace")).toBe(false); - - await groups.post(group.id, "@Ada ask Grace", "r-2"); - await quiet(groups, group.id); - expect(inputs.get("Grace")?.[0]).toContain( - "Ada: @Grace what do you think?", - ); - }); - - test("mentions during a running turn queue one follow-up turn", async () => { - const held = gate(); - - const { groups, group, inputs } = setup({ - Ada: async (input) => { - if (input.includes("first")) await held.opened; - - return say("Reply."); - }, - }); - - await groups.post(group.id, "@Ada first", "r-1"); - await until(() => inputs.has("Ada")); - await groups.post(group.id, "@Ada second", "r-2"); - await groups.post(group.id, "@Ada third", "r-3"); - expect(groups.activity(group.id).members[0]?.status).toBe("running"); - held.open(); - await quiet(groups, group.id); - - const turns = inputs.get("Ada")!; - - expect(turns).toHaveLength(2); - expect(turns[1]).toContain("@Ada second"); - expect(turns[1]).toContain("@Ada third"); - }); - - test("bots that keep mentioning each other pause at the budget", async () => { - const { groups, group, inputs } = setup({ - Ada: () => say("@Grace your turn"), - Grace: () => say("@Ada your turn"), - }); - - await groups.post(group.id, "@Ada start", "r-1"); - await until(() => groups.activity(group.id).paused); - await quiet(groups, group.id); - - const turns = () => - (inputs.get("Ada")?.length ?? 0) + (inputs.get("Grace")?.length ?? 0); - - expect(turns()).toBe(1 + GROUP_TURN_BUDGET); - expect(groups.activity(group.id).botTurns).toBe(GROUP_TURN_BUDGET); - - await groups.post(group.id, "@Ada once more", "r-2"); - expect(groups.activity(group.id).paused).toBe(false); - await until(() => turns() > 1 + GROUP_TURN_BUDGET); - await groups.stop(group.id); - }); - - test("stop ends running turns and starts no queued turn", async () => { - const { groups, group, inputs } = setup({ - Ada: hang, - Grace: hang, - }); - - await groups.post(group.id, "Think hard", "r-1"); - await until(() => - groups.activity(group.id).members.every((m) => m.status === "running"), - ); - await groups.post(group.id, "@Ada and then this", "r-2"); - expect(groups.activity(group.id).members.map((m) => m.status)).toEqual([ - "running", - "running", - ]); - - await groups.stop(group.id); - await quiet(groups, group.id); - expect(await botMessages(groups, group.id)).toEqual([]); - expect(inputs.get("Ada")).toHaveLength(1); - }); - - test("a disabled member starts no turn and shows as disabled", async () => { - const { groups, group, store, inputs, agents } = setup({ - Ada: () => say("Here."), - }); - - store.updateAgent(agents[1]!.id, { enabled: false }); - await groups.post(group.id, "Anyone?", "r-1"); - await quiet(groups, group.id); - expect(inputs.has("Grace")).toBe(false); - expect(groups.activity(group.id).members[1]?.status).toBe("disabled"); - }); - - test("a turn sees other members' messages but not their working context", async () => { - const { groups, group, inputs } = setup({ - Ada: () => - fauxAssistantMessage( - [ - fauxText("private reasoning"), - fauxToolCall("react", { emoji: "👍" }), - ], - { stopReason: "toolUse" }, - ), - Grace: (input) => - input.includes("second") ? say("Seen.") : call("pass"), - }); - - await groups.post(group.id, "first", "r-1"); - await quiet(groups, group.id); - await groups.post(group.id, "@Grace second", "r-2"); - await quiet(groups, group.id); - - const reaction = (await botMessages(groups, group.id)).find( - (message) => message.toolName === "react", - ); - - expect(reaction).toMatchObject({ toolDetails: { emoji: "👍" } }); - expect(inputs.get("Grace")!.join("\n")).not.toContain("private reasoning"); - }); - - test("a removed member's turn posts nothing", async () => { - const held = gate(); - - const { groups, group, agents } = setup( - { - Ada: async () => { - await held.opened; - - return say("Too late."); - }, - }, - ["Ada", "Grace", "Hopper"], - ); - - await groups.post(group.id, "@Ada go", "r-1"); - await groups.update(group.id, { - name: "Trip", - memberIds: [agents[1]!.id, agents[2]!.id], - }); - held.open(); - await quiet(groups, group.id); - expect(await botMessages(groups, group.id)).toEqual([]); - }); -}); - -describe("owner notifications", () => { - const replies = (service: ReturnType>) => { - const events: Array<{ preview: string; groupId?: string }> = []; - - service.onActivity((event) => { - if (event.type === "reply") events.push(event); - }); - - return events; - }; - - test("only the first bot answer to an owner message notifies", async () => { - const held = gate(); - - const { groups, group, service } = setup({ - Ada: () => call("react", { emoji: "👍" }), - Grace: async () => { - await held.opened; - - return say("Friday works."); - }, - }); - - const events = replies(service); - await groups.post(group.id, "When do we leave?", "r-1"); - await until(async () => (await botMessages(groups, group.id)).length === 1); - held.open(); - await quiet(groups, group.id); - - expect(events).toEqual([ - expect.objectContaining({ - preview: "Friday works.", - groupId: group.id, - groupName: "Trip", - origin: "group", - }), - ]); - }); - - test("a second bot answer to the same message does not notify", async () => { - const held = gate(); - - const { groups, group, service } = setup({ - Ada: () => say("Friday."), - Grace: async () => { - await held.opened; - - return say("Saturday works too."); - }, - }); - - const events = replies(service); - await groups.post(group.id, "When do we leave?", "r-1"); - await until(async () => (await botMessages(groups, group.id)).length === 1); - held.open(); - await quiet(groups, group.id); - expect(events.map((event) => event.preview)).toEqual(["Friday."]); - }); - - test("each of two overlapping owner messages notifies for its first answer", async () => { - const held = gate(); - - const { groups, group, service } = setup({ - Ada: async () => { - await held.opened; - - return say("Tent is packed."); - }, - Grace: () => say("Stove is packed."), - }); - - const events = replies(service); - await groups.post(group.id, "@Ada pack the tent", "r-1"); - await groups.post(group.id, "@Grace pack the stove", "r-2"); - await until(async () => (await botMessages(groups, group.id)).length === 1); - held.open(); - await quiet(groups, group.id); - expect(events.map((event) => event.preview).sort()).toEqual([ - "Stove is packed.", - "Tent is packed.", - ]); - }); - - test("retrying an owner message does not notify again", async () => { - const held = gate(); - - const { groups, group, service } = setup({ - Ada: () => say("Friday."), - Grace: async () => { - await held.opened; - - return say("Saturday."); - }, - }); - - const events = replies(service); - await groups.post(group.id, "When do we leave?", "r-1"); - await until(async () => events.length === 1); - await groups.post(group.id, "When do we leave?", "r-1"); - held.open(); - await quiet(groups, group.id); - expect(events.map((event) => event.preview)).toEqual(["Friday."]); - }); - - test("a bot mentioning the owner notifies; other bot messages don't", async () => { - const { groups, group, service } = setup({ - Ada: () => say("@Grace can you check the trains?"), - Grace: () => say("@owner the 9:10 train is booked."), - }); - - const events = replies(service); - await groups.post(group.id, "@Ada sort out travel", "r-1"); - await quiet(groups, group.id); - - expect(events.map((event) => event.preview)).toEqual([ - "@Grace can you check the trains?", - "@owner the 9:10 train is booked.", - ]); - }); - - test("a pause and bot-to-bot turns don't notify", async () => { - const { groups, group, service } = setup({ - Ada: () => say("@Grace your turn"), - Grace: () => say("@Ada your turn"), - }); - - const events = replies(service); - await groups.post(group.id, "@Ada start", "r-1"); - await until(() => groups.activity(group.id).paused); - await quiet(groups, group.id); - expect(events.map((event) => event.preview)).toEqual(["@Grace your turn"]); - }); -}); - -describe("joining members", () => { - async function joinHopper(bots: Record) { - const opened = setup({ Ada: () => call("pass"), ...bots }); - const { groups, group, store } = opened; - await groups.post(group.id, "We leave on Friday", "r-1"); - await groups.post(group.id, "Bring the tent", "r-2"); - await quiet(groups, group.id); - const hopper = store.createAgent(bot("Hopper")); - - await groups.update(group.id, { - name: "Trip", - memberIds: [...group.memberIds, hopper.id], - }); - - return opened; - } - - test("a member added later gets one summary on its first turn", async () => { - const { groups, group, inputs } = await joinHopper({ - summary: () => say("The group leaves Friday and needs a tent."), - Hopper: () => say("Got it."), - }); - - expect(inputs.has("summary")).toBe(false); - await groups.post(group.id, "@Hopper can you drive?", "r-3"); - await quiet(groups, group.id); - await groups.post(group.id, "@Hopper and the snacks?", "r-4"); - await quiet(groups, group.id); - - expect(inputs.get("summary")).toHaveLength(1); - expect(inputs.get("summary")![0]).toContain("Owner: We leave on Friday"); - const [first, second] = inputs.get("Hopper")!; - - expect(first).toStartWith( - "Summary of the conversation before you joined:\n\nThe group leaves Friday and needs a tent.", - ); - expect(first).toContain("Owner: @Hopper can you drive?"); - expect(first).not.toContain("Bring the tent"); - expect(second).not.toContain("Summary of the conversation"); - }); - - test("a member that leaves and rejoins gets a summary of what it missed", async () => { - const { groups, group, store, inputs } = setup({ - Ada: () => say("Noted."), - summary: () => say("While you were away, the group chose Friday."), - }); - - const [ada, grace] = group.memberIds; - await groups.post(group.id, "@Ada hello", "r-1"); - await quiet(groups, group.id); - await groups.update(group.id, { - name: "Trip", - memberIds: [grace!, store.createAgent(bot("Hopper")).id], - }); - await groups.post(group.id, "We leave on Friday", "r-2"); - await quiet(groups, group.id); - await groups.update(group.id, { name: "Trip", memberIds: [grace!, ada!] }); - await groups.post(group.id, "@Ada are you in?", "r-3"); - await quiet(groups, group.id); - - expect(inputs.get("summary")?.at(-1)).toContain("We leave on Friday"); - expect(inputs.get("Ada")!.at(-1)).toContain( - "While you were away, the group chose Friday.", - ); - }); - - test("a stalled summary does not hold up stopping the group", async () => { - const held = gate(); - - const { groups, group, store } = setup({ - Ada: hang, - summary: async () => { - await held.opened; - - return say("Summary."); - }, - }); - - await groups.post(group.id, "@Ada think it over", "r-1"); - await until( - () => groups.activity(group.id).members[0]?.status === "running", - ); - const hopper = store.createAgent(bot("Hopper")); - - await groups.update(group.id, { - name: "Trip", - memberIds: [...group.memberIds, hopper.id], - }); - await groups.post(group.id, "@Hopper welcome", "r-2"); - - const stopped = await Promise.race([ - groups.stop(group.id).then(() => true), - new Promise((resolve) => setTimeout(() => resolve(false), 3000)), - ]); - - held.open(); - expect(stopped).toBe(true); - await quiet(groups, group.id); - expect( - store - .listExecutions(hopper.id) - .filter((execution) => execution.requestId.startsWith("group-turn:")), - ).toEqual([]); - }); - - test("a founding member gets no summary", async () => { - const { groups, group, inputs } = setup({ Ada: () => say("Hi.") }); - - await groups.post(group.id, "@Ada hello", "r-1"); - await quiet(groups, group.id); - await groups.post(group.id, "@Ada again", "r-2"); - await quiet(groups, group.id); - expect(inputs.get("Ada")).toHaveLength(2); - expect(inputs.has("summary")).toBe(false); - }); - - test("a failed summary still starts the turn", async () => { - const { groups, group, inputs } = await joinHopper({ - summary: () => - fauxAssistantMessage([], { stopReason: "error", errorMessage: "down" }), - Hopper: () => say("Got it."), - }); - - await groups.post(group.id, "@Hopper can you drive?", "r-3"); - await quiet(groups, group.id); - expect(inputs.get("Hopper")![0]).toContain( - "The earlier conversation could not be summarized.", - ); - }); -}); - -describe("attachments", () => { - const png = - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="; - - const upload = ( - library: Library["Service"], - groupId: string, - name: string, - mimeType: string, - bytes: Uint8Array, - ) => - Effect.runPromise( - library.upload( - { kind: "group", groupId }, - { name, mimeType, body: new Blob([Uint8Array.from(bytes)]).stream() }, - ), - ); - const image = (library: Library["Service"], groupId: string) => - upload( - library, - groupId, - "map.png", - "image/png", - Buffer.from(png, "base64"), - ); - const note = (library: Library["Service"], groupId: string, n: number) => - upload( - library, - groupId, - `note-${n}.txt`, - "text/plain", - Buffer.from(`note ${n}`), - ); - - const blocks = (content: Message["content"] | undefined) => - Array.isArray(content) ? content : []; - - test("an owner image reaches each member and pages show it without bytes", async () => { - const { groups, group, contents, library } = setup(); - const { file } = await image(library, group.id); - - await groups.post(group.id, "Here is the route", "r-1", { - files: [file.id], - }); - await quiet(groups, group.id); - - for (const name of ["Ada", "Grace"]) - expect(blocks(contents.get(name)?.[0])).toContainEqual({ - type: "image", - data: png, - mimeType: "image/png", - }); - - const [message] = (await groups.snapshot(group.id, {})).messages; - - expect(message?.files).toEqual([ - { id: file.id, name: "map.png", mimeType: "image/png", size: 70 }, - ]); - expect(JSON.stringify(message)).not.toContain(png); - }); - - test("a text-only model gets the image's name instead", async () => { - const { groups, group, store, inputs, contents, agents, library } = setup(); - const { file } = await image(library, group.id); - - store.updateAgent(agents[1]!.id, { model: "text" }); - await groups.post(group.id, "@Grace look", "r-1", { files: [file.id] }); - await quiet(groups, group.id); - expect(inputs.get("Grace")![0]).toContain("left out: map.png"); - expect( - blocks(contents.get("Grace")?.[0]).some( - (block) => block.type === "image", - ), - ).toBe(false); - }); - - test("members see each file's ID and description, with a hint for undescribed ones", async () => { - const { groups, group, inputs, library } = setup(); - const { file: map } = await image(library, group.id); - const { file: plain } = await note(library, group.id, 1); - - await Effect.runPromise( - library.describe( - { kind: "group", groupId: group.id }, - map.id, - "Route map from Lyon", - ), - ); - await groups.post(group.id, "Two files", "r-1", { - files: [map.id, plain.id], - }); - await quiet(groups, group.id); - - const input = inputs.get("Ada")![0]!; - - expect(input).toContain( - `map.png (id: ${map.id}, description: "Route map from Lyon")`, - ); - expect(input).toContain(`note-1.txt (id: ${plain.id})`); - expect(input).toContain(DESCRIPTION_HINT); - }); - - test("with a vision model, a text-only model gets the image described", async () => { - const { groups, group, store, inputs, contents, agents, library } = setup( - {}, - ["Ada", "Grace"], - ["A route map from Lyon to Turin."], - ); - - const { file } = await image(library, group.id); - store.updateAgent(agents[1]!.id, { model: "text" }); - await groups.post(group.id, "@Grace look", "r-1", { files: [file.id] }); - await quiet(groups, group.id); - expect(inputs.get("Grace")![0]).not.toContain("left out"); - expect( - blocks(contents.get("Grace")?.[0]).some( - (block) => block.type === "image", - ), - ).toBe(false); - expect(blocks(contents.get("Grace")?.[0])).toContainEqual({ - type: "text", - text: expect.stringContaining( - 'described-by="vision model">\nA route map from Lyon to Turin.\n', - ), - }); - }); - - test("coalesced messages send their newest eight attachments", async () => { - const held = gate(); - - const { groups, group, contents, library } = setup({ - Ada: async (input) => { - if (input.includes("first")) await held.opened; - - return say("Read them."); - }, - }); - - const files = await Promise.all( - [1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => note(library, group.id, n)), - ); - await groups.post(group.id, "@Ada first", "r-1"); - await groups.post(group.id, "@Ada older", "r-2", { - files: files.slice(0, 5).map(({ file }) => file.id), - }); - await groups.post(group.id, "@Ada newer", "r-3", { - files: files.slice(5).map(({ file }) => file.id), - }); - held.open(); - await quiet(groups, group.id); - - const names = blocks(contents.get("Ada")?.[1]).flatMap((block) => - block.type === "text" - ? [...block.text.matchAll(//g)].map( - (match) => match[1], - ) - : [], - ); - - expect(names).toEqual([2, 3, 4, 5, 6, 7, 8, 9].map((n) => `note-${n}.txt`)); - }); - - test("a queued deleted file reaches a member as deleted", async () => { - const held = gate(); - const { groups, group, library, contents } = setup({ - Ada: async (input) => { - if (input.includes("first")) await held.opened; - return say("Done"); - }, - }); - const { file } = await note(library, group.id, 1); - await groups.post(group.id, "@Ada first", "r-1"); - await groups.post(group.id, "@Ada read", "r-2", { files: [file.id] }); - await Effect.runPromise( - library.remove({ kind: "group", groupId: group.id }, file.id), - ); - held.open(); - await quiet(groups, group.id); - expect(JSON.stringify(contents.get("Ada")?.[1])).toContain( - `File ${file.id} was deleted`, - ); - }); - - test("legacy files display as deleted and never reach member turns", async () => { - const { groups, group, transcripts, contents } = setup(); - await transcripts.post( - group.id, - { - text: "old", - sender: { kind: "owner" }, - attachments: [{ name: "old.png", mimeType: "image/png", data: png }], - }, - "legacy", - ); - const page = await groups.history(group.id, {}); - expect(page.messages[0]?.files?.[0]).toMatchObject({ deleted: true }); - await groups.post(group.id, "@Ada continue", "new"); - await quiet(groups, group.id); - expect(JSON.stringify(contents.get("Ada")?.[0])).not.toContain(png); - }); - - test("a text-only member receives a large image as a reference", async () => { - const { groups, group, library, store, agents, contents } = setup(); - store.updateAgent(agents[1]!.id, { model: "text" }); - const { file } = await upload( - library, - group.id, - "large.png", - "image/png", - new Uint8Array(5 * 1024 * 1024 + 1), - ); - await groups.post(group.id, "@Grace read", "large", { files: [file.id] }); - await quiet(groups, group.id); - expect(JSON.stringify(contents.get("Grace")?.[0])).toContain( - `id: ${file.id}`, - ); - }); - - test("an invalid attachment writes nothing", async () => { - const { groups, group } = setup(); - - await expect( - groups.post(group.id, "Look", "r-1", { - files: [crypto.randomUUID()], - }), - ).rejects.toThrow("File not found"); - expect((await groups.snapshot(group.id, {})).messages).toEqual([]); - }); -}); - -describe("admission failures", () => { - test("a turn that fails to start does not leave its member running", async () => { - const { groups, group, service, inputs } = setup({ - Ada: () => say("Back."), - }); - - const submit = service.runtime.submit.bind(service.runtime); - - service.runtime.submit = async () => { - throw new Error("disk full"); - }; - - await groups.post(group.id, "@Ada first", "r-1"); - await quiet(groups, group.id); - expect(groups.activity(group.id).members[0]).toEqual({ - agentId: group.memberIds[0]!, - status: "idle", - error: "disk full", - }); - - service.runtime.submit = submit; - await groups.post(group.id, "@Ada second", "r-2"); - await quiet(groups, group.id); - expect(inputs.get("Ada")).toHaveLength(1); - }); -}); - -describe("group turns across restarts", () => { - test("an accepted message with no started turn is recovered after reopening", async () => { - const { dir, groups, group, service, close } = setup(); - let attempted = false; - service.runtime.openAnchored = async () => { - attempted = true; - throw new Error("workspace unavailable"); - }; - - const receipt = await groups.post(group.id, "@Ada plan", "r-1"); - await until(() => attempted); - - await close(); - const reopened = open(dir, { Ada: () => say("Planned.") }); - await reopened.service.recover(); - await reopened.groups.recover(); - await quiet(reopened.groups, group.id); - expect( - (await reopened.groups.snapshot(group.id, {})).messages[0]?.entryId, - ).toBe(receipt.entryId); - expect( - (await botMessages(reopened.groups, group.id)).map((m) => m.content), - ).toEqual(["Planned."]); - }); - - test("a turn running at shutdown posts its answer once after reopening", async () => { - const { dir, groups, group, close } = setup({ - Ada: hang, - }); - - await groups.post(group.id, "@Ada plan", "r-1"); - await close(); - - const reopened = open(dir, { Ada: () => say("Planned.") }); - await reopened.service.recover(); - await reopened.groups.recover(); - await quiet(reopened.groups, group.id); - await until( - async () => (await botMessages(reopened.groups, group.id)).length > 0, - ); - expect( - (await botMessages(reopened.groups, group.id)).map((m) => m.content), - ).toEqual(["Planned."]); - }); - - test("an unfinished post is completed once", async () => { - const { dir, groups, group, store, close } = setup({ - Ada: () => say("Planned."), - }); - - await groups.post(group.id, "@Ada plan", "r-1"); - await quiet(groups, group.id); - expect(await botMessages(groups, group.id)).toHaveLength(1); - - const [turn] = store.listGroupTurns({ groupId: group.id }); - store.updateGroupTurn(turn!.executionId, { status: "posting" }); - await close(); - - const reopened = open(dir, {}); - await reopened.service.recover(); - await reopened.groups.recover(); - expect(reopened.store.getGroupTurn(turn!.executionId)?.status).toBe( - "settled", - ); - expect(await botMessages(reopened.groups, group.id)).toHaveLength(1); - }); -}); diff --git a/apps/server/src/group-chats/group-chats.ts b/apps/server/src/group-chats/group-chats.ts deleted file mode 100644 index 599cc48e..00000000 --- a/apps/server/src/group-chats/group-chats.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { Context, Effect, Layer } from "effect"; -import { accessOf, noServices, type Access } from "../shared/runner"; -import { AgentRepository } from "../bot-store/agent-repository"; -import { Bots } from "../bots/bots"; -import { ChatAttention } from "../push/chat-attention"; -import { ConversationRepository } from "../bot-store/conversation-repository"; -import { ExecutionRepository } from "../bot-store/execution-repository"; -import { BotRuntime } from "../bots/runtime"; -import { Library } from "../files/library"; -import { - groupChatContext, - groupChatState, - type GroupChatServices, -} from "./group-chat-context"; -import { groupChatMembers } from "./group-chat-members"; -import { GroupChatRepository } from "./group-chat-repository"; -import { - groupChatsService, - type GroupChatsService, -} from "./group-chat-service"; -import type { GroupTranscripts } from "./group-transcripts"; -import { groupTurnEngine, keepTurnsSettled } from "./group-turn-engine"; -import { groupTurnInput } from "./group-turn-input"; - -export type { - GroupActivity, - GroupChatSnapshot, - GroupMemberActivity, - GroupMessageReceipt, -} from "./group-chat-types"; - -export class GroupTranscriptStore extends Context.Service< - GroupTranscriptStore, - GroupTranscripts ->()("crumble/group-chats/GroupTranscriptStore") { - static layer(make: () => GroupTranscripts) { - return Layer.effect( - GroupTranscriptStore, - Effect.acquireRelease(Effect.sync(make), (transcripts) => - Effect.promise(() => transcripts.close()), - ), - ); - } -} - -export class GroupChats extends Context.Service< - GroupChats, - GroupChatsService ->()("crumble/group-chats/GroupChats") { - static readonly layer = Layer.effect( - GroupChats, - Effect.gen(function* () { - const services: GroupChatServices = { - attention: yield* ChatAttention, - groups: yield* GroupChatRepository, - agents: yield* AgentRepository, - executions: yield* ExecutionRepository, - conversations: yield* ConversationRepository, - transcripts: yield* GroupTranscriptStore, - bots: yield* Bots, - runtime: yield* BotRuntime, - library: yield* Library, - }; - - const context = groupChatContext(services, yield* groupChatState); - const members = groupChatMembers(context); - - const engine = groupTurnEngine({ - context, - members, - input: groupTurnInput(context), - }); - - yield* keepTurnsSettled(context, engine); - - return GroupChats.of(groupChatsService(context, members, engine)); - }), - ); -} - -const SYNC_GROUP_CHATS = ["list", "get", "create", "activity"] as const; - -export type GroupChatsAccess = Access< - GroupChats["Service"], - (typeof SYNC_GROUP_CHATS)[number] ->; - -export const groupChatsAccess = ( - chats: GroupChats["Service"], -): GroupChatsAccess => accessOf(chats, noServices, SYNC_GROUP_CHATS); diff --git a/apps/server/src/group-chats/group-conversation.ts b/apps/server/src/group-chats/group-conversation.ts deleted file mode 100644 index f4937e20..00000000 --- a/apps/server/src/group-chats/group-conversation.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { - defineDoc, - type ConversationId, - type DocumentReader, -} from "@earendil-works/pi-durable"; -import type { Context } from "@earendil-works/chord"; - -export const GroupConversation = defineDoc<{ groupId: string | null }>({ - kind: "crumble.group-conversation", - version: 1, - scope: "conversation", - history: "latest", - fork: "initial", - initial: () => ({ groupId: null }), - checkpointWhen: () => false, -}); - -export const groupOf = async ( - reader: DocumentReader, - conversationId: ConversationId, - context: Context, -) => - (await reader.snapshot(GroupConversation, conversationId, context)) - ?.groupId ?? null; diff --git a/apps/server/src/group-chats/group-lookup.test.ts b/apps/server/src/group-chats/group-lookup.test.ts deleted file mode 100644 index cb2582dc..00000000 --- a/apps/server/src/group-chats/group-lookup.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { afterEach, expect, setDefaultTimeout, test } from "bun:test"; -import { openGroupConversation } from "./group-turns"; -import { mkdtempSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { createModels, type Message } from "@earendil-works/pi-ai"; -import { - fauxAssistantMessage, - fauxProvider, - fauxText, - fauxToolCall, - type FauxResponseFactory, -} from "@earendil-works/pi-ai/providers/faux"; -import { z } from "zod"; -import { standaloneGroupChats } from "./group-chats-test-support"; -import { groupLookupExtension } from "./group-lookup"; -import { GroupTranscripts } from "./group-transcripts"; -import { AgentRuntime } from "../bots/runtime"; -import { standaloneBots } from "../bots/bots-test-support"; -import { Store } from "../../test/support/store"; -import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; - -// Each test posts 35 messages through the real group chat first. -setDefaultTimeout(15_000); - -const cleanups: (() => void | Promise)[] = []; - -afterEach(async () => { - while (cleanups.length) await cleanups.pop()!(); -}); - -const textOf = (message: Message) => - (Array.isArray(message.content) - ? message.content - : [{ type: "text" as const, text: message.content }] - ) - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join(""); - -function script(offered: string[][]): FauxResponseFactory { - return async (context) => { - offered.push( - context.messages.flatMap((message) => - message.role === "system" - ? (message.toolsAdded ?? []).map((tool) => tool.name) - : [], - ), - ); - - const last = context.messages.findLast( - (message) => message.role !== "system", - )!; - - if (last.role === "toolResult") - return fauxAssistantMessage([fauxText("Looked it up.")]); - - return fauxAssistantMessage( - fauxToolCall("group_chats", JSON.parse(textOf(last))), - { stopReason: "toolUse" }, - ); - }; -} - -const bot = (name: string) => ({ - name, - description: "", - instructions: "", - provider: "faux", - model: "chat", - enabled: false, - tools: [], - skills: [], - mcpServers: [], - delegates: [], -}); - -const lookup = z.object({ - groups: z - .array(z.object({ name: z.string(), members: z.array(z.string()) })) - .optional(), - messages: z - .array(z.object({ sender: z.string(), text: z.string() })) - .optional(), - before: z.string().nullable().optional(), -}); - -async function setup() { - const dir = mkdtempSync(join(tmpdir(), "bot-group-lookup-")); - cleanups.push(() => rmSync(dir, { recursive: true, force: true })); - const offered: string[][] = []; - const faux = fauxProvider({ provider: "faux", models: [{ id: "chat" }] }); - faux.setResponses(Array.from({ length: 20 }, () => script(offered))); - const models = createModels(); - models.setProvider(faux.provider); - const store = new Store(dir); - let groups!: ReturnType; - - const runtime = new AgentRuntime( - join(dir, "agents"), - runtimeCallbacks({ - models, - extensions: (agent) => [groupLookupExtension(agent, groups.service)], - }), - ); - - const service = standaloneBots(store, runtime); - groups = standaloneGroupChats( - service, - new GroupTranscripts(join(dir, "groups")), - ); - - cleanups.push(async () => { - await groups.close(); - await service.close(); - }); - - const [ada, grace, hopper] = ["Ada", "Grace", "Hopper"].map((name) => - store.createAgent(bot(name)), - ); - - const trip = groups.create({ name: "Trip", memberIds: [ada!.id, grace!.id] }); - groups.create({ name: "Other", memberIds: [grace!.id, hopper!.id] }); - - for (let i = 1; i <= 35; i++) - await groups.post(trip.id, `Message ${i}`, crypto.randomUUID()); - - const agent = { ...ada!, enabled: true }; - const chat = await runtime.openChat(agent); - - const call = async (args: Record) => { - const submission = await runtime.submit(agent, chat, JSON.stringify(args)); - await runtime.wait(submission, agent); - - const result = (await runtime.history(agent)).messages.findLast( - (message) => message.role === "toolResult", - ); - - return lookup.parse(JSON.parse(result!.content)); - }; - - return { runtime, agent, trip, offered, call }; -} - -test("lists only the bot's groups", async () => { - const { call } = await setup(); - - expect((await call({ action: "list" })).groups).toEqual([ - { name: "Trip", members: ["Ada", "Grace"] }, - ]); -}); - -test("reads the newest messages and pages back", async () => { - const { call, trip } = await setup(); - const first = await call({ action: "read", groupId: trip.id }); - - expect(first.messages).toHaveLength(30); - expect(first.messages![0]).toEqual({ sender: "Owner", text: "Message 6" }); - expect(first.messages!.at(-1)?.text).toBe("Message 35"); - - const older = await call({ - action: "read", - groupId: trip.id, - before: first.before!, - }); - - expect(older.messages!.map((message) => message.text)).toEqual( - [1, 2, 3, 4, 5].map((n) => `Message ${n}`), - ); - expect(older.before).toBeNull(); -}); - -test("a group the bot is not in reads as not found", async () => { - const { runtime, agent, call } = await setup(); - const other = crypto.randomUUID(); - - await expect(call({ action: "read", groupId: other })).rejects.toThrow(); - - const result = (await runtime.history(agent)).messages.findLast( - (message) => message.role === "toolResult", - ); - - expect(result?.isError).toBe(true); - expect(result?.content).toContain("Group chat not found"); -}); - -test("is offered in the bot chat but not in a group turn", async () => { - const { runtime, agent, offered, call } = await setup(); - - await call({ action: "list" }); - expect(offered.at(-1)).toContain("group_chats"); - - const group = await openGroupConversation(runtime, agent, "group-1"); - - const submission = await runtime.submit( - agent, - group, - JSON.stringify({ action: "list" }), - ); - - await runtime.wait(submission, agent); - expect(offered.at(-1)).not.toContain("group_chats"); -}); diff --git a/apps/server/src/group-chats/group-lookup.ts b/apps/server/src/group-chats/group-lookup.ts deleted file mode 100644 index c7ae61d0..00000000 --- a/apps/server/src/group-chats/group-lookup.ts +++ /dev/null @@ -1,73 +0,0 @@ -import type { JsonValue } from "@earendil-works/chord"; -import { Type } from "@earendil-works/pi-ai"; -import { defineExtension, defineTool } from "@earendil-works/pi-durable"; -import { Effect, Layer } from "effect"; -import type { Agent } from "../contract/agents"; -import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; -import { chatOnly } from "../shared/chat-only"; -import { GroupChats } from "./group-chats"; -import { senderLabel } from "./group-transcripts"; - -const READ_LIMIT = 30; - -export function groupLookupExtension( - agent: Pick, - groups: GroupChats["Service"], -) { - const tool = defineTool({ - name: "group_chats", - description: - "Look up the group chats you belong to when the owner asks about them. `list` returns your groups with their members and newest message time. `read` (groupId; before: the `before` cursor of a previous read for older messages) returns up to 30 newest messages, oldest first, with their senders.", - parameters: Type.Object({ - action: Type.Union([Type.Literal("list"), Type.Literal("read")]), - groupId: Type.Optional(Type.String({ minLength: 1, maxLength: 64 })), - before: Type.Optional(Type.String({ minLength: 1, maxLength: 200 })), - }), - callers: ["model"], - replay: "safe", - execute: async (args) => { - const text = (value: JsonValue) => ({ - output: [{ type: "text" as const, text: JSON.stringify(value) }], - }); - - if (args.action === "list") - return text({ - groups: await Effect.runPromise(groups.forMember(agent.id)), - }); - - if (!args.groupId) throw new Error("read needs a groupId from list"); - - const page = await Effect.runPromise( - groups.readAsMember(agent.id, args.groupId, { - before: args.before, - limit: READ_LIMIT, - }), - ); - - return text({ - messages: page.messages.map((message) => ({ - entryId: message.entryId, - sender: senderLabel(message.origin), - text: message.content, - ...(message.timestamp && { - at: new Date(message.timestamp).toISOString(), - }), - })), - before: page.hasMore ? page.oldestEntryId : null, - }); - }, - }); - - return chatOnly(defineExtension({ name: "group-lookup", tools: [tool] })); -} - -export const groupLookupTools = Layer.effectDiscard( - Effect.gen(function* () { - const groups = yield* GroupChats; - - yield* (yield* BotExtensions).register( - ExtensionPosition.groupLookup, - (agent) => [groupLookupExtension(agent, groups)], - ); - }), -); diff --git a/apps/server/src/group-chats/group-mentions.test.ts b/apps/server/src/group-chats/group-mentions.test.ts deleted file mode 100644 index 7ccc3e75..00000000 --- a/apps/server/src/group-chats/group-mentions.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, test } from "bun:test"; -import { mentionedMembers, mentionsOwner } from "./group-mentions"; - -const members = [ - { id: "ada", name: "Ada" }, - { id: "lovelace", name: "Ada Lovelace" }, - { id: "grace", name: "Grace" }, -]; - -describe("mentionedMembers", () => { - test("matches names case-insensitively in first-mention order", () => { - expect(mentionedMembers("@grace and @ADA, over to you", members)).toEqual([ - "grace", - "ada", - ]); - }); - - test("prefers the longest matching name", () => { - expect(mentionedMembers("@Ada Lovelace please check", members)).toEqual([ - "lovelace", - ]); - }); - - test("needs a word boundary after the name", () => { - expect(mentionedMembers("@Adam and @Graceful", members)).toEqual([]); - expect(mentionedMembers("Thanks @Grace!", members)).toEqual(["grace"]); - }); - - test("ignores email addresses, repeats, and the sender", () => { - expect(mentionedMembers("mail ada@example.com", members)).toEqual([]); - expect(mentionedMembers("@Grace @Grace @Ada", members, "ada")).toEqual([ - "grace", - ]); - }); -}); - -describe("mentionsOwner", () => { - test("finds @owner at word boundaries only", () => { - expect(mentionsOwner("@Owner, the tickets are booked")).toBe(true); - expect(mentionsOwner("Done (@owner)")).toBe(true); - expect(mentionsOwner("@owners and mail@owner.com")).toBe(false); - }); -}); diff --git a/apps/server/src/group-chats/group-mentions.ts b/apps/server/src/group-chats/group-mentions.ts deleted file mode 100644 index 78738092..00000000 --- a/apps/server/src/group-chats/group-mentions.ts +++ /dev/null @@ -1,47 +0,0 @@ -export const normalize = (text: string) => text.normalize("NFKC").toLowerCase(); - -const wordCharacter = /[\p{L}\p{N}_]/u; - -export function mentionedMembers( - text: string, - members: Array<{ id: string; name: string }>, - senderId?: string, -): string[] { - const source = normalize(text); - - const candidates = members - .flatMap((member) => { - const name = normalize(member.name.trim()); - - return name ? [{ id: member.id, name }] : []; - }) - .sort((a, b) => b.name.length - a.name.length); - - const found: string[] = []; - - for ( - let at = source.indexOf("@"); - at >= 0; - at = source.indexOf("@", at + 1) - ) { - // An @ inside a word belongs to an email address. - if (at > 0 && wordCharacter.test(source[at - 1]!)) continue; - - const match = candidates.find( - (member) => - source.startsWith(member.name, at + 1) && - !wordCharacter.test(source[at + 1 + member.name.length] ?? ""), - ); - - if (match && match.id !== senderId && !found.includes(match.id)) - found.push(match.id); - } - - return found; -} - -const ownerMention = /(? { - while (dirs.length) rmSync(dirs.pop()!, { recursive: true, force: true }); -}); - -const make = () => { - const dir = mkdtempSync(join(tmpdir(), "bot-groups-")); - dirs.push(dir); - - return dir; -}; - -const groupId = "00000000-0000-4000-8000-000000000001"; -const owner = { kind: "owner" }; - -describe("GroupTranscripts", () => { - test("pages messages in order with their sender", async () => { - const transcripts = new GroupTranscripts(make()); - - try { - const first = await transcripts.post( - groupId, - { text: "Plan the trip", sender: owner }, - "r-1", - ); - - await transcripts.post( - groupId, - { - text: "Budget first", - sender: { kind: "bot", agentId: "a-1", name: "Planner" }, - }, - "r-2", - ); - - const page = await transcripts.history(groupId); - - expect( - page.messages.map((message) => [ - message.role, - message.content, - message.origin?.kind, - message.requestId, - ]), - ).toEqual([ - ["user", "Plan the trip", "owner", "r-1"], - ["assistant", "Budget first", "bot", "r-2"], - ]); - expect(page.messages[1]!.origin).toEqual({ - kind: "bot", - agentId: "a-1", - name: "Planner", - }); - expect(first.startsWith(`${groupId}:`)).toBe(true); - expect(page.messages[0]!.entryId).toBe(first); - expect( - (await transcripts.history(groupId, { before: first })).messages, - ).toEqual([]); - } finally { - await transcripts.close(); - } - }); - - test("writes a retried request once and rejects a different message under its ID", async () => { - const transcripts = new GroupTranscripts(make()); - - try { - const message = { text: "Hello", sender: owner }; - const first = await transcripts.post(groupId, message, "r-1"); - - expect(await transcripts.post(groupId, message, "r-1")).toBe(first); - expect((await transcripts.history(groupId)).messages).toHaveLength(1); - await expect( - transcripts.post(groupId, { text: "Other", sender: owner }, "r-1"), - ).rejects.toThrow("Request ID already used for a different message"); - } finally { - await transcripts.close(); - } - }); - - test("keeps messages across reopen and deletes the store", async () => { - const dir = make(); - const first = new GroupTranscripts(dir); - - await first.post(groupId, { text: "Kept", sender: owner }, "r-1"); - await first.close(); - - const second = new GroupTranscripts(dir); - - try { - expect( - (await second.history(groupId)).messages.map((m) => m.content), - ).toEqual(["Kept"]); - await second.delete(groupId); - expect(existsSync(join(dir, `${groupId}.sqlite`))).toBe(false); - } finally { - await second.close(); - } - }); -}); diff --git a/apps/server/src/group-chats/group-transcripts.ts b/apps/server/src/group-chats/group-transcripts.ts deleted file mode 100644 index 455bdac0..00000000 --- a/apps/server/src/group-chats/group-transcripts.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; -import { createModels } from "@earendil-works/pi-ai"; -import { - Harness, - createRegistry, - type EntryId, -} from "@earendil-works/pi-durable"; -import { mkdirSync } from "node:fs"; -import { fileIdDigest } from "../shared/attachments"; -import { - GROUP_MESSAGE_ENTRY, - groupMessageData, - type GroupMessageData, -} from "../transcript/entries"; -import { isOwnerOrigin } from "../transcript/origins"; -import { - entryAt, - readTranscript, - type PageOptions, - type TranscriptPage, -} from "../transcript/transcript"; -import { formatEntryId, parseEntryId } from "../shared/entry-ids"; -import { Conflict, REQUEST_ID_REUSED } from "../shared/errors"; -import { HarnessFiles } from "../shared/harness-files"; - -export type GroupPost = Omit; - -export type GroupEntry = GroupMessageData & { entry: number; entryId: string }; - -export const senderLabel = ( - sender: { kind: string; name?: string | undefined } | undefined, -) => (isOwnerOrigin(sender) ? "Owner" : (sender?.name ?? "A bot")); - -function samePost(written: GroupMessageData, message: GroupPost): boolean { - return ( - written.text === message.text && - written.sender.kind === message.sender.kind && - written.sender.agentId === message.sender.agentId && - written.replyTo === message.replyTo && - written.reaction === message.reaction && - fileIdDigest((written.files ?? []).map((file) => file.id)) === - fileIdDigest((message.files ?? []).map((file) => file.id)) - ); -} - -export class GroupTranscripts { - private readonly files: HarnessFiles<{ harness: Harness }>; - - constructor(dataDir: string) { - mkdirSync(dataDir, { recursive: true }); - this.files = new HarnessFiles(dataDir, "Group transcripts are closed"); - } - - private async open(groupId: string) { - const { harness } = await this.files.get(groupId, async (storage) => ({ - harness: await Harness.open( - storage, - { models: createModels(), registry: createRegistry() }, - BACKGROUND_CONTEXT, - ), - })); - - return harness; - } - - async post(groupId: string, message: GroupPost, requestId: string) { - return (await this.write(groupId, message, requestId)).entryId; - } - - async write( - groupId: string, - message: GroupPost, - requestId: string, - ): Promise<{ entry: number; entryId: string; created: boolean }> { - const root = await (await this.open(groupId)).root(BACKGROUND_CONTEXT); - - const data: GroupMessageData = { - ...message, - requestId, - timestamp: Date.now(), - }; - - const submission = await root.submit( - { type: "write", requestId, entry: { kind: GROUP_MESSAGE_ENTRY, data } }, - BACKGROUND_CONTEXT, - ); - - const settled = await submission.wait(BACKGROUND_CONTEXT); - - if (settled.type !== "write" || settled.status !== "done") - throw new Error("The group message was not written"); - - // Pi returns the earlier submission for a reused request ID without comparing its content. - const written = groupMessageData.safeParse( - (await entryAt(root, Number(settled.entry)))?.data, - ); - - if (!written.success || !samePost(written.data, message)) - throw new Conflict({ message: REQUEST_ID_REUSED }); - - return { - entry: Number(settled.entry), - entryId: formatEntryId(groupId, Number(settled.entry)), - // An earlier call's entry carries that call's time. - created: written.data.timestamp === data.timestamp, - }; - } - - async after(groupId: string, cursor: number): Promise { - const root = await (await this.open(groupId)).root(BACKGROUND_CONTEXT); - const found: GroupEntry[] = []; - let page = undefined; - - do { - page = await root.entries( - // SAFETY: entry numbers are Pi entry IDs; the successor of the cursor starts the range. - { order: "ascending", minEntryId: (cursor + 1) as EntryId }, - 256, - page?.next, - BACKGROUND_CONTEXT, - ); - - for (const item of page.items) { - const parsed = groupMessageData.safeParse(item.data); - - if (item.kind === GROUP_MESSAGE_ENTRY && parsed.success) - found.push({ - ...parsed.data, - entry: Number(item.id), - entryId: formatEntryId(groupId, Number(item.id)), - }); - } - } while (page.next); - - return found; - } - - async byRequest(groupId: string, requestId: string) { - const harness = await this.open(groupId); - const root = await harness.root(BACKGROUND_CONTEXT); - - const submission = await harness.commit( - (tx) => tx.submissionByRequest(root.id, requestId), - BACKGROUND_CONTEXT, - ); - - if (submission?.type !== "write" || submission.status !== "done") return; - - return this.message( - groupId, - formatEntryId(groupId, Number(submission.entry)), - ); - } - - async message(groupId: string, entryId: string) { - const entry = parseEntryId(entryId, groupId); - - if (entry === "foreign" || entry === "malformed") return; - - const root = await (await this.open(groupId)).root(BACKGROUND_CONTEXT); - - const item = await entryAt(root, entry); - const parsed = groupMessageData.safeParse(item?.data); - - return item?.kind === GROUP_MESSAGE_ENTRY && parsed.success - ? { ...parsed.data, entry, entryId } - : undefined; - } - - async latest(groupId: string) { - const root = await (await this.open(groupId)).root(BACKGROUND_CONTEXT); - - const page = await root.entries( - { order: "descending" }, - 1, - undefined, - BACKGROUND_CONTEXT, - ); - - return page.items[0] ? Number(page.items[0].id) : 0; - } - - async history( - groupId: string, - options: PageOptions = {}, - ): Promise { - return readTranscript(await this.open(groupId), groupId, options); - } - - delete(groupId: string) { - return this.files.delete(groupId); - } - - close() { - return this.files.close(); - } -} diff --git a/apps/server/src/group-chats/group-turn-engine.ts b/apps/server/src/group-chats/group-turn-engine.ts deleted file mode 100644 index 38159978..00000000 --- a/apps/server/src/group-chats/group-turn-engine.ts +++ /dev/null @@ -1,565 +0,0 @@ -import { REPLY_ORIGIN } from "../contract/reply-event"; -import { formatEntryId, formatMessageId } from "../shared/entry-ids"; -import { activeExecution, type Execution } from "../shared/domain"; -import { logged, pi } from "../shared/app-errors"; -import { Effect } from "effect"; -import { groupPostRequest, groupTurnRequest } from "../shared/request-ids"; -import { type Agent } from "../contract/agents"; -import { - GROUP_TURN_BUDGET, - type GroupChat, - type GroupMember, - type GroupTurn, -} from "./group-chat-repository"; -import type { AppError } from "../shared/errors"; -import type { InputOrigin } from "../transcript/origins"; -import { memberKey, type GroupChatContext } from "./group-chat-context"; -import type { GroupChatMembers } from "./group-chat-members"; -import { mentionsOwner } from "./group-mentions"; -import type { GroupEntry, GroupPost } from "./group-transcripts"; -import type { GroupTurnInput } from "./group-turn-input"; -import { turnOutcome } from "./group-turn-outcome"; -import { MESSAGE_PREVIEW_CHARS } from "../shared/limits"; -import { nowIso } from "../shared/time"; - -const AWAITING_ANSWERS = 50; - -export type GroupTurnDeps = { - readonly context: GroupChatContext; - readonly members: GroupChatMembers; - readonly input: GroupTurnInput; -}; - -export type PostedMessage = { - entry: number; - woken: string[]; - created: boolean; -}; - -type TurnDispatch = { - group: GroupChat; - agent: Agent; - member: GroupMember; - unseen: GroupEntry[]; - conversationId: string; - botStarted: boolean; - first: boolean; - through: number; - pendingVersion: symbol | undefined; -}; - -/** - * The part of group chats that leads one turn to the next. Every operation takes the group's locks itself: `wake` must - * run inside `serial`, which cannot nest, so it stays private. Posting only takes the queue's lock, as a slow start - * holds `serial`. - */ -export const groupTurnEngine = ({ context, members, input }: GroupTurnDeps) => { - const { queueing } = context; - - const queueMember = Effect.fnUntraced(function* ( - groupId: string, - agentId: string, - botStarted: boolean, - ) { - const member = yield* context.groups.member(groupId, agentId); - - if (!member) return; - context.state.pendingVersions.set(memberKey(groupId, agentId), Symbol()); - yield* context.groups.setMember(groupId, agentId, { - pending: true, - pendingBotStarted: member.pending - ? member.pendingBotStarted && botStarted - : botStarted, - }); - }); - - const consumePending = Effect.fnUntraced( - function* ( - groupId: string, - agentId: string, - pendingVersion: symbol | undefined, - ) { - // A message accepted during startup must keep its follow-up queued. - const key = memberKey(groupId, agentId); - - if (context.state.pendingVersions.get(key) === pendingVersion) { - yield* context.groups.setMember(groupId, agentId, { pending: false }); - context.state.pendingVersions.delete(key); - } - }, - (effect, groupId) => context.queueing(groupId, effect), - ); - - const unseenFor = Effect.fnUntraced(function* ( - groupId: string, - agentId: string, - cursor: number, - ) { - return (yield* pi(() => context.transcripts.after(groupId, cursor))).filter( - (entry) => - entry.sender.agentId !== agentId && entry.reaction === undefined, - ); - }); - - const chargeTurn = Effect.fnUntraced( - function* (groupId: string) { - const { botTurns } = yield* context.groups.activity(groupId); - - if (botTurns >= GROUP_TURN_BUDGET) { - yield* context.groups.setActivity(groupId, { paused: true }); - - return false; - } - - yield* context.groups.setActivity(groupId, { - botTurns: botTurns + 1, - paused: botTurns + 1 >= GROUP_TURN_BUDGET, - }); - - return true; - }, - (effect, groupId) => context.queueing(groupId, effect), - ); - - const takeAnswered = Effect.fnUntraced( - function* (groupId: string, turn: GroupTurn, agent: Agent) { - const { awaitingAnswers } = yield* context.groups.activity(groupId); - - const answered = Object.entries(awaitingAnswers).filter( - ([entry, targets]) => - Number(entry) <= turn.through && targets.includes(agent.id), - ); - - for (const [entry] of answered) delete awaitingAnswers[entry]; - - if (answered.length) - yield* context.groups.setActivity(groupId, { awaitingAnswers }); - - return answered.length > 0; - }, - (effect, groupId) => context.queueing(groupId, effect), - ); - - /** - * Notifies the owner of the first bot answer to their newest message, if this turn saw it, and of any `@owner`. - * The event ID is the turn's execution, so a retried post notifies once. - */ - const notify = Effect.fnUntraced(function* ( - group: GroupChat, - turn: GroupTurn, - agent: Agent, - entryId: string, - text: string, - ) { - const answered = yield* takeAnswered(group.id, turn, agent); - - if (!answered && !mentionsOwner(text)) return; - yield* context.attention.register({ - eventId: turn.executionId, - chat: { kind: "group", id: group.id }, - messageId: formatMessageId(entryId, 0), - entryId, - surface: { kind: "text" }, - }); - yield* context.bots.announce({ - type: "reply", - executionId: turn.executionId, - agentId: agent.id, - agentName: agent.name, - entryId, - origin: REPLY_ORIGIN.group, - preview: text.trim().slice(0, MESSAGE_PREVIEW_CHARS), - createdAt: yield* nowIso, - groupId: group.id, - groupName: group.name, - }); - }); - - const wake = ( - groupId: string, - agentId: string, - botStarted: boolean, - ): Effect.Effect => - Effect.gen(function* () { - const member = yield* context.groups.member(groupId, agentId); - - if (!member || !(yield* context.enabled(agentId))) return; - - if (botStarted && (yield* context.groups.activity(groupId)).paused) { - if (member.pendingBotStarted) - yield* context.groups.setMember(groupId, agentId, { pending: false }); - - return; - } - - if (yield* context.groups.activeTurn(groupId, agentId)) { - yield* queueing(groupId, queueMember(groupId, agentId, botStarted)); - - return; - } - - yield* startTurn(groupId, agentId, botStarted).pipe( - logged("Group turn could not start", groupId, agentId), - ); - }); - - const startTurn = ( - groupId: string, - agentId: string, - botStarted: boolean, - ): Effect.Effect => - Effect.gen(function* () { - const group = yield* context.get(groupId); - const member = (yield* context.groups.member(groupId, agentId))!; - const agent = yield* context.bots.agent(agentId); - - const pendingVersion = context.state.pendingVersions.get( - memberKey(groupId, agentId), - ); - - const unseen = yield* unseenFor(groupId, agentId, member.cursor); - - if (!unseen.length) - return yield* consumePending(groupId, agentId, pendingVersion); - - const first = !(yield* context.groups.listTurns({ groupId })).some( - (turn) => turn.agentId === agentId && turn.createdAt >= member.joinedAt, - ); - - if (first && member.cursor > 0 && member.summary === null) { - yield* queueing(groupId, queueMember(groupId, agentId, botStarted)); - yield* startSummary(groupId, agentId, member.cursor); - - return; - } - - if (botStarted && !(yield* chargeTurn(groupId))) - return yield* consumePending(groupId, agentId, pendingVersion); - - const conversationId = - member.conversationId ?? - (yield* members.openConversation(group, agentId)); - - yield* dispatchTurn({ - group, - agent, - member, - unseen, - conversationId, - botStarted, - first, - through: unseen.at(-1)!.entry, - pendingVersion, - }); - }); - - const dispatchTurn = (turn: TurnDispatch): Effect.Effect => - Effect.gen(function* () { - const { group, agent, member, unseen } = turn; - const summary = turn.first ? member.summary : null; - const requestId = groupTurnRequest(group.id, agent.id, turn.through); - - const { files, omitted } = yield* input.turnAttachments( - group.id, - agent, - unseen, - ); - - const summaryPrefix = summary - ? `Summary of the conversation before you joined:\n\n${summary}\n\n` - : ""; - - const turnInput = yield* input.turnInput(group, agent.name, unseen); - - const omittedSuffix = omitted.length - ? `\n\nYour model cannot read images, so these were left out: ${omitted.join(", ")}.` - : ""; - - const prompt = `${summaryPrefix}${turnInput}${omittedSuffix}`; - - const execution = - (yield* context.executions.getByRequest( - turn.conversationId, - requestId, - )) ?? - (yield* context.bots - .send(turn.conversationId, prompt, requestId, { files }) - .pipe( - Effect.catchCause((cause) => - context.executions - .getByRequest(turn.conversationId, requestId) - .pipe( - Effect.flatMap((left) => - left ? Effect.succeed(left) : Effect.failCause(cause), - ), - ), - ), - )); - - if (!(yield* context.groups.getTurn(execution.id))) - yield* context.groups.createTurn({ - executionId: execution.id, - groupId: group.id, - agentId: agent.id, - through: turn.through, - botStarted: turn.botStarted, - status: "running", - }); - - yield* consumePending(group.id, agent.id, turn.pendingVersion); - - // An execution that failed to start settled before its turn existed, so its settlement found nothing. - if (!activeExecution(execution)) yield* finish(execution.id); - }); - - const startSummary = ( - groupId: string, - agentId: string, - cursor: number, - ): Effect.Effect => - Effect.sync(() => { - const key = memberKey(groupId, agentId); - - if (context.state.summarizing.has(key)) return; - context.state.summarizing.add(key); - - context.state.fork( - Effect.gen(function* () { - const agent = yield* context.agents.get(agentId); - - const summary = agent - ? yield* input.summarize(groupId, agent, cursor) - : null; - - yield* context.serial( - groupId, - Effect.gen(function* () { - const member = yield* context.groups.member(groupId, agentId); - - if (!member || summary === null) return; - yield* context.groups.setMember(groupId, agentId, { summary }); - - if (member.pending) - yield* wake(groupId, agentId, member.pendingBotStarted); - yield* context.changed(groupId); - }), - ); - }).pipe( - logged("Group summary failed", groupId, agentId), - Effect.ensuring( - Effect.sync(() => context.state.summarizing.delete(key)), - ), - ), - ); - }); - - const publish = ( - group: GroupChat, - turn: GroupTurn, - conversationId: string, - submissionId: string, - ): Effect.Effect => - Effect.gen(function* () { - const agent = yield* context.agents.get(turn.agentId); - - if (!agent) return; - - const outcome = yield* pi(() => - turnOutcome(context.runtime, agent, conversationId, submissionId), - ); - - if (outcome.kind === "pass") return; - - const sender = { - kind: "bot", - agentId: agent.id, - name: agent.name, - } satisfies InputOrigin; - - const requestId = groupPostRequest(turn.executionId); - - if (outcome.kind === "reaction") { - yield* pi(() => - context.transcripts.post( - group.id, - { - text: "", - sender, - reaction: outcome.emoji, - replyTo: formatEntryId(group.id, turn.through), - }, - requestId, - ), - ); - - return; - } - - const post: GroupPost = { text: outcome.text, sender }; - - if (outcome.sources.length > 0) post.sources = outcome.sources; - - const entryId = yield* pi(() => - context.transcripts.post(group.id, post, requestId), - ); - - yield* notify(group, turn, agent, entryId, outcome.text); - yield* context.changed(group.id); - - for (const agentId of yield* members.mentions( - group, - outcome.text, - agent.id, - )) - yield* wake(group.id, agentId, true); - }); - - const startWaiting = (groupId: string, agentId: string) => - Effect.gen(function* () { - const current = (yield* context.groups.member(groupId, agentId))!; - - if (current.pending) - yield* wake(groupId, agentId, current.pendingBotStarted); - - yield* context.changed(groupId); - }); - - const finish = (executionId: string): Effect.Effect => - Effect.gen(function* () { - const turn = yield* context.groups.getTurn(executionId); - const execution = yield* context.executions.get(executionId); - - if (!turn || turn.status === "settled" || !execution) return; - yield* context.groups.updateTurn(executionId, { status: "posting" }); - const group = yield* context.groups.get(turn.groupId); - const member = yield* context.groups.member(turn.groupId, turn.agentId); - - if (!group || !member) { - yield* context.groups.updateTurn(executionId, { status: "settled" }); - - return; - } - - if (execution.status === "done" && execution.submissionId) - yield* publish( - group, - turn, - execution.conversationId, - execution.submissionId, - ); - - yield* context.groups.updateTurn(executionId, { status: "settled" }); - - if (execution.status === "done") - yield* context.groups.setMember(group.id, turn.agentId, { - cursor: Math.max(member.cursor, turn.through), - }); - - yield* startWaiting(group.id, turn.agentId); - }); - - const settled = Effect.fnUntraced(function* (execution: Execution) { - const turn = yield* context.groups.getTurn(execution.id); - - if (!turn || turn.status === "settled") return; - - yield* context.serial(turn.groupId, finish(turn.executionId)); - }); - - const rememberAwaitingAnswers = Effect.fnUntraced(function* ( - groupId: string, - posted: number, - woken: string[], - ) { - const { awaitingAnswers } = yield* context.groups.activity(groupId); - - const entries = Object.keys(awaitingAnswers) - .map(Number) - .sort((a, b) => a - b); - - for (const entry of entries.slice( - 0, - Math.max(0, entries.length - AWAITING_ANSWERS + 1), - )) - delete awaitingAnswers[entry]; - - awaitingAnswers[posted] = yield* Effect.filter(woken, context.enabled); - yield* context.groups.setActivity(groupId, { - botTurns: 0, - paused: false, - awaitingAnswers, - }); - }); - - const queueWoken = Effect.fnUntraced(function* ( - groupId: string, - woken: string[], - through: number, - created: boolean, - ) { - for (const agentId of woken) { - const member = yield* context.groups.member(groupId, agentId); - const turn = yield* context.groups.activeTurn(groupId, agentId); - - if ( - member && - (yield* context.enabled(agentId)) && - member.cursor < through && - (created || !member.pending) && - (!turn || turn.through < through) - ) - yield* queueMember(groupId, agentId, false); - } - }); - - const queue = (groupId: string, message: PostedMessage) => - queueing( - groupId, - Effect.gen(function* () { - const { entry, woken, created } = message; - - if (created) yield* rememberAwaitingAnswers(groupId, entry, woken); - - yield* queueWoken(groupId, woken, entry, created); - }), - ); - - const startQueued = (groupId: string, agentIds: string[]) => - context.serial( - groupId, - Effect.gen(function* () { - for (const agentId of agentIds) { - const member = yield* context.groups.member(groupId, agentId); - - if ( - member?.pending && - !(yield* context.groups.activeTurn(groupId, agentId)) - ) - yield* wake(groupId, agentId, member.pendingBotStarted); - } - - yield* context.changed(groupId); - }), - ); - - return { queue, startQueued, settled }; -}; - -export type GroupTurnEngine = ReturnType; - -export const keepTurnsSettled = ( - context: GroupChatContext, - engine: GroupTurnEngine, -) => - Effect.acquireRelease( - Effect.sync(() => - context.bots.onSettled((execution) => { - context.state.fork( - engine - .settled(execution) - .pipe(logged("Settled execution handler failed", execution.id)), - ); - }), - ), - (stop) => Effect.sync(stop), - ); diff --git a/apps/server/src/group-chats/group-turn-input.ts b/apps/server/src/group-chats/group-turn-input.ts deleted file mode 100644 index 0260f378..00000000 --- a/apps/server/src/group-chats/group-turn-input.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { pi } from "../shared/app-errors"; -import { Effect } from "effect"; -import { - MAX_ATTACHMENTS, - MAX_IMAGE_BYTES, - attachmentKind, -} from "../shared/attachment-rules"; -import type { Agent } from "../contract/agents"; -import type { GroupChat } from "./group-chat-repository"; -import { replyText } from "../shared/reply-text"; -import { type GroupChatContext } from "./group-chat-context"; -import { senderLabel, type GroupEntry } from "./group-transcripts"; -import { DESCRIPTION_HINT, type MessageFile } from "../files/message-files"; - -const SUMMARY_TIMEOUT_MS = 60_000; - -const SUMMARY_INPUT_CHARACTERS = 40_000; - -const SUMMARY_INSTRUCTIONS = - "Summarize this group chat for a bot that is joining it, in under 200 words. Keep decisions, open questions, who asked whom for what, and facts the group relies on. Name senders. Write plain prose without a heading."; - -async function writeSummary( - context: GroupChatContext, - agent: Agent, - transcript: string, - signal: AbortSignal, -) { - const answer = await context.runtime.complete( - agent, - SUMMARY_INSTRUCTIONS, - transcript, - signal, - ); - - const summary = replyText(answer).trim(); - - if (answer.stopReason === "error" || answer.stopReason === "aborted") - throw new Error(answer.errorMessage ?? "The summary failed"); - - if (!summary) throw new Error("The summary was empty"); - - return summary; -} - -export const groupTurnInput = (context: GroupChatContext) => { - const summarize = Effect.fnUntraced(function* ( - groupId: string, - agent: Agent, - cursor: number, - ) { - const earlier = (yield* pi(() => - context.transcripts.after(groupId, 0), - )).filter((entry) => entry.entry <= cursor && entry.reaction === undefined); - - const lines: string[] = []; - let length = 0; - - for (const entry of earlier.toReversed()) { - const line = `${senderLabel(entry.sender)}: ${entry.text}`; - - if (length + line.length > SUMMARY_INPUT_CHARACTERS) break; - lines.unshift(line); - length += line.length; - } - - return yield* Effect.tryPromise({ - try: () => - writeSummary( - context, - agent, - lines.join("\n\n"), - AbortSignal.timeout(SUMMARY_TIMEOUT_MS), - ), - catch: (error) => error, - }).pipe( - Effect.catch((error) => - Effect.logError("Group summary failed", groupId, agent.id, error).pipe( - Effect.as("The earlier conversation could not be summarized."), - ), - ), - ); - }); - - const turnAttachments = Effect.fnUntraced(function* ( - groupId: string, - agent: Agent, - unseen: GroupEntry[], - ) { - const images = yield* pi(() => context.runtime.acceptsImages(agent)); - - const ids = unseen.flatMap((entry) => - (entry.files ?? []).map((file) => file.id), - ); - - const entries = yield* context.library.entries( - { kind: "group", groupId }, - ids, - ); - - const files: string[] = []; - const omitted: string[] = []; - - for (const entry of unseen.toReversed()) - for (const item of (entry.files ?? []).toReversed()) { - const file = entries.get(item.id); - - if ( - !images && - file && - attachmentKind(file.mimeType) === "image" && - file.size <= MAX_IMAGE_BYTES - ) - omitted.unshift(`${file.name} (id: ${file.id})`); - else if (files.length < MAX_ATTACHMENTS) files.unshift(item.id); - } - - return { files, omitted }; - }); - - const turnInput = Effect.fnUntraced(function* ( - group: GroupChat, - name: string, - unseen: GroupEntry[], - ) { - const members = (yield* Effect.forEach(group.memberIds, (agentId) => - context.agents.get(agentId), - )) - .map((agent) => agent?.name) - .filter((member) => member !== undefined && member !== name); - - const ids = unseen.flatMap((entry) => - (entry.files ?? []).flatMap((file) => - "deleted" in file ? [] : [file.id], - ), - ); - - const described = yield* context.library.entries( - { kind: "group", groupId: group.id }, - ids, - ); - - const fileLabel = (file: MessageFile) => { - if ("deleted" in file) return "File deleted"; - - const description = described.get(file.id)?.description; - - return description - ? `${file.name} (id: ${file.id}, description: ${JSON.stringify(description)})` - : `${file.name} (id: ${file.id})`; - }; - - const undescribed = [...described.values()].some( - (entry) => !entry.description, - ); - - const messages = unseen.map((entry) => { - const reply = - entry.replyPreview === undefined - ? "" - : ` (replying to "${entry.replyPreview.slice(0, 120)}")`; - - const files = entry.files?.length - ? ` [attached: ${entry.files.map(fileLabel).join(", ")}]` - : ""; - - return `${senderLabel(entry.sender)}${reply}: ${entry.text}${files}`; - }); - - return `Group chat ${JSON.stringify(group.name)}. You are ${name}; the other members are the owner and ${members.join(", ") || "no other bots"}.\n\nNew messages:\n\n${messages.join("\n\n")}${undescribed ? `\n\nFiles: ${DESCRIPTION_HINT}` : ""}`; - }); - - return { summarize, turnAttachments, turnInput }; -}; - -export type GroupTurnInput = ReturnType; diff --git a/apps/server/src/group-chats/group-turn-outcome.ts b/apps/server/src/group-chats/group-turn-outcome.ts deleted file mode 100644 index 26097320..00000000 --- a/apps/server/src/group-chats/group-turn-outcome.ts +++ /dev/null @@ -1,74 +0,0 @@ -import type { Conversation } from "@earendil-works/pi-durable"; -import type { AgentRuntime } from "../bots/runtime"; -import { - PASS_TOOL_NAME, - WEB_EXTRACT_TOOL_NAME, - WEB_SEARCH_TOOL_NAME, -} from "../contract/tools"; -import { webPagesDetails } from "../contract/tool-details"; -import type { WebSource } from "../contract/web-search"; -import type { Agent } from "../contract/agents"; -import { contentText } from "../transcript/entries"; -import { - isToolResult, - reactionOf, - toolResult, -} from "../transcript/tool-results"; -import { turnMessages, type ModelMessage } from "../transcript/transcript"; - -export type TurnOutcome = - | { kind: "message"; text: string; sources: WebSource[] } - | { kind: "reaction"; emoji: string } - | { kind: "pass" }; - -function toolOutcome(message: ModelMessage): TurnOutcome | null { - if (isToolResult(message, PASS_TOOL_NAME)) return { kind: "pass" }; - - const emoji = reactionOf(message); - - return emoji ? { kind: "reaction", emoji } : null; -} - -function webSourcesOf(messages: ModelMessage[]): WebSource[] { - const sources = new Map(); - - for (const message of messages) - for (const toolName of [WEB_SEARCH_TOOL_NAME, WEB_EXTRACT_TOOL_NAME]) - for (const page of toolResult(message, toolName, webPagesDetails) ?? []) - if ("title" in page) sources.set(page.url, page); - - return [...sources.values()]; -} - -async function readTurnOutcome( - conversation: Conversation, - inputEntryId: number, -): Promise { - const messages = await turnMessages(conversation, inputEntryId); - let text = ""; - - for (const message of messages) { - if (message.role === "assistant") - text = contentText(message.content).trim(); - const outcome = toolOutcome(message); - - if (outcome) return outcome; - } - - return text - ? { kind: "message", text, sources: webSourcesOf(messages) } - : { kind: "pass" }; -} - -export async function turnOutcome( - runtime: Pick, - agent: Agent, - conversationId: string, - submissionId: string, -): Promise { - const turn = await runtime.settledTurn(agent, conversationId, submissionId); - - return turn - ? readTurnOutcome(turn.conversation, turn.entry) - : { kind: "pass" }; -} diff --git a/apps/server/src/group-chats/group-turns.test.ts b/apps/server/src/group-chats/group-turns.test.ts deleted file mode 100644 index 1c833c4e..00000000 --- a/apps/server/src/group-chats/group-turns.test.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { afterEach, expect, test } from "bun:test"; -import { openGroupConversation } from "./group-turns"; -import { mkdtempSync, rmSync } from "node:fs"; -import { join } from "node:path"; -import { tmpdir } from "node:os"; -import { Type, createModels, type Message } from "@earendil-works/pi-ai"; -import { - fauxAssistantMessage, - fauxProvider, - fauxText, - fauxToolCall, - type FauxResponseFactory, -} from "@earendil-works/pi-ai/providers/faux"; -import { defineExtension, defineTool } from "@earendil-works/pi-durable"; -import { Effect, Layer } from "effect"; -import { Plugins } from "../plugins/plugins"; -import { BotExtensions } from "../bot-ports/bot-extensions"; -import { chatOnly } from "../shared/chat-only"; -import { configuredWebSearchTools } from "../web-search/web-search-tools"; -import { AgentRepository } from "../bot-store/agent-repository"; -import { SettingsRepository } from "../shared/settings-repository"; -import type { Agent } from "../contract/agents"; -import { defaultAvatarDefinition } from "../contract/avatar"; -import { reactionExtension } from "../bots/reaction"; -import { AgentRuntime } from "../bots/runtime"; -import { turnOutcome } from "./group-turn-outcome"; -import { turnReport } from "../learning/turn-report"; -import { runtimeCallbacks } from "../../test/support/runtime-callbacks"; - -const cleanups: (() => void | Promise)[] = []; - -afterEach(async () => { - while (cleanups.length) await cleanups.pop()!(); -}); - -const agent: Agent = { - id: "00000000-0000-4000-8000-000000000501", - name: "Ada", - avatar: defaultAvatarDefinition("ada"), - description: "", - instructions: "", - provider: "faux", - model: "chat", - enabled: true, - tools: ["memory"], - skills: [], - mcpServers: [], - delegates: [], - createdAt: "2026-10-21T00:00:00.000Z", - updatedAt: "2026-10-21T00:00:00.000Z", -}; - -const textOf = (message: Message) => - (Array.isArray(message.content) - ? message.content - : [{ type: "text" as const, text: message.content }] - ) - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join(""); - -function script(offered: string[][]): FauxResponseFactory { - return async (context) => { - offered.push( - context.messages.flatMap((message) => - message.role === "system" - ? (message.toolsAdded ?? []).map((tool) => tool.name) - : [], - ), - ); - - const last = context.messages.findLast( - (message) => message.role !== "system", - )!; - - const call = (name: string, args: Record) => - fauxAssistantMessage(fauxToolCall(name, args), { stopReason: "toolUse" }); - - if (last.role === "toolResult") - return fauxAssistantMessage([fauxText("unexpected")]); - const text = textOf(last); - - if (text === "react") return call("react", { emoji: "👍" }); - - if (text === "pass") return call("pass", {}); - - if (text === "empty") return fauxAssistantMessage([fauxText("")]); - - return fauxAssistantMessage([fauxText(`Answer to ${text}`)]); - }; -} - -const coordination = chatOnly( - defineExtension({ - name: "coordination", - tools: [ - defineTool({ - name: "delegate", - description: "Message another bot.", - parameters: Type.Object({}), - callers: ["model"], - execute: async () => ({ output: [{ type: "text", text: "Sent." }] }), - }), - ], - }), -); - -function open( - extensions?: (agent: Agent) => Promise[]>, -) { - const dir = mkdtempSync(join(tmpdir(), "bot-group-turns-")); - cleanups.push(() => rmSync(dir, { recursive: true, force: true })); - const offered: string[][] = []; - const faux = fauxProvider({ provider: "faux", models: [{ id: "chat" }] }); - faux.setResponses(Array.from({ length: 20 }, () => script(offered))); - const models = createModels(); - models.setProvider(faux.provider); - - const runtime = new AgentRuntime( - dir, - runtimeCallbacks({ - models, - extensions: extensions ?? (() => [coordination, reactionExtension()]), - }), - ); - - cleanups.push(() => runtime.close()); - - return { runtime, offered }; -} - -async function turn(runtime: AgentRuntime, conversation: string, text: string) { - const submission = await runtime.submit(agent, conversation, text, text); - await runtime.wait(submission, agent); - - return turnOutcome(runtime, agent, conversation, submission); -} - -test("a group conversation offers pass and react but no delegation", async () => { - const { runtime, offered } = open(); - const chat = await runtime.openChat(agent); - const group = await openGroupConversation(runtime, agent, "group-1"); - - await turn(runtime, group, "hello"); - expect(offered.at(-1)).toEqual([ - "memory", - "skill_manage", - "library", - "react", - "pass", - ]); - - await turn(runtime, chat, "hi"); - expect(offered.at(-1)).toEqual([ - "memory", - "skill_manage", - "library", - "delegate", - "react", - ]); -}); - -test("a turn longer than one entry page is read to its end", async () => { - const rounds = 110; - const faux = fauxProvider({ provider: "faux", models: [{ id: "chat" }] }); - - faux.setResponses([ - ...Array.from({ length: rounds }, () => - fauxAssistantMessage(fauxToolCall("ping", {}), { stopReason: "toolUse" }), - ), - fauxAssistantMessage([fauxText("The final answer")]), - fauxAssistantMessage([fauxText("The next turn")]), - ]); - const models = createModels(); - models.setProvider(faux.provider); - const dir = mkdtempSync(join(tmpdir(), "bot-long-turn-")); - cleanups.push(() => rmSync(dir, { recursive: true, force: true })); - - const ping = defineExtension({ - name: "ping", - tools: [ - defineTool({ - name: "ping", - description: "Ping.", - parameters: Type.Object({}), - replay: "safe", - execute: async () => ({ output: [{ type: "text", text: "pong" }] }), - }), - ], - }); - - const runtime = new AgentRuntime( - dir, - runtimeCallbacks({ models, extensions: () => [ping] }), - ); - - cleanups.push(() => runtime.close()); - await runtime.openChat(agent); - const group = await openGroupConversation(runtime, agent, "group-1"); - const long = await runtime.submit(agent, group, "work", "long"); - await runtime.wait(long, agent); - const next = await runtime.submit(agent, group, "again", "next"); - await runtime.wait(next, agent); - - expect(await turnOutcome(runtime, agent, group, long)).toEqual({ - kind: "message", - text: "The final answer", - sources: [], - }); - expect(await runtime.response(agent, group, long)).toEqual([ - "The final answer", - ]); - - const report = await turnReport(runtime, agent, group, long, 100_000); - - expect(report.rounds).toBe(rounds); - expect(report.digest).toContain("The final answer"); - expect(report.digest).not.toContain("The next turn"); -}); - -test("web tools are offered in bot chat and group turns", async () => { - const layers = configuredWebSearchTools.pipe( - Layer.provideMerge(BotExtensions.layer), - Layer.provide(Layer.mock(AgentRepository)({})), - Layer.provide(Layer.mock(SettingsRepository)({})), - Layer.provide( - Layer.succeed(Plugins, [ - { - id: "offline", - webSearchProviders: [ - { - id: "offline", - search: () => Effect.succeed([]), - extract: (url) => Effect.succeed({ url, title: "", text: "" }), - }, - ], - }, - ]), - ), - ); - - await Effect.runPromise( - Effect.scoped( - Effect.gen(function* () { - const registry = yield* BotExtensions; - const enabled = { ...agent, tools: [...agent.tools, "web"] }; - const { runtime, offered } = open((bot) => registry.forAgent(bot)); - const chat = yield* Effect.promise(() => runtime.openChat(enabled)); - - const group = yield* Effect.promise(() => - openGroupConversation(runtime, enabled, "group-1"), - ); - - yield* Effect.promise(async () => { - const submission = await runtime.submit(enabled, chat, "hi", "hi"); - - await runtime.wait(submission, enabled); - }); - expect(offered.at(-1)).toEqual([ - "memory", - "skill_manage", - "library", - "web_search", - "web_extract", - ]); - - yield* Effect.promise(async () => { - const submission = await runtime.submit( - enabled, - group, - "hello", - "hello", - ); - - await runtime.wait(submission, enabled); - }); - expect(offered.at(-1)).toEqual([ - "memory", - "skill_manage", - "library", - "web_search", - "web_extract", - "pass", - ]); - }).pipe(Effect.provide(layers)), - ), - ); -}); - -test("a group conversation stays out of the bot chat", async () => { - const { runtime } = open(); - const chat = await runtime.openChat(agent); - const group = await openGroupConversation(runtime, agent, "group-1"); - - expect(await turn(runtime, group, "secret plan")).toEqual({ - kind: "message", - text: "Answer to secret plan", - sources: [], - }); - expect((await runtime.history(agent)).messages).toEqual([]); - expect((await runtime.snapshot(agent, chat)).messages).toEqual([]); -}); - -test("a turn's outcome is its answer, a reaction, or a pass", async () => { - const { runtime } = open(); - const group = await openGroupConversation(runtime, agent, "group-1"); - - expect(await turn(runtime, group, "plans")).toEqual({ - kind: "message", - text: "Answer to plans", - sources: [], - }); - expect(await turn(runtime, group, "react")).toEqual({ - kind: "reaction", - emoji: "👍", - }); - expect(await turn(runtime, group, "pass")).toEqual({ kind: "pass" }); - expect(await turn(runtime, group, "empty")).toEqual({ kind: "pass" }); -}); diff --git a/apps/server/src/group-chats/group-turns.ts b/apps/server/src/group-chats/group-turns.ts deleted file mode 100644 index 48a4486b..00000000 --- a/apps/server/src/group-chats/group-turns.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Type } from "@earendil-works/pi-ai"; -import { defineExtension, defineTool } from "@earendil-works/pi-durable"; -import { inGroupTurns } from "../shared/chat-only"; -import { - chatTools, - type ConversationKind, -} from "../bot-ports/conversation-kind"; -import type { AgentRuntime } from "../bots/runtime"; -import { defineAnchorTask } from "../shared/anchor-task"; -import type { Agent } from "../contract/agents"; -import { PASS_TOOL_NAME } from "../contract/tools"; -import { GroupConversation, groupOf } from "./group-conversation"; - -export const GROUP_TURN_EXTENSION = "group-turn"; - -const GROUP_INSTRUCTIONS = - "This conversation is your private working context for a group chat between the owner and several bots. Each input names the group and its members and lists the group messages you have not seen, each with its sender. Your final answer is posted to the group as your message; the owner and every member read it. Your tool calls, tool results, and memory stay private, so share only what the group needs. Mentioning a member with @ and their exact name wakes them, so mention a bot only when you need it to respond, and never to thank or acknowledge it. Answer when you are addressed or have something the others have not said. React with one emoji to acknowledge a message without answering. Otherwise call `pass` to stay silent; silence is often right when other bots have answered. Mention the owner as @owner only when you need their attention: it notifies them. Memories you save here go to your own memory, never to shared memory."; - -// Owns a member's group conversation, so it outlives the bot chat's turns and Esc, like a coding job's anchor. -const GroupAnchor = defineAnchorTask("crumble.group-anchor"); - -function groupTurnExtension() { - const pass = defineTool({ - name: PASS_TOOL_NAME, - description: - "Stay silent in the group chat: nothing is posted for this turn. Use it when the new messages need nothing from you. Finish any other tool calls, such as saving memory, first. Your turn ends here, so do not write a reply.", - parameters: Type.Object({}), - callers: ["model"], - replay: "safe", - execute: async () => ({ - output: [{ type: "text" as const, text: "Passed." }], - control: { terminate: true }, - }), - }); - - return defineExtension({ - name: GROUP_TURN_EXTENSION, - tools: [pass], - tasks: [GroupAnchor], - }); -} - -export function groupConversations(): ConversationKind { - const extension = groupTurnExtension(); - - return { - extension, - recognize: async (reader, conversationId, context) => { - if (!(await groupOf(reader, conversationId, context))) return; - - return { - tools: (parts) => - chatTools(parts, parts.offered.filter(inGroupTurns), [ - ...(extension.tools ?? []), - ]), - extensions: (parts) => [ - parts.memoryExtension, - parts.skillExtension, - parts.libraryExtension, - ...parts.offered.filter(inGroupTurns), - extension, - parts.visionExtension, - ], - prompt: { addition: GROUP_INSTRUCTIONS }, - }; - }, - }; -} - -export const openGroupConversation = ( - runtime: Pick, - agent: Agent, - groupId: string, -) => - runtime.openAnchored(agent, GroupAnchor, async (tx, id) => { - (await tx.doc(GroupConversation, id)).groupId = groupId; - }); diff --git a/apps/server/src/group-chats/schema.ts b/apps/server/src/group-chats/schema.ts deleted file mode 100644 index 7be5bcbc..00000000 --- a/apps/server/src/group-chats/schema.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { - integer, - primaryKey, - sqliteTable, - text, -} from "drizzle-orm/sqlite-core"; -import { executions } from "../bot-store/schema.executions"; -import { agents } from "../bot-store/schema"; - -export const groupChats = sqliteTable("group_chats", { - id: text("id").primaryKey(), - name: text("name").notNull(), - botTurns: integer("bot_turns").notNull().default(0), - paused: integer("paused", { mode: "boolean" }).notNull().default(false), - awaitingAnswers: text("awaiting_answers").notNull().default("{}"), - createdAt: text("created_at").notNull(), - updatedAt: text("updated_at").notNull(), -}); - -const groupIdColumn = () => - text("group_id") - .notNull() - .references(() => groupChats.id, { onDelete: "cascade" }); - -const agentIdColumn = () => - text("agent_id") - .notNull() - .references(() => agents.id, { onDelete: "cascade" }); - -export const groupMembers = sqliteTable( - "group_members", - { - groupId: groupIdColumn(), - agentId: agentIdColumn(), - joinedAt: text("joined_at").notNull(), - conversationId: text("conversation_id"), - cursor: integer("cursor").notNull().default(0), - pending: integer("pending", { mode: "boolean" }).notNull().default(false), - pendingBotStarted: integer("pending_bot_started", { mode: "boolean" }) - .notNull() - .default(false), - summary: text("summary"), - }, - (table) => [primaryKey({ columns: [table.groupId, table.agentId] })], -); - -export const groupTurns = sqliteTable("group_turns", { - executionId: text("execution_id") - .primaryKey() - .references(() => executions.id, { onDelete: "cascade" }), - groupId: groupIdColumn(), - agentId: agentIdColumn(), - through: integer("through").notNull(), - botStarted: integer("bot_started", { mode: "boolean" }).notNull(), - status: text("status", { enum: ["running", "posting", "settled"] }).notNull(), - createdAt: text("created_at").notNull(), -}); diff --git a/apps/server/src/history/history-search.test.ts b/apps/server/src/history/history-search.test.ts index ceffbe1c..f3df8fea 100644 --- a/apps/server/src/history/history-search.test.ts +++ b/apps/server/src/history/history-search.test.ts @@ -1,4 +1,3 @@ -import { GROUP_MESSAGE_ENTRY } from "../transcript/entries"; import { expect, test } from "bun:test"; import { type TranscriptMessage, @@ -11,7 +10,7 @@ import { type HistorySource, } from "./history-search"; -const context: HistoryContext = { agentId: "bot-a", groupId: null }; +const context: HistoryContext = { agentId: "bot-a" }; type FakeChat = HistoryChat & { messages: TranscriptMessage[] }; @@ -137,57 +136,6 @@ test("search orders dated matches, then undated matches, then by durable identit expect(result.cursor).toBeNull(); }); -test("search reads owner and bot messages in a group and skips other kinds", async () => { - const engine = new HistorySearch( - sourceOf([ - { - id: "group-x", - kind: "group", - name: "Team", - messages: [ - message("group-x", 1, 0, { - kind: GROUP_MESSAGE_ENTRY, - role: "user", - content: "needle owner", - origin: { kind: "owner" }, - timestamp: 10, - }), - message("group-x", 2, 0, { - kind: GROUP_MESSAGE_ENTRY, - role: "assistant", - content: "needle bot", - origin: { kind: "bot", name: "Bea", agentId: "bot-b" }, - timestamp: 20, - }), - message("group-x", 3, 0, { - kind: "crumble.reaction", - role: "user", - content: "needle hidden", - timestamp: 30, - }), - ], - }, - ]), - ); - - const result = await engine.search( - { agentId: "bot-a", groupId: "group-x" }, - { query: "needle" }, - ); - - expect(result.matches.map((match) => match.excerpt)).toEqual([ - "needle bot", - "needle owner", - ]); - expect(result.matches[0]!.sender).toEqual({ - role: "assistant", - name: "Bea", - agentId: "bot-b", - origin: { kind: "bot", name: "Bea", agentId: "bot-b" }, - }); - expect(result.matches[1]!.sender.name).toBe("Owner"); -}); - test("search continues with a cursor and pages through a long transcript", async () => { const messages = Array.from({ length: 25 }, (_, position) => ownerMessage("bot-a", position + 1, `needle ${position + 1}`, position + 1), @@ -377,17 +325,14 @@ test("read rejects malformed or mismatched requests", async () => { await expect(engine.read(context, { match: "hs1.nope" })).rejects.toThrow( "Invalid or expired history token; start a new search", ); - await expect( - engine.read({ agentId: "bot-b", groupId: null }, { match }), - ).rejects.toThrow("Invalid or expired history token; start a new search"); + await expect(engine.read({ agentId: "bot-b" }, { match })).rejects.toThrow( + "Invalid or expired history token; start a new search", + ); await expect(engine.search(context, { cursor: match })).rejects.toThrow( "Expected a history search cursor", ); await expect( - engine.search( - { agentId: "bot-b", groupId: null }, - { cursor: found.cursor ?? match }, - ), + engine.search({ agentId: "bot-b" }, { cursor: found.cursor ?? match }), ).rejects.toThrow("Invalid or expired history token; start a new search"); }); @@ -557,19 +502,19 @@ test("search rejects invalid identifiers and unavailable chats on read", async ( "History message is no longer available; start a new search", ); - const groupOnly = new HistorySearch( + const foreignOnly = new HistorySearch( sourceOf([ { - id: "group-x", - kind: "group", - name: "Team", - messages: [ownerMessage("group-x", 1, "needle", 10)], + id: "bot-x", + kind: "bot", + name: "Other bot", + messages: [ownerMessage("bot-x", 1, "needle", 10)], }, ]), ); await expect( - groupOnly.search(context, { query: "needle" }), + foreignOnly.search(context, { query: "needle" }), ).resolves.toMatchObject({ matches: [], }); diff --git a/apps/server/src/history/history-search.ts b/apps/server/src/history/history-search.ts index 69a5ee80..fd1e39d3 100644 --- a/apps/server/src/history/history-search.ts +++ b/apps/server/src/history/history-search.ts @@ -1,11 +1,6 @@ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; import { z } from "zod"; -import { - ASSISTANT_ENTRY, - GROUP_MESSAGE_ENTRY, - type MessageOrigin, -} from "../transcript/entries"; -import { isBotOrigin, isOwnerOrigin } from "../transcript/origins"; +import { ASSISTANT_ENTRY, type MessageOrigin } from "../transcript/entries"; import { isConversational, isOwnerInput, @@ -29,9 +24,9 @@ const RESULT_MATCHES = 20; const EXCERPT_POINTS = 500; const MAX_QUERY_POINTS = 500; -export type HistoryContext = { agentId: string; groupId: string | null }; +export type HistoryContext = { agentId: string }; -export type HistoryChat = { id: string; kind: "bot" | "group"; name: string }; +export type HistoryChat = { id: string; kind: "bot"; name: string }; export type HistorySource = { chats(context: HistoryContext): Promise; @@ -89,7 +84,7 @@ export type HistoryReadResult = { const snapshotSchema = z.object({ chat: z.object({ id: z.string(), - kind: z.enum(["bot", "group"]), + kind: z.literal("bot"), name: z.string(), }), cutoff: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), @@ -110,7 +105,6 @@ const keySchema = z.object({ const caller = { agentId: z.string(), - groupId: z.string().nullable(), }; const tokenSchema = z.discriminatedUnion("type", [ @@ -201,20 +195,7 @@ function toolActivityOf( return message.kind === ASSISTANT_ENTRY && toolCalls(message).length > 0; } -function groupBody(message: TranscriptMessage): string | null { - if (message.kind !== GROUP_MESSAGE_ENTRY) return null; - - if (message.role !== "user" && message.role !== "assistant") return null; - - if (!isOwnerOrigin(message.origin) && !isBotOrigin(message.origin)) - return null; - - return message.content; -} - -function bodyOf(chat: HistoryChat, message: TranscriptMessage): string | null { - if (chat.kind === "group") return groupBody(message); - +function bodyOf(message: TranscriptMessage): string | null { // Reply context lives in blocks; normalize preserves the owner's metadata text in content. if (isOwnerInput(message)) return message.content; @@ -229,7 +210,7 @@ function rowOf(chat: HistoryChat, message: TranscriptMessage): Row { original: message, entry, index, - body: bodyOf(chat, message), + body: bodyOf(message), toolActivity: toolActivityOf(chat, message), }; } @@ -734,11 +715,7 @@ export class HistorySearch { const payload = tokenSchema.parse(JSON.parse(plaintext)); - if ( - payload.agentId !== context.agentId || - payload.groupId !== context.groupId - ) - throw new Error(); + if (payload.agentId !== context.agentId) throw new Error(); return payload; } catch { @@ -755,9 +732,7 @@ export class HistorySearch { throw new Error("History source returned duplicate chats"); seen.add(chat.id); - return context.groupId !== null - ? chat.kind === "group" && chat.id === context.groupId - : chat.kind === "group" || chat.id === context.agentId; + return chat.id === context.agentId; }); } diff --git a/apps/server/src/history/history-tools.test.ts b/apps/server/src/history/history-tools.test.ts index 692d367a..48aac7bb 100644 --- a/apps/server/src/history/history-tools.test.ts +++ b/apps/server/src/history/history-tools.test.ts @@ -12,8 +12,6 @@ import { import { defineExtension, defineTool } from "@earendil-works/pi-durable"; import { Effect } from "effect"; import { AgentRepository } from "../bot-store/agent-repository"; -import { standaloneGroupChats } from "../group-chats/group-chats-test-support"; -import { GroupTranscripts } from "../group-chats/group-transcripts"; import { HistorySearch } from "./history-search"; import { historySource } from "./history-tools"; import { AgentRuntime } from "../bots/runtime"; @@ -67,11 +65,6 @@ test("history search keeps committed assistant messages visible across turn comp const service = standaloneBots(store, runtime); - const groups = standaloneGroupChats( - service, - new GroupTranscripts(join(dir, "groups")), - ); - try { const agent = store.createAgent({ name: "Ada", @@ -90,11 +83,10 @@ test("history search keeps committed assistant messages visible across turn comp historySource( runtime, store.runtime.runSync(AgentRepository.use(Effect.succeed)), - groups.service, ), ); - const context = { agentId: agent.id, groupId: null }; + const context = { agentId: agent.id }; const chat = await runtime.openChat(agent); const submission = await runtime.submit(agent, chat, "Run the probe."); await waiting.promise; @@ -121,7 +113,6 @@ test("history search keeps committed assistant messages visible across turn comp expect(after.omittedToolActivity).toBe(true); } finally { finish.resolve(); - await groups.close(); await service.close(); rmSync(dir, { recursive: true, force: true }); } diff --git a/apps/server/src/history/history-tools.ts b/apps/server/src/history/history-tools.ts index 84838467..51b34965 100644 --- a/apps/server/src/history/history-tools.ts +++ b/apps/server/src/history/history-tools.ts @@ -1,21 +1,12 @@ import { Type } from "@earendil-works/pi-ai"; -import type { Context } from "@earendil-works/chord"; -import { - defineExtension, - defineTool, - type ConversationId, - type DocumentReader, -} from "@earendil-works/pi-durable"; +import { defineExtension, defineTool } from "@earendil-works/pi-durable"; import { Effect, Layer } from "effect"; import type { Agent } from "../contract/agents"; import { AgentRepository } from "../bot-store/agent-repository"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; import { BotRuntime, type AgentRuntime } from "../bots/runtime"; -import { GroupChats } from "../group-chats/group-chats"; -import { groupOf } from "../group-chats/group-conversation"; import { HistorySearch, - type HistoryChat, type HistoryContext, type HistorySource, } from "./history-search"; @@ -34,19 +25,12 @@ export function historyToolsExtension( agent: Pick, history: HistorySearch, ) { - // A group turn sees only its group, so the scope comes from the calling conversation on every call. - const contextOf = async ( - api: DocumentReader & { conversationId: ConversationId }, - callContext: Context, - ): Promise => ({ - agentId: agent.id, - groupId: await groupOf(api, api.conversationId, callContext), - }); + const context: HistoryContext = { agentId: agent.id }; const search = defineTool({ name: HISTORY_SEARCH_TOOL_NAME, description: - "Search original owner and bot messages in your own bot chat and current group chats. In a group turn, only that group's shared messages are available. Search is literal and case-insensitive; use the returned match token with history_read to read surrounding messages. Pass the cursor to continue a result page.", + "Search original owner and bot messages in your own bot chat. Search is literal and case-insensitive; use the returned match token with history_read to read surrounding messages. Pass the cursor to continue a result page.", parameters: Type.Object({ query: Type.Optional(Type.String()), chatId: Type.Optional(Type.String({ minLength: 1 })), @@ -54,12 +38,8 @@ export function historyToolsExtension( }), callers: ["model"], replay: "safe", - execute: async (args, api, callContext) => - textResult( - JSON.stringify( - await history.search(await contextOf(api, callContext), args), - ), - ), + execute: async (args) => + textResult(JSON.stringify(await history.search(context, args))), }); const read = defineTool({ @@ -75,12 +55,8 @@ export function historyToolsExtension( }), callers: ["model"], replay: "safe", - execute: async (args, api, callContext) => - textResult( - JSON.stringify( - await history.read(await contextOf(api, callContext), args), - ), - ), + execute: async (args) => + textResult(JSON.stringify(await history.read(context, args))), }); return defineExtension({ @@ -89,68 +65,21 @@ export function historyToolsExtension( }); } -async function reachableChats( - context: HistoryContext, - memberOf: ( - agentId: string, - ) => Promise, - agentOf: (agentId: string) => Agent | null, -): Promise { - if (context.groupId) { - const group = (await memberOf(context.agentId)).find( - (candidate) => candidate.id === context.groupId, - ); - - return group ? [{ id: group.id, kind: "group", name: group.name }] : []; - } - - const agent = agentOf(context.agentId); - - const chats: HistoryChat[] = agent - ? [{ id: agent.id, kind: "bot", name: agent.name }] - : []; - - chats.push( - ...(await memberOf(context.agentId)).map((group) => ({ - id: group.id, - kind: "group" as const, - name: group.name, - })), - ); - - return chats; -} - export function historySource( runtime: AgentRuntime, agents: AgentRepository["Service"], - groups: GroupChats["Service"], ): HistorySource { - const memberOf = (agentId: string) => - Effect.runPromise(groups.forMember(agentId)); - const agentOf = (agentId: string) => Effect.runSync(agents.get(agentId)); return { - chats: (context) => reachableChats(context, memberOf, agentOf), - - async page(context, chat, before) { - if (chat.kind === "group") { - if ( - (context.groupId !== null && context.groupId !== chat.id) || - !(await memberOf(context.agentId)).some( - (group) => group.id === chat.id, - ) - ) - throw new Error("Group chat not found"); + chats: async (context) => { + const agent = agentOf(context.agentId); - return Effect.runPromise( - groups.readAsMember(context.agentId, chat.id, { before }), - ); - } + return agent ? [{ id: agent.id, kind: "bot", name: agent.name }] : []; + }, - if (context.groupId !== null || chat.id !== context.agentId) - throw new Error("Bot chat not found"); + async page(context, chat, before) { + if (chat.id !== context.agentId) throw new Error("Bot chat not found"); const agent = agentOf(context.agentId); @@ -164,11 +93,7 @@ export function historySource( export const historyTools = Layer.effectDiscard( Effect.gen(function* () { const history = new HistorySearch( - historySource( - yield* BotRuntime, - yield* AgentRepository, - yield* GroupChats, - ), + historySource(yield* BotRuntime, yield* AgentRepository), ); yield* (yield* BotExtensions).register( diff --git a/apps/server/src/jobs/coding.test.ts b/apps/server/src/jobs/coding.test.ts index e79ba379..e46e5537 100644 --- a/apps/server/src/jobs/coding.test.ts +++ b/apps/server/src/jobs/coding.test.ts @@ -1,5 +1,4 @@ import { afterEach, expect, test } from "bun:test"; -import { openGroupConversation } from "../group-chats/group-turns"; import { inertCredentials } from "../../test/support/job-wiring"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; @@ -641,7 +640,7 @@ async function directWork() { return { runtime, agent, workspace, workspaces, offered, sections, say }; } -test("the bot works in its workspace itself, in its chat and group chats", async () => { +test("the bot works in its workspace itself, in its chat", async () => { const { runtime, agent, workspace, workspaces, offered, say } = await directWork(); @@ -660,23 +659,6 @@ test("the bot works in its workspace itself, in its chat and group chats", async "coding", "request_credential", ]); - - rmSync(join(workspace, "direct.txt")); - const group = await openGroupConversation(runtime, agent, "group-1"); - await say(group, "Write it in the group"); - - expect(readFileSync(join(workspace, "direct.txt"), "utf8")).toBe("direct"); - expect(workspaces.synced).toEqual([agent.id, agent.id]); - expect(offered.at(-1)).toEqual([ - "skill_manage", - "library", - "read", - "write", - "edit", - "bash", - "request_credential", - "pass", - ]); }); test("the chat's prompt never boots a stopped workspace, and shows its notes while it runs", async () => { diff --git a/apps/server/src/jobs/jobs.ts b/apps/server/src/jobs/jobs.ts index 3e379b06..0c31e42d 100644 --- a/apps/server/src/jobs/jobs.ts +++ b/apps/server/src/jobs/jobs.ts @@ -1,4 +1,3 @@ -import { chatOnly } from "../shared/chat-only"; import { JOB_QUESTION_ENTRY, MESSAGE_ENTRY } from "../transcript/entries"; import { sleep } from "../shared/time"; import { jobDeliveryRequest, jobReportRequest } from "../shared/request-ids"; @@ -1388,7 +1387,7 @@ const jobExtensions = ( }); return { - chat: [chatOnly(chat)], + chat: [chat], job: [input.job], }; }; diff --git a/apps/server/src/jobs/workspace-notes.ts b/apps/server/src/jobs/workspace-notes.ts index 1e53d48e..74394045 100644 --- a/apps/server/src/jobs/workspace-notes.ts +++ b/apps/server/src/jobs/workspace-notes.ts @@ -13,7 +13,7 @@ export const WORKSPACE_NOTES_MAX_BYTES = 4096; export const WORKSPACE_NOTES_SECTION = "workspace_notes"; -/** The bot's own workspace section, in its chat and group chats; job sections use other keys, which it must not shadow. */ +/** The bot's own workspace section, in its chat; job sections use other keys, which it must not shadow. */ export const WORKSPACE_SECTION = "workspace"; const NOTES_PATH = `${WORKSPACE_PATH}/${WORKSPACE_NOTES_FILE}`; diff --git a/apps/server/src/learned-changes/change-source.ts b/apps/server/src/learned-changes/change-source.ts index 8794e263..a1eb2c32 100644 --- a/apps/server/src/learned-changes/change-source.ts +++ b/apps/server/src/learned-changes/change-source.ts @@ -2,9 +2,8 @@ import { Effect } from "effect"; import { ExecutionRepository } from "../bot-store/execution-repository"; import type { ChangeBy, ChangeSource } from "../shared/domain"; -/** What a tool call knows of its turn: its group, its inputs, and the execution its review digests. */ +/** What a tool call knows of its turn: its inputs and the execution its review digests. */ export type ChangeContext = { - groupId: string | null; submissionIds: string[]; reviewOf: string | null; }; @@ -24,14 +23,13 @@ export const newestExecution = Effect.fnUntraced(function* ( export const changeSourceOf = Effect.fnUntraced(function* ( agentId: string, - context: { groupId: string | null; submissionIds: string[] }, + context: { submissionIds: string[] }, ) { const execution = yield* newestExecution(agentId, context.submissionIds); return { executionId: execution?.id ?? null, conversationId: execution?.conversationId ?? null, - groupId: context.groupId, } satisfies ChangeSource; }); diff --git a/apps/server/src/learned-changes/learned-change-repository.ts b/apps/server/src/learned-changes/learned-change-repository.ts index 5786aa94..2064f705 100644 --- a/apps/server/src/learned-changes/learned-change-repository.ts +++ b/apps/server/src/learned-changes/learned-change-repository.ts @@ -15,7 +15,6 @@ import { learnedChanges, reviewResults } from "./schema"; const changeSourceSchema = z.object({ executionId: z.exactOptional(z.string().nullable()), conversationId: z.exactOptional(z.string().nullable()), - groupId: z.exactOptional(z.string().nullable()), }); const memorySchema = z.object({ diff --git a/apps/server/src/learned-changes/review-conversation.ts b/apps/server/src/learned-changes/review-conversation.ts index fb0d958f..3c9fdcce 100644 --- a/apps/server/src/learned-changes/review-conversation.ts +++ b/apps/server/src/learned-changes/review-conversation.ts @@ -7,7 +7,6 @@ import { export const ReviewConversation = defineDoc<{ executionId: string | null; - groupId: string | null; skills: boolean; memory: boolean; budgetChars: number; @@ -19,7 +18,6 @@ export const ReviewConversation = defineDoc<{ fork: "initial", initial: () => ({ executionId: null, - groupId: null, skills: false, memory: false, budgetChars: 0, diff --git a/apps/server/src/learning/learning-review.test.ts b/apps/server/src/learning/learning-review.test.ts index a0d2b410..e4417bc7 100644 --- a/apps/server/src/learning/learning-review.test.ts +++ b/apps/server/src/learning/learning-review.test.ts @@ -1,5 +1,4 @@ import { afterEach, expect, test } from "bun:test"; -import { openGroupConversation } from "../group-chats/group-turns"; import { openReviewConversation } from "./review-kind"; import type { Effect } from "effect"; import { mkdtempSync, rmSync } from "node:fs"; @@ -343,7 +342,7 @@ test("turns below the threshold are not reviewed, scheduled runs count like chat expect(store.listPendingReviews()).toEqual([]); }); -test("a review of a group turn cannot change shared memory, while a review of a chat turn can", async () => { +test("a review of a chat turn can change shared memory", async () => { const turn = (answer: string, shared: string): FauxResponseStep[] => [ fauxAssistantMessage([fauxToolCall("memory", { action: "list" })], { stopReason: "toolUse", @@ -362,9 +361,8 @@ test("a review of a group turn cannot change shared memory, while a review of a fauxAssistantMessage("Done."), ]; - const { store, runtime, service, faux } = open([ + const { store, service, faux } = open([ ...turn("For the owner.", "from the chat"), - ...turn("For the group.", "from the group"), ]); const agent = store.createAgent({ @@ -381,14 +379,6 @@ test("a review of a group turn cannot change shared memory, while a review of a const chatTurn = await service.sendChat(agent.id, "hello", uuid(1)); expect(await settle(service, chatTurn.id)).toBe("done"); - await until(() => faux.getPendingResponseCount() === 4); - await until(() => store.listPendingReviews().length === 0); - expect(await shared()).toEqual(["from the chat"]); - - const group = await openGroupConversation(runtime, agent, "group-1"); - store.createConversation({ agentId: agent.id, title: "Group" }, group); - const groupTurn = await service.send(group, "hello", "group-turn:1"); - expect(await settle(service, groupTurn.id)).toBe("done"); await until(() => faux.getPendingResponseCount() === 0); await until(() => store.listPendingReviews().length === 0); expect(await shared()).toEqual(["from the chat"]); diff --git a/apps/server/src/learning/review-kind.ts b/apps/server/src/learning/review-kind.ts index 750df510..55487a70 100644 --- a/apps/server/src/learning/review-kind.ts +++ b/apps/server/src/learning/review-kind.ts @@ -1,4 +1,3 @@ -import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; import { defineExtension, GenerationTask, @@ -8,8 +7,6 @@ import type { AgentRuntime } from "../bots/runtime"; import type { ConversationKind } from "../bot-ports/conversation-kind"; import { defineAnchorTask } from "../shared/anchor-task"; import type { Agent } from "../contract/agents"; -import { localConversationId } from "../shared/entry-ids"; -import { groupOf } from "../group-chats/group-conversation"; import { ReviewConversation, reviewOf, @@ -18,7 +15,7 @@ import { reviewInstructions, type ReviewScope } from "./review-instructions"; export const REVIEW_EXTENSION = "learning-review"; -// Owns a review conversation, so it stays out of the bot chat transcript, like a group conversation's anchor. +// Owns a review conversation, so it stays out of the bot chat transcript, separate from the reviewed turn. export const ReviewAnchor = defineAnchorTask("crumble.review-anchor"); export class ReviewBudgetExceeded extends Error { @@ -110,16 +107,9 @@ export async function openReviewConversation( scope: ReviewScope, budgetChars: number, ) { - const reviewedGroup = await groupOf( - await runtime.documents(agent), - localConversationId(agent.id, reviewed.conversationId), - BACKGROUND_CONTEXT, - ); - return runtime.openAnchored(agent, ReviewAnchor, async (tx, id) => { const doc = await tx.doc(ReviewConversation, id); doc.executionId = reviewed.id; - doc.groupId = reviewedGroup; doc.skills = scope.skills; doc.memory = scope.memory; doc.budgetChars = budgetChars; diff --git a/apps/server/src/memory/bot-memory.test.ts b/apps/server/src/memory/bot-memory.test.ts index b6fdd4fa..375a274e 100644 --- a/apps/server/src/memory/bot-memory.test.ts +++ b/apps/server/src/memory/bot-memory.test.ts @@ -21,7 +21,6 @@ const run = ( ) => store.runtime.runPromise(BotMemory.use(use)); const chat: MemoryContext = { - groupId: null, submissionIds: [], reviewOf: null, }; @@ -59,34 +58,26 @@ describe("BotMemory", () => { }); }); - test("refuses empty memories, and any change to shared ones in a group", async () => { - const group = { ...chat, groupId: "g" }; - + test("refuses empty memories and permits shared memory changes in the bot chat", async () => { await expect( run((memory) => memory.create(solo.id, " ", false, chat)), ).rejects.toThrow("Memory must contain"); - await expect( - run((memory) => memory.create(sharing.id, "x", true, group)), - ).rejects.toThrow("save to your own memory"); - const shared = await run((memory) => memory.create(sharing.id, "for all", true, chat), ); - - await expect( - run((memory) => memory.update(sharing.id, shared.id, "y", group)), - ).rejects.toThrow("save to your own memory"); - await expect( - run((memory) => memory.delete(sharing.id, shared.id, group)), - ).rejects.toThrow("save to your own memory"); - - const own = await run((memory) => - memory.create(sharing.id, "mine", false, group), - ); - - expect(own.content).toBe("mine"); - await run((memory) => memory.delete(sharing.id, own.id, group)); + expect( + ( + await run((memory) => + memory.update(sharing.id, shared.id, "updated", chat), + ) + ).content, + ).toBe("updated"); await run((memory) => memory.delete(sharing.id, shared.id, chat)); + expect( + (await run((memory) => memory.list(sharing.id))).some( + (memory) => memory.id === shared.id, + ), + ).toBe(false); }); test("another bot's memory is not found, and a review's change names the review", async () => { diff --git a/apps/server/src/memory/bot-memory.ts b/apps/server/src/memory/bot-memory.ts index 3baf2fad..38033708 100644 --- a/apps/server/src/memory/bot-memory.ts +++ b/apps/server/src/memory/bot-memory.ts @@ -3,11 +3,10 @@ import { type ChangeBy, type Memory } from "../shared/domain"; import type { MemoryContext } from "./memory-tool"; import { AgentRepository } from "../bot-store/agent-repository"; import type { ExecutionRepository } from "../bot-store/execution-repository"; -import type { GroupChatRepository } from "../group-chats/group-chat-repository"; import type { ScheduleRepository } from "../automations/schedule-repository"; import { changeByOf } from "../learned-changes/change-source"; import { MemoryRepository } from "./memory-repository"; -import { assertOwnMemoryInGroup, memorySourceOf } from "./memory-sources"; +import { memorySourceOf } from "./memory-sources"; import { InvalidInput, NotFound, type AppError } from "../shared/errors"; import { MAX_MEMORY_CHARS } from "../shared/limits"; @@ -52,10 +51,7 @@ export class BotMemory extends Context.Service< const agents = yield* AgentRepository; const sources = yield* Effect.context< - | AgentRepository - | ExecutionRepository - | GroupChatRepository - | ScheduleRepository + AgentRepository | ExecutionRepository | ScheduleRepository >(); const usesSharedMemory = (agentId: string) => @@ -101,7 +97,6 @@ export class BotMemory extends Context.Service< create: Effect.fn("BotMemory.create")( function* (agentId, content, shared, context) { yield* validContent(content); - yield* assertOwnMemoryInGroup(context, shared); const source = yield* memorySourceOf(agentId, context).pipe( Effect.provideContext(sources), @@ -116,8 +111,7 @@ export class BotMemory extends Context.Service< ), update: Effect.fn("BotMemory.update")( function* (agentId, id, content, context) { - const memory = yield* reachable(agentId, id); - yield* assertOwnMemoryInGroup(context, memory.agentId === null); + yield* reachable(agentId, id); yield* validContent(content); const updated = yield* memories.update( @@ -135,8 +129,7 @@ export class BotMemory extends Context.Service< }, ), delete: Effect.fn("BotMemory.delete")(function* (agentId, id, context) { - const memory = yield* reachable(agentId, id); - yield* assertOwnMemoryInGroup(context, memory.agentId === null); + yield* reachable(agentId, id); yield* memories.delete(id, yield* changeBy(agentId, context)); }), }); diff --git a/apps/server/src/memory/memory-sources.test.ts b/apps/server/src/memory/memory-sources.test.ts index 02113f76..cd8cd994 100644 --- a/apps/server/src/memory/memory-sources.test.ts +++ b/apps/server/src/memory/memory-sources.test.ts @@ -1,5 +1,4 @@ import { afterEach, describe, expect, test } from "bun:test"; -import { openGroupConversation } from "../group-chats/group-turns"; import { mkdtempSync, rmSync } from "node:fs"; import { join } from "node:path"; import { tmpdir } from "node:os"; @@ -73,7 +72,6 @@ describe("a memory's source", () => { await store.runtime.runPromise( BotMemory.use((memory) => memory.create(agent.id, "fact", false, { - groupId: null, submissionIds: [], reviewOf: null, ...context, @@ -85,21 +83,6 @@ describe("a memory's source", () => { return { store, agent, other, execution, sourceOf }; } - test("names the group of a group turn", async () => { - const { store, agent, other, sourceOf } = setup(); - - const group = store.createGroupChat({ - name: "Trip", - memberIds: [agent.id, other.id], - }); - - expect(await sourceOf({ groupId: group.id })).toEqual({ - kind: "group", - groupId: group.id, - name: "Trip", - }); - }); - test("takes the newest input of a chat run", async () => { const { store, agent, other, execution, sourceOf } = setup(); @@ -192,11 +175,10 @@ test("the memory tool reports where it runs", async () => { cleanups.push(() => runtime.close()); const chat = await runtime.openChat(agent); - const group = await openGroupConversation(runtime, agent, "group-1"); const submissions: string[] = []; - for (const conversation of [chat, group]) { + for (const conversation of [chat]) { const submission = await runtime.submit(agent, conversation, "remember"); submissions.push(submission); @@ -204,7 +186,6 @@ test("the memory tool reports where it runs", async () => { } expect(contexts).toEqual([ - { groupId: null, submissionIds: [submissions[0]!], reviewOf: null }, - { groupId: "group-1", submissionIds: [submissions[1]!], reviewOf: null }, + { submissionIds: [submissions[0]!], reviewOf: null }, ]); }); diff --git a/apps/server/src/memory/memory-sources.ts b/apps/server/src/memory/memory-sources.ts index 0f21659b..4f86e0b1 100644 --- a/apps/server/src/memory/memory-sources.ts +++ b/apps/server/src/memory/memory-sources.ts @@ -3,9 +3,7 @@ import type { MemorySource } from "../shared/domain"; import type { MemoryContext } from "./memory-tool"; import { AgentRepository } from "../bot-store/agent-repository"; import { newestExecution } from "../learned-changes/change-source"; -import { GroupChatRepository } from "../group-chats/group-chat-repository"; import { ScheduleRepository } from "../automations/schedule-repository"; -import { InvalidInput, type AppError } from "../shared/errors"; import { turnSource, UNKNOWN_BOT_NAME, @@ -16,16 +14,6 @@ export const memorySourceOf = Effect.fnUntraced(function* ( agentId: string, context: MemoryContext, ) { - if (context.groupId) { - const group = yield* (yield* GroupChatRepository).get(context.groupId); - - return { - kind: "group", - groupId: context.groupId, - name: group?.name ?? "Group chat", - } satisfies MemorySource; - } - const execution = yield* newestExecution(agentId, context.submissionIds); const source = execution && turnSource(execution); @@ -52,17 +40,3 @@ export const memorySourceOf = Effect.fnUntraced(function* ( return { kind: "chat" } satisfies MemorySource; }); - -/** A group turn writes only to the bot's own memory, so one conversation cannot change every bot's context. */ -export const assertOwnMemoryInGroup = ( - context: MemoryContext, - shared: boolean, -): Effect.Effect => - context.groupId && shared - ? Effect.fail( - new InvalidInput({ - message: - "In a group chat, save to your own memory; shared memory cannot be changed here", - }), - ) - : Effect.void; diff --git a/apps/server/src/memory/memory-tool.ts b/apps/server/src/memory/memory-tool.ts index 99f06564..eea77160 100644 --- a/apps/server/src/memory/memory-tool.ts +++ b/apps/server/src/memory/memory-tool.ts @@ -9,7 +9,6 @@ import { MEMORY_TOOL_NAME, MEMORY_WRITE_ACTIONS, } from "../contract/tools"; -import { groupOf } from "../group-chats/group-conversation"; import type { Agent } from "../contract/agents"; import { MAX_MEMORY_CHARS } from "../shared/limits"; import type { ChangeContext } from "../learned-changes/change-source"; @@ -123,7 +122,7 @@ export function memoryExtension( const tool = defineTool({ name: MEMORY_TOOL_NAME, description: - "Read and manage this bot’s persistent memory. When the bot uses shared memory, `list` also returns shared memories (marked `shared`), which other bots see too; create one with `shared: true` only for what every bot should know. In a group chat only your own memory can be changed.", + "Read and manage this bot’s persistent memory. When the bot uses shared memory, `list` also returns shared memories (marked `shared`), which other bots see too; create one with `shared: true` only for what every bot should know.", parameters: Type.Object({ action: Type.Union([ Type.Literal("list"), @@ -140,13 +139,9 @@ export function memoryExtension( execute: async (args, api, callContext) => { const live = await api.snapshot(LiveDoc, api.conversationId, callContext); - const [groupId, review] = await Promise.all([ - groupOf(api, api.conversationId, callContext), - reviewOf(api, api.conversationId, callContext), - ]); + const review = await reviewOf(api, api.conversationId, callContext); const context: MemoryContext = { - groupId: groupId ?? review?.groupId ?? null, submissionIds: (live?.run?.inputs ?? []).map(String), reviewOf: review?.executionId ?? null, }; diff --git a/apps/server/src/push/chat-attention.ts b/apps/server/src/push/chat-attention.ts index 0a09e947..9daa360d 100644 --- a/apps/server/src/push/chat-attention.ts +++ b/apps/server/src/push/chat-attention.ts @@ -8,7 +8,6 @@ import type { } from "../contract/push"; import { replySurface } from "../contract/push"; import { replyEvent } from "../contract/reply-event"; -import { GroupChatRepository } from "../group-chats/group-chat-repository"; import { Conflict, NotFound } from "../shared/errors"; import { PushDatabase } from "./push-database"; import { chatViews, pushOutbox, replyAssociations } from "./schema"; @@ -51,14 +50,11 @@ export class ChatAttention extends Context.Service< Effect.gen(function* () { const db = yield* PushDatabase; const agents = yield* AgentRepository; - const groups = yield* GroupChatRepository; const exists = Effect.fn("ChatAttention.exists")(function* ( chat: ChatReference, ) { - return !!(yield* chat.kind === "bot" - ? agents.get(chat.id) - : groups.get(chat.id)); + return !!(yield* agents.get(chat.id)); }); const requireChat = Effect.fnUntraced(function* (chat: ChatReference) { @@ -269,11 +265,7 @@ export class ChatAttention extends Context.Service< for (const row of rows) { const event = replyEvent.parse(JSON.parse(row.eventJson)); - if ( - event.groupId - ? chat.kind === "group" && event.groupId === chat.id - : chat.kind === "bot" && event.agentId === chat.id - ) + if (event.agentId === chat.id) yield* tx.delete(pushOutbox).where(eq(pushOutbox.id, row.id)); } }), @@ -307,9 +299,7 @@ export class ChatAttention extends Context.Service< for (const row of outbox) { const event = replyEvent.parse(JSON.parse(row.eventJson)); - const chat: ChatReference = event.groupId - ? { kind: "group", id: event.groupId } - : { kind: "bot", id: event.agentId }; + const chat: ChatReference = { kind: "bot", id: event.agentId }; chats.set(`${chat.kind}:${chat.id}`, chat); } diff --git a/apps/server/src/push/push-model.ts b/apps/server/src/push/push-model.ts index 2dc344cb..de38a628 100644 --- a/apps/server/src/push/push-model.ts +++ b/apps/server/src/push/push-model.ts @@ -11,10 +11,7 @@ export type PushDevice = PushDeviceInput & { updatedAt: string; }; -export const notificationTitle = (event: ReplyEvent) => - event.groupName - ? `${event.agentName} in ${event.groupName}` - : event.agentName; +export const notificationTitle = (event: ReplyEvent) => event.agentName; export function notificationPreview(value: string) { const cleaned = value diff --git a/apps/server/src/push/push-transports.test.ts b/apps/server/src/push/push-transports.test.ts index 30f6dc87..5dc9b312 100644 --- a/apps/server/src/push/push-transports.test.ts +++ b/apps/server/src/push/push-transports.test.ts @@ -279,19 +279,17 @@ describe("APNs requests", () => { }); }); - test("the alert shows the bot, the group, and the reply fields", () => { + test("the alert shows the bot and the reply fields", () => { const payload = apnsPayload( event({ agentName: "Ada", - origin: "group", + origin: "owner", preview: "**Booked.**", - groupId: "group-1", - groupName: "Trip", }), ); expect(payload.aps).toEqual({ - alert: { title: "Ada in Trip", body: "Booked." }, + alert: { title: "Ada", body: "Booked." }, sound: "default", }); expect(payload).toMatchObject({ @@ -301,11 +299,9 @@ describe("APNs requests", () => { agentId: "agent", agentName: "Ada", entryId: null, - origin: "group", + origin: "owner", preview: "**Booked.**", createdAt: "2026-01-01T00:00:00.000Z", - groupId: "group-1", - groupName: "Trip", }); expect(payload).not.toHaveProperty("jobName"); }); @@ -396,12 +392,8 @@ describe("FCM requests", () => { expect(data).not.toHaveProperty("jobName"); }); - test("data carries the group and job the answer came from", () => { - expect( - fcmData(event({ groupId: "group-1", jobName: "github-login" })), - ).toMatchObject({ - groupId: "group-1", - groupName: "", + test("data carries the job the answer came from", () => { + expect(fcmData(event({ jobName: "github-login" }))).toMatchObject({ jobName: "github-login", }); }); diff --git a/apps/server/src/push/push-transports.ts b/apps/server/src/push/push-transports.ts index 3a486809..1ede53a7 100644 --- a/apps/server/src/push/push-transports.ts +++ b/apps/server/src/push/push-transports.ts @@ -268,10 +268,6 @@ const replyFields = (event: ReplyEvent) => ({ origin: event.origin, preview: event.preview, createdAt: event.createdAt, - ...(event.groupId && { - groupId: event.groupId, - groupName: event.groupName, - }), ...(event.jobName && { jobName: event.jobName }), ...(event.waitingFor && { waitingFor: event.waitingFor }), }); diff --git a/apps/server/src/push/push.test.ts b/apps/server/src/push/push.test.ts index 2e0eea8d..5f82e2fc 100644 --- a/apps/server/src/push/push.test.ts +++ b/apps/server/src/push/push.test.ts @@ -18,7 +18,7 @@ import { type ReplyActivity, type ReplyEvent, } from "../contract/reply-event"; -import { notificationTitle, type PushDeviceInput } from "./push-model"; +import type { PushDeviceInput } from "./push-model"; import { PushRepository } from "./push-repository"; import { PermanentRejection, @@ -51,8 +51,6 @@ import { } from "../credentials/credentials"; import { loginExtension, loginsAccess } from "../logins/logins"; import { parseEntryId } from "../shared/entry-ids"; -import { standaloneGroupChats } from "../group-chats/group-chats-test-support"; -import { GroupTranscripts } from "../group-chats/group-transcripts"; type TestRequestInit = Omit & { headers?: Record; @@ -319,80 +317,6 @@ describe("push registration and durable delivery", () => { await second.dispose(); }); - test("delivers a group answer even while its bot's chat is visible", async () => { - const dir = tempDir("crumble-push-"); - const now = 1_000_000; - const installationId = id(); - const agentId = id(); - const sent: ReplyEvent[] = []; - - const push = await pushRuntime( - dir, - fcmOnly({ - send: (_device, event) => - Effect.sync(() => { - sent.push(event); - - return "delivered" as const; - }), - }), - now, - ); - - const groupStore = new Store(push); - createBot(groupStore, agentId); - groupStore.createGroupChat( - { name: "Trip", memberIds: [agentId] }, - "group-1", - ); - const answer = reply(agentId, now); - - const serverId = await push.runPromise( - Effect.gen(function* () { - const store = yield* PushRepository; - yield* store.upsertDevice(installationId, android("token")); - yield* (yield* ChatAttention).view(installationId, { - kind: "bot", - id: agentId, - }); - - const service = yield* Push; - - yield* service.enqueue({ - ...answer, - agentName: "Ada", - entryId: "group-1:4", - origin: "group", - preview: "Booked.", - groupId: "group-1", - groupName: "Trip", - }); - yield* TestClock.adjust(3000); - yield* service.drain; - - return service.serverId; - }), - ); - - expect(sent).toEqual([ - { - type: "reply", - eventId: answer.executionId, - serverId, - agentId, - agentName: "Ada", - entryId: "group-1:4", - origin: "group", - preview: "Booked.", - createdAt: "1970-01-01T00:16:40.000Z", - groupId: "group-1", - groupName: "Trip", - }, - ]); - expect(notificationTitle(sent[0]!)).toBe("Ada in Trip"); - await push.dispose(); - }); - test("suppresses visible-agent replies and sends once across concurrent drains", async () => { const dir = tempDir("crumble-push-"); const now = 1_000_000; @@ -873,20 +797,18 @@ test("suppresses matching chats across views and destination devices", async () mcpServers: [], delegates: [], }); - const group = store.createGroupChat({ name: "Group", memberIds: [agent.id] }); + const otherBot = store.duplicateAgent(agent.id, "Other")!; const botChat = { kind: "bot" as const, id: agent.id }; - const groupChat = { kind: "group" as const, id: group.id }; + const otherChat = { kind: "bot" as const, id: otherBot.id }; const botHidden = reply(agent.id, 0); const waiting = { ...reply(agent.id, 0), waitingFor: "approval" as const }; - const groupHidden = { + const otherHidden = { ...reply(agent.id, 0), - origin: "group", - groupId: group.id, + agentId: otherBot.id, }; - const groupVisible = { + const otherVisible = { ...reply(agent.id, 0), - origin: "group", - groupId: group.id, + agentId: otherBot.id, }; const botVisible = reply(agent.id, 0); const afterClear = reply(agent.id, 0); @@ -901,16 +823,16 @@ test("suppresses matching chats across views and destination devices", async () yield* push.device(id(), android("two")); yield* push.enqueue(botHidden); yield* push.enqueue(waiting); - yield* push.enqueue(groupVisible); + yield* push.enqueue(otherVisible); yield* TestClock.adjust(3000); yield* push.drain; expect(sent.map((s) => s.eventId)).toEqual([ - groupVisible.executionId, - groupVisible.executionId, + otherVisible.executionId, + otherVisible.executionId, ]); - yield* attention.view("group", groupChat); + yield* attention.view("other", otherChat); yield* attention.view("web", null); - yield* push.enqueue(groupHidden); + yield* push.enqueue(otherHidden); yield* push.enqueue(reply(agent.id, 3000)); yield* TestClock.adjust(3000); yield* push.drain; @@ -925,11 +847,10 @@ test("suppresses matching chats across views and destination devices", async () .map((s) => s.token) .sort(), ).toEqual(["one", "two"]); - yield* attention.view("group", null); + yield* attention.view("other", null); yield* push.enqueue({ ...afterClear, - origin: "group", - groupId: group.id, + agentId: otherBot.id, }); yield* TestClock.adjust(3000); yield* push.drain; @@ -1269,7 +1190,6 @@ test("acknowledges exact reply surfaces before enqueue and after restart", async fauxAssistantMessage(`Please provide ${name}.`), ]), fauxAssistantMessage("another answer"), - fauxAssistantMessage("A group answer."), ]); const models = createModels(); models.setProvider(faux.provider); @@ -1414,56 +1334,14 @@ test("acknowledges exact reply surfaces before enqueue and after restart", async ); await push.runPromise(Push.use((p) => p.enqueue(held))); suppressed.push(held); - const groups = standaloneGroupChats( - service, - new GroupTranscripts(join(dir, "groups")), - ); - const group = groups.create({ name: "Trip", memberIds: [agent.id] }); - const groupChat = { kind: "group" as const, id: group.id }; - await groups.post(group.id, "Plan the trip", id()); - await until(() => - activities.some((activity) => activity.groupId === group.id), - ); - const groupActivity = activities.find( - (activity) => activity.groupId === group.id, - )!; - const groupMessages = (await groups.history(group.id, { limit: 200 })) - .messages; - const groupMessage = groupMessages.find( - (message) => message.content === "A group answer.", - )!; - expect(groupActivity.entryId).toBe(groupMessage.entryId); - expect(groupMessage.replyReferences).toEqual([ - { eventId: groupActivity.executionId, surface: { kind: "text" } }, - ]); - expect( - (await groups.snapshot(group.id, { limit: 200 })).messages.find( - (message) => message.id === groupMessage.id, - )?.replyReferences, - ).toEqual(groupMessage.replyReferences); - expect( - (await service.history(agent.id, { limit: 200 })).messages - .flatMap((message) => message.replyReferences) - .some((reference) => reference.eventId === groupActivity.executionId), - ).toBe(false); await push.runPromise( ChatAttention.use((attention) => - attention.seen(groupChat, [groupActivity.executionId]), - ), - ); - await push.runPromise(Push.use((p) => p.enqueue(groupActivity))); - await push.runPromise( - ChatAttention.use((attention) => - Effect.gen(function* () { - yield* attention.seen( - chat, - suppressed.map((activity) => activity.executionId), - ); - yield* attention.seen(groupChat, [groupActivity.executionId]); - }), + attention.seen( + chat, + suppressed.map((activity) => activity.executionId), + ), ), ); - await groups.close(); await service.close(); await push.dispose(); const reopened = openPush(); @@ -1471,7 +1349,6 @@ test("acknowledges exact reply surfaces before enqueue and after restart", async Effect.gen(function* () { const p = yield* Push; for (const activity of suppressed) yield* p.enqueue(activity); - yield* p.enqueue(groupActivity); yield* p.enqueue(secondActivity); yield* TestClock.adjust(3000); yield* p.drain; diff --git a/apps/server/src/push/push.ts b/apps/server/src/push/push.ts index 1882375a..ccd010d1 100644 --- a/apps/server/src/push/push.ts +++ b/apps/server/src/push/push.ts @@ -152,9 +152,7 @@ export class Push extends Context.Service< const event = yield* decodeEvent(row.eventJson).pipe(Effect.orDie); - const chat = event.groupId - ? { kind: "group" as const, id: event.groupId } - : { kind: "bot" as const, id: event.agentId }; + const chat = { kind: "bot" as const, id: event.agentId }; const suppressed = yield* attention .isSuppressed(chat, event.eventId) @@ -202,9 +200,7 @@ export class Push extends Context.Service< const enqueue = Effect.fn("Push.enqueue")(function* ( activity: ReplyActivity, ) { - const chat = activity.groupId - ? { kind: "group" as const, id: activity.groupId } - : { kind: "bot" as const, id: activity.agentId }; + const chat = { kind: "bot" as const, id: activity.agentId }; if (!(yield* attention.exists(chat))) return; diff --git a/apps/server/src/push/schema.ts b/apps/server/src/push/schema.ts index 65dbc071..46bb8231 100644 --- a/apps/server/src/push/schema.ts +++ b/apps/server/src/push/schema.ts @@ -28,14 +28,14 @@ export const pushDevices = sqliteTable("push_devices", { export const chatViews = sqliteTable("chat_views", { viewId: text("view_id").primaryKey(), - chatKind: text("chat_kind", { enum: ["bot", "group"] }).notNull(), + chatKind: text("chat_kind", { enum: ["bot"] }).notNull(), chatId: text("chat_id").notNull(), refreshedAt: integer("refreshed_at").notNull(), }); export const replyAssociations = sqliteTable("reply_associations", { eventId: text("event_id").primaryKey(), - chatKind: text("chat_kind", { enum: ["bot", "group"] }).notNull(), + chatKind: text("chat_kind", { enum: ["bot"] }).notNull(), chatId: text("chat_id").notNull(), messageId: text("message_id").notNull(), entryId: text("entry_id").notNull(), diff --git a/apps/server/src/shared/chat-only.ts b/apps/server/src/shared/chat-only.ts index 9d4e5ce5..e7e21d0c 100644 --- a/apps/server/src/shared/chat-only.ts +++ b/apps/server/src/shared/chat-only.ts @@ -1,16 +1,8 @@ import type { Extension } from "@earendil-works/pi-durable"; -const chatOnlyExtensions = new WeakSet(); - const callOnlyExtensions = new WeakSet(); -export const chatOnly = (extension: E) => { - chatOnlyExtensions.add(extension); - - return extension; -}; - -/** Offered only to the conversation of an outside call: the chat and group turns leave it out. */ +/** Offered only to the conversation of an outside call: the bot chat leaves it out. */ export const callOnly = (extension: E) => { callOnlyExtensions.add(extension); @@ -21,6 +13,3 @@ export const isCallOnly = (extension: Extension) => callOnlyExtensions.has(extension); export const inChat = (extension: Extension) => !isCallOnly(extension); - -export const inGroupTurns = (extension: Extension) => - !chatOnlyExtensions.has(extension) && inChat(extension); diff --git a/apps/server/src/shared/domain.ts b/apps/server/src/shared/domain.ts index dfa8ad63..4a5036b3 100644 --- a/apps/server/src/shared/domain.ts +++ b/apps/server/src/shared/domain.ts @@ -1,12 +1,6 @@ import { z } from "zod"; -export const MEMORY_SOURCE_KINDS = [ - "chat", - "owner", - "task", - "bot", - "group", -] as const; +export const MEMORY_SOURCE_KINDS = ["chat", "owner", "task", "bot"] as const; const memorySourceKind = z.enum(MEMORY_SOURCE_KINDS); @@ -23,11 +17,6 @@ export const memorySource = z.discriminatedUnion("kind", [ agentId: z.string(), name: z.string(), }), - z.object({ - kind: memorySourceKind.extract(["group"]), - groupId: z.string(), - name: z.string(), - }), ]); export type MemorySource = z.infer; @@ -97,7 +86,6 @@ export type ChangeActor = (typeof CHANGE_ACTORS)[number]; export type ChangeSource = { executionId?: string | null; conversationId?: string | null; - groupId?: string | null; }; export type ChangeBy = { actor: ChangeActor; source?: ChangeSource | null }; diff --git a/apps/server/src/shared/entry-ids.ts b/apps/server/src/shared/entry-ids.ts index 79311d3d..e57c3ae2 100644 --- a/apps/server/src/shared/entry-ids.ts +++ b/apps/server/src/shared/entry-ids.ts @@ -9,7 +9,7 @@ export const positiveId = (raw: string) => ? Number(raw) : undefined; -/** `:`: a durable entry or conversation of a bot or group. Entry numbers are unique across its conversations. */ +/** `:`: a durable entry or conversation of a bot. Entry numbers are unique across its conversations. */ export const formatEntryId = (owner: string, id: number) => `${owner}:${id}`; export const formatMessageId = (entryId: string, index: number) => diff --git a/apps/server/src/shared/limits.ts b/apps/server/src/shared/limits.ts index 8b619d67..f5945d0a 100644 --- a/apps/server/src/shared/limits.ts +++ b/apps/server/src/shared/limits.ts @@ -39,10 +39,6 @@ export const MAX_CREDENTIAL_HOST_CHARS = 253; export const MAX_CREDENTIAL_HOSTS = 20; export const MAX_SECRET_CHARS = 16000; -export const MIN_GROUP_MEMBERS = 2; -export const MAX_GROUP_MEMBERS = 6; -export const MAX_GROUP_NAME_CHARS = 80; - export const clip = (text: string, max: number) => text.length > max ? `${text.slice(0, max - 1)}…` : text; diff --git a/apps/server/src/shared/request-ids.test.ts b/apps/server/src/shared/request-ids.test.ts index e8ec29dc..d165f3fa 100644 --- a/apps/server/src/shared/request-ids.test.ts +++ b/apps/server/src/shared/request-ids.test.ts @@ -4,9 +4,6 @@ import { delegationRequest, eventRequest, gatewayRequest, - groupPostRequest, - groupTurnRequest, - groupTurnScope, jobDeliveryRequest, jobQuestionRequest, jobReportRequest, @@ -38,27 +35,12 @@ describe("request IDs", () => { [voiceCallRequest("c1", "started"), "voice-call:c1:started"], [voiceCallRequest("c1", "ended"), "voice-call:c1:ended"], [reviewRequest("x1"), "review:x1"], - [groupTurnRequest("g1", "a1", 7), "group-turn:g1:a1:7"], - [groupPostRequest("x1"), "group-turn:x1"], [jobDeliveryRequest("coding", 42), "coding:42"], [jobReportRequest("desktop", 42), "desktop-report:42"], ])("%s keeps its format", (built, stored) => { expect(built).toBe(stored); }); - test("group turn scope accepts only canonical member turn IDs", () => { - expect(groupTurnScope(groupTurnRequest("g1", "a1", 7), "a1")).toEqual({ - kind: "group", - groupId: "g1", - }); - expect( - groupTurnScope(groupTurnRequest("g1", "a1", 7), "a2"), - ).toBeUndefined(); - expect(groupTurnScope(groupPostRequest("x1"), "a1")).toBeUndefined(); - expect(groupTurnScope("group-turn:g1:a1:7:extra", "a1")).toBeUndefined(); - expect(groupTurnScope("group-turn:g1:a1:-1", "a1")).toBeUndefined(); - }); - test.each([ [scheduleRequest("s1", due), { kind: "schedule", scheduleId: "s1", due }], [ @@ -93,8 +75,6 @@ describe("request IDs", () => { [voiceRequest("c1", "u1"), { kind: "voice", callId: "c1", id: "u1" }], [voiceCallRequest("c1", "ended"), { kind: "voice-call", callId: "c1" }], [reviewRequest("x1"), { kind: "review", executionId: "x1" }], - [groupTurnRequest("g1", "a1", 7), { kind: "group-turn" }], - [groupPostRequest("x1"), { kind: "group-turn" }], [jobDeliveryRequest("coding", 42), { kind: "other" }], [jobReportRequest("desktop", 42), { kind: "other" }], ["0b0e1f2a-5b1c-4a9e-8f00-000000000000", { kind: "other" }], diff --git a/apps/server/src/shared/request-ids.ts b/apps/server/src/shared/request-ids.ts index 3e1a0a8e..66fa2c27 100644 --- a/apps/server/src/shared/request-ids.ts +++ b/apps/server/src/shared/request-ids.ts @@ -44,32 +44,6 @@ export const botMessageRequest = (executionId: string, status: string) => export const reviewRequest = (executionId: string) => `review:${executionId}`; -export const groupTurnRequest = ( - groupId: string, - agentId: string, - through: number, -) => `group-turn:${groupId}:${agentId}:${through}`; - -export const groupPostRequest = (executionId: string) => - `group-turn:${executionId}`; - -export function groupTurnScope(requestId: string, agentId: string) { - const [prefix, groupId, memberId, through, ...extra] = requestId.split(":"); - - if ( - prefix !== "group-turn" || - !groupId || - memberId !== agentId || - !through || - !/^(0|[1-9]\d*)$/.test(through) || - !Number.isSafeInteger(Number(through)) || - extra.length > 0 - ) - return; - - return { kind: "group" as const, groupId }; -} - /** The ID a job's turn is reviewed under: it has no execution, so nothing resolves this as one. */ export const jobTurnId = ( jobKind: string, @@ -98,7 +72,6 @@ export type ParsedRequest = | { kind: "outside-call"; callId: string; id: string } | { kind: "call-request"; callRequestId: string } | { kind: "review"; executionId: string } - | { kind: "group-turn" } /** A client's own ID. Job deliveries and reports land here too: they never become executions, so nothing decodes them. */ | { kind: "other" }; @@ -162,8 +135,6 @@ export function parseRequestId(requestId: string): ParsedRequest { const [prefix, subject, ...rest] = requestId.split(":"); const detail = rest.join(":"); - if (prefix === "group-turn") return { kind: "group-turn" }; - if (!subject || !prefix) return { kind: "other" }; return PREFIXES.get(prefix)?.(subject, detail) ?? { kind: "other" }; diff --git a/apps/server/src/shared/store.test.ts b/apps/server/src/shared/store.test.ts index 07851cb2..98e8da61 100644 --- a/apps/server/src/shared/store.test.ts +++ b/apps/server/src/shared/store.test.ts @@ -62,7 +62,7 @@ describe("Store", () => { ALTER TABLE agents ADD COLUMN delegates text NOT NULL DEFAULT '[]'; ALTER TABLE agents ADD COLUMN shared_memory integer NOT NULL DEFAULT 0; ALTER TABLE skills DROP COLUMN copied_from_skill_id; - DELETE FROM __drizzle_migrations WHERE id IN (SELECT id FROM __drizzle_migrations ORDER BY id DESC LIMIT 8)`, + DELETE FROM __drizzle_migrations WHERE name >= '20261102093803_skill_copy_provenance'`, ); db.close(); const reopened = new Store(dir); @@ -220,7 +220,7 @@ describe("Store", () => { ALTER TABLE agents ADD COLUMN skills text NOT NULL DEFAULT '[]'; ALTER TABLE agents ADD COLUMN delegates text NOT NULL DEFAULT '[]'; ALTER TABLE agents ADD COLUMN shared_memory integer NOT NULL DEFAULT 0; - DELETE FROM __drizzle_migrations WHERE id IN (SELECT id FROM __drizzle_migrations ORDER BY id DESC LIMIT 5)`); + DELETE FROM __drizzle_migrations WHERE name >= '20261105191327_drop_unused_agent_columns'`); db.query("INSERT INTO settings (key, value) VALUES (?, ?)").run( `chat:${agent.id}`, JSON.stringify(chat.id), @@ -490,7 +490,7 @@ describe("Store memory sources", () => { const sourced = first.createMemory({ agentId: agent.id, content: "Leaves Friday", - source: { kind: "group", groupId: "group-1", name: "Trip" }, + source: { kind: "bot", agentId: agent.id, name: "Ada" }, }); first.close(); @@ -498,172 +498,10 @@ describe("Store memory sources", () => { const reopened = new Store(dir); expect(reopened.getMemory(older.id)?.source).toBeNull(); expect(reopened.getMemory(sourced.id)?.source).toEqual({ - kind: "group", - groupId: "group-1", - name: "Trip", + kind: "bot", + agentId: agent.id, + name: "Ada", }); reopened.close(); }); }); - -describe("Store group chats", () => { - test("keeps members in join order, replaces them, and survives reopen", () => { - const dir = make(); - const first = new Store(dir); - const a = first.createAgent({ ...input, name: "A" }); - const b = first.createAgent({ ...input, name: "B" }); - const c = first.createAgent({ ...input, name: "C" }); - - const group = first.createGroupChat({ - name: "Trip", - memberIds: [b.id, a.id], - }); - - expect(group).toMatchObject({ name: "Trip", memberIds: [b.id, a.id] }); - - const updated = first.updateGroupChat(group.id, { - name: "Holiday", - memberIds: [a.id, c.id], - }); - - expect(updated).toMatchObject({ - id: group.id, - name: "Holiday", - memberIds: [a.id, c.id], - }); - expect(first.updateGroupChat(crypto.randomUUID(), group)).toBeNull(); - first.close(); - - const second = new Store(dir); - expect(second.listGroupChats()).toEqual([updated!]); - second.close(); - }); - - test("drops a deleted bot from its groups and deletes members with the group", () => { - const dir = make(); - const store = new Store(dir); - const a = store.createAgent({ ...input, name: "A" }); - const b = store.createAgent({ ...input, name: "B" }); - const c = store.createAgent({ ...input, name: "C" }); - - const group = store.createGroupChat({ - name: "Trip", - memberIds: [a.id, b.id, c.id], - }); - - store.deleteAgent(b.id); - expect(store.getGroupChat(group.id)?.memberIds).toEqual([a.id, c.id]); - expect(store.deleteGroupChat(group.id)).toBe(true); - expect(store.getGroupChat(group.id)).toBeNull(); - expect(store.listGroupChats()).toEqual([]); - store.close(); - - const db = new Database(join(dir, "store.sqlite")); - - expect(db.query("SELECT COUNT(*) AS n FROM group_members").get()).toEqual({ - n: 0, - }); - db.close(); - }); - - test("keeps member progress, group activity, and turns across reopen", () => { - const dir = make(); - const first = new Store(dir); - const a = first.createAgent({ ...input, name: "A" }); - const b = first.createAgent({ ...input, name: "B" }); - - const group = first.createGroupChat({ - name: "Trip", - memberIds: [a.id, b.id], - }); - - const conversation = first.createConversation( - { agentId: a.id, title: "Trip" }, - `${a.id}:2`, - ); - - const execution = first.createExecution({ - agentId: a.id, - conversationId: conversation.id, - scheduleId: null, - requestId: "group-turn:1", - prompt: "", - submissionId: null, - status: "pending", - error: null, - }); - - first.setGroupMember(group.id, a.id, { - conversationId: conversation.id, - cursor: 3, - pending: true, - pendingBotStarted: true, - summary: "Earlier: packing list.", - }); - first.setGroupActivity(group.id, { - botTurns: 5, - paused: true, - awaitingAnswers: { "2": [a.id] }, - }); - first.createGroupTurn({ - executionId: execution.id, - groupId: group.id, - agentId: a.id, - through: 3, - botStarted: true, - status: "running", - }); - first.close(); - - const second = new Store(dir); - expect(second.groupMember(group.id, a.id)).toMatchObject({ - conversationId: conversation.id, - cursor: 3, - pending: true, - pendingBotStarted: true, - summary: "Earlier: packing list.", - }); - expect(second.groupActivity(group.id)).toEqual({ - botTurns: 5, - paused: true, - awaitingAnswers: { "2": [a.id] }, - }); - expect(second.activeGroupTurn(group.id, a.id)).toMatchObject({ - executionId: execution.id, - through: 3, - botStarted: true, - status: "running", - }); - second.updateGroupTurn(execution.id, { status: "settled" }); - expect(second.activeGroupTurn(group.id, a.id)).toBeUndefined(); - expect( - second.listGroupTurns({ groupId: group.id, status: ["settled"] }), - ).toHaveLength(1); - second.deleteGroupChat(group.id); - expect(second.listGroupTurns()).toEqual([]); - second.close(); - }); -}); - -test("an agent keeps its desktop job model across reopen", () => { - const dir = make(); - const first = new Store(dir); - - const agent = first.createAgent({ - ...input, - desktopModel: { provider: "opencode-go", model: "gpt-6-luna" }, - }); - - first.close(); - - const second = new Store(dir); - - expect(second.getAgent(agent.id)?.desktopModel).toEqual({ - provider: "opencode-go", - model: "gpt-6-luna", - }); - expect( - second.updateAgent(agent.id, { desktopModel: undefined })?.desktopModel, - ).toBeUndefined(); - second.close(); -}); diff --git a/apps/server/src/skills/skill-installer.test.ts b/apps/server/src/skills/skill-installer.test.ts index 44be5e9e..5891406c 100644 --- a/apps/server/src/skills/skill-installer.test.ts +++ b/apps/server/src/skills/skill-installer.test.ts @@ -338,7 +338,7 @@ test("bots and reviews can't change a skill the owner pinned", () => { }); const skills = standaloneSkills(store); - const context = { groupId: null, submissionIds: [], runKey: null }; + const context = { submissionIds: [], reviewOf: null, runKey: null }; for (const write of [ skills.update( diff --git a/apps/server/src/skills/skill-library.ts b/apps/server/src/skills/skill-library.ts index cbae3c77..8153a2de 100644 --- a/apps/server/src/skills/skill-library.ts +++ b/apps/server/src/skills/skill-library.ts @@ -8,7 +8,6 @@ import { MAX_SKILL_DOCUMENT_PATH_CHARS, MAX_SKILL_NAME_CHARS, } from "../shared/limits"; -import { groupOf } from "../group-chats/group-conversation"; import type { ChangeContext } from "../learned-changes/change-source"; import { reviewOf } from "../learned-changes/review-conversation"; import { SKILL_TOOL_NAME } from "../contract/tools"; @@ -28,14 +27,12 @@ export async function skillToolContext( api: ToolExecutionApi, callContext: Context, ): Promise { - const [live, groupId, review] = await Promise.all([ + const [live, review] = await Promise.all([ api.snapshot(LiveDoc, api.conversationId, callContext), - groupOf(api, api.conversationId, callContext), reviewOf(api, api.conversationId, callContext), ]); return { - groupId, reviewOf: review?.executionId ?? null, submissionIds: (live?.run?.inputs ?? []).map(String), // The run's task changes with every tool round; its inputs stay the same for the whole turn. diff --git a/apps/server/src/transcript/citations.test.ts b/apps/server/src/transcript/citations.test.ts index 8fa0a2f0..6e505f83 100644 --- a/apps/server/src/transcript/citations.test.ts +++ b/apps/server/src/transcript/citations.test.ts @@ -35,15 +35,19 @@ describe("citation projection", () => { ], }); }); - test("resets sources at a user message and supports group sources", () => { + test("resets sources at a user message and uses only the new turn's sources", () => { const stale = message("assistant", "[source](https://example.com)"); - - const group = message("assistant", "([source](https://example.com))", { - sources: [{ url: "https://example.com", title: "Example" }], - }); - + const reply = message("assistant", "([source](https://example.com))"); projectCitations( - [message("user", "next"), stale, group], + [ + message("user", "next"), + stale, + message("toolResult", "", { + toolName: "web_search", + toolDetails: [{ url: "https://example.com", title: "New" }], + }), + reply, + ], [ message("toolResult", "", { toolName: "web_search", @@ -52,10 +56,10 @@ describe("citation projection", () => { ], ); expect(stale.presentation).toEqual({ text: stale.content, citations: [] }); - expect(group.presentation).toEqual({ + expect(reply.presentation).toEqual({ text: "", citations: [ - { href: "https://example.com", title: "Example", site: "example.com" }, + { href: "https://example.com", title: "New", site: "example.com" }, ], }); }); diff --git a/apps/server/src/transcript/citations.ts b/apps/server/src/transcript/citations.ts index a1da9f45..f5be0632 100644 --- a/apps/server/src/transcript/citations.ts +++ b/apps/server/src/transcript/citations.ts @@ -88,10 +88,6 @@ function replaceCitations( } function present(message: TranscriptMessage, sources: Sources) { - const available = message.sources ? new Map() : sources; - - if (message.sources) addSources(available, message.sources); - const chips = new Map(); let fenced = false; @@ -109,9 +105,7 @@ function present(message: TranscriptMessage, sources: Sources) { return line .split(/(`[^`]*`)/) .map((part) => - part.startsWith("`") - ? part - : replaceCitations(part, available, chips), + part.startsWith("`") ? part : replaceCitations(part, sources, chips), ) .join(""); }) diff --git a/apps/server/src/transcript/entries.ts b/apps/server/src/transcript/entries.ts index 0e2edb1e..b3b68d73 100644 --- a/apps/server/src/transcript/entries.ts +++ b/apps/server/src/transcript/entries.ts @@ -1,13 +1,11 @@ import type { EntryRecord } from "@earendil-works/pi-durable"; import { z } from "zod"; import { botCommunication } from "../contract/api-responses"; -import { webSource } from "../contract/web-search"; -import { ATTACHMENT_KINDS, attachmentInput } from "../shared/attachment-rules"; +import { ATTACHMENT_KINDS } from "../shared/attachment-rules"; export const MESSAGE_ENTRY = "crumble.message"; export const BOT_MESSAGE_ENTRY = "crumble.bot-message"; -export const GROUP_MESSAGE_ENTRY = "crumble.group-message"; export const JOB_QUESTION_ENTRY = "crumble.job-question"; @@ -104,21 +102,6 @@ export const messageFile = z.union([ z.object({ id: z.string(), deleted: z.literal(true) }), ]); -export const groupMessageData = z.object({ - text: z.string(), - sender: messageOrigin, - requestId: z.string(), - timestamp: z.number(), - replyTo: z.string().exactOptional(), - replyPreview: z.string().exactOptional(), - reaction: z.string().exactOptional(), - attachments: z.array(attachmentInput).exactOptional(), - files: z.array(messageFile).catch([]).exactOptional(), - sources: z.array(webSource).exactOptional(), -}); - -export type GroupMessageData = z.infer; - export const inputMetadata = z.object({ text: z.string().optional().catch(undefined), replyTo: z.string().optional().catch(undefined), diff --git a/apps/server/src/transcript/origins.ts b/apps/server/src/transcript/origins.ts index 104618cc..da3af8a2 100644 --- a/apps/server/src/transcript/origins.ts +++ b/apps/server/src/transcript/origins.ts @@ -12,7 +12,6 @@ export const UNKNOWN_SCHEDULE_NAME = "Deleted automation"; */ export type InputOrigin = | { kind: "owner"; via?: string } - | { kind: "group" } | { kind: "task"; name: string } | { kind: "event"; name: string; source: string } | { kind: "script"; name: string } @@ -44,7 +43,6 @@ const REQUEST_SOURCES: Record< owner: "owner", task: "automation", event: "automation", - group: undefined, script: undefined, bot: undefined, credential: undefined, @@ -69,7 +67,6 @@ export const messageTag = ( ) => (requestSource(originKind) ? `[message ${requestId}]\n${text}` : text); export type TurnSource = - | { kind: "group" } | { kind: "event"; eventId: string; scheduleId: string } | { kind: "task"; scheduleId: string } | { kind: "bot"; agentId: string } @@ -89,8 +86,6 @@ export function turnSource({ }: Pick): TurnSource { const request = parseRequestId(requestId); - if (request.kind === "group-turn") return { kind: "group" }; - if (request.kind === "event") return request; if (scheduleId) return { kind: "task", scheduleId }; diff --git a/apps/server/src/transcript/transcript.ts b/apps/server/src/transcript/transcript.ts index 337ad2ff..0907505e 100644 --- a/apps/server/src/transcript/transcript.ts +++ b/apps/server/src/transcript/transcript.ts @@ -28,8 +28,6 @@ import { CALL_ENTRY, callEventData, contentText, - GROUP_MESSAGE_ENTRY, - groupMessageData, HELD_ACTION_ENTRY, heldActionData, inputMetadata, @@ -39,11 +37,10 @@ import { messageOrigin, USER_ENTRY, type CallEventData, - type GroupMessageData, type MessageOrigin, type ModelContent, } from "./entries"; -import { isBotOrigin, isOwnerOrigin } from "./origins"; +import { isBotOrigin } from "./origins"; import { isToolResult, jobCardName, @@ -52,7 +49,6 @@ import { } from "./tool-results"; import { DESKTOP_SCREENSHOT_TOOL_NAME, - REACTION_TOOL_NAME, REQUEST_CALL_TOOL_NAME, REQUEST_CREDENTIAL_TOOL_NAME, REQUEST_LOGIN_TOOL_NAME, @@ -62,7 +58,6 @@ import { transcriptBlock, type BotCommunication, } from "../contract/api-responses"; -import type { WebSource } from "../contract/web-search"; import { MESSAGE_PREVIEW_CHARS } from "../shared/limits"; import { JOB_FAILURE_EVENT } from "../contract/tools"; @@ -120,7 +115,6 @@ export type TranscriptMessage = { toolName?: string | undefined; isError?: boolean | undefined; toolDetails?: unknown; - sources?: WebSource[]; presentation?: { text: string; citations: { href: string; title: string; site: string }[]; @@ -468,62 +462,6 @@ function normalizeCallEvent( ]; } -function normalizeGroupMessage( - entryId: string, - entry: EntryRecord, -): TranscriptMessage[] { - const parsed = groupMessageData.safeParse(entry.data); - - if (!parsed.success) return []; - - const { text, sender, requestId, timestamp, replyTo, replyPreview } = - parsed.data; - - const message: TranscriptMessage = - parsed.data.reaction === undefined - ? { - id: formatMessageId(entryId, 0), - entryId, - requestId, - role: isOwnerOrigin(sender) ? "user" : "assistant", - content: text, - timestamp, - kind: entry.kind, - origin: sender, - } - : { - id: formatMessageId(entryId, 0), - entryId, - requestId, - role: "toolResult", - content: `Reacted ${parsed.data.reaction}`, - timestamp, - kind: entry.kind, - origin: sender, - toolName: REACTION_TOOL_NAME, - toolDetails: { emoji: parsed.data.reaction }, - }; - - if (replyTo !== undefined) message.replyTo = replyTo; - - if (replyPreview !== undefined) message.replyPreview = replyPreview; - - addGroupExtras(message, parsed.data); - - return [message]; -} - -function addGroupExtras(message: TranscriptMessage, data: GroupMessageData) { - if (data.files?.length) message.files = data.files; - else if (data.attachments?.length) - message.files = data.attachments.map((_, index) => ({ - id: `legacy:${message.entryId}:${index}`, - deleted: true, - })); - - if (data.sources?.length) message.sources = data.sources; -} - export type ModelMessage = NonNullable[number]; type ToolMetadata = ReturnType; @@ -668,9 +606,6 @@ function normalize(agentId: string, entry: EntryRecord): TranscriptMessage[] { if (entry.kind === BOT_MESSAGE_ENTRY) return normalizeBotMessage(entryId, entry); - if (entry.kind === GROUP_MESSAGE_ENTRY) - return normalizeGroupMessage(entryId, entry); - if (entry.kind === HELD_ACTION_ENTRY) return normalizeHeldAction(entryId, entry); @@ -727,7 +662,7 @@ async function earlierCitationContext( const needsContext = messages .slice(0, firstUser < 0 ? undefined : firstUser) - .some((message) => message.role === "assistant" && !message.sources); + .some((message) => message.role === "assistant"); while ( conversation && diff --git a/apps/server/src/voice-gateway/call-owner.ts b/apps/server/src/voice-gateway/call-owner.ts index 5912d83a..da80f9b4 100644 --- a/apps/server/src/voice-gateway/call-owner.ts +++ b/apps/server/src/voice-gateway/call-owner.ts @@ -4,7 +4,7 @@ import { Effect, Layer } from "effect"; import { BotExtensions, ExtensionPosition } from "../bot-ports/bot-extensions"; import { CALL_OWNER_TOOL_NAME, HANG_UP_TOOL_NAME } from "../contract/tools"; import { VOICE_CALL_GREETING_MAX } from "../contract/voice-gateway"; -import { callOnly, chatOnly } from "../shared/chat-only"; +import { callOnly } from "../shared/chat-only"; import { CallConversation } from "./call-conversation"; import { VoiceGateway, type VoiceCallResult } from "./voice-gateway"; @@ -75,7 +75,7 @@ export function callOwnerExtension(botId: string, calls: Calls) { }); // A spoken reply reaches only the line's bot chat. - return chatOnly(defineExtension({ name: "voice-call", tools: [callOwner] })); + return defineExtension({ name: "voice-call", tools: [callOwner] }); } const hangUpResult = (ending: boolean) => ({ @@ -102,7 +102,7 @@ export function hangUpExtension(botId: string, calls: HangUps) { hangUpResult(await Effect.runPromise(calls.hangUp(botId))), }); - return chatOnly(defineExtension({ name: "voice-hang-up", tools: [hangUp] })); + return defineExtension({ name: "voice-hang-up", tools: [hangUp] }); } /** `hang_up` for an outside call's conversation; `objected` withholds the call's transcript once the call ends. */ diff --git a/apps/server/src/voice-gateway/request-call.ts b/apps/server/src/voice-gateway/request-call.ts index 32484a8a..88315532 100644 --- a/apps/server/src/voice-gateway/request-call.ts +++ b/apps/server/src/voice-gateway/request-call.ts @@ -9,7 +9,6 @@ import { CALL_GOAL_MAX, VOICE_CALL_GREETING_MAX, } from "../contract/voice-gateway"; -import { chatOnly } from "../shared/chat-only"; import { errorText } from "../shared/errors"; import { toolOutput } from "../shared/tool-output"; import { CallRequests } from "./call-requests"; @@ -81,12 +80,10 @@ export const requestCallTools = Layer.effectDiscard( (await Effect.runPromise(gateway.currentCall(agent.id)))?.party !== "outside" ? [ - chatOnly( - defineExtension({ - name: "call_requests", - tools: [requestCallTool(agent.id, service)], - }), - ), + defineExtension({ + name: "call_requests", + tools: [requestCallTool(agent.id, service)], + }), ] : [], ); diff --git a/apps/server/test/support/api.ts b/apps/server/test/support/api.ts index e19c025f..0f380d60 100644 --- a/apps/server/test/support/api.ts +++ b/apps/server/test/support/api.ts @@ -10,7 +10,6 @@ import type { BotsAccess } from "../../src/bots/bots"; import type { AgentRuntime } from "../../src/bots/runtime"; import { EventSources } from "../../src/event-sources/event-sources"; import { Library } from "../../src/files/library"; -import { GroupChats } from "../../src/group-chats/group-chats"; import { McpIntegrations } from "../../src/integrations/integrations"; import { mcpServersOver } from "../../src/integrations/integrations-test-support"; import { McpServers } from "../../src/integrations/mcp-servers"; @@ -40,7 +39,6 @@ import { BotWorkspaces, type Workspaces } from "../../src/workspaces/workspace"; export type TestServices = { library?: Library["Service"]; scheduler?: { service: Scheduler["Service"] }; - groupChats?: { service: GroupChats["Service"] }; push?: Runner; scriptRuns?: ScriptRuns["Service"]; defaultSkills?: DefaultSkill[]; @@ -111,10 +109,6 @@ function testServices( Context.add(BotWorkspaces, services.workspaces), Context.add(DefaultSkills, services.defaultSkills ?? []), Context.add(Plugins, plugins), - Context.add( - GroupChats, - services.groupChats?.service ?? notReached(), - ), Context.add(Push, testPush(services.push)), Context.add( ProviderSignIns, diff --git a/apps/server/test/support/runtime-callbacks.ts b/apps/server/test/support/runtime-callbacks.ts index 0bb15cf8..b486ff26 100644 --- a/apps/server/test/support/runtime-callbacks.ts +++ b/apps/server/test/support/runtime-callbacks.ts @@ -1,5 +1,4 @@ import { Effect } from "effect"; -import { groupConversations } from "../../src/group-chats/group-turns"; import { reviewConversations } from "../../src/learning/review-kind"; import { callConversations } from "../../src/voice-gateway/call-conversation"; import { hostModels } from "../../src/providers/providers"; @@ -60,11 +59,7 @@ export const runtimeCallbacks = ( visionModel: () => {}, extensions: () => [], jobExtensions: () => [], - conversationKinds: () => [ - groupConversations(), - reviewConversations(), - callConversations(), - ], + conversationKinds: () => [reviewConversations(), callConversations()], env: () => {}, ...overrides, }); diff --git a/apps/server/test/support/store-bots.ts b/apps/server/test/support/store-bots.ts index bc626c2f..3467ab58 100644 --- a/apps/server/test/support/store-bots.ts +++ b/apps/server/test/support/store-bots.ts @@ -8,23 +8,11 @@ import { ExecutionRepository, type NewExecution, } from "../../src/bot-store/execution-repository"; -import { - GroupChatRepository, - type GroupProgress, - type GroupMemberChange, -} from "../../src/group-chats/group-chat-repository"; import { ScheduleRepository } from "../../src/automations/schedule-repository"; import type { Agent, AgentInput } from "../../src/contract/agents"; import type { Execution } from "../../src/shared/domain"; import type { Schedule, ScheduleInput } from "../../src/contract/schedules"; import type { Conversation } from "../../src/bot-store/conversation-repository"; -import type { - GroupChat, - GroupChatInput, - GroupMember, - GroupTurn, - GroupTurnStatus, -} from "../../src/group-chats/group-chat-repository"; import type { StoreRun } from "./store"; const agentStore = (run: StoreRun) => ({ @@ -125,64 +113,9 @@ const executionStore = (run: StoreRun) => ({ }, }); -const groupChatStore = (run: StoreRun) => ({ - listGroupChats: (): GroupChat[] => { - return run(GroupChatRepository.use((r) => r.list)); - }, - getGroupChat: (groupId: string) => { - return run(GroupChatRepository.use((r) => r.get(groupId))); - }, - createGroupChat: (input: GroupChatInput, groupId?: string): GroupChat => { - return run(GroupChatRepository.use((r) => r.create(input, groupId))); - }, - updateGroupChat: (groupId: string, input: GroupChatInput) => { - return run(GroupChatRepository.use((r) => r.update(groupId, input))); - }, - deleteGroupChat: (groupId: string) => { - return run(GroupChatRepository.use((r) => r.delete(groupId))); - }, - groupMember: (groupId: string, agentId: string): GroupMember | undefined => { - return run(GroupChatRepository.use((r) => r.member(groupId, agentId))); - }, - setGroupMember: ( - groupId: string, - agentId: string, - change: GroupMemberChange, - ) => { - run(GroupChatRepository.use((r) => r.setMember(groupId, agentId, change))); - }, - groupActivity: (groupId: string): GroupProgress => { - return run(GroupChatRepository.use((r) => r.activity(groupId))); - }, - setGroupActivity: (groupId: string, change: Partial) => { - run(GroupChatRepository.use((r) => r.setActivity(groupId, change))); - }, - createGroupTurn: (turn: Omit): GroupTurn => { - return run(GroupChatRepository.use((r) => r.createTurn(turn))); - }, - getGroupTurn: (executionId: string) => { - return run(GroupChatRepository.use((r) => r.getTurn(executionId))); - }, - updateGroupTurn: ( - executionId: string, - change: { status: GroupTurnStatus }, - ) => { - run(GroupChatRepository.use((r) => r.updateTurn(executionId, change))); - }, - activeGroupTurn: (groupId: string, agentId: string) => { - return run(GroupChatRepository.use((r) => r.activeTurn(groupId, agentId))); - }, - listGroupTurns: ( - filter: { groupId?: string; status?: GroupTurnStatus[] } = {}, - ): GroupTurn[] => { - return run(GroupChatRepository.use((r) => r.listTurns(filter))); - }, -}); - export const botStore = (run: StoreRun) => ({ ...agentStore(run), ...conversationStore(run), ...scheduleStore(run), ...executionStore(run), - ...groupChatStore(run), }); diff --git a/apps/server/test/support/store.ts b/apps/server/test/support/store.ts index c487e480..e3958971 100644 --- a/apps/server/test/support/store.ts +++ b/apps/server/test/support/store.ts @@ -58,21 +58,6 @@ export class Store { createExecution = this.bots.createExecution; updateExecution = this.bots.updateExecution; - listGroupChats = this.bots.listGroupChats; - getGroupChat = this.bots.getGroupChat; - createGroupChat = this.bots.createGroupChat; - updateGroupChat = this.bots.updateGroupChat; - deleteGroupChat = this.bots.deleteGroupChat; - groupMember = this.bots.groupMember; - setGroupMember = this.bots.setGroupMember; - groupActivity = this.bots.groupActivity; - setGroupActivity = this.bots.setGroupActivity; - createGroupTurn = this.bots.createGroupTurn; - getGroupTurn = this.bots.getGroupTurn; - updateGroupTurn = this.bots.updateGroupTurn; - activeGroupTurn = this.bots.activeGroupTurn; - listGroupTurns = this.bots.listGroupTurns; - getMemory = this.learning.getMemory; createMemory = this.learning.createMemory; diff --git a/apps/web/app/activity-stream.ts b/apps/web/app/activity-stream.ts index ae60943a..6ac2db07 100644 --- a/apps/web/app/activity-stream.ts +++ b/apps/web/app/activity-stream.ts @@ -5,7 +5,6 @@ import { } from "@crumble/server/contract/api-responses"; import { authClient } from "@/lib/auth-client"; import { type Bot, botsQuery, invalidateBots } from "@/features/bots/api"; -import { groupChatQuery, invalidateGroups } from "@/features/group-chats/api"; import { chatQuery } from "@/features/chat/api"; import { follow, queryClient } from "@/lib/api"; import { type ChatLinks, notifyReply } from "@/lib/notifications"; @@ -68,10 +67,9 @@ export function followActivity(links: ChatLinks, signal: AbortSignal) { { onStatus: report, onOpen: () => { - // Bots, groups, and pins may have changed while the stream was down. + // Bots and pins may have changed while the stream was down. if (connections++ > 0) { void invalidateBots(); - void invalidateGroups(); authClient.$store.notify("$sessionSignal"); } }, @@ -91,9 +89,7 @@ export function followActivity(links: ChatLinks, signal: AbortSignal) { if (event.type === "chat-preview") preview(event.agentId, event.lastMessage); else { - const queryKey = event.groupId - ? groupChatQuery(event.groupId).queryKey - : chatQuery(event.agentId).queryKey; + const queryKey = chatQuery(event.agentId).queryKey; void queryClient.invalidateQueries({ queryKey }); notifyReply(event, links); diff --git a/apps/web/app/command-palette.tsx b/apps/web/app/command-palette.tsx index 59ed027b..c8572a63 100644 --- a/apps/web/app/command-palette.tsx +++ b/apps/web/app/command-palette.tsx @@ -1,7 +1,7 @@ import { useEffect, useEffectEvent } from "react"; import { useQuery } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; -import { IconPlus, IconUsersGroup } from "@tabler/icons-react"; +import { IconPlus } from "@tabler/icons-react"; import { defaultFilter } from "cmdk"; import { Command, @@ -15,13 +15,11 @@ import { } from "@/components/ui/command"; import { useSidebar } from "@/components/ui/sidebar"; import { type Bot, botsQuery } from "@/features/bots/api"; -import { type GroupChat, groupsQuery } from "@/features/group-chats/api"; import { setTheme, useTheme } from "@/lib/theme"; import { BotAvatar } from "@/components/bot-avatar"; import { settingsSections } from "@/features/settings/sections"; import { useIsAdmin } from "@/lib/auth-client"; import { THEME_OPTIONS, PAGES } from "./navigation"; -import { MIN_GROUP_MEMBERS } from "@crumble/server/contract/limits"; // Chat items keep their id as the value so equal names stay distinct; match them by name only. const filter = (value: string, search: string, keywords?: string[]) => @@ -85,42 +83,6 @@ function BotCommands({ bots, run }: { bots: Bot[] | undefined; run: Run }) { ); } -function GroupCommands({ - groups, - run, -}: { - groups: GroupChat[] | undefined; - run: Run; -}) { - const navigate = useNavigate(); - - if (!groups?.length) return null; - - return ( - - {groups.map((group) => ( - - run( - () => - void navigate({ - to: "/groups/$groupId", - params: { groupId: group.id }, - }), - ) - } - > - - {group.name} - - ))} - - ); -} - function PageCommands({ admin, go }: { admin: boolean; go: Go }) { return ( <> @@ -181,7 +143,6 @@ export function CommandPalette({ }) { const navigate = useNavigate(); const bots = useQuery(botsQuery); - const groups = useQuery(groupsQuery); const admin = useIsAdmin(); const theme = useTheme(); const { setOpenMobile } = useSidebar(); @@ -208,18 +169,11 @@ export function CommandPalette({ No results - go({ to: "/bots/new" })}> New bot - {(bots.data?.length ?? 0) >= MIN_GROUP_MEMBERS && ( - go({ to: "/groups/new" })}> - - New group chat - - )} diff --git a/apps/web/app/router.tsx b/apps/web/app/router.tsx index ecdca0d3..37d9c12c 100644 --- a/apps/web/app/router.tsx +++ b/apps/web/app/router.tsx @@ -22,7 +22,6 @@ import { Shell } from "./shell"; import { HttpError, queryClient } from "@/lib/api"; import { botsQuery } from "@/features/bots/api"; import { chatQuery } from "@/features/chat/api"; -import { groupChatQuery, groupsQuery } from "@/features/group-chats/api"; import { authClient } from "@/lib/auth-client"; import { ActivityPage } from "@/features/activity/activity"; import { BotForm } from "@/features/bots/bot-form"; @@ -35,7 +34,6 @@ import { GitHubAppCallback } from "@/features/github-apps/github-apps"; import { UsersPage } from "@/features/settings/admin-settings"; import { LoginsSettings } from "@/features/logins/logins"; import { BotDesktop } from "@/features/bot-desktop/desktop"; -import { GroupChatView, GroupForm } from "@/features/group-chats/groups"; import { IntegrationsPage, OAuthCallback, @@ -100,7 +98,6 @@ const newBotRoute = createRoute({ }); const botParams = z.object({ botId: z.string() }); -const groupParams = z.object({ groupId: z.string() }); const gatewayParams = z.object({ gatewayId: z.string() }); const botRoute = createRoute({ @@ -149,57 +146,7 @@ const botLibraryRoute = createRoute({ component: function BotLibraryPage() { const { botId } = botParams.parse(botLibraryRoute.useParams()); - return ; - }, -}); - -const groupLibraryRoute = createRoute({ - getParentRoute: () => appRoute, - path: "/groups/$groupId/library", - component: function GroupLibraryPage() { - const { groupId } = groupParams.parse(groupLibraryRoute.useParams()); - - return ; - }, -}); - -const newGroupRoute = createRoute({ - getParentRoute: () => appRoute, - path: "/groups/new", - component: () => , -}); - -const groupRoute = createRoute({ - getParentRoute: () => appRoute, - path: "/groups/$groupId", - loader: ({ params }) => - queryClient.query({ - ...groupChatQuery(params.groupId), - staleTime: "static", - }), - component: function GroupPage() { - const { groupId } = groupParams.parse(groupRoute.useParams()); - - return ; - }, -}); - -const editGroupRoute = createRoute({ - getParentRoute: () => appRoute, - path: "/groups/$groupId/edit", - loader: () => queryClient.query({ ...groupsQuery, staleTime: "static" }), - component: function EditGroupPage() { - const { groupId } = groupParams.parse(editGroupRoute.useParams()); - - const group = useQuery(groupsQuery).data?.find( - (each) => each.id === groupId, - ); - - return group ? ( - - ) : ( -

Group chat not found.

- ); + return ; }, }); @@ -392,10 +339,6 @@ export const router = createRouter({ editBotRoute, desktopRoute, botLibraryRoute, - groupLibraryRoute, - newGroupRoute, - groupRoute, - editGroupRoute, memoryRoute, automationsRoute, activityRoute, @@ -426,6 +369,18 @@ export const router = createRouter({ ]), ]), ]), + defaultNotFoundComponent: () => ( + + + Not found + + + + + + ), defaultPreload: "intent", defaultViewTransition: true, // Query owns caching; the router only triggers loads. diff --git a/apps/web/app/shell.tsx b/apps/web/app/shell.tsx index a9937f8f..b565df6a 100644 --- a/apps/web/app/shell.tsx +++ b/apps/web/app/shell.tsx @@ -45,13 +45,8 @@ import { } from "@/components/ui/dropdown-menu"; import { TooltipProvider } from "@/components/ui/tooltip"; import { CrumbleMark } from "@/components/crumble-mark"; -import { cn, numberWord, plainMarkdown } from "@/lib/utils"; +import { cn, plainMarkdown } from "@/lib/utils"; import { type Bot, botsQuery } from "@/features/bots/api"; -import { - type GroupChat, - groupsQuery, - membersOf, -} from "@/features/group-chats/api"; import { authClient } from "@/lib/auth-client"; import { setTheme, @@ -60,15 +55,14 @@ import { useTheme, } from "@/lib/theme"; import { resetSession, signedOut } from "@/lib/session"; -import { botPin, groupPin, type Pins, usePins } from "@/lib/pins"; +import { botPin, type Pins, usePins } from "@/lib/pins"; import { botStatusLine, isBusy, useWorking } from "@/features/bot-chat/working"; import { followActivity, useConnectionStatus } from "./activity-stream"; import { markSeen, useUnreadCount } from "@/lib/notifications"; -import { BotAvatar, botColor, botStyle } from "@/components/bot-avatar"; +import { botColor, botStyle } from "@/components/bot-avatar"; import { LiveBotAvatar } from "@/features/bot-chat/avatar"; import { CommandPalette, PALETTE_SHORTCUT } from "./command-palette"; import { THEME_OPTIONS, PAGES } from "./navigation"; -import { MIN_GROUP_MEMBERS } from "@crumble/server/contract/limits"; import type { ReplyChat } from "@/lib/notifications"; function useResetOnUserChange(userId: string | undefined) { @@ -91,10 +85,8 @@ function useResetOnUserChange(userId: string | undefined) { }, [navigate, userId]); } -const chatLocation = ({ kind, id }: ReplyChat) => - kind === "group" - ? ({ to: "/groups/$groupId", params: { groupId: id } } as const) - : ({ to: "/bots/$botId", params: { botId: id } } as const); +const chatLocation = ({ id }: ReplyChat) => + ({ to: "/bots/$botId", params: { botId: id } }) as const; function useFollowActivity(userId: string | undefined) { const navigate = useNavigate(); @@ -120,24 +112,14 @@ function useFollowActivity(userId: string | undefined) { }, [navigate, router, userId]); } -function useDocumentTitle( - bots: Bot[] | undefined, - groups: GroupChat[] | undefined, -) { +function useDocumentTitle(bots: Bot[] | undefined) { const matchRoute = useMatchRoute(); const unread = useUnreadCount(); const bot = matchRoute({ to: "/bots/$botId" }); - const group = matchRoute({ to: "/groups/$groupId" }); - - const groupName = group - ? groups?.find(({ id }) => id === group.groupId)?.name - : undefined; - - const chat = bot ? bots?.find(({ id }) => id === bot.botId)?.name : groupName; + const chat = bot ? bots?.find(({ id }) => id === bot.botId)?.name : undefined; useEffect(() => { const title = chat ? `${chat} | Crumble` : "Crumble"; - document.title = unread ? `(${unread}) ${title}` : title; }, [chat, unread]); } @@ -168,13 +150,12 @@ function SidebarThemeColor() { export function Shell() { const session = authClient.useSession(); const bots = useQuery(botsQuery); - const groups = useQuery(groupsQuery); const [paletteOpen, setPaletteOpen] = useState(false); - const pins = usePins(bots.data, groups.data); + const pins = usePins(bots.data); const userId = session.data?.user.id; useResetOnUserChange(userId); useFollowActivity(userId); - useDocumentTitle(bots.data, groups.data); + useDocumentTitle(bots.data); useAccountTheme(); return ( @@ -189,9 +170,8 @@ export function Shell() { setPaletteOpen(true)} /> - + - @@ -217,24 +197,17 @@ type DragProps = Pick< function PinnedSection({ pins, bots, - groups, }: { pins: Pins; bots: Bot[] | undefined; - groups: GroupChat[] | undefined; }) { const matchRoute = useMatchRoute(); const dragged = useRef(null); if (pins.pinned.length === 0) return null; - const botsById = new Map(bots?.map((bot) => [bot.id, bot])); const botsByPin = new Map(bots?.map((bot) => [botPin(bot.id), bot])); - const groupsByPin = new Map( - groups?.map((group) => [groupPin(group.id), group]), - ); - const drag = (key: string): DragProps => ({ draggable: true, onDragStart: (event) => { @@ -266,7 +239,6 @@ function PinnedSection({ {pins.pinned.map((key) => { const bot = botsByPin.get(key); - const group = groupsByPin.get(key); if (bot) return ( @@ -285,17 +257,7 @@ function PinnedSection({ /> ); - return ( - group && ( - - ) - ); + return null; })} @@ -388,98 +350,6 @@ function BotsSection({ ); } -function GroupsSection({ - bots, - groups, - pins, -}: { - bots: Bot[] | undefined; - groups: GroupChat[] | undefined; - pins: Pins; -}) { - const byId = new Map(bots?.map((bot) => [bot.id, bot])); - const canGroup = (bots?.length ?? 0) >= MIN_GROUP_MEMBERS; - - return ( - - Group chats - {canGroup && ( - } - > - - New group chat - - )} - - - {groups - ?.filter((group) => !pins.isPinned(groupPin(group.id))) - .map((group) => ( - - ))} - {groups?.length === 0 && ( -

- {canGroup - ? "No group chats yet" - : `Create ${numberWord(MIN_GROUP_MEMBERS)} bots to start a group chat`} -

- )} -
-
-
- ); -} - -function GroupRow({ - group, - members, - pins, - drag, -}: { - group: GroupChat; - members: Bot[]; - pins: Pins; - drag?: DragProps; -}) { - const matchRoute = useMatchRoute(); - - return ( - - } - > - - {members.slice(0, 2).map((member) => ( - - ))} - - - {group.name} - - {members.map((member) => member.name).join(", ")} - - - - - - ); -} - function WorkspaceSection() { const matchRoute = useMatchRoute(); diff --git a/apps/web/features/chat/conversation-target.ts b/apps/web/features/chat/conversation-target.ts index e2d4e468..369bd5fe 100644 --- a/apps/web/features/chat/conversation-target.ts +++ b/apps/web/features/chat/conversation-target.ts @@ -3,12 +3,12 @@ import type { RoutePath } from "@/lib/api"; import type { HistoryPage, Message } from "./api"; import type { ReactionTarget } from "./transcript"; -export type HistoryRoute = "history" | "groupChatHistory"; +export type HistoryRoute = "history"; export type ConversationTarget = { - /** `bot:` or `group:`, which keys its drafts and outgoing messages. */ + /** `bot:`, which keys its drafts and outgoing messages. */ key: string; - path: `/v1/agents/${string}` | `/v1/group-chats/${string}`; + path: `/v1/agents/${string}`; history: RoutePath; query: UseQueryOptions; shown: (message: Message) => boolean; diff --git a/apps/web/features/chat/conversation.dom.test.tsx b/apps/web/features/chat/conversation.dom.test.tsx index 0a3ddbce..a63c31bc 100644 --- a/apps/web/features/chat/conversation.dom.test.tsx +++ b/apps/web/features/chat/conversation.dom.test.tsx @@ -45,20 +45,14 @@ const bot = { }; const owner = { - id: "g:1:0", - entryId: "g:1", + id: "bot:1:0", + entryId: "bot:1", role: "user", content: "The original", replyReferences: [], }; -const page = { messages: [owner], hasMore: false, oldestEntryId: "g:1" }; - -const groupSnapshot = { - ...page, - groupChat: { id: "g", name: "Group", memberIds: ["bot"] }, - activity: { members: [], paused: false }, -}; +const page = { messages: [owner], hasMore: false, oldestEntryId: "bot:1" }; const silentStream = (signal: AbortSignal | null | undefined) => new Response( @@ -202,35 +196,29 @@ async function render( const shows = (container: HTMLElement, text: string) => () => container.textContent?.includes(text) === true; -const loadGroup = async () => { - const { GroupChatView } = await import("@/features/group-chats/groups"); - - return () => ; -}; - const loadChat = async () => { const { Chat } = await import("@/features/bot-chat/chat"); return () => ; }; -test("a group reply being sent shows what it answers", async () => { +test("a bot reply being sent shows what it answers", async () => { await render( - "/groups/g", + "/bots/bot", new Map([ ["/v1/agents", Response.json([bot])], - ["/v1/group-chats/g/chat", Response.json(groupSnapshot)], + ["/v1/agents/bot/chat", Response.json(chatSnapshot("idle"))], ]), - loadGroup, + loadChat, async (container) => { const { deliver, discard } = await import("./delivery"); await waitFor(shows(container, "The original")); await act(async () => { - await deliver("group:g", "/v1/group-chats/g/messages", { + await deliver("bot:bot", "/v1/agents/bot/messages", { requestId: "request", content: "My answer", - replyTo: "g:1", + replyTo: "bot:1", uploads: [], }); }); @@ -239,12 +227,12 @@ test("a group reply being sent shows what it answers", async () => { // Once as its own message and once quoted above the reply. expect(container.textContent?.split("The original")).toHaveLength(3); - await act(async () => discard("group:g", "request")); + await act(async () => discard("bot:bot", "request")); }, ); }); -async function sendInGroup(container: HTMLElement, text: string) { +async function sendInChat(container: HTMLElement, text: string) { const field = container.querySelector("textarea")!; await act(async () => { @@ -265,19 +253,19 @@ async function sendInGroup(container: HTMLElement, text: string) { test("a message the server refused goes back to the composer and leaves the transcript", async () => { await render( - "/groups/g", + "/bots/bot", new Map([ ["/v1/agents", Response.json([bot])], - ["/v1/group-chats/g/chat", Response.json(groupSnapshot)], + ["/v1/agents/bot/chat", Response.json(chatSnapshot("idle"))], [ - "/v1/group-chats/g/messages", + "/v1/agents/bot/messages", Response.json({ error: "Too long" }, { status: 400 }), ], ]), - loadGroup, + loadChat, async (container) => { await waitFor(shows(container, "The original")); - await sendInGroup(container, "Refused"); + await sendInChat(container, "Refused"); await waitFor(shows(container, "Too long")); expect(container.querySelector("textarea")!.value).toBe("Refused"); @@ -288,19 +276,19 @@ test("a message the server refused goes back to the composer and leaves the tran test("a message that may have arrived stays for Retry, and the composer stays empty", async () => { await render( - "/groups/g", + "/bots/bot", new Map([ ["/v1/agents", Response.json([bot])], - ["/v1/group-chats/g/chat", Response.json(groupSnapshot)], + ["/v1/agents/bot/chat", Response.json(chatSnapshot("idle"))], [ - "/v1/group-chats/g/messages", + "/v1/agents/bot/messages", Response.json({ error: "Bad gateway" }, { status: 502 }), ], ]), - loadGroup, + loadChat, async (container) => { await waitFor(shows(container, "The original")); - await sendInGroup(container, "Maybe arrived"); + await sendInChat(container, "Maybe arrived"); await waitFor(shows(container, "Maybe arrivedNot sent")); expect(container.querySelector("textarea")!.value).toBe(""); @@ -380,26 +368,6 @@ test("a bot left while it works stays followed until it finishes", async () => { ); }); -test("a group chat stops following once left", async () => { - const signals: (AbortSignal | null | undefined)[] = []; - - await render( - "/groups/g", - new Map([ - ["/v1/agents", Response.json([bot])], - ["/v1/group-chats/g/chat", Response.json(groupSnapshot)], - ["/v1/group-chats/g/events", recordingStream(signals)], - ]), - loadGroup, - async (_container, { leave }) => { - await waitFor(() => signals.length > 0, "the event stream"); - expect(signals[0]?.aborted).toBe(false); - await leave(); - await waitFor(() => signals[0]?.aborted === true, "the stream to stop"); - }, - ); -}); - const jobResult = (id: number, toolName: string) => ({ id: `bot:${id}:0`, entryId: `bot:${id}`, diff --git a/apps/web/features/chat/conversation.tsx b/apps/web/features/chat/conversation.tsx index e7e24159..d74ec94b 100644 --- a/apps/web/features/chat/conversation.tsx +++ b/apps/web/features/chat/conversation.tsx @@ -358,7 +358,7 @@ export function ConversationMessages({ const kind = chatKey.slice(0, separator); const id = chatKey.slice(separator + 1); - if ((kind !== "bot" && kind !== "group") || !id) return; + if (kind !== "bot" || !id) return; const controller = getChatAttention(); const release = selectAttentionChat(chatKey); diff --git a/apps/web/features/chat/delivery.ts b/apps/web/features/chat/delivery.ts index be846139..3f705d95 100644 --- a/apps/web/features/chat/delivery.ts +++ b/apps/web/features/chat/delivery.ts @@ -68,7 +68,7 @@ export function discard(chat: string, requestId: string) { */ export async function deliver( chat: string, - path: RoutePath<"sendMessage" | "sendGroupMessage">, + path: RoutePath<"sendMessage">, message: Omit, extra: { timezone?: string } = {}, ) { @@ -78,7 +78,7 @@ export async function deliver( ]); try { - await send<"sendMessage" | "sendGroupMessage">(path, "POST", { + await send<"sendMessage">(path, "POST", { content: message.content, requestId: message.requestId, ...(message.replyTo && { replyTo: message.replyTo }), diff --git a/apps/web/features/chat/drafts.ts b/apps/web/features/chat/drafts.ts index d7612c74..f659e376 100644 --- a/apps/web/features/chat/drafts.ts +++ b/apps/web/features/chat/drafts.ts @@ -2,6 +2,15 @@ import { onSessionReset } from "@/lib/session"; const PREFIX = "crumble.draft:"; +try { + const keys = Array.from({ length: localStorage.length }, (_, index) => + localStorage.key(index), + ); + + for (const key of keys) + if (key?.startsWith(`${PREFIX}group:`)) localStorage.removeItem(key); +} catch {} + export const readDraft = (chat: string) => localStorage.getItem(`${PREFIX}${chat}`) ?? ""; diff --git a/apps/web/features/chat/transcript.tsx b/apps/web/features/chat/transcript.tsx index edf88b7d..27b88191 100644 --- a/apps/web/features/chat/transcript.tsx +++ b/apps/web/features/chat/transcript.tsx @@ -60,7 +60,7 @@ export const hasContent = (message: Message) => export type Reaction = { emoji: string; from?: string | undefined }; -/** The entry a reaction answers: bots react to the owner's last message, unless the group's records its target. */ +/** The entry a reaction answers: the owner's last message. */ export type ReactionTarget = ( message: Message, lastOwner: string | undefined, diff --git a/apps/web/features/group-chats/api.ts b/apps/web/features/group-chats/api.ts deleted file mode 100644 index ac32b216..00000000 --- a/apps/web/features/group-chats/api.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { queryOptions } from "@tanstack/react-query"; -import type { z } from "@hono/zod-openapi"; -import type { - groupChatResponse, - groupChatSnapshotResponse, -} from "@crumble/server/contract/api-responses"; -import { api, queryClient } from "@/lib/api"; - -export type GroupChat = z.infer; - -export type GroupChatSnapshot = z.infer; - -export const membersOf = (memberIds: string[], byId: Map) => - memberIds.flatMap((id) => { - const bot = byId.get(id); - - return bot ? [bot] : []; - }); - -export const groupPath = (id: string) => - `/v1/group-chats/${encodeURIComponent(id)}` as const; - -export const groupsQuery = queryOptions({ - queryKey: ["groups"], - queryFn: ({ signal }) => api<"listGroupChats">("/v1/group-chats", { signal }), -}); - -export const invalidateGroups = () => - queryClient.invalidateQueries({ queryKey: groupsQuery.queryKey }); - -export const groupChatQuery = (id: string) => - queryOptions({ - queryKey: ["group-chat", id], - queryFn: ({ signal }) => - api<"groupChatSnapshot">(`${groupPath(id)}/chat`, { signal }), - }); diff --git a/apps/web/features/group-chats/groups.tsx b/apps/web/features/group-chats/groups.tsx deleted file mode 100644 index 3cd3d733..00000000 --- a/apps/web/features/group-chats/groups.tsx +++ /dev/null @@ -1,532 +0,0 @@ -import { useMemo, useState } from "react"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { Link, useNavigate } from "@tanstack/react-router"; -import { IconPencil } from "@tabler/icons-react"; -import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; -import { AlertDialog, AlertDialogTrigger } from "@/components/ui/alert-dialog"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { ScrollArea } from "@/components/ui/scroll-area"; -import { - Field, - FieldDescription, - FieldError, - FieldGroup, - FieldLabel, - FieldLegend, - FieldSet, -} from "@/components/ui/field"; -import { Input } from "@/components/ui/input"; -import { MessageScrollerItem } from "@/components/ui/message-scroller"; -import { cn, numberWord } from "@/lib/utils"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "@/components/ui/tooltip"; -import { type Bot, botsQuery } from "@/features/bots/api"; -import { - type GroupChat, - type GroupChatSnapshot, - groupChatQuery, - groupPath, - invalidateGroups, - membersOf, -} from "./api"; -import type { Message } from "@/features/chat/api"; -import { call, queryClient, send } from "@/lib/api"; -import { BotAvatar, type BotState, botColor } from "@/components/bot-avatar"; -import { ConfirmDeleteContent, MobileSidebarTrigger } from "@/components/page"; -import { - ConversationEmpty, - ConversationError, - ConversationLoading, - ConversationMessages, - ConversationScroller, - SendError, - useConversation, -} from "@/features/chat/conversation"; -import type { ConversationTarget } from "@/features/chat/conversation-target"; -import { - BotMessage, - TypingDots, - ARRIVAL, - hasContent, -} from "@/features/chat/transcript"; -import { Composer } from "@/features/chat/composer"; -import { - MAX_GROUP_MEMBERS, - MAX_GROUP_NAME_CHARS, - MIN_GROUP_MEMBERS, -} from "@crumble/server/contract/limits"; -import { BotSwitchField } from "@/features/bots/bot-switch-field"; - -function senderBot(message: Message, byId: Map) { - return message.origin?.agentId ? byId.get(message.origin.agentId) : undefined; -} - -function replyLabel(replyTo: Message | null) { - if (!replyTo) return; - - return replyTo.role === "user" ? "You" : (replyTo.origin?.name ?? "a bot"); -} - -const MEMBER_STATUS = { - running: "is answering", - queued: "answers next", - disabled: "is disabled and skipped", - idle: "is here", -}; - -const memberAvatar = (status: keyof typeof MEMBER_STATUS): BotState => { - if (status === "running") return "working"; - - return status === "queued" ? "waiting" : "idle"; -}; - -const groupConversation = ( - id: string, -): ConversationTarget => { - const path = groupPath(id); - - return { - key: `group:${id}`, - path, - history: `${path}/history`, - query: groupChatQuery(id), - shown: (message) => - (message.role === "user" || message.role === "assistant") && - hasContent(message), - reactionTarget: (message) => message.replyTo, - sendContext: () => ({}), - stop: () => send<"stopGroupChat">(`${path}/stop`, "POST"), - followsAfterView: () => false, - refreshList: invalidateGroups, - }; -}; - -function GroupHeader({ - groupId, - name, - members, - statusOf, -}: { - groupId: string; - name: string; - members: Bot[]; - statusOf: (id: string) => { status: keyof typeof MEMBER_STATUS } | undefined; -}) { - return ( -
- - {name} -
- {members.map((member) => { - const status = statusOf(member.id)?.status ?? "idle"; - - return ( - - }> - - - - {member.name} {MEMBER_STATUS[status]} - - - ); - })} -
- - -
- ); -} - -function WorkingRow({ - working, - byId, -}: { - working: GroupChatSnapshot["activity"]["members"]; - byId: Map; -}) { - return ( - -
-
- {working.flatMap((member) => { - const bot = byId.get(member.agentId); - - return bot - ? [] - : []; - })} -
- -
-
- ); -} - -function GroupActivityRows({ - activity, - byId, -}: { - activity: GroupChatSnapshot["activity"]; - byId: Map; -}) { - const working = activity.members.filter( - (member) => member.status === "running", - ); - - const failures = activity.members.filter((member) => member.error); - - return ( - <> - {working.length > 0 && } - {failures.map((member) => ( - - - - {byId.get(member.agentId)?.name ?? "A bot"} couldn't finish - - {member.error} - - - ))} - {activity.paused && ( - -

- The bots are waiting for you. Your next message lets them continue. -

-
- )} - - ); -} - -function isRunning(activity: GroupChatSnapshot["activity"]) { - return activity.members.some( - (member) => member.status === "running" || member.status === "queued", - ); -} - -function colorOf(message: Message, byId: Map) { - const bot = senderBot(message, byId); - - return bot ? botColor(bot) : undefined; -} - -function GroupSender({ - message, - byId, -}: { - message: Message; - byId: Map; -}) { - const bot = senderBot(message, byId); - - return ( - - {message.origin?.name ?? bot?.name ?? "Bot"} - - ); -} - -function GroupConversationEmpty() { - return ( - - Everyone here reads every message. Mention a bot with @ to ask only it. - - ); -} - -export function GroupChatView({ groupId }: { groupId: string }) { - const target = useMemo(() => groupConversation(groupId), [groupId]); - const { snapshot, ...conversation } = useConversation(target); - const bots = useQuery(botsQuery).data ?? []; - const { replyTo, setReplyTo, sendError, sendMessage } = conversation.sending; - - if (snapshot.isError) return ; - - if (!snapshot.data) return ; - - const { groupChat, activity } = snapshot.data; - const byId = new Map(bots.map((bot) => [bot.id, bot])); - const members = membersOf(groupChat.memberIds, byId); - - const statusOf = (id: string) => - activity.members.find((member) => member.agentId === id); - - return ( -
- - - } - renderMessage={(message) => ( - } - color={colorOf(message, byId)} - reactions={conversation.reactions.get(message.entryId)} - onReply={setReplyTo} - /> - )} - /> - - - - setReplyTo(null)} - mentionable={members.filter((member) => member.enabled)} - onSend={(content, uploads) => sendMessage(content, uploads)} - onStop={() => conversation.stop.mutate()} - /> -
- ); -} - -function DeleteGroup({ - group, - error, - pending, - onConfirm, -}: { - group: GroupChat; - error: Error | null; - pending: boolean; - onConfirm: () => void; -}) { - return ( - - - } - > - Delete - - - - ); -} - -function GroupFormButtons({ - group, - valid, - pending, -}: { - group?: GroupChat | undefined; - valid: boolean; - pending: boolean; -}) { - const navigate = useNavigate(); - - return ( -
- - -
- ); -} - -function isValidGroup(name: string, memberIds: string[]) { - return ( - name.trim() !== "" && - memberIds.length >= MIN_GROUP_MEMBERS && - memberIds.length <= MAX_GROUP_MEMBERS - ); -} - -function useGroupForm(group: GroupChat | undefined) { - const navigate = useNavigate(); - const [name, setName] = useState(group?.name ?? ""); - const [memberIds, setMemberIds] = useState(group?.memberIds ?? []); - - const save = useMutation({ - mutationFn: () => { - const input = { name: name.trim(), memberIds }; - - return group - ? call<"updateGroupChat">(groupPath(group.id), "PATCH", input) - : call<"createGroupChat">("/v1/group-chats", "POST", input); - }, - onSuccess: async (saved) => { - await invalidateGroups(); - await queryClient.invalidateQueries({ - queryKey: groupChatQuery(saved.id).queryKey, - }); - await navigate({ to: "/groups/$groupId", params: { groupId: saved.id } }); - }, - }); - - const remove = useMutation({ - mutationFn: (id: string) => - send<"deleteGroupChat">(groupPath(id), "DELETE"), - onSuccess: async () => { - await invalidateGroups(); - await navigate({ to: "/" }); - }, - }); - - return { name, setName, memberIds, setMemberIds, save, remove }; -} - -function GroupMembersFields({ - memberIds, - onChange, -}: { - memberIds: string[]; - onChange: (memberIds: string[]) => void; -}) { - const bots = useQuery(botsQuery).data ?? []; - const selected = new Set(memberIds); - - const toggle = (bot: Bot, on: boolean) => - onChange( - on ? [...memberIds, bot.id] : memberIds.filter((id) => id !== bot.id), - ); - - return ( -
- Members - - {`Choose ${numberWord(MIN_GROUP_MEMBERS)} to ${numberWord(MAX_GROUP_MEMBERS)} bots. A bot added later gets a summary of the conversation so far.`} - - - {bots.map((bot) => ( - = MAX_GROUP_MEMBERS - } - onCheckedChange={(next) => toggle(bot, next)} - > - {!bot.enabled && Disabled} - - ))} - -
- ); -} - -export function GroupForm({ group }: { group?: GroupChat }) { - const { name, setName, memberIds, setMemberIds, save, remove } = - useGroupForm(group); - - const valid = isValidGroup(name, memberIds); - - return ( - -
{ - event.preventDefault(); - - if (valid) save.mutate(); - }} - > -
- - {group ? `Edit ${group.name}` : "New group chat"} - - - - Name - setName(event.target.value)} - /> - - -
- - {save.isError && {save.error.message}} -
- {group && ( - remove.mutate(group.id)} - /> - )} - -
- -
- ); -} diff --git a/apps/web/features/library/api.ts b/apps/web/features/library/api.ts index 5555fadf..39be71d6 100644 --- a/apps/web/features/library/api.ts +++ b/apps/web/features/library/api.ts @@ -53,7 +53,6 @@ export function useFileDownload() { if (error instanceof HttpError && error.status === 404) { void queryClient.invalidateQueries({ queryKey: ["library"] }); void queryClient.invalidateQueries({ queryKey: ["chat"] }); - void queryClient.invalidateQueries({ queryKey: ["group-chat"] }); } }, }); diff --git a/apps/web/features/library/library.dom.test.tsx b/apps/web/features/library/library.dom.test.tsx index 0264f058..29d86201 100644 --- a/apps/web/features/library/library.dom.test.tsx +++ b/apps/web/features/library/library.dom.test.tsx @@ -166,7 +166,7 @@ async function withLibrary( path: "/", component: () => ( - + ), }), diff --git a/apps/web/features/library/library.tsx b/apps/web/features/library/library.tsx index 31932fdb..84fefe22 100644 --- a/apps/web/features/library/library.tsx +++ b/apps/web/features/library/library.tsx @@ -22,7 +22,6 @@ import { Spinner } from "@/components/ui/spinner"; import { ErrorAlert, Page } from "@/components/page"; import { apiRaw, bodyOf, queryClient } from "@/lib/api"; import { agentPath, botsQuery } from "@/features/bots/api"; -import { groupPath, groupsQuery } from "@/features/group-chats/api"; import { MAX_FILE_BYTES } from "@crumble/server/contract/limits"; import { uploadFile, useFileDownload, type LibraryFile } from "./api"; import { type FileActions, FileGrid, FileTable } from "./files-view"; @@ -111,13 +110,10 @@ function ViewSwitch({ ); } -function useLibraryTitle(kind: "bot" | "group", id: string) { - const bots = useQuery({ ...botsQuery, enabled: kind === "bot" }); - const groups = useQuery({ ...groupsQuery, enabled: kind === "group" }); +function useLibraryTitle(id: string) { + const bots = useQuery(botsQuery); - const name = (kind === "bot" ? bots.data : groups.data)?.find( - (owner) => owner.id === id, - )?.name; + const name = bots.data?.find((owner) => owner.id === id)?.name; return name ? `${name}'s library` : "Library"; } @@ -243,8 +239,8 @@ function useDropZone(onDrop: (files: File[]) => void) { }; } -function useLibraryFiles(kind: "bot" | "group", id: string, path: string) { - const key = ["library", kind, id]; +function useLibraryFiles(id: string, path: string) { + const key = ["library", "bot", id]; const download = useFileDownload(); const files = useInfiniteQuery({ @@ -273,7 +269,7 @@ function useLibraryFiles(kind: "bot" | "group", id: string, path: string) { await Promise.all([ queryClient.invalidateQueries({ queryKey: key }), queryClient.invalidateQueries({ - queryKey: [kind === "bot" ? "chat" : "group-chat", id], + queryKey: ["chat", id], }), ]); }, @@ -304,19 +300,13 @@ function useLibraryFiles(kind: "bot" | "group", id: string, path: string) { }; } -function BackToChat({ kind, id }: { kind: "bot" | "group"; id: string }) { +function BackToChat({ id }: { id: string }) { return (