diff --git a/docs/bots.md b/docs/bots.md index 51ef4e9ee6..eefa0cc50e 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -807,18 +807,42 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda ### Asks first -The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, granted tools run as before. Tool selection, the approval card, scheduled runs that wait, withdrawal and timed expiry are separate work before this can be switched on. +The engine for holding an MCP call until Send is built behind `experimental.botAsksFirst`, which defaults to off and has no settings control. With it off, new granted-tool calls run as before. Existing held rows still withdraw, expire, settle and clear their arguments. Send still works on a card left from when the switch was on; the switch gates only new holds. Tool selection, the approval card and scheduled runs that wait are separate work before this can be switched on. A held call belongs to one piece of work and one runtime call in its dispatch. Mousse keeps its exact arguments in the action row until it settles; the chat, journal and export get a masked copy. Only unmistakable credential shapes are refused before a card is written: provider-prefixed keys, PEM private-key blocks, a password in a URL's userinfo, or a secret-named URL query value. Document IDs, base64 attachments, JWT-shaped page tokens and prose mentioning passwords remain reviewable. Values are not decoded or normalized to find more possible secrets: split or hex keys, upper-case `SK-` and a zero-width character inside `sk-` remain visible for the owner to judge. A value is hidden by its key name only where the installed input schema declares that property, following `properties`, array `items`, local `$ref`, every `allOf`, `anyOf` and `oneOf` branch, `if`/`then`/`else`, `dependentSchemas` and indexed `prefixItems`. `$dynamicRef` is treated as unresolved. References have a cycle guard and a 32-step expansion limit. Under a broken, remote or depth-limited schema part, secret-named keys are hidden conservatively throughout that subtree; free-form keys elsewhere remain visible. Invented names in free-form objects stay visible, at every depth. The masked copy represents a hidden value as `{ "$mousse": "hidden", "text": "hidden · will be sent" }`; the exact value is sent unchanged on Send. Literal argument objects with a `$mousse` key are escaped as `{ "$mousse": "literal", "value": }`, recursively. Text saying "hidden · will be sent" is ordinary argument text. `card_json.hasHiddenValues` records whether a hidden value actually exists, for the card to say so beside its buttons. -Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the grant revision and the starting device's permission limit. A changed or expired binding needs a fresh review. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. +Argument text is never cut from the review: at most 256,000 characters of serialized argument JSON are accepted in total, and larger calls are refused with a request to send less. Send names the action and the argument digest shown with it. It is bound to the installed server's configuration, the server id and tool name, the tool's schema, the held server/tool pair and its permission level, and the starting device's permission limit. Unrelated permissions and a grant revision bump leave that binding intact; removing or changing the pair withdraws its card, and granting it again does not revive the old card. A changed or expired binding needs a fresh review. Cards held by the #1340 build use the older whole-grant binding and are withdrawn on upgrade. These are development profiles only; the upgrade fails safe. Until the bridge carries whole large cards, a device's Send is refused when the complete message and its reply envelope exceed its 56 KiB limit: "Open it on the computer to send." Not now still works. Mousse makes the stored call once, without asking the model to recreate it. It commits approval and then the start of execution separately. After a restart, an approved call is checked again before running; a call whose execution had started becomes uncertain and is never repeated. A call that never left Mousse, or Not now, reads "Not sent". When the server answered with an error the row is `failed` but reads "The tool reported an error": the work gets its framed error and is told that the tool may have done part of it, so it must check before trying again. A request sent without an answer becomes `uncertain`, "Couldn't tell if it went through". Settled actions join the same ordered, timed updates as waits, notes and answers. An action that caused the resume leads with its outcome. Its id is kept on the dispatch. Work's stored updates (waits, action outcomes, notes and answers, including work without wait history) count as told only when a dispatch carrying them produces model output or completes. Nonempty model text or thinking, or a model tool-call start, confirms delivery; merely preparing or starting a request does not. A failed, interrupted or replaced dispatch without that evidence leaves its updates pending, including after a time-limit card. A repeated update is acceptable; losing one is not. Carried/read (`read_at` and `applied_at`, plus the dispatch's `workDelivery`) keeps its existing meaning for late taps, Forget and compaction. Confirmation is a separate fact used only to decide what the next prompt carries: `unreadWorkAnswers`, `unreadWorkQuestion` and `unreadWorkNotes` include carried-but-unconfirmed updates without clearing those read markers. New carrying dispatches start with `prompt.workTold = pending`; `BotStore.confirmWorkDelivery` changes only that marker to `output` or `completed`. Reads happen before any confirmation write transaction, so a dispatch with no updates never opens one. A failed confirmation is caught and logged once per dispatch; it never fails the runtime's turn, and the next continuation can carry the update again. Completion of a new dispatch is confirmed explicitly; older rows with no marker also accept a completed stored outcome. Startup recovers a completion written before settlement. A usage retry carries the previous prompt's update ids, so it confirms only what that prompt contained. A database written by master as of #1339 has `workDelivery` for work that waited but no confirmation marker. If its carrying dispatch ended at a wall, a deadline or a turn cap, its notes and answers can be told once more after upgrading (twice is acceptable; losing them is not). Their carried/read behavior is preserved. Earlier databases with no such delivery ids gain no retrospective replay. Approval parks before a time or event wait and has no idle or week exemption. +A held call is withdrawn, with executable arguments cleared in the same transaction, when its work ends (Stop, failure or a limit included), its card or the owner's request is forgotten, or its grant changes. Removing its tool or MCP server withdraws it on positive configuration evidence or when a successful listing no longer contains that tool. Starting, failing and not-yet-listed servers leave cards intact; Send still checks the binding. An accepted call waits for its service for at most ten minutes after the tap. The row reads "Not sent". A tool or permission withdrawal lets the work carry on with the outcome through the same unread updates; forgetting only its card withdraws and forgets the call, then continues the work told: "Your owner removed this request. Do not ask for it again unless they write." No tombstone text is read back to the work. Forgetting its request ends the work through the normal engine ending, with its journal entry and release of scratch, browser, progress and live status. A work row stranded on a settled call without its continuation marker ends too. Forget of a card or its request also tombstones the content of every matching action, including settled calls, in both its record and export. A running call is never withdrawn: it settles, or becomes uncertain after a restart. Deleting the bot keeps withdrawn and settled rows until the 30-day purge. + +`/clear` ends work waiting on its cards and removes the cards with the chat; running and settled action records stay, preserving the protection against running a call twice. `/reset` ends all work first and keeps those records too. `/forget history` also replaces every action's display arguments, argument digest, card metadata, bot note and stored result with fixed forgotten markers. The owner-message and work-note counters in its card metadata stay, as do its call key, target, status and timestamps. A forgotten row no longer matches an argument digest; the call key still prevents a second execution. A late result cannot restore forgotten content. Exact arguments of an already running call stay until it settles; the work's runtime transcript and the provider's own session are not rewritten. + +An owner pause keeps a held card: a pause is not a refusal. Send says `Resume to send this.` while paused. Pausing also withdraws an approved call still waiting for its service; recovery while owner-paused settles it as not sent, and its outcome joins unread updates for Resume. An open card expires 48 hours after its row was written, including time while Mousse was closed or the computer slept. The engine's due timer reads `expires_at` directly, keeping the original deadline across restarts without another timer marker. Expiry clears executable arguments and reads "Expired · not sent"; the work carries on, told not to try the same call again without a new reason. Send checks that deadline before accepting the approval. An accepted Send must reach the service within ten minutes of the owner's tap (`APPROVED_SEND_WINDOW_MS`, from `answered_at`), independent of the card's original deadline. The due timer includes that deadline, so restart, sleep or a missing listing cannot leave it waiting indefinitely. Before dispatch the row stays `approved`, with message text `Waiting for …`; execution changes it to `running`, "Sending…". Past the ten minutes it settles `failed`, clears executable arguments, and says ` couldn't be reached, so nothing was sent.` The work gets that outcome once through the ordered update list and may decide to ask again. This timeout is neither a declined nor an expired card: it does not count toward the three-card rule or the identical-call refusal. Once dispatched, a running call settles normally or becomes uncertain after restart. + +Forgetting a still-open or accepted waiting card blocks further calls of that tool in that piece of work until the owner writes or notes the work, including calls with changed arguments. Another tool is unaffected. Forgetting an already settled card only removes its content: it keeps its sent, not-sent, tool-error or uncertain outcome and does not block later calls. This uses a content-free owner-removal marker and owner-input numbers in the tombstoned card metadata; no digest or call content is kept for it. + +After Not now or expiry, the same work cannot post another card for the same tool and argument digest until its owner writes to the chat or adds a note to the work. That refusal writes neither a card nor an action row; a Mousse update in the same ordered list preserves it for the next continuation. It is not an owner note: it neither steers the work as owner words nor starts another turn or report. Its delivery is confirmed on model output or completion, as for settled calls. Changed arguments may get a new review, but after three declined or expired cards for the same tool in the same work since its owner last wrote, further calls are refused until the owner writes or notes the work; the work is told to say what it needs in its report and wait. This uses the wake loop rule’s count and owner-input fact; the sentence says three cards were not sent, without treating expiry as an owner refusal. Any owner row, including a tapped answer to a question, lifts these refusals, as it does for wake loops. Only one call can wait at a time, and all later app tools are refused until it is answered. Send and Not now reset the work's wait chain and its repeated-wait history, as the owner's question answer does; an expiry does not. + +The engine keeps its action-note and action-owner counters in `bot_memory_state` under `cursor:action-note:` and `cursor:action-owner:`. These survive restarts without a database-version change and are deleted in the transaction that ends the work. Pending Mousse refusal updates use `cursor:action-refusal::…`; their ids travel in `workRefusalIds` and they are removed when output or completion confirms delivery. Unconfirmed updates survive an interrupted continuation while work remains resumable (for example running, waiting or paused). They are deleted in the same transaction that makes the work terminal (`done`, `failed` or `cancelled`); startup also removes entries for already ended or missing work. All of this state stays out of the memory export and is removed by the bot's purge. The numeric owner/message facts in a tombstoned card remain for refusal decisions. + +Send refusals use these owner-facing sentences, preserved by the chat service: + +| Code | Sentence | +| --- | --- | +| `bot_action_expired` | This expired, so nothing was sent. | +| `bot_action_withdrawn` | No longer needed, so nothing was sent. | +| `bot_action_changed` | This changed since you saw it. Check it again before sending. | +| `bot_action_settled` | This was already answered. | +| `bot_action_gone` | This can't be sent any more. | +| `bot_action_paused` | `Resume to send this.` | +| `bot_action_unreachable` | ` couldn't be reached, so nothing was sent.` | + Hidden argument values of four to eight characters require an adjacent character outside `[A-Za-z0-9_]` only at an edge whose own character is an ASCII letter, digit or underscore. Other edges require no boundary; longer values are replaced wherever they occur. Values shorter than four characters are left alone. Replacement runs in the server's own text before Mousse frames it, including JSON-escaped string echoes and numeric echoes. Credential masking still applies to the result. Transformed echoes (for example encoded, upper-case or truncated values) are not caught by this exact-value replacement. The stored result is capped at 64 KiB in total; images are omitted with a note, never cut into invalid data. Journal key-name masking applies only to work with a held action; other work keeps master's tool input capture. Send is honoured from any device that may reach the bot, whatever that device's own permission limit, as an Allow of a permission is today (subject to the complete-card size check above). Executable arguments are cleared from the action row with every settled state. The model's own tool call, including its exact arguments, remains in the work's runtime transcript and the provider's session file. Mousse does not rewrite those transcripts; clearing the stored action arguments does not remove those copies. This covers Mousse's MCP calls, not commands, browser actions or actions on the owner's threads. diff --git a/src/mms/bots/actions/BotActions.ts b/src/mms/bots/actions/BotActions.ts index f09f454269..513af2b93f 100644 --- a/src/mms/bots/actions/BotActions.ts +++ b/src/mms/bots/actions/BotActions.ts @@ -1,3 +1,7 @@ +/** Longest an accepted Send may wait before transport dispatch, counted from the owner's tap. */ +export const APPROVED_SEND_WINDOW_MS = 10 * 60_000 +import { MAX_SAME_WAKES } from '../../../shared/bots/personal/wakes' +import { registerHeldCalls } from './lifecycle' import { randomUUID } from 'node:crypto' import type { MousseSettings } from '../../../shared/settings' import type { BotMcpTool } from '../../../shared/bots/personal/authority' @@ -55,7 +59,7 @@ export function removeHiddenArguments(result: ToolOutcome, args: unknown, schema function boundedActionResult(result: BotMcpCallOutcome): BotMcpCallOutcome { const note = result.images?.length ? `\n[${result.images.length} image(s) left out of the stored result.]` : '' const text = String(maskedActionData(result.text, Infinity)) - const build = (end: number): BotMcpCallOutcome => ({ text: `${text.slice(0, end)}${end < text.length ? '\n[Result cut to fit stored size.]' : ''}${note}`, ...(result.isError ? { isError: true } : {}), ...(result.toolReportedError ? { toolReportedError: true } : {}) }) + const build = (end: number): BotMcpCallOutcome => ({ text: `${text.slice(0, end)}${end < text.length ? '\n[Result cut to fit stored size.]' : ''}${note}`, ...(result.isError ? { isError: true } : {}), ...(result.toolReportedError ? { toolReportedError: true } : {}), ...(result.notSentInTime ? { notSentInTime: true } : {}) }) let low = 0, high = Math.min(text.length, 32_000) while (low < high) { const mid = Math.ceil((low + high) / 2) @@ -153,32 +157,111 @@ export interface ActionRow { answered_at: string | null; ran_at: string | null; args_json: string; card_json: string | null; message_id: string; expires_at: string; result_json: string | null } /** Stored outcomes are timed updates, assembled with all other work updates at dispatch. */ -export function actionContinuation(action: Pick): string { +export function actionContinuation(action: Pick & Partial>): string { const result = action.result_json ? JSON.parse(action.result_json) as BotMcpCallOutcome : undefined - const line = action.status === 'done' ? 'Your owner sent it. The tool answered:' + if (JSON.parse(action.card_json ?? '{}').ownerRemoved) return 'Your owner removed this request. Do not ask for it again unless they write.' + const forgotten = result?.text === '[forgotten]' + const card = JSON.parse(action.card_json ?? '{}') + if (result?.notSentInTime) return `${result.text} Nothing left Mousse. Decide whether a new request is needed.` + const line = action.status === 'done' ? forgotten ? 'Your owner sent it.' : 'Your owner sent it. The tool answered:' : action.status === 'declined' ? 'Your owner chose not to send this: carry on without it and say what you skipped.' + : action.status === 'expired' ? 'This call expired. Nothing was sent; do not try the same call again without a new reason.' + : action.status === 'withdrawn' ? 'No longer needed, so nothing was sent.' : action.status === 'uncertain' ? 'It could not be confirmed whether this went through: check before trying again.' - : result?.toolReportedError ? 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:' + : result?.toolReportedError || card.toolReportedError ? 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:' : 'Nothing was sent. The call failed:' + if (forgotten) return `${line} The saved details of this outcome were removed.` return `${line}${['done', 'failed', 'withdrawn', 'expired'].includes(action.status) ? `\n${result?.text ?? 'Carry on without it.'}` : ''}` } interface Host { store: BotStore enabled(): boolean + name(botId: string): string refresh(): Promise park(row: BotActivationRow): void schema(tool: BotMcpTool): unknown binding(row: BotActivationRow, tool: BotMcpTool): unknown | undefined + obsolete(action: ActionRow): boolean post(row: BotActivationRow, id: string, text: string): void settled(row: BotActivationRow): void + publish(messageId: string): void + ownerAnswered(row: BotActivationRow): void + held(): void + forgottenRequest(row: BotActivationRow): void execute(row: BotActivationRow, tool: BotMcpTool, args: Record): Promise } const pending = new Set(['open', 'approved', 'running']) -export class BotActionChanged extends Error { readonly code = 'bot_action_changed' } -const changed = () => new BotActionChanged('This changed since you saw it. Redraw the action.') +export class BotActionChanged extends Error { constructor(message: string, readonly code = 'bot_action_changed') { super(message) } } +const changed = () => new BotActionChanged('This changed since you saw it. Check it again before sending.') export class BotActions { private readonly executing = new Set() - constructor(private readonly host: Host) {} + constructor(private readonly host: Host) { + registerHeldCalls(host.store.db, { + endWork: id => this.withdrawWork(id), + grantChanged: botId => this.withdrawChanged(botId), + forgetMessage: (botId, messageId) => { + const ids = host.store.all(`SELECT a.* FROM bot_actions a JOIN bot_activations w ON w.id = a.activation_id + WHERE a.bot_id = ? AND (a.message_id = ? OR json_extract(w.trigger_json, '$.replyTo') = ?)`, botId, messageId, messageId) + for (const action of ids) { + const pending = ['open', 'approved'].includes(String(action.status)) + if (pending) this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'The request was forgotten. Nothing was sent.' }) + this.forgetText(botId, String(action.id)) + if (pending && action.message_id === messageId) this.host.store.run(`UPDATE bot_actions SET card_json = json_set(card_json, + '$.ownerRemoved', json('true'), '$.removedOwnerSeq', ?, '$.removedNoteSeq', ?) WHERE id = ?`, + host.store.ownerLastWroteSeq(botId), Number(host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-note:${action.activation_id}`)?.value ?? 0), String(action.id)) + if (!pending) continue + const row = host.store.activation(String(action.activation_id)) + if (row && row.trigger.kind === 'work' && row.trigger.replyTo === messageId) host.forgottenRequest(row) + else host.store.db.afterCommit(() => this.finish(action as unknown as ActionRow)) + } + } + }) + } + /** Erase call content without erasing owner intervention facts or the run-once key. */ + forgetText(botId: string, actionId?: string): void { + this.host.store.run(`UPDATE bot_actions SET args_json = ?, args_digest = '[forgotten]', + card_json = json_object('text', '[forgotten]', 'ownerSeq', COALESCE(json_extract(card_json, '$.ownerSeq'), 0), 'noteSeq', COALESCE(json_extract(card_json, '$.noteSeq'), 0), + 'toolReportedError', COALESCE(json_extract(result_json, '$.toolReportedError'), json_extract(card_json, '$.toolReportedError')), + 'ownerRemoved', json_extract(card_json, '$.ownerRemoved'), 'removedOwnerSeq', json_extract(card_json, '$.removedOwnerSeq'), 'removedNoteSeq', json_extract(card_json, '$.removedNoteSeq')), + bot_note = ?, result_json = ? WHERE bot_id = ? AND (? IS NULL OR id = ?)`, + '"[forgotten]"', '[forgotten]', '{"text":"[forgotten]"}', botId, actionId ?? null, actionId ?? null) + } + withdrawWork(id: string): void { + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND status IN ('open', 'approved')", id)) + this.transition(String(action.id), String(action.status), 'withdrawn', { text: 'This work ended. Nothing was sent.' }) + } + withdrawPaused(botId: string): void { + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE bot_id = ? AND status = 'approved'", botId)) { + if (this.transition(String(action.id), 'approved', 'withdrawn', { text: 'This bot was paused by its owner. Nothing was sent; carry on without it when resumed.' })) + this.host.store.db.afterCommit(() => this.finish(action as unknown as ActionRow)) + } + } + private approvedDeadline(action: Pick): number { + return action.answered_at ? Date.parse(action.answered_at) + APPROVED_SEND_WINDOW_MS : 0 + } + nextDueAt(botId?: string): number | undefined { + const times = (this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null) as unknown as ActionRow[]) + .map(action => action.status === 'approved' ? this.approvedDeadline(action) : Date.parse(action.expires_at)) + return times.length ? Math.min(...times) : undefined + } + private sendTimeout(action: ActionRow): boolean { + const service = JSON.parse(action.card_json ?? '{}').serverName ?? 'The service' + const moved = this.transition(action.id, action.status, 'failed', { isError: true, notSentInTime: true, text: `${service} couldn't be reached, so nothing was sent.` }) + if (moved) this.finish(action) + return moved + } + expireDue(): void { + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'open' AND expires_at <= ?", this.host.store.now())) { + if (this.transition(String(a.id), String(a.status), 'expired', { text: 'This call expired. Carry on without it; do not try the same call again without a new reason.' })) this.finish(a as unknown as ActionRow) + } + for (const action of this.host.store.all("SELECT * FROM bot_actions WHERE status = 'approved'") as unknown as ActionRow[]) + if (this.approvedDeadline(action) <= Date.parse(this.host.store.now())) this.sendTimeout(action) + } + withdrawChanged(botId?: string): void { + for (const a of this.host.store.all("SELECT * FROM bot_actions WHERE status IN ('open', 'approved') AND (? IS NULL OR bot_id = ?)", botId ?? null, botId ?? null)) { + if (this.host.obsolete(a as unknown as ActionRow) && this.transition(String(a.id), String(a.status), 'withdrawn', { text: 'This tool or its permission changed. Carry on without it.' })) this.host.store.db.afterCommit(() => this.finish(a as unknown as ActionRow)) + } + } get(id: string): ActionRow | undefined { return this.host.store.get('SELECT * FROM bot_actions WHERE id = ?', id) as unknown as ActionRow | undefined } forWork(id: string): ActionRow | undefined { return this.host.store.get("SELECT * FROM bot_actions WHERE activation_id = ? ORDER BY rowid DESC LIMIT 1", id) as unknown as ActionRow | undefined @@ -190,11 +273,32 @@ export class BotActions { const dispatch = this.host.store.dispatches(activationId).find(d => d.clientRequestId === dispatchId) return dispatch && (dispatch.n === mainN || dispatch.mainN === mainN) ? action : undefined } + private ownerWroteAfter(action: ActionRow, removed = false): boolean { + const card = JSON.parse(action.card_json ?? '{}') + const note = Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', action.bot_id, `cursor:action-note:${action.activation_id}`)?.value ?? 0) + return this.host.store.ownerLastWroteSeq(action.bot_id) > Number((removed ? card.removedOwnerSeq : card.ownerSeq) ?? 0) || note > Number((removed ? card.removedNoteSeq : card.noteSeq) ?? 0) + } + private refuse(row: BotActivationRow, action: ActionRow, text: string): ToolOutcome { + this.host.store.recordWorkRefusal(row.id, row.botId, `${action.id}:${text.startsWith('Your owner declined') ? 'repeat' : 'loop'}`, text) + return { text, isError: true } + } hold(row: BotActivationRow, dispatch: string, tool: BotMcpTool, args: Record, toolCallId?: string): ToolOutcome { + if (!this.host.enabled()) return { text: 'Asks first is off.', isError: true } if (!toolCallId) return { text: 'This call cannot be held without its call id. Carry on without it.', isError: true } const callKey = JSON.stringify([row.id, dispatch, toolCallId]) const existing = this.host.store.get('SELECT id FROM bot_actions WHERE call_key = ?', callKey) if (existing) return { text: 'This call is held for your owner. End your turn now.' } + if (pending.has(this.forWork(row.id)?.status ?? '')) return { text: 'A call is already held for your owner. End your turn now.', isError: true } + const removed = (this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND json_extract(card_json, '$.ownerRemoved') = 1 ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[]).find(action => !this.ownerWroteAfter(action, true)) + if (removed) return this.refuse(row, removed, 'Your owner removed this request. Do not ask for it again unless they write.') + const declined = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool })) as unknown as ActionRow[] + const unanswered = declined.filter(action => !this.ownerWroteAfter(action)) + if (unanswered.length >= MAX_SAME_WAKES) + return this.refuse(row, unanswered[0], 'You had three cards for this tool that were not sent. Say what you need in your report and wait for your owner to write.') + const digest = actionDigest(args) + const refused = this.host.store.all("SELECT * FROM bot_actions WHERE activation_id = ? AND target_json = ? AND args_digest = ? AND status IN ('declined', 'expired') ORDER BY rowid DESC", row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), digest)[0] + if (refused && !this.ownerWroteAfter(refused as unknown as ActionRow)) + return this.refuse(row, refused as unknown as ActionRow, 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.') const binding = this.host.binding(row, tool) if (!binding) return { text: 'This tool changed. Carry on without it.', isError: true } if (containsCredential(args)) return { text: 'This contains something that looks like a secret. It is never sent through a tool this way. Send it without that value.', isError: true } @@ -208,26 +312,40 @@ export class BotActions { this.host.store.run(`INSERT INTO bot_actions(id, call_key, bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, card_json, status, message_id, expires_at, created_at) VALUES(?, ?, ?, ?, 'run', 'mcp', ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?)`, - id, callKey, row.botId, row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), exact, JSON.stringify(review.args), actionDigest(JSON.parse(exact)), JSON.stringify(binding), JSON.stringify({ hasHiddenValues: review.hasHiddenValues }), messageId, + id, callKey, row.botId, row.id, JSON.stringify({ server: tool.server, tool: tool.tool }), exact, JSON.stringify(review.args), actionDigest(JSON.parse(exact)), JSON.stringify(binding), JSON.stringify({ hasHiddenValues: review.hasHiddenValues, serverName: tool.serverName }), messageId, new Date(Date.parse(this.host.store.now()) + 48 * 3600_000).toISOString(), this.host.store.now()) this.host.park(row) this.host.post(row, messageId, `${tool.serverName} · ${tool.tool}\n${review.hasHiddenValues ? 'Hidden values will be sent.\n' : ''}${JSON.stringify(review.args)}`) }) + this.host.held() return { text: 'This call is held for your owner. End your turn now.' } } /** The only status writer. Settlement clears executable arguments in the same statement. */ transition(id: string, from: string, to: string, result?: BotMcpCallOutcome): boolean { return this.host.store.db.transaction(() => { const moved = this.host.store.run(`UPDATE bot_actions SET status = ?, exec_args = CASE WHEN ? THEN exec_args ELSE NULL END, - result_json = ?, answered_at = CASE WHEN ? = 'open' THEN ? ELSE answered_at END, + result_json = CASE WHEN args_json = '"[forgotten]"' THEN '{"text":"[forgotten]"}' ELSE ? END, answered_at = CASE WHEN ? = 'open' THEN ? ELSE answered_at END, ran_at = CASE WHEN ? IN ('running', 'done') THEN ? ELSE ran_at END WHERE id = ? AND status = ?`, to, pending.has(to) ? 1 : 0, result ? JSON.stringify(boundedActionResult(result)) : null, from, this.host.store.now(), to, this.host.store.now(), id, from) > 0 + if (moved && result?.notSentInTime) this.host.store.run("UPDATE bot_actions SET card_json = json_set(card_json, '$.settledAt', ?) WHERE id = ?", this.host.store.now(), id) + if (moved && ['approved', 'running'].includes(to)) { + const action = this.get(id)! + const service = JSON.parse(action.card_json ?? '{}').serverName ?? 'the service' + this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'approved' ? `Waiting for ${service}…` : 'Sending…', action.message_id) + this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) + } + if (moved && ['declined', 'expired'].includes(to)) { + const action = this.get(id)! + this.host.store.run(`UPDATE bot_actions SET card_json = json_set(COALESCE(card_json, '{}'), '$.ownerSeq', ?, '$.noteSeq', ?) WHERE id = ?`, + this.host.store.ownerLastWroteSeq(action.bot_id), Number(this.host.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', action.bot_id, `cursor:action-note:${action.activation_id}`)?.value ?? 0), id) + } if (moved && !pending.has(to)) { const action = this.get(id)! const row = this.host.store.activation(action.activation_id) - this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) + if (action.args_json !== '"[forgotten]"') this.host.store.run('UPDATE bot_messages SET text = ? WHERE id = ?', result?.notSentInTime ? result.text : to === 'expired' ? 'Expired · not sent' : to === 'done' ? 'Sent' : to === 'uncertain' ? "Couldn't tell if it went through" : result?.toolReportedError ? 'The tool reported an error' : 'Not sent', action.message_id) if (row?.endReason === 'approval') this.host.store.moveActivation(row.id, ['blocked'], 'blocked', { endReason: 'approval_answered' }) + this.host.store.db.afterCommit(() => this.host.publish(action.message_id)) } return moved }) @@ -235,13 +353,13 @@ export class BotActions { private valid(action: ActionRow): BotActivationRow | undefined { const row = this.host.store.activation(action.activation_id) - if (!row || !action.exec_args || action.exec_args.length > ACTION_MAX_ARGUMENT_CHARS || Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) return undefined + if (!row || !action.exec_args || action.exec_args.length > ACTION_MAX_ARGUMENT_CHARS || (action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now()))) return undefined try { const args: unknown = JSON.parse(action.exec_args) if (containsCredential(args) || actionDigest(args) !== action.args_digest) return undefined const review = reviewArguments(args, this.host.schema(JSON.parse(action.target_json))) - if (canonicalJson(JSON.parse(action.args_json)) !== canonicalJson(review.args) - || Boolean(JSON.parse(action.card_json ?? '{}').hasHiddenValues) !== review.hasHiddenValues) return undefined + if (action.args_json !== '"[forgotten]"' && (canonicalJson(JSON.parse(action.args_json)) !== canonicalJson(review.args) + || Boolean(JSON.parse(action.card_json ?? '{}').hasHiddenValues) !== review.hasHiddenValues)) return undefined const binding = this.host.binding(row, JSON.parse(action.target_json)) return binding && canonicalJson(binding) === canonicalJson(JSON.parse(action.binding_json)) ? row : undefined } catch { return undefined } @@ -249,28 +367,58 @@ export class BotActions { assertRunning(id: string): void { const action = this.get(id) + if (action?.status === 'running' && this.approvedDeadline(action) <= Date.parse(this.host.store.now())) { + this.sendTimeout(action) + throw new BotActionChanged(JSON.parse(this.get(id)!.result_json!).text, 'bot_action_unreachable') + } if (!action || action.status !== 'running' || !this.valid(action)) throw changed() } async answer(input: { actionId: string; digest: string; answer: 'send' | 'not_now' }): Promise<{ status: string }> { - if (!this.host.enabled()) throw new BotActionChanged('Asks first is not available while its switch is off.') - await this.host.refresh() const action = this.get(input.actionId) + if (!action) throw new BotActionChanged("This can't be sent any more.", 'bot_action_gone') + if (action.result_json && JSON.parse(action.result_json).notSentInTime) throw new BotActionChanged(JSON.parse(action.result_json).text, 'bot_action_unreachable') + if (action.status === 'expired') throw new BotActionChanged('This expired, so nothing was sent.', 'bot_action_expired') + if (action.status === 'withdrawn') throw new BotActionChanged('No longer needed, so nothing was sent.', 'bot_action_withdrawn') + if (action.status !== 'open') throw new BotActionChanged('This was already answered.', 'bot_action_settled') + if (action && action.status === 'open' && Date.parse(action.expires_at) <= Date.parse(this.host.store.now())) { + this.expireDue() + throw new BotActionChanged('This expired, so nothing was sent.', 'bot_action_expired') + } + if (action && input.answer === 'send' && this.host.store.registry(action.bot_id)?.pausedReason === 'owner') throw new BotActionChanged(`Resume ${this.host.name(action.bot_id)} to send this.`, 'bot_action_paused') if (!action || action.status !== 'open' || action.args_digest !== input.digest || !this.valid(action)) throw changed() if (input.answer === 'not_now') { - if (!this.transition(action.id, 'open', 'declined', { text: 'Your owner chose not to send this: carry on without it and say what you skipped.' })) throw changed() + this.host.store.db.transaction(() => { + if (!this.transition(action.id, 'open', 'declined', { text: 'Your owner chose not to send this: carry on without it and say what you skipped.' })) throw changed() + this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) + }) this.finish(action) return { status: 'declined' } } - if (!this.transition(action.id, 'open', 'approved')) throw changed() - await this.runApproved(action.id) + this.host.store.db.transaction(() => { + if (!this.transition(action.id, 'open', 'approved')) throw changed() + this.host.ownerAnswered(this.host.store.activation(action.activation_id)!) + }) + this.host.held() + await this.runApproved(action.id, true) return { status: this.get(action.id)!.status } } - private async runApproved(id: string): Promise { + private async runApproved(id: string, refresh = false): Promise { + if (refresh) await this.host.refresh() const action = this.get(id) if (!action || action.status !== 'approved') return + if (this.approvedDeadline(action) <= Date.parse(this.host.store.now())) { this.sendTimeout(action); return } + if (this.host.store.registry(action.bot_id)?.pausedReason === 'owner') { + this.transition(id, 'approved', 'withdrawn', { text: 'This bot was paused by its owner. Nothing was sent; carry on without it when resumed.' }) + this.finish(action) + return + } const row = this.valid(action) if (!row) { - this.transition(id, 'approved', Date.parse(action.expires_at) <= Date.parse(this.host.store.now()) ? 'expired' : 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) + const current = this.host.store.activation(action.activation_id) + let intact = false + try { intact = Boolean(action.exec_args && action.exec_args.length <= ACTION_MAX_ARGUMENT_CHARS && !containsCredential(JSON.parse(action.exec_args)) && actionDigest(JSON.parse(action.exec_args)) === action.args_digest) } catch { /* Corrupt arguments are never recoverable. */ } + if (intact && current && !this.host.binding(current, JSON.parse(action.target_json)) && !this.host.obsolete(action)) return + this.transition(id, 'approved', 'withdrawn', { text: 'This changed since you saw it. Nothing was sent; carry on without it.' }) this.finish(action) return } @@ -293,10 +441,18 @@ export class BotActions { if (!row) return this.host.settled(row) } + async retryApproved(): Promise { + for (const action of this.host.store.all("SELECT id FROM bot_actions WHERE status = 'approved'")) + await this.runApproved(String(action.id)) + } async reconcile(): Promise { - if (!this.host.enabled()) return + this.host.store.pruneWorkRefusals() + this.withdrawChanged() + this.expireDue() const interrupted = this.host.store.all("SELECT id FROM bot_actions WHERE status IN ('running', 'approved')") await this.host.refresh() + this.withdrawChanged() + if (this.host.store.get("SELECT 1 FROM bot_actions WHERE status IN ('open', 'approved') LIMIT 1")) this.host.held() for (const a of interrupted) { const action = this.get(String(a.id)) if (!action || this.executing.has(action.id)) continue diff --git a/src/mms/bots/actions/lifecycle.ts b/src/mms/bots/actions/lifecycle.ts new file mode 100644 index 0000000000..70e948fc45 --- /dev/null +++ b/src/mms/bots/actions/lifecycle.ts @@ -0,0 +1,11 @@ +import type { BotStoreTx } from '../store/BotStore' + +/** Per open database: existing held rows settle even when new holds are disabled. */ +export interface HeldCallLifecycle { + endWork(id: string): void + grantChanged(botId: string): void + forgetMessage(botId: string, messageId: string): void +} +const lifecycles = new WeakMap() +export function registerHeldCalls(db: BotStoreTx, lifecycle: HeldCallLifecycle): void { lifecycles.set(db, lifecycle) } +export function heldCalls(db: BotStoreTx): HeldCallLifecycle | undefined { return lifecycles.get(db) } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index daafea6e51..a1fb4201a9 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -1,5 +1,5 @@ import { WORK_WAIT_RULES, workWaitInput, workWaitRule, workReadiness, workWaitLine, parkedNeedsOwner, type WorkWaitLookups, type WorkWaitFacts, type WorkWaitReason } from './workWaiting' -import { BotActions, BotActionChanged, actionContinuation, removeHiddenArguments, botAsksFirst, actionDigest, maskedActionData } from '../actions/BotActions' +import { BotActions, BotActionChanged, actionContinuation, removeHiddenArguments, botAsksFirst, maskedActionData } from '../actions/BotActions' import { callForBot, type BotMcp } from '../mcp/BotMcp' import { isQuietHours } from '../../../shared/settings' import { BotTellings } from '../chat/BotTellings' @@ -601,22 +601,57 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { readonly chat: BotChatProjection /** The Bot UI's methods (`bots.*` v2). */ readonly actions: BotActions + /** A held call is authorized only for its own pair, independent of unrelated grant revisions. */ + private actionPair(row: BotActivationRow, tool: BotMcpTool): BotManifest['mcp'][number] | undefined { + const current = this.store.activation(row.id) + const grant = this.store.activeGrant(row.botId) + const definition = current && this.host.definitions.revision(row.botId, current.revision) + if (!current || !['running', 'blocked'].includes(current.status) || !grant || !definition) return undefined + const offered = this.effectiveManifest(current, definition.permissions, grant.manifest).mcp.some(p => p.serverId === tool.server && p.tool === tool.tool) + return offered ? grant.manifest.mcp.find(p => p.serverId === tool.server && p.tool === tool.tool) : undefined + } private createActions(): BotActions { return new BotActions({ store: this.host.store, refresh: async () => { await this.host.mcp?.warm() }, park: (row) => { if (!this.park(row, 'approval')) throw new Error('work ended') }, + name: botId => this.definitionOf(botId).name, enabled: () => botAsksFirst(this.host.settings?.get()), + publish: id => { this.chat.republish(id) }, + ownerAnswered: row => { + this.resetWorkWaitChain(row.id) + const last = this.store.get('SELECT MAX(rowid) AS n FROM bot_reminders WHERE work_id = ?', row.id) + this.store.db.statement(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?) ON CONFLICT(bot_id, key) DO UPDATE SET value = excluded.value`).run(row.botId, `cursor:action-owner:${row.id}`, String(last?.n ?? 0)) + }, + held: () => { this.watchMcp(); this.armDue() }, + forgottenRequest: row => { + const ended = this.endWaitingInTx(row, 'request_gone', 'This work ended because its request was forgotten.') + if (ended) this.store.db.afterCommit(() => this.afterEnd(ended)) + }, schema: (tool) => this.host.mcp?.inputSchema?.(tool), binding: (row, tool) => { - const grant = this.store.activeGrant(row.botId) - const current = this.store.activation(row.id) - if (!grant || !current || !['running', 'blocked'].includes(current.status) || current.grantDigest !== grant.digest || !this.grantNow(row.id)?.mcp.some(p => p.serverId === tool.server && p.tool === tool.tool)) return undefined + const pair = this.actionPair(row, tool) + if (!pair) return undefined const server = this.host.mcp?.binding?.(tool) if (!server) return undefined const source = row.trigger.kind === 'work' ? this.store.activation(row.trigger.from) : row const limit = source?.trigger.kind === 'manual' ? source.trigger.owner?.limit ?? null : null - const revision = this.store.get('SELECT grant_id FROM bot_grants WHERE bot_id = ? AND revoked_at IS NULL ORDER BY grant_id DESC LIMIT 1', row.botId)?.grant_id - return { ...server, grantRevision: revision, grantDigest: actionDigest(grant.manifest), deviceLimit: limit } + return { ...server, pairLevel: pair.level ?? 'allowed', deviceLimit: limit } + }, + obsolete: action => { + const row = this.store.activation(action.activation_id) + const held = JSON.parse(action.binding_json) + const tool = JSON.parse(action.target_json) as BotMcpTool + const pair = row && this.actionPair(row, tool) + if (!pair || held.pairLevel !== (pair.level ?? 'allowed')) return true + const where = this.host.mcp?.where?.(tool.server) + if (!where) return false // A cold catalogue is not evidence of removal. + if (where.state !== 'on') return true + const config = this.host.mcp?.configurationDigest?.(tool.server) + if (config && config !== held.configDigest) return true + if (where.server.failing || where.server.starting) return false + if (!where.server.tools.some(t => t.tool === tool.tool)) return true + const binding = this.host.mcp?.binding?.(tool) + return Boolean(binding && (binding.configDigest !== held.configDigest || binding.schemaDigest !== held.schemaDigest)) }, post: (row, id, text) => this.chat.post({ id, botId: row.botId, author: 'bot', kind: 'notice', text, external: true, activationId: row.id, lane: 'run', ...(row.trigger.kind === 'work' && row.trigger.replyTo ? { replyTo: row.trigger.replyTo } : {}) }), settled: (row) => { this.chat.republish(this.actions.forWork(row.id)!.message_id); this.changed({ botId: row.botId }); this.pumpLater(row.botId) }, @@ -628,7 +663,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const actionId = this.actions.forWork(row.id)!.id return callForBot({ mcp: mcp as BotMcp, bot: { activationId: row.id, mcpTools: [tool], workspace: null, time: { signal, deadline: () => Number.MAX_SAFE_INTEGER }, - check: () => this.grantNow(row.id)?.mcp.some(p => p.serverId === target.server && p.tool === target.tool) ? { ok: true } : { ok: false, wall: { kind: 'revoked' } } + check: () => this.actionPair(row, target) ? { ok: true } : { ok: false, wall: { kind: 'revoked' } } }, name: tool.name, args, signal, heldAction: true, sanitizeResult: (result) => removeHiddenArguments(result, args, mcp.inputSchema?.(target)), assertDispatchActive: () => { this.actions.assertRunning(actionId) } }) @@ -2222,14 +2257,14 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } private approvalPending(id: string): boolean { - return botAsksFirst(this.host.settings?.get()) && ['open', 'approved', 'running'].includes(this.actions.forWork(id)?.status ?? '') + return ['open', 'approved', 'running'].includes(this.actions.forWork(id)?.status ?? '') } private readonly workWaitLookups: WorkWaitLookups = { store: () => this.store } private readonly workWaitFacts: WorkWaitFacts = { approvalReady: (row) => this.store.lastMainDispatch(row.id)?.endedAt !== null && !this.live.has(row.id), - approvalExists: (row) => Boolean(this.actions.forWork(row.id)), + approvalExists: (row) => { const action = this.actions.forWork(row.id); return Boolean(action && (row.endReason === 'approval_answered' || ['open', 'approved', 'running'].includes(action.status))) }, timerExists: (row) => { const wait = this.store.workWait(row.id); return Boolean(wait && wait.status !== 'cancelled') }, usageResumable: (row) => this.usageResumable(row), questionExists: (row) => Boolean(this.store.workQuestion(row.id)), @@ -3116,6 +3151,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { fillMcpAsks(): void { const mcp = this.host.mcp if (!mcp || this.closed) return + this.actions.withdrawChanged() + void this.actions.retryApproved().catch(error => console.warn('held calls could not be checked after a tool listing', error)) const waiting = this.store.escalations({ status: 'open' }).filter((row) => waitsForTools(row.permission)) if (!waiting.length) return let servers: BotMcpServer[] @@ -4807,7 +4844,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } else if (openWalls.length) { // The chat turn asked (`escalate`): it waits for the owner with every card on its message. this.store.moveActivation(row.id, ['running'], 'waiting_grant', { endReason: 'wall', ...(text !== undefined ? { result: text } : {}) }) - } else if (botAsksFirst(this.host.settings?.get()) && this.actions.pendingInTurn(row.id, main.n) && this.askedIn.get(row.id) === main.n) { + } else if (this.actions.pendingInTurn(row.id, main.n) && this.askedIn.get(row.id) === main.n) { if (!this.park(row, 'approval', ['running'], this.approvalPending(row.id) ? 'approval' : 'approval_answered')) return undefined } else if (this.store.workWait(row.id)?.status === 'waiting') { if (!this.park(row, 'waiting', ['running'])) return undefined @@ -5295,6 +5332,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } const waits = current.trigger.kind === 'work' ? this.store.unreadWorkWaits(current.id) : [] const actions = current.trigger.kind === 'work' ? this.store.unreadWorkActions(current.id) : [] + const refusals = this.workRefusalUpdates(current.id) const actionCaused = current.endReason === 'approval_answered' ? actions.at(-1) : undefined const waited = waits.length > 0 const n = this.store.nextDispatchN(row.id) @@ -5310,7 +5348,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { const deliveryQuestion = input.usageRetry ? undefined : durableWork ? this.store.unreadWorkQuestion(current.id) : question const answered = deliveryQuestion?.status === 'answered' || deliveryQuestion?.status === 'defaulted' ? this.workAnswerOf(deliveryQuestion) : undefined const workEvents: WorkContinuationEvent[] | undefined = durableWork ? [ - ...actions.map(action => ({ at: (action.status === 'declined' ? action.answered_at : action.ran_at) ?? action.answered_at ?? current.createdAt, text: actionContinuation(action), actionId: action.id })), + ...refusals, + ...actions.map(action => ({ at: JSON.parse(action.card_json ?? '{}').settledAt ?? (action.status === 'declined' ? action.answered_at : action.ran_at) ?? action.answered_at ?? current.createdAt, text: actionContinuation(action), actionId: action.id })), ...waits.map(wait => ({ at: wait.dueAt, text: workWaitInput(wait, clockTime) })), ...answers.map(answer => ({ at: answer.answeredAt ?? answer.createdAt, answer })), ...(notes?.events ?? []), @@ -5320,10 +5359,12 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if (answered) this.store.markAnswerSent(deliveryQuestion!.id, n, answered, !readAtStart) // A usage retry repeats the previous text, so only its carried ids may be confirmed by that retry. const delivery = input.usageRetry && previous ? { + ...(previous.prompt.workRefusalIds ? { workRefusalIds: previous.prompt.workRefusalIds } : {}), ...(previous.prompt.workActionIds ? { workActionIds: previous.prompt.workActionIds } : {}), ...(previous.prompt.workWaitIds ? { workWaitIds: previous.prompt.workWaitIds } : {}), ...(previous.prompt.workDelivery ? { workDelivery: previous.prompt.workDelivery } : {}) } : { + ...(refusals.length ? { workRefusalIds: refusals.map(event => event.id) } : {}), ...(actions.length ? { workActionIds: actions.map(action => action.id) } : {}), ...(waits.length ? { workWaitIds: waits.map(wait => wait.id) } : {}), ...(durableWork ? { workDelivery: { answers: answers.map(answer => answer.id), notes: notes?.ids ?? [], ...(answered ? { question: deliveryQuestion!.id } : {}) } } : {}) @@ -6394,6 +6435,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } /** Confirmation is advisory: a failed write means repeat the update, never fail the runtime's turn. */ + private workRefusalUpdates(workId: string) { return this.store.unreadWorkRefusals(workId) } + private confirmWorkDelivery(activationId: string, n: number, why: 'output' | 'completed'): void { try { this.store.confirmWorkDelivery(activationId, n, why) } catch (error) { @@ -7309,7 +7352,10 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { /** `bots.personal.pause`: the owner pauses the bot's schedules. Chat still works. */ pauseBot(botId: string): void { this.entry(botId) - this.store.setPaused(botId, 'owner') + this.store.db.transaction(() => { + this.store.setPaused(botId, 'owner') + this.actions.withdrawPaused(botId) + }) // A paused bot runs nothing in the background either. this.stopWatchersOf(botId) this.changed({ botId }) @@ -7423,6 +7469,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { await this.endAll([...this.store.laneActivations(botId, 'chat', [...NOT_ENDED]), ...waiting], 'stopped', () => { this.store.withdrawAsks(botId) this.store.withdrawQuestions(botId) + this.store.run("DELETE FROM bot_messages WHERE bot_id = ? AND id IN (SELECT message_id FROM bot_actions WHERE bot_id = ?)", botId, botId) }) // Deleted once the turns stopped, so a turn ending meanwhile adds no row to the cleared chat. this.store.deleteMessages(botId) @@ -7449,7 +7496,11 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } // The chat turn is stopped first, so it copies nothing more into the history once it is gone. await this.clearChat(botId) - const removed = memory.wipeHistory(botId) + const removed = this.store.db.transaction(() => { + const removed = memory.wipeHistory(botId) + this.actions.forgetText(botId) + return removed + }) this.changed({ botId }) return removed } @@ -7969,6 +8020,8 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { // The note keeps the owner's message it came from (the chat turn's), so a forget of that message reaches it. if (from && this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)) this.resetWorkWaitChain(workId) this.store.addWorkNote(workId, botId, text, from ? this.ownerMessageOf(from) : undefined) + if ((botAsksFirst(this.host.settings?.get()) || this.actions.forWork(workId)) && (!from || (this.store.activation(from) && ownerChatTurn(this.store.activation(from)!)))) + this.store.run(`INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, '1') ON CONFLICT(bot_id, key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`, botId, `cursor:action-note:${workId}`) return 'noted' as const }) } @@ -8155,7 +8208,9 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private refuseWakeLoop(botId: string, brief: string, event: BotWakeEvent | null, workId?: string): void { const key = wakeLoopKey(brief, event) - const same = this.store.wakesSetSince(botId, this.store.ownerLastWroteAt(botId), workId).filter((wake) => wakeLoopKey(wake.text, wake.event) === key).length + const after = workId ? Number(this.store.get('SELECT value FROM bot_memory_state WHERE bot_id = ? AND key = ?', botId, `cursor:action-owner:${workId}`)?.value ?? 0) : 0 + const same = after ? this.store.all('SELECT text, event_json FROM bot_reminders WHERE bot_id = ? AND work_id = ? AND rowid > ? AND created_at >= ?', botId, workId!, after, this.store.ownerLastWroteAt(botId)).filter(wake => wakeLoopKey(String(wake.text), wake.event_json ? JSON.parse(String(wake.event_json)) : null) === key).length + : this.store.wakesSetSince(botId, this.store.ownerLastWroteAt(botId), workId).filter((wake) => wakeLoopKey(wake.text, wake.event) === key).length if (same >= MAX_SAME_WAKES) throw new BotEngineError('wake_loop', `You have set this same wake-up ${same} times since your owner last wrote, with nothing new in it: that is a loop. Don't set it again: tell your owner where things stand and what you are waiting on, and carry on when they write. If something did change, say what in the brief.`) } @@ -8599,6 +8654,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { */ private dueAt(botId?: string, forTimer = false): number | undefined { const sources: Array<() => number | undefined> = [ + () => this.actions.nextDueAt(botId), () => this.tellings.next(botId), () => { const row = this.store.nextReminder(botId) @@ -8663,6 +8719,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { // Never synchronous: the pass is held below before any of it runs, so its end always lets go of it. await Promise.resolve() try { + this.actions.expireDue() // Reminders cancelled, forgotten or purged since they failed are no longer tried. for (const id of this.reminderRetryAt.keys()) if (this.store.reminder(id)?.status !== 'waiting') this.reminderRetryAt.delete(id) for (const reminder of this.store.dueReminders(now.toISOString())) { diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index a51b0f3be5..7182cb799e 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -410,7 +410,7 @@ export class BotChatService { const action = this.engine.actions.get(input.actionId) if (input.botId && action?.bot_id !== input.botId) throw new BotEngineError('not_found', 'No held action here.') try { return await this.engine.actions.answer(input) } catch (error) { - if (error instanceof BotActionChanged) throw new BotEngineError('bot_action_changed', error.message) + if (error instanceof BotActionChanged) throw new BotEngineError(error.code, error.message) throw error } } diff --git a/src/mms/bots/mcp/BotMcp.ts b/src/mms/bots/mcp/BotMcp.ts index f9eb8d772b..b8113217d8 100644 --- a/src/mms/bots/mcp/BotMcp.ts +++ b/src/mms/bots/mcp/BotMcp.ts @@ -100,6 +100,8 @@ export interface BotMcpHost { /** Whether the servers were read since Mousse started: before that, `servers()` says nothing of a server being gone. */ listed?(): boolean inputSchema?(tool: BotMcpTool): unknown + /** Configuration evidence remains available when a server has no successful tool listing. */ + configurationDigest?(serverId: string): string | undefined binding?(tool: BotMcpTool): { serverId: string; tool: string; configDigest: string; schemaDigest: string } | undefined call?: BotMcp['call'] /** The granted tools (`::`) of servers set up now. */ @@ -223,7 +225,7 @@ export function failureText(serverName: string, error: unknown, signal?: AbortSi return `${serverName} couldn't run this call. ${carryOn}` } -export type BotMcpCallOutcome = ToolOutcome & { callState?: 'failed' | 'uncertain'; toolReportedError?: true } +export type BotMcpCallOutcome = ToolOutcome & { callState?: 'failed' | 'uncertain'; toolReportedError?: true; notSentInTime?: true } export class BotMcp implements BotMcpHost { constructor(private readonly deps: BotMcpDeps) {} @@ -292,6 +294,10 @@ export class BotMcp implements BotMcpHost { return this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(tool.server))?.tools.find(t => t.toolName === tool.tool)?.inputSchema } + configurationDigest(serverId: string): string | undefined { + return (this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(serverId)) as { configDigest?: string } | undefined)?.configDigest + } + binding(tool: BotMcpTool): { serverId: string; tool: string; configDigest: string; schemaDigest: string } | undefined { if (!this.deps.enabled()) return undefined const server = this.deps.catalog.servers(undefined).find(s => s.installationId === installationOf(tool.server)) diff --git a/src/mms/bots/memory/BotMemoryStore.ts b/src/mms/bots/memory/BotMemoryStore.ts index 926828bf90..e8279ce50f 100644 --- a/src/mms/bots/memory/BotMemoryStore.ts +++ b/src/mms/bots/memory/BotMemoryStore.ts @@ -1,3 +1,4 @@ +import { heldCalls } from '../actions/lifecycle' import { requestJournalRows } from './requestFrames' import { createHash } from 'node:crypto' import type { ProfileDatabase } from '../../run/db/ProfileDatabase' @@ -1345,6 +1346,7 @@ function redactQuestionCopies(tx: BotStoreTx, has: (table: string) => boolean, b } function defaultRedactMessage(tx: BotStoreTx, botId: string, messageId: string, text: string): void { + heldCalls(tx)?.forgetMessage(botId, messageId) const has = (table: string) => Boolean(tx.statement("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table)) if (!has('bot_messages')) return tx.statement('UPDATE bot_messages SET text = ? WHERE id = ? AND bot_id = ?').run(text, messageId, botId) diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index 4c551088d0..abf6340c02 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1,3 +1,4 @@ +import { heldCalls } from '../actions/lifecycle' import type { ActionRow } from '../actions/BotActions' import { readdirSync, rmSync } from 'node:fs' import { join } from 'node:path' @@ -795,6 +796,7 @@ export interface BotDispatchRow { workTold?: 'pending' | 'output' | 'completed' workWaitIds?: string[] workActionIds?: string[] + workRefusalIds?: string[] /** Carried ids for replay; existing read/applied markers remain independent of confirmation. */ workDelivery?: { answers: string[]; notes: number[]; question?: string } } @@ -889,7 +891,7 @@ export interface BotCountersRow { const WORK_TOLD = "(COALESCE(json_extract(d.prompt_json, '$.workTold'), '') IN ('output', 'completed') OR (json_extract(d.prompt_json, '$.workTold') IS NULL AND d.outcome IS 'completed'))" const hasWorkUpdates = (prompt: BotDispatchRow['prompt']): boolean => Boolean( - prompt.workActionIds?.length || prompt.workWaitIds?.length || prompt.workDelivery?.notes.length || + prompt.workRefusalIds?.length || prompt.workActionIds?.length || prompt.workWaitIds?.length || prompt.workDelivery?.notes.length || prompt.workDelivery?.answers.length || prompt.workDelivery?.question ) @@ -1164,12 +1166,17 @@ export class BotStore { const at = this.now() this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', at, botId) this.run('INSERT INTO bot_grants(bot_id, digest, manifest_json, approved_at) VALUES(?, ?, ?, ?)', botId, digest, JSON.stringify(manifest), at) + heldCalls(this.db)?.grantChanged(botId) return { botId, digest, manifest, approvedAt: at } }) } revoke(botId: string): boolean { - return this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', this.now(), botId) > 0 + return this.db.transaction(() => { + const revoked = this.run('UPDATE bot_grants SET revoked_at = ? WHERE bot_id = ? AND revoked_at IS NULL', this.now(), botId) > 0 + if (revoked) heldCalls(this.db)?.grantChanged(botId) + return revoked + }) } // -- Threads --------------------------------------------------------------------------------- @@ -1300,6 +1307,9 @@ export class BotStore { if (moved && to !== 'done') this.withdrawUnpostedQuestions(id) if (moved) { this.withdrawWorkQuestions(id) + heldCalls(this.db)?.endWork(id) + const refusalPrefix = `cursor:action-refusal:${id}:` + this.run('DELETE FROM bot_memory_state WHERE key IN (?, ?) OR substr(key, 1, ?) = ?', `cursor:action-note:${id}`, `cursor:action-owner:${id}`, refusalPrefix.length, refusalPrefix) this.run("UPDATE bot_reminders SET status = 'cancelled', delivered_at = ? WHERE work_id = ? AND status = 'waiting'", this.now(), id) } return moved @@ -2002,6 +2012,28 @@ export class BotStore { ORDER BY COALESCE(a.ran_at, a.answered_at, a.created_at), a.rowid`, workId) as unknown as ActionRow[] } + pruneWorkRefusals(): void { + const prefix = 'cursor:action-refusal:' + if (!this.get('SELECT 1 FROM bot_memory_state WHERE substr(key, 1, ?) = ? LIMIT 1', prefix.length, prefix)) return + this.run(`DELETE FROM bot_memory_state AS s WHERE substr(s.key, 1, ?) = ? AND NOT EXISTS ( + SELECT 1 FROM bot_activations a WHERE a.bot_id = s.bot_id AND a.status NOT IN ('done', 'failed', 'cancelled') + AND substr(s.key, 1, length(? || a.id || ':')) = ? || a.id || ':')`, prefix.length, prefix, prefix, prefix) + } + + recordWorkRefusal(workId: string, botId: string, id: string, text: string): void { + this.run('INSERT OR IGNORE INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', botId, + `cursor:action-refusal:${workId}:${id}`, JSON.stringify({ at: this.now(), text })) + } + + /** Mousse updates are neither owner notes nor a reason to start another turn. */ + unreadWorkRefusals(workId: string): Array<{ id: string; at: string; text: string }> { + const prefix = `cursor:action-refusal:${workId}:` + return this.all(`SELECT s.key, s.value FROM bot_memory_state s WHERE substr(s.key, 1, ?) = ? + AND NOT EXISTS (SELECT 1 FROM bot_dispatches d, json_each(d.prompt_json, '$.workRefusalIds') told + WHERE d.activation_id = ? AND ${WORK_TOLD} AND told.value = s.key) ORDER BY s.rowid`, prefix.length, prefix, workId) + .map(row => ({ id: String(row.key), ...JSON.parse(String(row.value)) as { at: string; text: string } })) + } + /** Confirmation controls replay only; existing carried/read markers are not changed here. */ confirmWorkDelivery(activationId: string, n: number, why: 'output' | 'completed'): void { const needsConfirmation = (dispatch: BotDispatchRow | undefined): boolean => Boolean(dispatch && dispatch.startedAt !== null && @@ -2011,6 +2043,7 @@ export class BotStore { this.db.transaction(() => { if (!needsConfirmation(this.dispatch(activationId, n))) return this.run("UPDATE bot_dispatches SET prompt_json = json_set(prompt_json, '$.workTold', ?) WHERE activation_id = ? AND n = ?", why, activationId, n) + for (const id of this.dispatch(activationId, n)?.prompt.workRefusalIds ?? []) this.run('DELETE FROM bot_memory_state WHERE key = ?', id) }) } diff --git a/tests/bots/botActions.test.ts b/tests/bots/botActions.test.ts index 6cbd879bc0..4d8bc9d891 100644 --- a/tests/bots/botActions.test.ts +++ b/tests/bots/botActions.test.ts @@ -1,3 +1,6 @@ +import { BOT_SCHEDULE_ACT_TOOLS } from '../../src/shared/bots/personal/manifest' +import { createBotMemoryAdmin } from '../../src/mms/bots/memory/admin' +import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { afterEach, expect, it, vi } from 'vitest' import { remoteBotMethods } from '../../src/mms/bridge/remote/RemoteBots' import { setDiagSink } from '../../src/mms/log/diag' @@ -21,7 +24,7 @@ import { botFixture, createBot, finish, flush, start, type BotFixture } from './ let f: BotFixture const connections: McpManager[] = [] afterEach(async () => { f?.close(); await Promise.all(connections.splice(0).map(m => m.shutdown())) }) -async function setup(on: boolean, realServer = false, secondTool = false, threads = false) { +async function setup(on: boolean, realServer = false, secondTool = false, threads = false, ownerTools = false) { f = botFixture() const settings = getDefaultSettings() settings.experimental.botAsksFirst = on @@ -70,6 +73,14 @@ async function setup(on: boolean, realServer = false, secondTool = false, thread await f.bots.service.answer(botId, f.store.openAsks(botId)[0]!.id, 'allow') await finish(f, askingThreads.payload) } + if (ownerTools) { + const current = f.bots.definitionOf(botId) + const held = f.store.activeGrant(botId)!.manifest + const manifest = { ...held, appTools: [...held.appTools, 'secrets', 'schedules', 'quick_actions'], tools: [...held.tools, 'shell' as const] } + const revision = f.host.definitions.publishRevision({ ...current, permissions: manifest }) + f.store.setPublished(botId, revision.revision!) + f.store.approve(botId, botManifestDigest(manifest), manifest) + } const grant = f.store.activeGrant(botId)! const manifest = { ...grant.manifest, mcp: server.tools.map(d => ({ serverId: 'mail', tool: d.toolName, ...(on ? { level: 'asks_first' as const } : {}) })) } f.store.approve(botId, botManifestDigest(manifest), manifest) @@ -108,7 +119,7 @@ it('holds once, frees the slot, and Send executes exactly the stored arguments o // Actors: a second device, changed schema/configuration/grant/device ceiling, restart. // Orders: answer before/after turn end, double Send, Send versus Not now, approved/running crash. -it.each(['digest', 'schema', 'configuration', 'grant', 'device'] as const)('refuses a stale %s without making a call', async (change) => { +it.each(['digest', 'schema', 'configuration', 'device'] as const)('refuses a stale %s without making a call', async (change) => { const t = await setup(true) await t.call() await finish(f, t.work.payload) @@ -117,10 +128,6 @@ it.each(['digest', 'schema', 'configuration', 'grant', 'device'] as const)('refu if (change === 'digest') answer.digest = 'old-digest' if (change === 'schema') t.descriptor.inputSchema = { type: 'object', required: ['extra'] } as never if (change === 'configuration') t.server.configDigest = 'changed' - if (change === 'grant') { - const grant = f.store.activeGrant(t.botId)! - f.store.approve(t.botId, grant.digest, grant.manifest) - } if (change === 'device') f.store.narrowOwnerLimit(t.chatId, 'plan') await expect(f.bots.actions.answer(answer)).rejects.toThrow('changed since') expect(t.calls).toEqual([]) @@ -186,24 +193,24 @@ it('reload and internet-back continuations cannot pass an open card', async () = expect(f.store.lastMainDispatch(t.workId)?.n).toBe(1) expect(t.calls).toEqual([]) }) -it.each(['approved', 'running'] as const)('restart clears arguments from an expired %s row', async state => { +it.each(['approved', 'running'] as const)('restart preserves timely approval and settles a %s row', async state => { const t = await setup(true) await t.call() await finish(f, t.work.payload) const a = f.bots.actions.forWork(t.workId)! f.bots.actions.transition(a.id, 'open', 'approved') if (state === 'running') f.bots.actions.transition(a.id, 'approved', 'running') - f.clock.now += 49 * 3600_000 + f.clock.now += 48 * 3600_000 + 1000 await f.bots.actions.reconcile() expect(t.calls).toEqual([]) - expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'expired' : 'uncertain', exec_args: null }) + expect(f.bots.actions.forWork(t.workId)).toMatchObject({ status: state === 'approved' ? 'failed' : 'uncertain', exec_args: null }) }) it('an expired Send is refused', async () => { const t = await setup(true) await t.call() const a = f.bots.actions.forWork(t.workId)! - f.clock.now += 49 * 3600_000 - await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('changed since') + f.clock.now += 48 * 3600_000 + 1000 + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() expect(t.calls).toEqual([]) }) it('the app answer method reaches the held call and returns redraw for a repeated Send', async () => { @@ -216,7 +223,7 @@ it('the app answer method reaches the held call and returns redraw for a repeate const context = { connection: { id: 'c', binding: { profileId: 'p1', epoch: 1 }, capabilities: new Set() } } as never const params = { actionId: a.id, digest: a.args_digest, answer: 'send' } expect(await domains.dispatch(context, 'bots.actions.answer', params)).toMatchObject({ status: 'done' }) - await expect(domains.dispatch(context, 'bots.actions.answer', params)).rejects.toMatchObject({ code: 'bot_action_changed' }) + await expect(domains.dispatch(context, 'bots.actions.answer', params)).rejects.toMatchObject({ code: 'bot_action_settled' }) expect(t.calls).toEqual([t.args]) }) it.each(['relay', 'pi'] as const)('%s holds through the common path, and journals masked arguments', async runtime => { @@ -453,7 +460,7 @@ it('R5-words gives by-hand runs and disabled answers their own refusal', async ( expect(result.text).toContain('run started by hand') expect(result.text).not.toContain('scheduled') f.host.settings!.get().experimental.botAsksFirst = false - await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/not available/i) + await expect(f.bots.service.answerAction({ actionId: 'missing', digest: 'missing', answer: 'send' })).rejects.toThrow(/can.t be sent any more/i) }) it('R5-time transports the sent instant instead of a UTC clock string', async () => { const t = await setup(true) @@ -964,15 +971,915 @@ it.each([true, false].flatMap(on => ['work', 'subagent'].map(caller => ({ on, ca const child = await start(f, t.workId, d.n) const authorities = [t.work.prepared.authority, child.prepared.authority] for (const bot of authorities) for (const name of ['thread_create', 'thread_send', 'thread_archive']) { - if (bot === t.work.prepared.authority) expect(botAppToolRefusal(bot, name, {})).toBeUndefined() - else expect(botAppToolRefusal(bot, name, {})).toBeTruthy() + expect(botAppToolRefusal(bot, name, {})).toBeUndefined() } if (caller === 'work') await t.call() else await callForBot({ bot: child.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'child-mail', signal: new AbortController().signal }) for (const bot of authorities) for (const name of ['thread_create', 'thread_send', 'thread_archive']) { const refused = botAppToolRefusal(bot, name, {}) - if (on || bot === child.prepared.authority) expect(refused).toBeTruthy() + if (on) expect(refused).toBeTruthy() else expect(refused).toBeUndefined() } expect(t.calls).toEqual(on ? [] : [t.args]) }) + +// C3b inputs: open/approved/running, owner stop and engine end, wipes, +// forgotten card/request, changed permission/tool, expiry, repeat and owner intervention. +it.each(['open', 'approved'] as const)('withdraws %s calls atomically when work ends', async status => { + const t = await setup(true) + await t.call() + const a = f.bots.actions.forWork(t.workId)! + if (status === 'approved') f.bots.actions.transition(a.id, 'open', 'approved') + f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + expect(() => f.store.moveActivation(t.workId, ['blocked'], 'cancelled')).toThrow() + expect(f.bots.actions.get(a.id)).toMatchObject({ status, exec_args: JSON.stringify(t.args) }) + expect(f.store.activation(t.workId)?.status).toBe('blocked') + f.store.db.statement('DROP TRIGGER fail_card').run() + await f.bots.stopWork(t.botId, t.workId) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Not sent') +}) + +it('expires on the due timer and carries its outcome until model output', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + expect(f.bots.nextDueAt(t.botId)).toBe(a.expires_at) + f.clock.now = Date.parse(a.expires_at) + f.timers.at(-1)!.fn() + await flush() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'expired', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Expired · not sent') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('expired') + expect(f.store.unreadWorkActions(t.workId)).toHaveLength(1) + const receiving = await start(f, t.workId, 2) + ;(receiving.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(t.calls).toEqual([]) +}) + +it.each(['declined', 'expired'] as const)('refuses an identical %s call without a new row; owner notes and changed arguments allow a card', async outcome => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (outcome === 'declined') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + else { f.clock.now = Date.parse(a.expires_at); await f.bots.deliverDueReminders() } + await flush() + const next = await start(f, t.workId, 2) + const call = (args = t.args, id = 'repeat') => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args, toolCallId: id, signal: new AbortController().signal }) + expect(await call()).toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(f.bots.noteWork(t.botId, t.workId, 'Please try it again')).toBe('noted') + expect(await call(t.args, 'after-note')).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it('allows a different argument after Not now, with only one outstanding card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() + const next = await start(f, t.workId, 2) + const call = (body: string) => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal }) + expect(await call('new reason')).not.toMatchObject({ isError: true }) + expect(await call('another reason')).toMatchObject({ isError: true }) + expect(f.store.all("SELECT id FROM bot_actions WHERE status = 'open'")).toHaveLength(1) +}) + +it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget history', 'permission', 'allowed', 'tool', 'server', 'card', 'request'] as const)('withdraws pending arguments on %s and preserves a running row', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + // A second work's running call is independent and must retain its run-once record. + f.store.run(`INSERT INTO bot_actions SELECT id || '_running', call_key || '_running', bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, place_json, card_json, bot_note, 'running', result_json, message_id, next_at, nudges, expires_at, answered_at, answered_device, created_at, ran_at FROM bot_actions WHERE id = ?`, a.id) + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (['failed', 'limits', 'week'].includes(path)) f.store.moveActivation(t.workId, ['blocked'], 'failed', { endReason: path }) + if (path === 'allowed') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) + if (path === 'server') { vi.spyOn(t.mcp, 'where').mockReturnValue({ state: 'gone' }); f.bots.fillMcpAsks() } + if (path === 'card' || path === 'request') { + const id = path === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'request' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + if (path === 'clear') await f.bots.clearChat(t.botId) + if (path === 'reset') await f.bots.resetBot(t.botId) + if (path === 'delete') await f.bots.remove(t.botId) + if (path === 'forget history') await f.bots.wipeMemory(t.botId, 'saved') + if (path === 'permission') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + if (path === 'tool') { t.server.tools.splice(0); f.bots.fillMcpAsks() } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.bots.actions.get(`${a.id}_running`)).toMatchObject({ status: 'running', exec_args: JSON.stringify(t.args) }) + await f.bots.actions.reconcile() + expect(f.bots.actions.get(`${a.id}_running`)).toMatchObject({ status: 'uncertain', exec_args: null }) +}) + +it('keeps the card during an owner pause and refuses Send in plain words', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.pauseBot(t.botId) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('to send this.') + expect(f.bots.actions.get(a.id)?.status).toBe('open') + expect(t.calls).toEqual([]) +}) + +it.each(['card', 'request'] as const)('Forget of the %s withdraws exact arguments in the redaction transaction', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const request = f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0]! + const id = which === 'card' ? a.message_id : String(request.id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: which === 'card' ? 'notice' : 'owner_msg', who: which === 'card' ? 'bot' : 'owner', text: f.store.message(id)!.text })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + f.bots.afterForget() + await flush() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.activation(t.workId)?.status).toBe(which === 'card' ? 'running' : 'failed') +}) + +it('forget history removes settled text and preserves the call key that prevents another execution', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await f.bots.wipeMemory(t.botId, 'saved') + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ call_key: a.call_key, status: 'declined', args_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) + const result = f.bots.actions.hold(f.store.activation(t.workId)!, JSON.parse(a.call_key)[1], { server: 'mail', tool: 'send' } as never, t.args, 'runtime-call-1') + expect(result).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(t.calls).toEqual([]) +}) + +it.each(['restart', 'sleep', 'late Send'] as const)('expires at the written deadline after %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) + 1000 + if (path === 'restart') { f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() } + else if (path === 'sleep') await f.bots.deliverDueReminders() + else await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow('expired') + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'expired', exec_args: null }) + expect(t.calls).toEqual([]) +}) + +it('an owner chat message lifts the identical-call refusal using its sequence', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() + const next = await start(f, t.workId, 2) + await f.bots.service.chatSend({ botId: t.botId, text: 'Please try again', clientRequestId: 'retry-owner' }) + expect(await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'after-owner', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it('settled approval stranded before its readiness write ends with a line', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.store.run("UPDATE bot_actions SET status = 'withdrawn', exec_args = NULL WHERE id = ?", a.id) + f.bots.afterForget() + expect(f.store.activation(t.workId)).toMatchObject({ status: 'failed', endReason: 'action_gone' }) + expect(f.store.message(`bm_${t.workId}_ended`)?.text).toContain('nothing could let it carry on') +}) + +it.each(['stop', 'expiry', 'forget'] as const)('the disabled switch settles existing held rows on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.host.settings!.get().experimental.botAsksFirst = false + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'expiry') { f.clock.now = Date.parse(a.expires_at); await f.bots.deliverDueReminders() } + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${a.message_id}`, who: 'bot', text: 'Held call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: path === 'expiry' ? 'expired' : 'withdrawn', exec_args: null }) +}) + +it.each(['send', 'not_now'] as const)('owner %s resets detection of repeated waits, as a question answer does', async answer => { + const t = await setup(true, false, true) + for (let round = 0; round < 4; round++) { + const current = f.store.activation(t.workId)! + const n = f.store.lastMainDispatch(t.workId)!.n + const runtime = round === 0 ? t.work : await start(f, t.workId, n) + await f.bots.tools.wakes!.wait!(t.botId, t.workId, { brief: 'Wait for mail evidence', dueAt: new Date(f.clock.now + 300_000).toISOString() }) + await finish(f, runtime.payload) + f.clock.now += 300_000 + await f.bots.deliverDueReminders(); await flush() + const next = await start(f, t.workId, n + 1) + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: round % 2 ? 'Mail__other' : 'Mail__send', args: { ...t.args, body: `mail ${round}` }, toolCallId: `mail-${round}`, signal: new AbortController().signal }) + await finish(f, next.payload) + const a = f.bots.actions.forWork(current.id)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer }) + await flush() + } +}) + +it('a tool withdrawal is delivered through unread updates and confirmed on completion', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + t.server.tools.splice(0) + f.bots.fillMcpAsks(); await flush() + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('No longer needed') + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + const next = await start(f, t.workId, 2) + await finish(f, next.payload) + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) +}) + +it.each(['stop', 'failed', 'limits', 'week', 'clear', 'reset', 'delete', 'forget history', 'permission', 'allowed', 'tool', 'server', 'card', 'request'] as const)('%s rolls back withdrawal and its owning change together on a failed write', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const before = f.store.activation(t.workId)! + const grant = f.store.activeGrant(t.botId) + f.store.db.statement(`CREATE TRIGGER fail_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + let change: () => unknown + if (path === 'stop') change = () => f.bots.stopWork(t.botId, t.workId) + else if (['failed', 'limits', 'week'].includes(path)) change = () => f.store.moveActivation(t.workId, ['blocked'], 'failed', { endReason: path }) + else if (path === 'forget history') change = () => f.bots.wipeMemory(t.botId, 'saved') + else if (path === 'allowed') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: m.mcp.map(p => ({ ...p, level: 'allowed' as const })) })) + else if (path === 'tool' || path === 'server') change = () => { + if (path === 'tool') t.server.tools.splice(0) + else vi.spyOn(t.mcp, 'where').mockReturnValue({ state: 'gone' }) + f.bots.fillMcpAsks() + } + else if (path === 'clear') change = () => f.bots.clearChat(t.botId) + else if (path === 'reset') change = () => f.bots.resetBot(t.botId) + else if (path === 'delete') change = () => f.bots.remove(t.botId) + else if (path === 'permission') change = () => f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + else { + const memory = new BotMemoryStore({ db: f.store.db }) + const id = path === 'request' ? String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) : a.message_id + const seq = memory.append({ botId: t.botId, kind: 'notice', sourceKey: `bm:${id}`, who: 'bot', text: 'Held call' })! + change = () => memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + await expect(Promise.resolve().then(change)).rejects.toThrow() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'open', exec_args: JSON.stringify(t.args) }) + expect(f.store.activation(t.workId)).toEqual(before) + expect(f.store.activeGrant(t.botId)).toEqual(grant) + expect(f.store.registry(t.botId)?.deletedAt).toBeNull() + expect(f.store.message(a.message_id)?.text).not.toBe('Not sent') +}) + + +it('a repeat refusal joins unread work updates without another action or card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush() + const next = await start(f, t.workId, 2) + ;(next.prepared as any).modelOutput?.() + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'repeat-refused', signal: new AbortController().signal }) + expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('Do not ask again') + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + await f.bots.tools.wakes!.wait!(t.botId, t.workId, { brief: 'Wait for progress', dueAt: new Date(f.clock.now + 300_000).toISOString() }) + await finish(f, next.payload) + expect(f.store.unreadWorkRefusals(t.workId)).toHaveLength(1) + f.clock.now += 300_000; await f.bots.deliverDueReminders(); await flush() + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Do not ask again') + const receiving = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(receiving.prepared as any).modelOutput?.() + expect(f.store.unreadWorkRefusals(t.workId)).toEqual([]) +}) + +it('switch off keeps repeated and differing calls direct without cards or refusal notes', async () => { + const t = await setup(false) + for (const body of [t.args.body, t.args.body, 'different']) { + expect(await callForBot({ bot: t.work.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + } + expect(t.calls).toHaveLength(3) + expect(f.store.all('SELECT id FROM bot_actions')).toEqual([]) + expect(f.store.unreadWorkNotes(t.workId)).toEqual([]) +}) + + +it.each(['failing', 'starting', 'cold restart'] as const)('B1 keeps a live card through a %s listing and sends once after recovery', async state => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const tools = t.server.tools.splice(0) + if (state === 'failing') t.server.failing = true + if (state === 'starting') Object.assign(t.server, { starting: true }) + const listing = state === 'cold restart' ? vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) : undefined + if (state === 'cold restart') { f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() } + else f.bots.fillMcpAsks() + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + t.server.tools.push(...tools); t.server.failing = false; Object.assign(t.server, { starting: false }); listing?.mockRestore() + f.bots.fillMcpAsks() + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(t.calls).toEqual([t.args]) +}) + +it.each(['card', 'request'].flatMap(which => ['open', 'declined', 'done'].map(status => ({ which, status }))))('B2 Forget $which erases $status call text from the record and export', async ({ which, status }) => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (status !== 'open') await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: status === 'done' ? 'send' : 'not_now' }) + const counters = JSON.parse(f.bots.actions.get(a.id)!.card_json!) + const request = f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0]! + const id = which === 'card' ? a.message_id : String(request.id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ args_json: '"[forgotten]"', result_json: '{"text":"[forgotten]"}' }) + expect(JSON.parse(saved.card_json!)).toMatchObject({ text: '[forgotten]', ownerSeq: counters.ownerSeq ?? 0, noteSeq: counters.noteSeq ?? 0 }) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('Exact text') + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('one@example.test') + expect(saved.call_key).toBe(a.call_key) +}) + +it('B4 forget history keeps the refusal counters while erasing card text', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + const before = JSON.parse(f.bots.actions.get(a.id)!.card_json!) + await f.bots.wipeMemory(t.botId, 'saved') + expect(JSON.parse(f.bots.actions.get(a.id)!.card_json!)).toMatchObject({ text: '[forgotten]', ownerSeq: before.ownerSeq, noteSeq: before.noteSeq }) +}) + +it.each(['card', 'request', 'history'] as const)('B5 Forget %s erases the argument digest and keeps the call key', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + if (which === 'history') await f.bots.wipeMemory(t.botId, 'saved') + else { + const id = which === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ args_digest: '[forgotten]', call_key: a.call_key, status: 'declined' }) + f.bots.actions.hold(f.store.activation(t.workId)!, JSON.parse(a.call_key)[1], { server: 'mail', tool: 'send' } as never, t.args, 'runtime-call-1') + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(f.store.get('SELECT id FROM bot_actions WHERE args_digest = ?', a.args_digest)).toBeUndefined() + expect(t.calls).toEqual([]) +}) + +it.each([true, false])('B3 three declined cards stop changed calls until owner input, switch=%s', async on => { + const t = await setup(on, false, true) + let runtime = t.work + for (let n = 0; n < 20; n++) { + const outcome = await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: t.args.body + ' '.repeat(n) }, toolCallId: `loop-${n}`, signal: new AbortController().signal }) + if (!on) continue + if (n < 3) { + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }) + await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + } else expect(outcome).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) + } + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(on ? 3 : 0) + if (!on) { expect(t.calls).toHaveLength(20); return } + expect(f.store.unreadWorkRefusals(t.workId).map(n => n.text).join(' ')).toContain('had three cards for this tool that were not sent') + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__other', args: t.args, toolCallId: 'another-tool', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + await finish(f, runtime.payload) + const other = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: other.id, digest: other.args_digest, answer: 'not_now' }) + await flush(); runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + f.bots.noteWork(t.botId, t.workId, 'Please try again') + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'try again' }, toolCallId: 'after-note', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) +}) + +it.each(['unrelated permission', 'revision only'] as const)('B6 %s preserves an open card and Send executes once', async change => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (change === 'unrelated permission') f.bots.narrowGrant(t.botId, m => ({ ...m, appTools: [...m.appTools, 'web_search', 'web_fetch'] })) + else { const grant = f.store.activeGrant(t.botId)!; f.store.approve(t.botId, grant.digest, grant.manifest); f.bots.fillMcpAsks() } + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + expect(t.calls).toEqual([t.args]) +}) + +it('B6 removal then re-grant of the pair cannot revive its old card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const pairs = f.store.activeGrant(t.botId)!.manifest.mcp + f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + expect(f.bots.actions.get(a.id)?.status).toBe('withdrawn') + f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: pairs })) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toThrow() + expect(f.bots.actions.get(a.id)?.status).toBe('withdrawn') + expect(t.calls).toEqual([]) +}) + +it('restart never executes a previously approved call while its owner has paused the bot', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.actions.transition(a.id, 'open', 'approved') + f.bots.pauseBot(t.botId) + f.bots.close(); f.bots = new BotEngine(f.host) + await f.bots.reconcileOnStartup() + expect(t.calls).toEqual([]) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe('Not sent') + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + await f.bots.resumeBot(t.botId); await flush() + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('paused') + const next = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(next.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(t.calls).toEqual([]) +}) + +it.each([false, true])('B1 an approved row survives a cold restart, past deadline=%s, and runs after listing', async late => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.bots.actions.transition(a.id, 'open', 'approved') + const tools = t.server.tools.splice(0) + const where = vi.spyOn(t.mcp, 'where').mockReturnValue(undefined) + if (late) f.clock.now = Date.parse(a.expires_at) + 1000 + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.bots.actions.get(a.id)?.status).toBe(late ? 'failed' : 'approved') + expect(t.calls).toEqual([]) + t.server.tools.push(...tools); where.mockRestore() + f.bots.fillMcpAsks(); await flush() + expect(f.bots.actions.get(a.id)?.status).toBe(late ? 'failed' : 'done') + expect(t.calls).toEqual(late ? [] : [t.args]) +}) + +it('B1 a real configuration change withdraws even while the server listing fails', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + t.server.tools.splice(0); t.server.failing = true; t.server.configDigest = 'changed' + f.bots.fillMcpAsks() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(t.calls).toEqual([]) +}) + +it('B2 a running call cannot restore its forgotten content when its result arrives', async () => { + const t = await setup(true) + let release!: () => void + const result = new Promise(resolve => { release = resolve }) + vi.spyOn(t.manager, 'callTool').mockImplementationOnce(async () => { await result; return { content: [{ type: 'text', text: 'private delivered receipt' }] } as never }) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + expect(f.bots.actions.get(a.id)?.status).toBe('running') + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const forgottenText = f.store.message(a.message_id)?.text + release(); await sending + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'done', exec_args: null, result_json: '{"text":"[forgotten]"}', args_digest: '[forgotten]' }) + expect(f.store.message(a.message_id)?.text).toBe(forgottenText) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('private delivered receipt') +}) + +it('R2-4 three expired cards refuse further calls without claiming the owner declined', async () => { + const t = await setup(true) + let runtime = t.work + for (let n = 0; n < 3; n++) { + await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: `expires ${n}` }, toolCallId: `expires-${n}`, signal: new AbortController().signal }) + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + // Move just the card's deadline: advancing three real deadlines would also end the work's week. + f.store.run('UPDATE bot_actions SET expires_at = ? WHERE id = ?', f.store.now(), a.id) + await f.bots.deliverDueReminders(); await flush() + runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + } + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'before-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) + const a = f.bots.actions.forWork(t.workId)! + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'declined call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + expect(await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'one more change' }, toolCallId: 'after-forget', signal: new AbortController().signal })).toMatchObject({ isError: true, text: expect.stringContaining('had three cards for this tool that were not sent') }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(3) +}) + +it.each(['repeat', 'loop'] as const)('R2-1 %s refusal is a Mousse update and never starts an extra report', async reason => { + const t = await setup(true) + let runtime = t.work + for (let n = 0; n < (reason === 'loop' ? 3 : 1); n++) { + await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, ...(reason === 'loop' ? { body: `body ${n}` } : {}) }, toolCallId: `decline-${n}`, signal: new AbortController().signal }) + await finish(f, runtime.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + ;(runtime.prepared as any).modelOutput?.() + } + const dispatches = f.store.dispatches(t.workId).length + const result = await callForBot({ bot: runtime.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'refused', signal: new AbortController().signal }) + expect(result.isError).toBe(true) + expect(f.store.pendingWorkNotes(t.workId)).toEqual([]) + await finish(f, runtime.payload, 'completed', { text: 'Finished without sending.' }); await flush() + expect(f.store.dispatches(t.workId)).toHaveLength(dispatches) + expect(f.store.activation(t.workId)?.status).toBe('done') + expect(JSON.stringify(f.store.dispatches(t.workId))).not.toContain('owner added') + expect(f.store.all("SELECT id FROM bot_messages WHERE activation_id = ? AND kind = 'run_report'", t.workId)).toHaveLength(1) +}) + + +it.each(['card', 'request'] as const)('R2-2 forgetting the %s uses the appropriate continuation or normal end', async which => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const scratch = `${f.base}/forget-scratch`; mkdirSync(scratch) + f.store.run('UPDATE bot_activations SET scratch = ? WHERE id = ?', scratch, t.workId) + const browserEnd = vi.fn(); const progressEnd = vi.fn() + f.host.browser = { activationEnded: browserEnd } as never + f.host.progress = { finishProgress: progressEnd } as never + const id = which === 'card' ? a.message_id : String(f.store.all("SELECT id FROM bot_messages WHERE bot_id = ? AND author = 'owner' ORDER BY seq DESC", t.botId)[0].id) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }); await flush() + if (which === 'card') { + expect(f.store.activation(t.workId)?.status).toBe('running') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain('Your owner removed this request') + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).not.toContain('request was forgotten') + } else { + expect(f.store.activation(t.workId)?.status).toBe('failed') + expect(f.journal.some(j => j.kind === 'run_end' && j.activationId === t.workId)).toBe(true) + expect(existsSync(scratch)).toBe(false) + expect(browserEnd).toHaveBeenCalledWith({ botId: t.botId, activationId: t.workId }) + expect(progressEnd).toHaveBeenCalledWith(t.botId, t.workId, false) + } +}) + +it('R2-3 allowing use your threads from chat preserves a sendable card', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.service.chatSend({ botId: t.botId, text: 'Use my threads', clientRequestId: 'allow-threads-with-card' }) + const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! + const asking = await start(f, chat.id) + asking.prepared.authority.escalate!({ permission: { tool: 'threads' }, reason: 'Help in threads' }) + await finish(f, asking.payload, 'completed', { text: 'May I use your threads?' }) + await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(t.calls).toEqual([t.args]) +}) + +it('R2-3 every grant approval checks removal of the held pair in the grant transaction', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const grant = f.store.activeGrant(t.botId)! + const removed = { ...grant.manifest, mcp: [] } + f.store.approve(t.botId, botManifestDigest(removed), removed) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) +}) + +it('R2-5 a timely Send remains running when the deadline passes', async () => { + const t = await setup(true) + let release!: () => void + const waiting = new Promise(resolve => { release = resolve }) + vi.spyOn(t.manager, 'callTool').mockImplementationOnce(async () => { await waiting; return { content: [{ type: 'text', text: 'delivered' }] } as never }) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) - 1000 + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + f.clock.now += 2000 + await f.bots.deliverDueReminders() + expect(f.bots.actions.get(a.id)?.status).toBe('running') + expect(() => f.bots.actions.assertRunning(a.id)).not.toThrow() + release(); await sending + expect(f.bots.actions.get(a.id)?.status).toBe('done') +}) + +it.each(['stop', 'expiry', 'forget'] as const)('R2-6 existing rows still settle after switch-off on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.host.settings!.get().experimental.botAsksFirst = false + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'expiry') { f.clock.now = Date.parse(a.expires_at); f.timers.at(-1)!.fn(); await flush() } + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: path === 'expiry' ? 'expired' : 'withdrawn', exec_args: null }) +}) + + +it.each(['stop', 'complete', 'purge'] as const)('R2-7 action cursors stay out of export and disappear on %s', async end => { + const t = await setup(true) + f.bots.noteWork(t.botId, t.workId, 'Owner note') + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + const keys = [`cursor:action-note:${t.workId}`, `cursor:action-owner:${t.workId}`] + expect(f.store.all('SELECT key FROM bot_memory_state WHERE key IN (?, ?)', ...keys)).toHaveLength(2) + const memory = new BotMemoryStore({ db: f.store.db }) + const exported = await createBotMemoryAdmin({ store: memory }).export(t.botId, f.base) + const text = exported.files.map(file => readFileSync(file, 'utf8')).join(' ') + for (const key of keys) expect(text).not.toContain(key) + if (end === 'purge') memory.purge(t.botId) + else if (end === 'stop') await f.bots.stopWork(t.botId, t.workId) + else { const runtime = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n); (runtime.prepared as any).modelOutput?.(); await finish(f, runtime.payload) } + expect(f.store.all('SELECT key FROM bot_memory_state WHERE key IN (?, ?)', ...keys)).toEqual([]) +}) + +it.each(['paused', 'expired', 'withdrawn', 'binding'] as const)('R2-8 Send reports its specific %s refusal code and sentence', async reason => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (reason === 'paused') f.bots.pauseBot(t.botId) + if (reason === 'expired') f.clock.now = Date.parse(a.expires_at) + 1000 + if (reason === 'withdrawn') await f.bots.stopWork(t.botId, t.workId) + if (reason === 'binding') t.server.configDigest = 'changed' + const code = reason === 'binding' ? 'bot_action_changed' : `bot_action_${reason}` + const sentence = reason === 'paused' ? `Resume ${f.bots.definitionOf(t.botId).name} to send this.` : reason === 'expired' ? 'This expired, so nothing was sent.' : reason === 'withdrawn' ? 'No longer needed, so nothing was sent.' : 'This changed since you saw it. Check it again before sending.' + await expect(f.bots.service.answerAction({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code, message: sentence }) + expect(t.calls).toEqual([]) +}) + +it('R2-5 accepts Send before refreshing tools so the timer cannot overtake it', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + f.clock.now = Date.parse(a.expires_at) - 1000 + let release!: () => void + const refresh = new Promise(resolve => { release = resolve }) + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(() => refresh) + const sending = f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await flush() + expect(f.bots.actions.get(a.id)?.status).toBe('approved') + f.clock.now += 2000; await f.bots.deliverDueReminders() + expect(f.bots.actions.get(a.id)?.status).toBe('approved') + release(); await sending + expect(t.calls).toEqual([t.args]) + expect(f.bots.actions.get(a.id)?.status).toBe('done') +}) + +it('R2-3 revoking a grant withdraws its held pair in the same transaction', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const grant = f.store.activeGrant(t.botId)! + f.store.db.statement(`CREATE TRIGGER fail_revoke_card BEFORE UPDATE ON bot_messages WHEN OLD.id = '${a.message_id}' BEGIN SELECT RAISE(ABORT, 'card failure'); END`).run() + expect(() => f.store.revoke(t.botId)).toThrow() + expect(f.store.activeGrant(t.botId)).toEqual(grant) + expect(f.bots.actions.get(a.id)?.status).toBe('open') + f.store.db.statement('DROP TRIGGER fail_revoke_card').run() + f.store.revoke(t.botId) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) +}) + +it.each([9, 11])('R3-1 accepted Send recovers at %s minutes only within its tap window', async minutes => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + const deadline = f.clock.now + 10 * 60_000 + expect(f.bots.nextDueAt(t.botId)).toBe(new Date(deadline).toISOString()) + expect(f.bots.isIdle(t.botId)).toBe(false) + expect(f.store.message(a.message_id)?.text).toBe('Waiting for Mail…') + f.clock.now += minutes * 60_000 + if (minutes === 11) { f.timers.at(-1)!.fn(); await flush() } + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + if (minutes === 9) { expect(t.calls).toEqual([t.args]); expect(f.bots.actions.get(a.id)?.status).toBe('done'); return } + expect(t.calls).toEqual([]) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'failed', exec_args: null }) + expect(f.store.message(a.message_id)?.text).toBe("Mail couldn't be reached, so nothing was sent.") + expect(f.store.lastMainDispatch(t.workId)!.prompt.text).toContain("Mail couldn't be reached") + expect(f.store.unreadWorkActions(t.workId).map(a => a.id)).toEqual([a.id]) + const next = await start(f, t.workId, 2) + ;(next.prepared as any).modelOutput?.() + expect(f.store.unreadWorkActions(t.workId)).toEqual([]) + expect(await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'after-send-timeout', signal: new AbortController().signal })).not.toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) +}) + +it.each(['inside two restarts', 'outside two restarts', 'sleep', 'card deadline'] as const)('R3-1 tap deadline survives %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + if (path === 'card deadline') f.clock.now = Date.parse(a.expires_at) - 1000 + const tapped = f.clock.now + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + expect(f.bots.nextDueAt(t.botId)).toBe(new Date(tapped + 600_000).toISOString()) + if (path.includes('restarts')) { + for (const elapsed of [240_000, path.startsWith('inside') ? 540_000 : 660_000]) { + f.clock.now = tapped + elapsed + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + } + } else { f.clock.now = tapped + (path === 'sleep' ? 660_000 : 540_000); f.timers.at(-1)!.fn(); await flush() } + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + const sent = path === 'inside two restarts' || path === 'card deadline' + expect(t.calls).toEqual(sent ? [t.args] : []) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: sent ? 'done' : 'failed', exec_args: null }) +}) + +it('R3-2 Forget blocks the tool until owner input without retaining call content', async () => { + const t = await setup(true, false, true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'call' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }); await flush() + const prompt = f.store.lastMainDispatch(t.workId)!.prompt.text + expect(prompt).toContain('Your owner removed this request') + expect(prompt).not.toContain('[forgotten]') + let next = await start(f, t.workId, 2) + const call = (body: string, name = 'Mail__send') => callForBot({ bot: next.prepared.authority, mcp: t.mcp, name, args: { ...t.args, body }, toolCallId: body, signal: new AbortController().signal }) + expect(await call(t.args.body)).toMatchObject({ isError: true }) + expect(await call('changed')).toMatchObject({ isError: true }) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(1) + expect(await call('other', 'Mail__other')).not.toMatchObject({ isError: true }) + await finish(f, next.payload) + const other = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: other.id, digest: other.args_digest, answer: 'not_now' }); await flush() + next = await start(f, t.workId, f.store.lastMainDispatch(t.workId)!.n) + f.bots.noteWork(t.botId, t.workId, 'Please try again') + expect(await call('after-owner')).not.toMatchObject({ isError: true }) + const saved = f.bots.actions.get(a.id)! + expect(saved).toMatchObject({ args_json: '"[forgotten]"', args_digest: '[forgotten]', exec_args: null, result_json: '{"text":"[forgotten]"}' }) + expect(JSON.stringify(memory.actions(t.botId))).not.toContain('Exact text') +}) + + +it.each(['gone', 'settled', 'unreachable'] as const)('R3-3 owner wording for %s reaches the service unchanged', async reason => { + const t = await setup(true) + let id = 'missing', digest = 'missing' + if (reason !== 'gone') { + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)!; id = a.id; digest = a.args_digest + if (reason === 'settled') await f.bots.actions.answer({ actionId: id, digest, answer: 'not_now' }) + else { + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: id, digest, answer: 'send' }) + f.clock.now += 11 * 60_000; await f.bots.deliverDueReminders() + } + } + const sentence = reason === 'gone' ? "This can't be sent any more." : reason === 'settled' ? 'This was already answered.' : "Mail couldn't be reached, so nothing was sent." + await expect(f.bots.service.answerAction({ actionId: id, digest, answer: 'send' })).rejects.toMatchObject({ code: `bot_action_${reason}`, message: sentence }) +}) + +it('R3-3 a failing card of another bot cannot undo this bot grant change', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const b = await createBot(f, { reply: 'Hello' }) + const definition = f.bots.definitionOf(b.botId) + const revision = f.host.definitions.publishRevision({ ...definition, permissions: { ...definition.permissions, mcp: [{ serverId: 'mail', tool: 'send', level: 'asks_first' }] } }) + f.store.setPublished(b.botId, revision.revision!) + f.store.approve(b.botId, botManifestDigest(revision.permissions), revision.permissions) + const workB = await f.bots.activate({ botId: b.botId, input: 'Work B', clientRequestId: 'work-b' }) + await start(f, workB.id) + f.store.run(`INSERT INTO bot_actions(id, call_key, bot_id, activation_id, lane, kind, target_json, exec_args, args_json, args_digest, binding_json, card_json, status, message_id, expires_at, created_at) + SELECT id || '_b', call_key || '_b', ?, ?, lane, kind, target_json, exec_args, args_json, args_digest, 'null', card_json, status, message_id, expires_at, created_at FROM bot_actions WHERE id = ?`, b.botId, workB.id, a.id) + // Positive control: reading B's corrupt but valid-JSON binding really fails. + expect(() => f.bots.actions.withdrawChanged()).toThrow() + const grant = f.store.activeGrant(t.botId)! + expect(() => f.store.approve(t.botId, grant.digest, grant.manifest)).not.toThrow() + expect(f.bots.actions.get(a.id)?.status).toBe('open') +}) + + +it.each(['done', 'failed', 'cancelled', 'purge'] as const)('R3-3 refusal records end with work %s', async end => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'not_now' }); await flush() + const next = await start(f, t.workId, 2) + await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'refused', signal: new AbortController().signal }) + expect(f.store.unreadWorkRefusals(t.workId)).toHaveLength(1) + if (end === 'cancelled') await f.bots.stopWork(t.botId, t.workId) + else if (end === 'purge') new BotMemoryStore({ db: f.store.db }).purge(t.botId) + else await finish(f, next.payload, end === 'done' ? 'completed' : 'failed', { outcome: end === 'failed' ? { error: 'fatal' } : undefined }) + expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) +}) + +it.each(['stop', 'forget', 'pause', 'grant', 'delete'] as const)('R3-1 accepted waiting call ends early on %s', async path => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + vi.spyOn(t.mcp, 'warm').mockImplementationOnce(async () => { t.server.tools.splice(0); t.server.failing = true }) + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + if (path === 'stop') await f.bots.stopWork(t.botId, t.workId) + if (path === 'pause') f.bots.pauseBot(t.botId) + if (path === 'grant') f.bots.narrowGrant(t.botId, m => ({ ...m, mcp: [] })) + if (path === 'delete') await f.bots.remove(t.botId) + if (path === 'forget') { + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + } + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + t.server.tools.push(t.descriptor); t.server.failing = false + f.bots.fillMcpAsks(); await flush() + expect(t.calls).toEqual([]) +}) + +it('R3-3 restart removes refusal records left by ended or missing work', async () => { + const t = await setup(true) + await finish(f, t.work.payload) + for (const workId of [t.workId, 'missing-work']) f.store.run('INSERT INTO bot_memory_state(bot_id, key, value) VALUES(?, ?, ?)', t.botId, `cursor:action-refusal:${workId}:old`, JSON.stringify({ at: f.store.now(), text: 'old refusal' })) + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.store.all("SELECT key FROM bot_memory_state WHERE key LIKE 'cursor:action-refusal:%'")).toEqual([]) +}) + +it.each(['open', 'approved'] as const)('R3-3 legacy #1340 %s cards withdraw on upgrade', async status => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + const oldBinding = { ...JSON.parse(a.binding_json), grantRevision: 1, grantDigest: 'old-whole-grant' } + delete oldBinding.pairLevel + f.store.run('UPDATE bot_actions SET binding_json = ? WHERE id = ?', JSON.stringify(oldBinding), a.id) + if (status === 'approved') f.bots.actions.transition(a.id, 'open', 'approved') + f.clock.now += 11 * 60_000 + f.bots.close(); f.bots = new BotEngine(f.host); await f.bots.reconcileOnStartup() + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'withdrawn', exec_args: null }) + expect(t.calls).toEqual([]) +}) + +it('R4-1 forgetting a sent card permits a different call of the same tool', async () => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }); await flush() + const next = await start(f, t.workId, 2) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'sent card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + const result = await callForBot({ bot: next.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: { ...t.args, body: 'A different email' }, toolCallId: 'different-email', signal: new AbortController().signal }) + expect(result).not.toMatchObject({ isError: true }) + expect(f.store.all("SELECT id FROM bot_actions WHERE status = 'open'")).toHaveLength(1) + expect(f.store.all('SELECT id FROM bot_actions')).toHaveLength(2) + expect(f.bots.actions.get(a.id)).toMatchObject({ status: 'done', args_digest: '[forgotten]', exec_args: null }) +}) + +it.each(['done', 'declined', 'tool_error', 'uncertain'] as const)('R4-1 forgetting untold %s content preserves the outcome', async outcome => { + const t = await setup(true) + if (outcome === 'tool_error') vi.spyOn(t.manager, 'callTool').mockResolvedValueOnce({ isError: true, content: [{ type: 'text', text: 'private tool answer' }] } as never) + if (outcome === 'uncertain') vi.spyOn(t.manager, 'callTool').mockRejectedValueOnce(new Error('connection lost')) + await t.call() + const a = f.bots.actions.forWork(t.workId)! + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: outcome === 'declined' ? 'not_now' : 'send' }) + const memory = new BotMemoryStore({ db: f.store.db }) + const seq = memory.append({ botId: t.botId, sourceKey: `bm:${a.message_id}`, kind: 'notice', who: 'bot', text: 'settled card' })! + memory.forget(t.botId, { refs: [`j${seq}`], by: 'owner_ui' }) + await finish(f, t.work.payload); await flush() + const prompt = f.store.lastMainDispatch(t.workId)!.prompt.text + const line = outcome === 'done' ? 'Your owner sent it' : outcome === 'declined' ? 'Your owner chose not to send' : outcome === 'tool_error' ? 'The tool reported an error' : 'It could not be confirmed whether this went through' + expect(prompt).toContain(line) + expect(prompt).not.toContain('[forgotten]') + expect(prompt).not.toContain('private tool answer') + expect(prompt).not.toContain('Exact text') + expect(prompt).not.toContain('Your owner removed this request') +}) + + +it.each(['secrets', 'schedules', 'quick_actions'] as const)('R4-3 allowing %s from chat leaves the open card sendable once', async tool => { + const t = await setup(true) + await t.call(); await finish(f, t.work.payload) + const a = f.bots.actions.forWork(t.workId)! + await f.bots.service.chatSend({ botId: t.botId, text: 'Allow this permission for my work', clientRequestId: `allow-${tool}-with-card` }) + const chat = f.store.laneActivations(t.botId, 'chat', ['running'])[0]! + const asking = await start(f, chat.id) + asking.prepared.authority.escalate!({ permission: { tool }, reason: 'To help with this work' }) + await finish(f, asking.payload, 'completed', { text: 'May I use this permission?' }) + await f.bots.service.answer(t.botId, f.store.openAsks(t.botId)[0].id, 'allow') + expect(f.bots.actions.get(a.id)?.status).toBe('open') + await f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' }) + await expect(f.bots.actions.answer({ actionId: a.id, digest: a.args_digest, answer: 'send' })).rejects.toMatchObject({ code: 'bot_action_settled' }) + expect(t.calls).toEqual([t.args]) +}) + +it.each([true, false].flatMap(on => ['work', 'subagent'].map(caller => ({ on, caller }))))('R4-3 new app-tool gates after $caller holds, switch=$on', async ({ on, caller }) => { + const t = await setup(on, false, false, true, true) + await t.work.prepared.authority.subagents!.start({ title: 'Helper', brief: 'Help with mail', toolCallId: 'helper' }) + const d = f.store.dispatches(t.workId).find(d => d.kind === 'subagent')! + const child = await start(f, t.workId, d.n) + const tools = ['secret_request', 'secret_run', 'schedule_list', ...BOT_SCHEDULE_ACT_TOOLS, 'create_quick_action', 'approval_respond'] + const authorities = [t.work.prepared.authority, child.prepared.authority] + const before = authorities.map(bot => tools.map(name => botAppToolRefusal(bot, name, {}))) + expect(before[0]).toEqual(tools.map(() => undefined)) + expect(before[1][tools.indexOf('approval_respond')]).toBeUndefined() + if (caller === 'work') await t.call() + else await callForBot({ bot: child.prepared.authority, mcp: t.mcp, name: 'Mail__send', args: t.args, toolCallId: 'child-mail', signal: new AbortController().signal }) + for (const [i, bot] of authorities.entries()) for (const [j, name] of tools.entries()) { + const refused = botAppToolRefusal(bot, name, {}) + if (on) expect(refused, name).toMatch(i === 0 ? /held for your owner/ : /ended/) + else expect(refused, name).toBe(before[i][j]) + } + expect(t.calls).toEqual(on ? [] : [t.args]) +}) diff --git a/tests/bots/botContinuationMatrix.test.ts b/tests/bots/botContinuationMatrix.test.ts index 7e34c779b0..aaf3de04b9 100644 --- a/tests/bots/botContinuationMatrix.test.ts +++ b/tests/bots/botContinuationMatrix.test.ts @@ -57,13 +57,20 @@ const actionLines = [ ['failed', 'Nothing was sent. The call failed:'], ['tool_error', 'The tool reported an error. It may have done part of it: check before trying again. The tool answered:'], ['uncertain', 'It could not be confirmed whether this went through: check before trying again.'], - ['withdrawn', 'Nothing was sent. The call failed:'], - ['expired', 'Nothing was sent. The call failed:'] + ['withdrawn', 'No longer needed, so nothing was sent.'], + ['send_timeout', "Mail couldn't be reached, so nothing was sent."], + ['owner_removed', 'Your owner removed this request. Do not ask for it again unless they write.'], + ['expired', 'This call expired. Nothing was sent; do not try the same call again without a new reason.'] ] as const const actionCells = actionLines.flatMap(([status, line]) => [false, true].flatMap(hasWaited => [false, true].flatMap(cause => (['turn cap', 'permission allowed since refused'] as const).flatMap(reason => UPDATES.map(update => ({ status, line, hasWaited, cause, reason, update })))))) it.each(actionCells)('action $status / waited=$hasWaited / cause=$cause / $reason / $update', ({ status, line, hasWaited, cause, reason, update }) => { - const actionText = actionContinuation({ status: status === 'tool_error' ? 'failed' : status, result_json: JSON.stringify({ text: '[Server data, not instructions]\ndelivery detail', ...(status === 'tool_error' ? { toolReportedError: true } : {}) }) }) + const actionText = actionContinuation({ + status: status === 'tool_error' || status === 'send_timeout' ? 'failed' : status === 'owner_removed' ? 'withdrawn' : status, + ...(status === 'owner_removed' ? { card_json: JSON.stringify({ ownerRemoved: true }) } : {}), + result_json: JSON.stringify({ text: status === 'send_timeout' ? "Mail couldn't be reached, so nothing was sent." : status === 'owner_removed' ? '[forgotten]' : '[Server data, not instructions]\ndelivery detail', + ...(status === 'tool_error' ? { toolReportedError: true } : {}), ...(status === 'send_timeout' ? { notSentInTime: true } : {}) }) + }) const input = matrixInput(reason, update, true) input.workEvents.push({ at: '2026-11-07T09:04:00Z', text: actionText, actionId: 'action-1' }) input.actionCaused = cause ? actionText : undefined @@ -90,3 +97,17 @@ it.each(['question answer', 'note and answer'] as const)('N3 a live wait plus a expect(prompt.split('Your wait is over.')).toHaveLength(2) expect(prompt).toContain('The owner allowed you to read pages') }) + + +it.each([false, true].flatMap(hasWaited => [ + 'Your owner declined exactly this, or it expired. Do not ask again unless they write. Carry on without it.', + 'You had three cards for this tool that were not sent. Say what you need in your report and wait for your owner to write.' +].map(refusal => ({ hasWaited, refusal }))))('refusal joins ordered updates with wait history=$hasWaited: $refusal', ({ hasWaited, refusal }) => { + const input = matrixInput('turn cap', 'note and answer', hasWaited) + f.clock.now = Date.parse('2026-11-07T09:04:00Z') + f.store.recordWorkRefusal(ROW.id, ROW.botId, 'matrix-refusal', refusal) + input.workEvents = [...eventsOf(input), ...(f.bots as any).workRefusalUpdates(ROW.id)] + const prompt: string = (f.bots as any).continuationPrompt(ROW, input) + expect(prompt.split(refusal)).toHaveLength(2) + expect(prompt.indexOf(NOTE)).toBeLessThan(prompt.indexOf(refusal)) +})