From a5560321f5222c2fc016b2ba0f2a10284af232c9 Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Tue, 1 Dec 2026 00:38:17 +0530 Subject: [PATCH 1/6] feat(bots): a bot of another computer offers a message, and the owner sends it to a bot here --- src/main/ipc/registerGuiIpc.ts | 2 + src/mms/MmsProfileServices.ts | 17 + src/mms/MousseMainService.ts | 1 + src/mms/bots/activation/BotEngine.ts | 85 ++++- src/mms/bots/chat/BotChatService.ts | 73 +++- .../bots/definitions/BotOfferAccessStore.ts | 138 ++++++++ src/mms/bots/deviceMethods.ts | 14 +- src/mms/bots/grants/compile.ts | 6 +- src/mms/bots/seams.ts | 6 + src/mms/bots/store/BotStore.ts | 13 + src/mms/bridge/BridgeProfileService.ts | 6 + src/mms/bridge/remote/BotStreamSources.ts | 4 +- src/mms/bridge/remote/RemoteBots.ts | 54 +-- src/mms/bridge/routed/BotRouter.ts | 163 ++++++++- src/mms/bridge/routed/ThreadRouter.ts | 5 +- src/mms/protocol/botRouterPort.ts | 5 + src/mms/protocol/gitAccess.ts | 2 + src/mms/protocol/handlers.ts | 27 ++ src/mms/protocol/types.ts | 2 + src/mms/run/mcp/appTools/bots.ts | 39 +++ src/renderer/components/bots/BotCards.tsx | 10 +- src/renderer/components/bots/BotChatView.tsx | 2 +- src/renderer/components/bots/BotDevices.tsx | 18 + src/renderer/components/bots/BotOfferCard.tsx | 116 +++++++ src/renderer/services/personalBotsClient.ts | 12 +- src/renderer/stores/botsStore.ts | 4 +- src/renderer/styles/bots.css | 7 + src/shared/bots/personal/cards.ts | 40 ++- src/shared/bots/personal/catalogue.ts | 3 +- src/shared/bots/personal/definition.ts | 5 + src/shared/bots/personal/deviceAccess.ts | 10 +- src/shared/bots/personal/manifest.ts | 2 + src/shared/bots/personal/methodTable.ts | 5 +- src/shared/bots/personal/offers.ts | 179 ++++++++++ src/shared/platform.ts | 3 +- tests/bots/botFixture.ts | 2 +- tests/bots/offeredMessages.test.ts | 321 ++++++++++++++++++ 37 files changed, 1349 insertions(+), 52 deletions(-) create mode 100644 src/mms/bots/definitions/BotOfferAccessStore.ts create mode 100644 src/renderer/components/bots/BotOfferCard.tsx create mode 100644 src/shared/bots/personal/offers.ts create mode 100644 tests/bots/offeredMessages.test.ts diff --git a/src/main/ipc/registerGuiIpc.ts b/src/main/ipc/registerGuiIpc.ts index 985c9157cc..1a3dea5896 100644 --- a/src/main/ipc/registerGuiIpc.ts +++ b/src/main/ipc/registerGuiIpc.ts @@ -30,6 +30,7 @@ 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_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,7 @@ export const PLATFORM_REQUEST_METHODS: ReadonlySet = new ...BOT_MARK_METHODS, ...BOTS_WORK_METHODS, ...BOT_DEVICE_METHODS, + ...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..22b3135bfb 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..9a3cb8ebe1 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' @@ -250,7 +252,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 +277,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 +306,70 @@ 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' + }) + return { delivered: { to: { botId: input.to, name: nameOf(input.to) }, at: posted.at } } + }) + } + + /** Where the offered message kept under `rowId` is (`keepOffered`): in whose chat, and when; undefined when it is not kept here. */ + offerKept(rowId: string): BotOfferDelivered | undefined { + if (!rowId.startsWith(OFFERED_ROW_PREFIX)) return undefined + const kept = this.store.message(rowId) + return kept ? { to: { botId: kept.botId, name: this.botName(kept.botId) }, at: kept.at } : undefined + } + + /** 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 +824,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-