diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 605268f1f6..b750562891 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -88,6 +88,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Bot journal:** Mousse's complete record of what a bot did and was told: every message, run report, ask, answer and tool call, kept in `bots.db`. A bot's memory, chat summary and search are built from it. See `docs/bot-memory.md`. - **Bot memory:** the short, dated facts about its owner and notes a bot keeps and sees in every turn, within a fixed size. The owner manages it by asking the bot ("remember …", "forget …", "export your memory"). - **Bot tool catalogue:** how a bot reaches the tools beyond its core set (memory, replies, asks, work, reminders, thread basics). Its instructions name each group in one line; the bot reads a group with `tool_catalogue` when it first needs it, which also gives that group's guidance. On Claude Code every tool is listed and loaded on demand by its tool search; on Codex and Pi only the core set is listed, and the rest are called through one fixed `use_tool` entry. Every permission and refusal is the same either way. See `docs/plans/bot-context.md` §15. +- **Offered message:** a message a bot on one of the owner's computers wants to send to a bot on another computer it can't reach. It waits in the first bot's chat; on the computer it is for, a person sees the exact words, picks a bot and presses Send. The receiving bot gets it as a message in its chat and does nothing until its owner writes to it. Make private, or a switch in the bot's About, stops a bot from taking them. See `docs/bots.md`. - **Chat summary:** a short summary of a bot's older chat, kept in `bots.db` and given to every turn with the recent messages. Mousse folds the oldest messages into it without a model call. - **Files folder:** the folder where a bot keeps the documents it makes and copies of the files its owner attaches (`/bots/files//`). The bot may always write there; it is not memory, and none of its contents are read back into prompts: only its files' names and dates are. Its file tools reach no other folder but its scratch folder: "use files on this computer" was removed, and a grant an older build wrote with it keeps working without it. - **Bot browser:** a bot's own browser, which it uses once its owner allowed "use the browser": a browser without a window, on a Chromium profile of that bot alone, apart from the owner's tabs and every thread's. Sites the owner signs in to there stay signed in for that bot. Its reply shows a live preview of it; Expand opens the split view, the browser beside the bot chat, where the owner uses it just by using its page; it goes back to the bot when they message it, close the view or press Give back. Both get pictures only while they are on screen, pushed as the page paints. See `docs/bots.md`. diff --git a/docs/bots.md b/docs/bots.md index 99aef78581..9f2f737e4b 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -362,6 +362,19 @@ A bot can tell another of its owner's bots something: `bot_list()` names the own - **Stored.** The row is an ordinary chat message, the turn an ordinary chat activation; an older build reads both and ignores `fromBot`. What is held is a `bot_chain_holds` row (`bots.db` v16), and the latest Continue is `bot_memory_state`'s `chain-renewed`. Threads never read either. - **The risk that remains.** A bot's message can carry what its sender read on the web or in a file. The receiving bot is told it is information, and its turn can't act on the owner's threads, but what it does with its own permissions (its files, commands if it has them) rests on the model's judgement. +### Offered messages + +When the owner writes from one computer (here "the PC") to a bot of another (here "the Mac") that the PC uses one way, the Mac has no grant at the PC, so `bot_send` can't reach the PC's bots. The bot can offer the message instead (issue #2490): the PC shows the exact words, and a person there sends them, or doesn't. Nothing crosses from the Mac to the PC; the PC reads the offer on the chat stream it opened. + +- **The tool.** `bot_offer({ message, to? })` (`src/shared/bots/personal/offers.ts`, `BotEngine.offerBotMessage`), compiled only for the chat front desk (`compileBotThread`'s `bots` with `frontDesk`) and listed only for a chat turn. It works only in a chat turn the owner started from another device whose message said it takes offers: that device's router adds `offers: 1` to `bots.chat.send` (a version 3 row; added only when the bot's computer lists that version in `net.info`, and never taken from a window), and the turn keeps it on its owner (`BotOwnerTurn.offers`) with the device's node. Any other turn (this computer's own window, a phone, an older PC, a wake, work, another bot's message) is refused with `offer_unsupported` and words to tell the owner to write from the device it is for; there is no other way to send it, ever. Up to 3 offers in a turn (`MAX_OFFERS_PER_TURN`), each up to 2,000 characters and 6 KiB (`MAX_OFFER_CHARS`, `MAX_OFFER_BYTES`). `to` is a name the bot was told, shown as the first pick; it chooses nothing. A retry under the same tool call is the same offer (`replayed`). +- **Where it waits.** In the offering bot's chat, as a notice (`bm_offer_`: "I'd like to send a message to a bot on ANIMATRIX. It waits for you there.") with an `offer` card: the offer id, the words, `to`, the computer's name and the node it is for. The node never leaves the Mac: each reader gets the card through `offerCardFor` (in `remoteBotMessage`, so chat streams, `bots.chat.list` and every other bot method), which drops it and marks `forYou` for the device the offer is for alone. On the Mac, and on every other device, the card shows the words and where it waits, with no Send. +- **Send.** On the PC the card shows the words as plain text (no Markdown, no HTML), a pick of the PC's bots that take offered messages (the one `to` names first, else the only one) and Send. `bots.remote.offerSend` (`BotRouter.offerSend`, a local method) takes only a person at a Mousse window of the PC (`clientType: 'gui'`, not through Bridge; the command line, agents and bots are `forbidden`; #2052 applies). It finds the offer in the PC's own copy of the chat (`RemoteBotChats`), or reads that one row from the Mac (`bots.chat.list` by `seq`), never from what the window says, and checks that it is the PC's (`offer_not_here`), that the words are the window's (`offer_changed`), and, with nothing awaited after it, that the PC still lists the bot and has not blocked the Mac (`sender_blocked`). Then `BotChatService.keepOffered` keeps it in one transaction: one row per offer (`bm_offered_`) and its receipt, kept apart from every chat (`bot_memory_state` under `mousse:offered`). So a second Send, after a reconnect, a restart, with the Mac away, or after that chat was cleared or that bot deleted, answers `replayed` from the PC alone, and one to another bot is `offer_sent`; the bot is here (`recipient_gone`) and takes offered messages (`recipient_closed`); at most 30 a hour on this computer (`too_many`). A second Send while one runs is `offer_busy`. +- **What the receiving bot gets.** A notice in its chat ("**Message from your bot Loki on Mac mini**, sent by you" and the words as a quote), marked as outside text (`external`: its journal gives it as text from outside, not the owner's) and quiet. It starts no turn and answers nothing: the bot reads it with the owner's next message to it. Working on it is the owner's own message. +- **States on the PC's card** (`BotOfferRow`): Send; Sent to Alpha; a refusal in its words (`BOT_OFFER_REFUSALS`; `offer_offline` when the offer is in no copy here and the Mac can't be reached); "No bot here takes these." when none does. A Send whose answer was lost is looked up (`bots.remote.offerState`, which reads the PC alone) before Send comes back. The Mac's row is not told the outcome. +- **Which bots take them.** Every bot of a computer, until the owner says otherwise: Make private closes it first, then makes the bot private, and stops if closing fails (`bots.devices.offers`, this computer's alone: no other device has a row for it, at any bot access), and About → Devices has the switch "Messages from other computers' bots". Kept in `/bots/offers.json` (`BotOfferAccessStore`); a file that can't be read closes every bot, and the next change keeps the others closed. Make private on a bot of another computer leaves that computer's switch alone. +- **A bot that moves** to another computer takes its offers without the device each was for (`offerCardFor` in the bundle), so there they wait for no Send. +- **Not yet.** Offers don't expire. A picture's path in the words shows that picture in the receiving bot's chat on the PC, as in any message between bots; nothing leaves the PC. + ## Asks An ask is a request for one permission, shown as a card with Allow and Not now (`bot_escalations`, `mode` `wall` or `ask`). @@ -840,7 +853,7 @@ A bot is held on two sides, both set on the computer that holds it (its home com ### Which devices reach a bot -- **Per bot.** About → Devices: This computer, always on, then a switch for each other device of the owner's (phones too), each off until the owner turns it on. With no other device it says Only this computer. A device linked later reaches no bot until it is turned on in that bot's About. Kept in `/bots/device-access.json` (`BotDeviceAccessStore`), not in `bots.db`, so no database version moves: `this_computer`, or `chosen` with the devices turned on; none turned on is `this_computer`. The bot's menu has Make private (this computer alone, in one click). +- **Per bot.** About → Devices: This computer, always on, then a switch for each other device of the owner's (phones too), each off until the owner turns it on. With no other device it says Only this computer. A device linked later reaches no bot until it is turned on in that bot's About. Kept in `/bots/device-access.json` (`BotDeviceAccessStore`), not in `bots.db`, so no database version moves: `this_computer`, or `chosen` with the devices turned on; none turned on is `this_computer`. The bot's menu has Make private (this computer alone, in one click; it also closes the bot to offered messages, see Messages between bots). - **New bot.** When the owner has another device (`devices` in `bots.model.choices`, the other devices linked now), New bot has a Devices step after Runs on, with the same switches, all off. With this computer the only device there is no step, and the bot is this computer's alone. Either way About changes it later. `access` is sent only to a service that says `reachOnCreate`; an older service gets none. - **Saved before the bot exists.** `bots.create`'s choice is written before the bot is published, so no list or call ever shows a new bot to a device it leaves out. A create that fails before publishing takes its choice off again; a crash between the two leaves a choice for a bot that was never made, which the next start removes (`BotDeviceAccessStore.dropBots`) before any create can run. A retry of the same request returns the bot it made and changes nothing. This computer alone writes nothing once no stored choice already means it. `access: { mode: 'all' }` from an older window is taken as this computer alone. - **Per device.** Settings → Devices → Bots on this computer, beside each device's other switches: an Off / Use / Full picker (`net_node_policy.bots`, `bridge.policy`'s `bots`, `mousse-cli bridge limits --bots off|use|full`). A new device starts at Use. **Off:** the device reaches no bot here, whatever each bot says. **Use:** it lists and opens the bots it reaches, reads their chat, images, cards and memory, sends messages, answers questions and held actions (within the bot's existing permissions), stops work, snoozes reminders, marks read, and watches the browser and opens applets. **Full:** every other remote action as well: rename and look, pause and resume, permissions (answering an ask is a grant), memory edits, cancelling reminders, schedules, taking over the browser, the bot's Devices, delete, and making bots here. The presets set it with their other switches (View and chat and Work on threads give Use, Full control gives Full); changed on its own, the preset shows Custom, and Full control for remote updates and the engine grant role does not move. Full bot access never widens thread access: turning on Allow everything, or allowing "Use your threads", also needs the device's highest permission mode here to be Full access, and a turn a device starts stays under that mode. It is the only device-level setting for bots: the computer-wide "Share bots with other devices" of earlier builds is gone. On update, a computer that had it off sets every device it knows to Off (its account's devices, every device with a record here and every engine pairing), once, so no device gains access; one that had it on changes nothing. The update to levels (Net schema 2) keeps Off as Off and makes an on device Full if it was at Full control and Use otherwise. Dictation and read-aloud (`speech.*`) are not bot calls and do not follow the level. @@ -976,6 +989,7 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda | Work and reminders | `BotEngine` (`startWork`, `listWork`, `noteWork`, `addReminder`, `deliverDueReminders`), `src/mms/bots/grants/compile.ts` (`frontDeskManifest`) | | Subagents of work | `BotEngine` (`startSubagent`, `compileSubagent`, `holdOf`, `prepareSubagent`, `settleSubagent`, `acknowledgeReportStops`), `src/shared/bots/personal/subagentHold.ts` (the hold rule), `HarnessDriver.botHold`, `src/mms/bots/grants/compile.ts` (`subagentManifest`), `subagent_*` in `src/mms/run/mcp/appTools/bots.ts` | | Messages between bots (`bot_list`, `bot_send`) | `src/shared/bots/personal/botMessages.ts`, `BotEngine.sendBotMessage`, `receiveBotMessage`, `otherBots` and `unownedChainOf`, `BotStore.botMessageRowAfter`, `botMessageRowSince`, `botMessagesReceivedAfter`; other computers' bots: `src/mms/bridge/routed/otherComputersBots.ts`, `src/mms/protocol/otherComputersBotsPort.ts`, `RemoteBotRegistry`'s `FeedState` | +| Offered messages (`bot_offer`) | `src/shared/bots/personal/offers.ts`, `BotEngine.offerBotMessage`, `offerCardFor` in `RemoteBots.ts`, `BotRouter.offerSend` and `offerState`, `BotChatService.keepOffered`, `src/mms/bots/definitions/BotOfferAccessStore.ts`, the card's `BotOfferCard.tsx` | | Questions (`question_ask`, taps, moving on, work that waits on one) | `src/shared/bots/personal/questions.ts`, `BotEngine.askOwner`, `askFromWork`, `postReply`, `parkForQuestion`, `answerWorkInTx` and `relayAnswer`, `BotChatService.answerQuestion`, `answerWork` and `send`, `src/renderer/components/bots/BotQuestionReplies.tsx` | | Cards (`show_card`, a question's card) | `src/shared/bots/personal/cards.ts` (`cardOf`, `plainCard`), `src/mms/bots/chat/replyCards.ts` (`galleryPicture`), `BotEngine.showCard`, `BotChatProjection.shown` and `toMessage`, `src/renderer/components/bots/BotCards.tsx` | | Question follow-ups (nudges, defaults, late answers) | `questionFollowOf` (`questions.ts`), `src/mms/bots/activation/questionFollowUps.ts` (`nudgeSlot`), `BotEngine.armDue`, `followUpQuestion`, `nudge`, `goWithDefault` and `lateWorkAnswerInTx`, `BotChatService.workAnswerMode` | diff --git a/src/main/ipc/registerGuiIpc.ts b/src/main/ipc/registerGuiIpc.ts index 985c9157cc..b24803176b 100644 --- a/src/main/ipc/registerGuiIpc.ts +++ b/src/main/ipc/registerGuiIpc.ts @@ -29,7 +29,8 @@ import { BRIDGE_LISTS_METHODS } from '../../shared/bridge/computerProjects' import { SPACES_LOCAL_METHODS } from '../../shared/spaces/local' import { BOTS_LOCAL_METHODS } from '../../shared/bots/space/local' import { BOTS_ELSEWHERE_METHODS, BOTS_PERSONAL_V2_METHODS, BOTS_WORK_METHODS } from '../../shared/bots/personal/methods' -import { BOT_DEVICE_METHODS } from '../../shared/bots/personal/deviceAccess' +import { BOT_DEVICE_METHODS, BOT_OFFERS_SWITCH_METHOD } from '../../shared/bots/personal/deviceAccess' +import { BOT_OFFER_METHODS } from '../../shared/bots/personal/offers' import { BOT_MARK_METHODS } from '../../shared/bots/personal/marks' import { BOTS_BROWSER_METHODS } from '../../shared/bots/personal/browser' import type { BotChatMessage } from '../../shared/bots/personal/chat' @@ -312,6 +313,8 @@ export const PLATFORM_REQUEST_METHODS: ReadonlySet = new ...BOT_MARK_METHODS, ...BOTS_WORK_METHODS, ...BOT_DEVICE_METHODS, + BOT_OFFERS_SWITCH_METHOD, + ...BOT_OFFER_METHODS, ...BOTS_BROWSER_METHODS, ...AUTOMATIONS_METHODS, ...SECRET_METHODS, diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 8970ec5fd1..15f3f55449 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -167,6 +167,7 @@ import type { EditorAsksPort } from './protocol/editorAsksPort' import type { BotReachPort } from './protocol/botReachPort' import type { OtherComputersBotsPort } from './protocol/otherComputersBotsPort' import { BotDeviceAccessStore } from './bots/definitions/BotDeviceAccessStore' +import { BotOfferAccessStore } from './bots/definitions/BotOfferAccessStore' import { ensureBuiltInBots, renameOldDefaultBot } from './bots/builtIn' import { BotMarksStore } from './bots/marks/BotMarksStore' import type { RemoteListsPort } from './protocol/remoteListsPort' @@ -377,6 +378,11 @@ export class MmsProfileServices { * keeps of their feeds, and a message sent to their computer. Set by the Bridge service with `botRouter`. */ otherComputersBots?: OtherComputersBotsPort + /** + * Another device's name as Settings, Devices names it, for words a bot says about it (an offer names the computer it + * is for). Set by the Bridge service; absent while it is off. + */ + deviceName?: (node: string) => string | undefined /** * The threads, projects and statuses of the user's other computers, merged into this computer's lists * for windows. Set and cleared with `threadRouter`; empty while routing is off. @@ -489,6 +495,8 @@ export class MmsProfileServices { readonly botBrowsers: BotBrowsers /** Which devices reach each bot (About → Devices), in `/bots/device-access.json`. */ readonly botDeviceAccess: BotDeviceAccessStore + /** Which bots here take offered messages (issue #2490); Make private closes a bot. */ + readonly botOfferAccess: BotOfferAccessStore /** Pin, hide, mute and marked unread on every bot this computer lists, in `/bots/bot-marks.json`. */ readonly botMarks: BotMarksStore /** Bots' schedules: automations whose Who is the bot, in the shared scheduled-job store. */ @@ -882,6 +890,7 @@ export class MmsProfileServices { }) this.botBrowsers = botBrowsers this.botDeviceAccess = new BotDeviceAccessStore(join(homeDir, 'bots')) + this.botOfferAccess = new BotOfferAccessStore(join(homeDir, 'bots')) // Read on first use (the Bots list asks once it shows), never here. this.botMarks = new BotMarksStore(join(homeDir, 'bots')) this.platform.onDispose(() => botBrowsers.dispose()) @@ -973,6 +982,7 @@ export class MmsProfileServices { // A device's limit now, for a turn held to it; while Bridge is off it can't be read, and the saved limit holds. deviceLimit: (botId, node) => this.botReach?.turnLimit?.(botId, node), otherComputersBots: () => this.otherComputersBots, + deviceName: (node) => this.deviceName?.(node), // The shared store, through the book made once the scheduler exists below (nothing reads it before that). schedules: { list: (botId) => this.botSchedules?.list(botId) ?? [], @@ -1049,6 +1059,8 @@ export class MmsProfileServices { }, // Which devices reach each bot: a new bot's choice is saved before the bot is published. deviceAccess: this.botDeviceAccess, + // Which bots take offered messages from bots of the owner's other computers. + offerAccess: this.botOfferAccess, // New bot's Devices step lists the owner's other devices, as About's Devices does. devices: async () => this.botReach?.devices(), // The secrets a bot's home thread may use, for its profile: names and labels only, read when it asks. @@ -1138,6 +1150,11 @@ export class MmsProfileServices { } catch (error) { console.warn('bot device choices could not be tidied', error instanceof Error ? error.message : String(error)) } + try { + this.botOfferAccess.dropBots((botId) => opened.store.registry(botId) !== undefined) + } catch (error) { + console.warn('bot offer choices could not be tidied', error instanceof Error ? error.message : String(error)) + } try { renameOldDefaultBot(opened.engine) } catch (error) { diff --git a/src/mms/MousseMainService.ts b/src/mms/MousseMainService.ts index f6eeba14de..3a031111f1 100644 --- a/src/mms/MousseMainService.ts +++ b/src/mms/MousseMainService.ts @@ -346,6 +346,7 @@ export class MousseMainService extends MmsProfileServices { if (!engine.botIds().includes(botId)) throw new BotDefinitionError('bot_not_found', 'This bot is gone.') }, store: services.botDeviceAccess, + offers: services.botOfferAccess, devices: async () => services.botReach?.devices(), changed: (botId) => engine.reachChanged(botId) } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 3c270efa9d..e5305067da 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -120,6 +120,7 @@ import { addedPermissions, BOT_FULL_TRUST_PERMISSION, intersectManifest, manifes import { allPinned, copyPick, customSlotsOf, imagePickOf, isPinned, limitFamilyOf, limitOnPick, pickProblemText, plainLabel, rowName, samePick, samePickTarget, sameStoredPick, slotsOf, slotsWith, startDepthOf, stuckRowsOf, turnModelOf, UNPICKED_SLOTS, withCustomSlot, withImagePick, withSlots, type BotPickMiss, type BotStuckEntry, type BotTurnModel } from '../../../shared/bots/personal/modelSlots' import type { BotModelOption, BotSystemInstructions } from '../../../shared/bots/personal/methods' import type { BotDeviceAccessStore } from '../definitions/BotDeviceAccessStore' +import type { BotOfferAccessStore } from '../definitions/BotOfferAccessStore' import type { BotDeviceChoice } from '../../../shared/bots/personal/deviceAccess' import { defaultChatInput, defaultWorkLine, lateWorkNote, DEFAULT_NUDGE_AFTER_MINUTES, MAX_NUDGES_PER_QUESTION, MAX_QUESTIONS_PER_CALL, QUESTION_DUPLICATE_TEXT, questionIdentity, NUDGE_AGAIN_MS, NUDGE_TEXT, plainChoices, QUESTION_AFTER_ASK_TEXT, QUESTION_ASKED_TEXT, QUESTION_END_TURN_TEXT, QUESTION_ANSWER_FORGOTTEN_TEXT, QUESTION_NOT_OFFERED_TEXT, QUESTION_WORK_ASKED_TEXT, QUESTION_WORK_WAITING_TEXT, questionGoneText, keepsWorking, openQuestionAnswerNote, questionWorkKeepsWorkingText, waitingQuestionLine, workAnswerLine, type BotQuestionAnswer, type BotQuestionAsk, type BotQuestionFollow, type BotQuestionSpec, type BotQuestionStatus } from '../../../shared/bots/personal/questions' import { CARD_SHOWN_TEXT, type BotCard } from '../../../shared/bots/personal/cards' @@ -129,6 +130,7 @@ import { botTaskItems } from './botTasks' import type { BackgroundJobService } from '../../background/BackgroundJobService' import { BotWatchers, DEFAULT_WATCHER_MINUTES, MAX_WATCHER_COMMAND_CHARS, MAX_WATCHER_MINUTES, watcherMatchProblem, type WatcherEnd, type WatcherSpec, type WatcherView } from '../watchers' import { lockedEnv } from '../../harness/env' +import { BOT_OFFERS_VERSION, MAX_OFFERS_PER_TURN, MAX_OFFER_TO_CHARS, OFFER_ROW_PREFIX, offerMessageProblem, offerRowText, plainOfferName, type BotOfferCard } from '../../../shared/bots/personal/offers' import { MAX_BOT_MESSAGE_CHARS, MAX_BOT_MESSAGES_UNANSWERED_BY_OWNER, botAddressName, botMessageInput, botMessageKey, botMessageRowId, botMessageRowText, botNamed, otherComputerNote, type BotMessageSender, type OtherComputerBotsStatus } from '../../../shared/bots/personal/botMessages' import { qualifyId } from '../../../shared/threadRef' import { OtherComputerBotRefusal, type OtherComputerBotMessage, type OtherComputersBotsPort } from '../../protocol/otherComputersBotsPort' @@ -231,6 +233,17 @@ function requestedMessageId(sender: string, requestKey: string): string { return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${((parseInt(hex[16]!, 16) & 3) | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}` } +/** + * The device to keep on a chat turn the owner's message starts (`deviceToSave`), with `offers` when that device takes + * offered messages: kept on that turn's own trigger alone, never with what the turn sets up (a reminder, a schedule, + * work), so only a chat turn the owner started from that device offers it a message (`offerBotMessage`). + */ +function turnOwnerToSave(owner: BotOwnerTurn | undefined): BotOwnerTurn | undefined { + const saved = deviceToSave(owner) + if (!saved) return undefined + return saved.node && !saved.readOnly && owner?.offers === BOT_OFFERS_VERSION ? { ...saved, offers: BOT_OFFERS_VERSION } : saved +} + /** The hold of a message held under its id: one per message, so a retry never holds it twice. */ function heldMessageId(messageId: string): string { return `bhold_${messageId}` @@ -347,6 +360,8 @@ export interface BotEngineHost { * one reach, and a message sent to the bot's own computer. Absent, or undefined now: only this computer's bots. */ otherComputersBots?(): OtherComputersBotsPort | undefined + /** Another device's name, as Settings, Devices names it (an offer names the computer it is for). Absent: none known. */ + deviceName?(node: string): string | undefined /** * The bots' schedules, in the shared scheduled-job store (`BotScheduleBook`): automations whose Who is the bot. The * one scheduler claims each occurrence and hands it to `runScheduledOccurrence`. Absent: no bot has schedules here. @@ -435,6 +450,8 @@ export interface BotEngineHost { * and the bot's menu reads it (Make private). Absent: no bot is given a choice when it is made, and none is listed with one. */ deviceAccess?: Pick + /** Which bots take offered messages from bots of the owner's other computers (`BotOfferAccessStore`). Absent: none does. */ + offerAccess?: Pick /** The owner's other devices, for New bot's Devices step (`BotReachPort.devices`); undefined while Bridge is off. */ devices?(): Promise /** The secrets a thread's agents may use (the bot's home thread: the bot's), by name and label, never a value. */ @@ -1180,6 +1197,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { ...(host.computerName ? { computerName: host.computerName } : {}), ...(host.otherComputers ? { otherComputers: host.otherComputers } : {}), ...(host.deviceAccess ? { deviceAccess: host.deviceAccess } : {}), + ...(host.offerAccess ? { offerAccess: host.offerAccess } : {}), ...(host.devices ? { devices: host.devices } : {}), ...(host.webPictures ? { webPictures: host.webPictures } : {}) }) @@ -2007,7 +2025,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { * repeat of `key` returns the same activation; messages in the chat lane run in order. */ async enqueueChat(botId: string, key: string, input: string, activationId?: string, owner?: BotOwnerTurn): Promise { - return this.enqueue(botId, key, { kind: 'manual', input, ...(deviceToSave(owner) ? { owner: deviceToSave(owner) } : {}) }, 'chat', activationId) + const saved = turnOwnerToSave(owner) + return this.enqueue(botId, key, { kind: 'manual', input, ...(saved ? { owner: saved } : {}) }, 'chat', activationId) } /** @@ -2098,9 +2117,10 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } // A message from another device holds what the turn starts or messages to that device's limit (`BotOwnerTurn`). // One another bot's message started says who sent it, and which turn in a row without the owner it is. + const saved = turnOwnerToSave(owner) const trigger: BotActivationTrigger = { kind: 'manual', input, - ...(deviceToSave(owner) ? { owner: deviceToSave(owner) } : {}), + ...(saved ? { owner: saved } : {}), ...(options?.fromBot ? { fromBot: options.fromBot } : {}), ...(options?.fast ? { fast: true } : {}), ...(options?.spoken ? { spoken: true } : {}) @@ -10616,7 +10636,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { ...(bot.elsewhere ? { computer: bot.elsewhere.computer, ...(bot.elsewhere.offline ? { offline: true as const } : {}) } : {}) })), elsewhere: () => this.computersElsewhere(), - send: (botId, from, input) => this.sendBotMessage(botId, from, input) + send: (botId, from, input) => this.sendBotMessage(botId, from, input), + offer: (botId, from, input) => this.offerBotMessage(botId, from, input) }, jobs: { open: (botId, from, input) => this.openJob(botId, from, input), @@ -11851,6 +11872,64 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } } + /** + * `bot_offer` (issue #2490): the chat turn `from`, which the owner's message from another computer started, offers a + * message for a bot of that computer. It is kept as a row of this bot's own chat (`bm_offer_`) with an + * `offer` card naming that device; that device's window shows it with Send, and only that computer keeps it for one of + * its bots, when the owner sends it there (`BotRouter.offerSend`). Nothing is sent from here: the owner's computer + * reads the offer on the chat stream it opened. Refused, in words for the bot: any other turn (work, a schedule, a + * wake, another bot's message, a message written on this computer), a device that takes no offers (a phone, an older + * Mousse) or no longer reaches the bot, an empty or too long message, or more than `MAX_OFFERS_PER_TURN` in one turn. + * + * `requestKey` (the call's key): a retry under it is the same offer (`replayed`), never a second row. + */ + offerBotMessage(botId: string, from: string, input: { message: string; to?: string; requestKey?: string }): { offerId: string; computer: string; replayed?: true } { + const row = this.store.activation(from) + if (!row || row.botId !== botId) throw new BotEngineError('invalid_params', 'Only a chat turn your owner started from another computer can offer a message there. Nothing was offered.') + if (row.status !== 'running') throw new BotEngineError('invalid_params', 'This turn has ended; nothing was offered.') + const trigger = row.trigger + const owner = trigger.kind === 'manual' && ownerChatTurn(row) ? trigger.owner : undefined + const device = savedDevice(owner) + if (!device?.node || device.readOnly) + throw new BotEngineError('offer_not_here', "Your owner didn't write this from another of their computers, so there is nowhere to offer it. Nothing was offered: use bot_send for your owner's bots you can reach, or tell your owner.") + const computer = this.deviceName(device.node) + if (owner?.offers !== BOT_OFFERS_VERSION) + throw new BotEngineError('offer_unsupported', `${computer} can't take offered messages: it needs a newer Mousse, or it is a phone. Nothing was offered: tell your owner instead.`) + // The device must still reach this bot: one taken off it, or blocked here, is offered nothing. + if (this.deviceLimitNow(row) === null) + throw new BotEngineError('offer_unsupported', `${computer} can no longer reach me here. Nothing was offered: tell your owner instead.`) + const message = input.message.trim() + const problem = offerMessageProblem(message) + if (problem) throw new BotEngineError('invalid_params', problem) + const to = input.to?.replace(/\s+/g, ' ').trim() + if (to !== undefined && to.length > MAX_OFFER_TO_CHARS) throw new BotEngineError('invalid_params', `Name the bot in at most ${MAX_OFFER_TO_CHARS} characters. Nothing was offered.`) + const offerId = input.requestKey ? requestedMessageId(`offer:${botId}:${row.id}`, input.requestKey) : randomUUID() + const id = `${OFFER_ROW_PREFIX}${offerId}` + return this.store.db.transaction(() => { + const kept = this.store.message(id) + if (kept) { + if (kept.botId !== botId) throw new BotEngineError('client_request_id_conflict', 'This clientRequestId was used for another offer. Nothing was offered.') + return { offerId, computer, replayed: true as const } + } + if (this.store.countMessagesWithPrefix(row.id, OFFER_ROW_PREFIX) >= MAX_OFFERS_PER_TURN) + throw new BotEngineError('invalid_params', `You offered ${MAX_OFFERS_PER_TURN} messages in this turn already. Nothing more was offered: put what is left in one of them next time.`) + const card: BotOfferCard = { type: 'offer', offerId, message, ...(to ? { to } : {}), computer, node: device.node! } + this.chat.post({ id, botId, author: 'bot', kind: 'notice', text: offerRowText(computer), cards: [card], activationId: row.id, lane: 'chat' }) + return { offerId, computer } + }) + } + + /** A device's name as this computer knows it (Settings, Devices), for a bot's words; never its id. */ + private deviceName(node: string): string { + let name: string | undefined + try { + name = this.host.otherComputersBots?.()?.computerName(node) ?? this.host.deviceName?.(node) + } catch { + name = undefined + } + return plainOfferName(name ?? '', 'your other computer') + } + /** * `bots.botMessage.send`: a bot of the owner's on another computer (`from.node`) sends bot `botId` here a message, as * `sendBotMessage` does for a bot of this computer: shown in its chat as the sender's, it starts a chat turn here that diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index 30c2d063ce..bc94275cda 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -1,3 +1,5 @@ +import { BOT_OFFER_REFUSALS, MAX_OFFERS_KEPT_PER_HOUR, OFFERED_ROW_PREFIX, offeredRowText, type BotOfferDelivered, type BotOfferRecipient, type BotOfferRefusal } from '../../../shared/bots/personal/offers' +import type { BotOfferAccessStore } from '../definitions/BotOfferAccessStore' import { PageChecks } from '../pageChecks' import { botScheduleProblem } from '../../scheduled/botJobs' import { BOT_SETUP_REFUSALS, customSlotName, MODEL_UNAVAILABLE_TEXT, type BotSetupRefusal } from '../setupRefusals' @@ -64,6 +66,13 @@ export interface BotAutomationFacts { ask?: { text: string; activationId: string; askId?: string } } +/** + * The receipts of offered messages sent here (`keepOffered`), one per offer, keyed by its row id: kept beside the bots' + * own state under a name no bot has, so clearing a chat and resetting or deleting a bot never remove one, and no bot's + * move takes one along. As creations' are (`BotStore.recordCreation`). + */ +const OFFER_RECEIPTS = 'mousse:offered' + /** A custom slot or a schedule refused before anything is saved: its code, and its reason with the words for it. */ const setupRefused = (code: string, reason: BotSetupRefusal, asked: Record): BotEngineError => new BotEngineError(code, BOT_SETUP_REFUSALS[reason](asked), { reason }) @@ -250,7 +259,7 @@ interface BotChatSendInput { clientRequestId: string replyTo?: string spoken?: true - from?: { limit: PermissionMode; node?: string } + from?: { limit: PermissionMode; node?: string; offers?: 1 } } export class BotChatService { @@ -275,6 +284,8 @@ export class BotChatService { devices?(): Promise /** The pictures from the web its chats show (`bots.chat.webPicture`), kept by the profile's service. */ webPictures?(): WebPictures + /** Which bots take offered messages (issue #2490). Absent: none does. */ + offerAccess?: Pick }) {} private get store(): BotStore { @@ -302,6 +313,76 @@ export class BotChatService { return { ...summary, ...(access ? { reach: alone ? 'this_computer' as const : 'chosen' as const } : {}), facePicture: key ? { key } : {} } } + /** + * An offered message the owner sends to bot `to` here (issue #2490), once `BotRouter.offerSend` checked the offer + * against this computer's copy of the offering bot's chat. Kept in `to`'s chat as a message from that bot, marked as + * outside text (`external`), in one transaction that first checks: whether it was kept before (`rowId`, one per + * offer: kept for `to` it is `replayed`, kept for another bot it is `offer_sent`), that `to` is a bot here that + * takes offered messages (`offerAccess`; Make private closes it), and this computer's count of the last hour. It + * starts no turn and tells nobody: the owner just sent it, and the bot reads it when its owner next writes to it. + */ + keepOffered(input: { rowId: string; to: string; fromName: string; computer: string; message: string }): { delivered: BotOfferDelivered; replayed?: true } { + if (!input.rowId.startsWith(OFFERED_ROW_PREFIX)) throw new BotEngineError('invalid_params', 'Not an offered message.') + const nameOf = (botId: string): string => this.botName(botId) + const refuse = (code: BotOfferRefusal, details?: Record): never => { + throw new BotEngineError(code, BOT_OFFER_REFUSALS[code], details) + } + return this.store.db.transaction(() => { + const kept = this.offerKept(input.rowId) + if (kept) { + if (kept.to.botId !== input.to) refuse('offer_sent', { to: kept.to }) + return { delivered: kept, replayed: true as const } + } + if (!this.engine.botIds().includes(input.to)) refuse('recipient_gone') + if (!this.options.offerAccess?.open(input.to)) refuse('recipient_closed') + const since = new Date(Date.parse(this.store.now()) - 60 * 60_000).toISOString() + if (this.store.countRowsSince(OFFERED_ROW_PREFIX, since) >= MAX_OFFERS_KEPT_PER_HOUR) refuse('too_many') + const posted = this.engine.chat.post({ + id: input.rowId, + botId: input.to, + author: 'bot', + kind: 'notice', + text: offeredRowText({ fromName: input.fromName, computer: input.computer, message: input.message }), + // Another bot's words, which the owner passed on unchanged: the bot's memory keeps them as from outside. + external: true, + quiet: true, + lane: 'chat' + }) + this.store.run('INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', OFFER_RECEIPTS, input.rowId, JSON.stringify({ to: input.to, at: posted.at })) + return { delivered: { to: { botId: input.to, name: nameOf(input.to) }, at: posted.at } } + }) + } + + /** + * Where the offered message kept under `rowId` went (`keepOffered`): to which bot, and when; undefined when it was never + * sent here. Read from its receipt, not the chat row, so it stays sent when that chat is cleared or that bot deleted. + */ + offerKept(rowId: string): BotOfferDelivered | undefined { + if (!rowId.startsWith(OFFERED_ROW_PREFIX)) return undefined + const row = this.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', OFFER_RECEIPTS, rowId) + if (!row) return undefined + const kept = JSON.parse(row.value as string) as { to: string; at: string } + return { to: { botId: kept.to, name: this.botName(kept.to) }, at: kept.at } + } + + /** The bots here an offered message may be sent to now: each that takes them (`offerAccess`), by name. */ + offerRecipients(): BotOfferRecipient[] { + const access = this.options.offerAccess + if (!access) return [] + return this.engine.botIds() + .filter((botId) => access.open(botId)) + .map((botId) => ({ botId, name: this.botName(botId) })) + .sort((a, b) => a.name.localeCompare(b.name)) + } + + private botName(botId: string): string { + try { + return this.engine.definitionOf(botId).name + } catch { + return 'a bot' + } + } + /** `bots.facePicture.save`: the app's picture of the bot's face, written into its files folder as `face.png`. */ facePictureSave(botId: string, key: string, png: Buffer): { path: string } { this.engine.definitionOf(botId) @@ -756,7 +837,8 @@ export class BotChatService { const key = `${tap ? 'answer' : 'chat'}:${input.clientRequestId}` // The owner wrote this: the turn it starts or continues may start, message and stop their threads, held to the // limit of the device it came from (`BotOwnerTurn`; absent: this computer's own window). - const owner: BotOwnerTurn = input.from ? { limit: input.from.limit, ...(input.from.node ? { node: input.from.node } : {}) } : {} + // A device that takes offered messages says so; a turn it starts may offer it one (`bot_offer`). + const owner: BotOwnerTurn = input.from ? { limit: input.from.limit, ...(input.from.node ? { node: input.from.node, ...(input.from.offers === 1 ? { offers: 1 as const } : {}) } : {}) } : {} let messageId: string let prompt = '' let refused: BotEngineError | undefined diff --git a/src/mms/bots/definitions/BotOfferAccessStore.ts b/src/mms/bots/definitions/BotOfferAccessStore.ts new file mode 100644 index 0000000000..9c1bacc835 --- /dev/null +++ b/src/mms/bots/definitions/BotOfferAccessStore.ts @@ -0,0 +1,138 @@ +import { mkdirSync, readFileSync, renameSync, statSync } from 'node:fs' +import { join } from 'node:path' +import { atomicWriteJsonSync } from '../../data/AtomicFs' + +/** + * Which bots of this computer take offered messages (issue #2490): a message a bot of another computer offered while the + * owner chatted with it from here, which the owner sends to a bot of this computer they pick (`BotRouter.offerSend`). + * Kept on this computer in `/bots/offers.json`, beside the bots' Devices choices and apart from `bots.db`: + * + * { "version": 1, "others": "open", "bots": { "": "closed" } } + * + * - With no file every bot takes them (`others: open`). Make private closes a bot (with its Devices at this computer + * alone), and its About opens or closes it again. + * - A file that can't be read (not JSON, another version, a value it does not know) closes every bot. The next change + * puts it aside (`offers.json.corrupt-