diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index d6bca62ae..088f451bc 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -55,7 +55,7 @@ Use these terms in issues, PRs, comments, and docs. If you need a term that is n - **Bot:** an agent a person makes from a look and one sentence to do one job on its own, within permissions they approved. Mousse makes built-in bots. A bot lives in the Chats tab, where its owner talks to it in its bot chat. It runs when asked there and on its own schedules. A personal bot runs only for its owner, on this computer and the owner's own providers. Its models are named only on Runs on (in About and New bot), beside its name at the top of About (its Talk model), in one chat line when a model picked there can't run, and on the line of one piece of work the owner asked to run on another model, and in the owner's own `/model` lines in the bot chat. See `docs/bots.md`. - **Built-in bot:** a bot Mousse makes for the profile when a feature needs it. Enabling the pill adds Mousse for quick questions. Finishing the first meeting adds Meeting notes. Both start with an empty bot chat, unpicked models and Reach limited to this computer. - **Bound secret:** a secret the owner gave a bot for one HTTPS service. Mousse keeps the value and adds it only to that service's fixed authentication header through a GET or HEAD read. Known services also fix the allowed path segments and version headers. Commands outside a sandbox can still read the owner's secret-store files. -- **Command sandbox:** the owner's per-bot switch in About → Can use ("Sandbox commands", and "Allow network for sandboxed commands") that decides whether a bot's commands run in a sandbox that limits the files they can change, and whether those commands may use the network. Off, commands run as the owner's own threads run them, with the bot's permissions and approvals still applied. When it is on but can't start on the bot's computer, the owner gets a card with Turn off sandbox for this bot and, where a package fixes it, Install what's missing. See `docs/plans/bot-sandbox-setting.md`. +- **Command sandbox:** the owner's per-bot setting in About → Sandbox (a dialog) that decides whether a bot's commands run in a sandbox that limits the files they can change, and what network those commands get: Blocked, Public web (public internet sites only) or Direct (this computer's network). Off, commands run as the owner's own threads run them, with the bot's permissions and approvals still applied. When it is on but can't start on the bot's computer, the owner gets a card with Turn off this limit and, where it may help, Repair. See `docs/plans/bot-sandbox-setting.md`. - **Space bot:** a bot a member adds to a Space, which answers in the Space's chat. Its code lives in `bots/space/`, apart from personal bots. - **Grant:** what a bot's owner approved: the tools the bot may use beyond what every bot has, and its limits. The bot works inside its grant without asking. Every bot also has, without a grant, the profiler, Mousse's look, scheduled jobs, secrets the owner gives and quick actions, and, unless switched off in About, every MCP server set up in Mousse, every skill and the automation tools. - **Use your threads:** the bot permission, off by default, to read, search and act on its owner's reachable threads. Work and scheduled runs, their subagents, and chat turns started by creation, an owner message or tap, a wake, a question or a job may act under the grant. A turn from another bot's message is read-only. A thread it starts uses the target computer's default permission mode, capped by device limits. A message uses the target thread's mode. It answers the questions and approvals of the threads it reaches, labelled as its own answers; in a thread it started, those requests don't ping the owner. Private threads and other bots' threads stay out of reach. The owner can switch the permission off in About. See `docs/bots.md`. diff --git a/docs/bots.md b/docs/bots.md index 26ac1f386..b2a3da22c 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -471,7 +471,7 @@ With the sandbox off, a bot that holds "run commands" can read anything its owne ## Command sandbox -The owner decides, per bot, whether its commands run in a sandbox and whether sandboxed commands may use the network: About → Can use, under Run commands, **Sandbox commands** and **Allow network for sandboxed commands** (`bots.sandbox.get` and `.set`; design in [the plan](plans/bot-sandbox-setting.md)). The setting is the bot's own row in `bots.db` (`bot_sandbox`, v19), apart from its grant: no grant, Allow everything or ask changes it, and a bot can't ask for it. Only a person at a Mousse window changes it or asks to install what's missing: locally only the app's window, and from another device only with its router's person mark (`window: person`), as for the system instructions. The bot's computer reads that mark as the calling device's router set it: it can't itself tell that a window made the call, here or for any other person-only method, local or remote (#2052). A device paired at Full can already change the bot's grant from there. +The owner decides, per bot, whether its commands run in a sandbox and whether sandboxed commands may use the network: About → Can use, under Run commands, one **Sandbox** row with its state ("Off", "On · Public web"), which opens the Sandbox dialog: the switch, Files, Network (**Blocked**, **Public web**, **Direct**), Local servers, the bot's secrets and their rules, Approvals (Auto, or Full commands) and a summary of what commands reach, read from the resolver (`bots.sandbox.get` and `.set`; `BotSandboxSettings.tsx`; design in [the plan](plans/bot-sandbox-setting.md)). The dialog names the bot's computer, where the setting is kept. New bot has the same controls as a Sandbox step after Runs on, off by default, written with the bot before its first turn (`bots.create`'s `sandbox`, sent only where the choices carry `sandboxOnCreate`). The setting is the bot's own row in `bots.db` (`bot_sandbox`, v19), apart from its grant: no grant, Allow everything or ask changes it, and a bot can't ask for it. Only a person at a Mousse window changes it or asks to install what's missing: locally only the app's window, and from another device only with its router's person mark (`window: person`), as for the system instructions. The bot's computer reads that mark as the calling device's router set it: it can't itself tell that a window made the call, here or for any other person-only method, local or remote (#2052). A device paired at Full can already change the bot's grant from there. - **One policy per launch.** `BotSandboxResolver` reads the setting with the actual entry (or Mousse's own runner, for background and secret commands) and gives `open`, `held` (with the network) or `unavailable` (why, and whether a package fixes it). Every turn carries it (`BotAuthority.sandbox`), and About, the card and the bot's system text read the same result. - **Off** runs commands as the owner's own threads run them on that provider: no sandbox and no command-network block. The grant gate, approvals and destructive-command cards, bound-secret rules, masking and the filtered command environment stay. @@ -484,15 +484,16 @@ The owner decides, per bot, whether its commands run in a sandbox and whether sa | Pi's `bash`, background commands, secret commands | Mousse's bubblewrap (`mousseHeldSpawn`): the system's folders read-only, the bot's folders writable, a new network namespace only when blocked | `sandbox-exec` with a profile over the same folders: the home folder unreadable but for the bot's folders, writes only to them, the network denied when blocked | unavailable | | Antigravity | unavailable: it has no command sandbox | unavailable | unavailable | -- **Network open on Mousse's runner.** With the network allowed, a command on Mousse's runner uses this computer's own network, so it can reach services listening here (`127.0.0.1`) and on the local network. That is wider than Claude Code's path, whose proxy refuses those addresses. Blocking the network closes both. -- **Network open on Claude Code.** Claude Code's sandbox sends commands' traffic through a proxy that takes only listed hosts, and the pinned CLI refuses a bare `*`. So Mousse runs its own small HTTP proxy on `127.0.0.1` (`connectProxy.ts`), named in the sandbox's `network.httpProxyPort`. It tunnels `CONNECT` without reading the traffic, so `gh` and `git` check certificates as usual, and allows every host for now. It reaches ordinary public addresses only (`refusedAddress`), whatever name leads there. It follows IANA's IPv4 and IPv6 special-purpose address registries and refuses every block in them: loopback, the owner's private network (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`), carrier-grade NAT (`100.64/10`), link-local addresses such as cloud metadata, documentation, benchmarking and reserved ranges, and the anycast service ranges the registry marks globally reachable, since their nearest server can be the owner's own router. It also refuses multicast, IPv6 outside global unicast (`2000::/3`), and any address of this computer's own network cards, read at each request. An IPv6 address that carries an IPv4 address (`::ffff:`, NAT64, 6to4) is judged by that IPv4 address. It looks each name up once, checks every address the name leads to, and connects to the address it checked. Plain `http://` requests follow the same rule. Any program on this computer can connect to the proxy, not only the bot's sandbox: Claude Code takes an outside proxy as a port number alone and gives it no password, so the sandbox has no secret it could show. That is safe because the proxy only reaches what any program here can already reach directly. Blocked is the empty, strict list of hosts. +- **Network choices.** Each launcher says which networks it gives (`BotSandboxSupport.networks`), and the resolver makes any other choice unavailable (`network_mode`) instead of giving a wider or narrower one: Claude Code gives Blocked and Public web; Codex and Mousse's runner give Blocked and Direct. A choice saved as `open` before the split keeps its meaning: the public web on Claude Code, this computer's network on Codex and the runner; the dialog shows no choice picked for it, and a new choice is never `open`. The runner's own launch opens this computer's network only for Direct. A subagent on Direct is never within work held to the public web (`BotCommandHold.publicOnly`). +- **Direct on Mousse's runner and Codex.** A command uses this computer's own network, so it can reach services listening here (`127.0.0.1`) and on the local network, and servers it starts can be reached from this computer. +- **Public web on Claude Code.** Claude Code's sandbox sends commands' traffic through a proxy that takes only listed hosts, and the pinned CLI refuses a bare `*`. So Mousse runs its own small HTTP proxy on `127.0.0.1` (`connectProxy.ts`), named in the sandbox's `network.httpProxyPort`. It tunnels `CONNECT` without reading the traffic, so `gh` and `git` check certificates as usual, and allows every host for now. It reaches ordinary public addresses only (`refusedAddress`), whatever name leads there. It follows IANA's IPv4 and IPv6 special-purpose address registries and refuses every block in them: loopback, the owner's private network (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`), carrier-grade NAT (`100.64/10`), link-local addresses such as cloud metadata, documentation, benchmarking and reserved ranges, and the anycast service ranges the registry marks globally reachable, since their nearest server can be the owner's own router. It also refuses multicast, IPv6 outside global unicast (`2000::/3`), and any address of this computer's own network cards, read at each request. An IPv6 address that carries an IPv4 address (`::ffff:`, NAT64, 6to4) is judged by that IPv4 address. It looks each name up once, checks every address the name leads to, and connects to the address it checked. Plain `http://` requests follow the same rule. Any program on this computer can connect to the proxy, not only the bot's sandbox: Claude Code takes an outside proxy as a port number alone and gives it no password, so the sandbox has no secret it could show. That is safe because the proxy only reaches what any program here can already reach directly. Blocked is the empty, strict list of hosts. - **When it can't start.** Before a turn the sandbox is started for real (`BotEngine.refresh`): the programs on the command's own PATH, WSL 1, user namespaces, and a harmless command in it. Only a start that worked is kept; a real start failure later drops it (`BotAuthority.sandbox.startFailed`). On Claude Code a real start failure is what Claude Code says (`claudeSandboxStartFailure`): its sandbox required but unavailable at its start, its subprocess scrub finding no bubblewrap at its start, "Sandbox is required but failed to initialize" at a command, or bubblewrap's own refusal, such as `bwrap: Can't mkdir /mnt/c/…` on WSL with a Windows drive mounted (the card then names the drive). A turn that fails at its start that way starts again once with its commands refused, so the chat still answers. Then: - the turn's commands don't run, and the bot is told why and what to tell its owner (`botSandboxRefusal`, `botSandboxSystemLine`); - - Mousse posts one card per reason in the chat (`BotSandboxCard`): **Command sandbox unavailable on {computer}**, the reason, "This bot's work is waiting. Mousse checks again on the next turn.", **Turn off sandbox for this bot** and, when a package fixes it, **Install what's missing**. About shows the same state. Each card names the launcher that failed (`provider`, and `entry`: the provider entry, or `mousse` for Mousse's runner) and reads that launcher's own state (`BotSandboxView.entries`), standing as posted while the view has none of it; with the sandbox off every card settles, whatever launcher it names. A card of Mousse's runner, or of a subagent's other entry, keeps its buttons while that launcher can't start, even when the work's provider can, and About shows the runner's state ("background and secret commands can't start") when the work's provider starts (`BotSandboxView.runner`). Install what's missing types the packages every failing launcher needs, the card's own launcher included (`bots.sandbox.install` with the card's `entry`); when the computer has nothing to install for a card, only that card stops offering it; + - Mousse posts one card per reason in the chat (`BotSandboxCard`): **Command sandbox unavailable on {computer}**, the reason, "This bot's work is waiting. Mousse checks again on the next turn.", **Repair** where installing a package or a fresh start may fix it, and **Turn off this limit** (`botSandboxCardActions`). Allow once and Keep allowing need a launch Mousse holds and can let through; they come with Mousse's command runner and never show before. The Sandbox dialog shows the same state. Each card names the launcher that failed (`provider`, and `entry`: the provider entry, or `mousse` for Mousse's runner) and reads that launcher's own state (`BotSandboxView.entries`), standing as posted while the view has none of it; with the sandbox off every card settles, whatever launcher it names. A card of Mousse's runner, or of a subagent's other entry, keeps its buttons while that launcher can't start, even when the work's provider can, and the dialog's summary names the runner's commands ("Background commands: Can't start") when the work's provider starts (`BotSandboxView.runner`). Repair types the packages every failing launcher needs, the card's own launcher included (`bots.sandbox.install` with the card's `entry`); when the computer has nothing to install for a card, only that card stops offering it; - work that met it waits once (`blocked`, end reason `sandbox`), a background or secret command refused by Mousse's runner included (a secret command's real start failure is recorded against the runner, `BotCommandSandbox.runnerFailed`), and carries on when the owner turns the sandbox off, or when a later turn or a recheck finds every launcher it met unavailable starts (`sandbox_ready`): a turn whose provider starts doesn't wake work the runner parked. The launchers it waits for are kept with it (`bot_memory_state`, `sandbox-needs:`), so a restart doesn't narrow them to its provider's. A launcher not probed since the start or a recheck never counts as started, and one that failed may have been fixed: each is probed again before the work carries on (`wakeSandboxWaiters`, `BotSandboxResolver.probed`). A Codex thread setup's finding of the owner's command rules (`command_rules`) is the bot's own: the resolver keeps no launcher-wide failure for it, and reads the rules again for each bot's folder at each resolve. A subagent's entry is probed when it starts and when its turn starts, as a work's turn is. -- **Install what's missing** opens the owner's terminal on the bot's computer with the package manager's command typed, not run (`apt-get`, `dnf`, `pacman` or `zypper`, read from `/etc/os-release`; `bots.sandbox.install`). The owner signs in to `sudo` there; closing the terminal checks again. Mousse ships no helper programs. WSL 1, blocked user namespaces and a provider or OS with no sandbox get no Install button. GitHub sign-in errors and DNS outages are a command's own failures, not the sandbox's. -- **Changing it while work runs.** Tighter (the sandbox on, or the network blocked) stops running work that holds commands and its subagents (`cutForSwitch`), stops the bot's background commands, and closes the chat's warm process. Looser closes the warm process and carries on work that waited for the sandbox. An interrupted command never runs again by itself. The chat's warm key and Codex's thread key include the setting's revision. -- **Defaults.** Every bot starts off, a new one and one from before the setting (`BOT_SANDBOX_DEFAULT`), with the network open for when the owner turns it on. A bot from before the setting gets that row once, when this version first starts (`upgradeSandboxSettings`), with nothing posted in its chat; any later first read writes the same default. +- **Repair**, where a package fixes it, opens the owner's terminal on the bot's computer with the package manager's command typed, not run (`apt-get`, `dnf`, `pacman` or `zypper`, read from `/etc/os-release`; `bots.sandbox.install`). The owner signs in to `sudo` there; closing the terminal checks again. Mousse ships no helper programs. Without a package to install, Repair starts the sandbox again; WSL 1, a network a launcher can't give and a provider or OS with no sandbox get no Repair. GitHub sign-in errors and DNS outages are a command's own failures, not the sandbox's. +- **Changing it while work runs.** Tighter (the sandbox on, or any network change that is not only wider, `botSandboxNetworkWidens`) stops running work that holds commands and its subagents (`cutForSwitch`), stops the bot's background commands, and closes the chat's warm process. Looser closes the warm process and carries on work that waited for the sandbox. An interrupted command never runs again by itself. The chat's warm key and Codex's thread key include the setting's revision. + - **Moving.** The setting moves with the bot (bundle format 3), its revision starting again at 1. The target checks support at the first turn. An older Mousse refuses a format 3 bundle at its commit, so the bot stays where it was. ## Files diff --git a/docs/plans/bot-sandbox-setting.md b/docs/plans/bot-sandbox-setting.md index cc539e9a0..309023ee0 100644 --- a/docs/plans/bot-sandbox-setting.md +++ b/docs/plans/bot-sandbox-setting.md @@ -14,7 +14,7 @@ A sandbox the owner can't switch off is not useful. Every restriction here can b - One revisioned row per bot in `/bots/bots.db` (`bot_sandbox`, schema v19), apart from `bot_grants`: - `sandbox`: `on` or `off`; - - `network`: a typed value, `{ kind: 'blocked' }` or `{ kind: 'open' }`, with room for `{ kind: 'sites', sites }` later. It is kept while the sandbox is off. + - `network`: a typed value, `{ kind: 'blocked' }`, `{ kind: 'public' }` (the public web through Mousse's proxy) or `{ kind: 'direct' }` (this computer's network), with room for `{ kind: 'sites', sites }` later. A row saved before the split keeps `{ kind: 'open' }`, which each launcher gives as it did: the public web on Claude Code, this computer's network on Codex and Mousse's runner. It is kept while the sandbox is off. - It is never part of a grant's digest, never asked for by a bot, and **Allow everything** leaves it alone. - **Owner only.** `bots.sandbox.set` and the install action are called only from the owner's Mousse window: locally only by the app window, and from another device only with the person key its router adds for a window's call (as for the system instructions). A bot, a thread it started, the command line or an ordinary agent call can't change it. @@ -89,6 +89,22 @@ The setting travels in the bot's bundle (bundle format 3). The destination check - **Existing bots** get that row once, when this version first starts, after which no code reads "unset". Nothing is posted in their chats. - **The network choice** stored with Off is open, so a bot the owner turns On has the network until they block it. Where On can't start, the card shows. +## Network choices + +Each launcher declares the networks it gives; any other choice is `unavailable` (`network_mode`), never swapped for a wider or narrower one: + +| Launcher | Blocked | Public web | Direct | saved `open` | +|---|---|---|---|---| +| Claude Code | yes | yes, Mousse's proxy | unavailable | Public web | +| Codex | yes | unavailable | yes | Direct | +| Mousse's runner (Pi, background, secret) | yes | unavailable until the proxy relay ships | yes | Direct | + +## The owner's view + +About → Can use has one **Sandbox** row with its state ("Off", "On · Public web", "On · Can't start"). It opens a dialog on the modal surface that names the bot's computer and holds every setting: the switch, Files (the bot's folders; owner-granted folders fill this section later), Network, Local servers (what holds now; opening one to the owner's browser comes later), the bot's secrets with each one's rule, Approvals (Auto, or Full commands, the permission the owner allows on a card) and a summary of what commands reach, from the resolver. New bot shows the same controls as a step after Runs on, off by default, and the bot is written with them before its first turn. + +The words below are from the first version, before the dialog; button names are now **Repair** and **Turn off this limit**. + ## Words **About → Can use**, under Run commands: diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 6c8369d5c..17dfd1935 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -136,7 +136,7 @@ import { BotSandboxResolver, type BotSandboxSupport, type BotSandboxTarget } fro import { mousseRunnerSupport } from '../sandbox/runnerSupport' import { heldStartFailure, mousseHeldSpawn } from '../sandbox/mousseRunner' import { sandboxInstallCommand } from '../sandbox/install' -import { BOT_SANDBOX_DEFAULT, BOT_SANDBOX_RUNTIME_NAMES, botSandboxCard, botSandboxRefusal, botSandboxSystemLine, type BotSandboxLaunch, type BotSandboxNetwork, type BotSandboxPolicy, type BotSandboxSetting, type BotSandboxUnavailable, type BotSandboxView } from '../../../shared/bots/personal/sandbox' +import { BOT_SANDBOX_DEFAULT, BOT_SANDBOX_RUNTIME_NAMES, botSandboxCard, botSandboxNetworkWidens, botSandboxRefusal, botSandboxSystemLine, type BotSandboxLaunch, type BotSandboxNetwork, type BotSandboxPolicy, type BotSandboxReach, type BotSandboxSetting, type BotSandboxUnavailable, type BotSandboxView } from '../../../shared/bots/personal/sandbox' import type { BotCommandSandbox } from '../../../shared/bots/personal/authority' import { BOT_OFFERS_REPORTED, MAX_OFFERS_PER_TURN, MAX_OFFER_TO_CHARS, OFFER_ROW_PREFIX, RECENT_OFFERS_LISTED, RECENT_OFFERS_WINDOW_MS, RECENT_OFFER_ROWS_READ, isOffersTaken, isRunToken, offerMessageProblem, offerRowText, offerShownState, plainOfferName, type BotOfferCard, type BotOfferOutcome, type BotRecentOffer } from '../../../shared/bots/personal/offers' import { MAX_BOT_MESSAGE_CHARS, MAX_BOT_MESSAGES_UNANSWERED_BY_OWNER, botAddressName, botMessageInput, botMessageKey, botMessageRowId, botMessageRowText, botNamed, otherComputerNote, type BotMessageSender, type OtherComputerBotsStatus } from '../../../shared/bots/personal/botMessages' @@ -4557,12 +4557,26 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { this.wakeSandboxWaiters(botId, true) // Every other launcher a card was posted for, read as it stands: its card shows its own state (`BotSandboxView.entries`). const entries: Record = {} - for (const entry of this.sandboxCards.get(botId)?.keys() ?? []) entries[entry] = this.sandboxes.resolveNow(botId, sandboxTargetOf(entry), entry === RUNNER_ENTRY ? 'watcher' : 'work') + // A recheck (Repair) starts each card's launcher again too, so one fixed since shows started. + for (const entry of [...(this.sandboxCards.get(botId)?.keys() ?? [])]) { + const launch = entry === RUNNER_ENTRY ? 'watcher' : 'work' + entries[entry] = options.recheck ? await this.sandboxes.resolve(botId, sandboxTargetOf(entry), launch) : this.sandboxes.resolveNow(botId, sandboxTargetOf(entry), launch) + if (options.recheck && entries[entry].kind !== 'unavailable') this.sandboxCards.get(botId)?.delete(entry) + } entries[sandboxEntry(target)] = policy if (runner) entries[RUNNER_ENTRY] = runner const support = instanceId ? this.host.harness.botSandbox?.(instanceId) : undefined const provider = support ? BOT_SANDBOX_RUNTIME_NAMES[support.runtime] : instanceId ? (this.host.providerLabel?.(instanceId) ?? 'This provider') : 'Mousse' - return { setting: this.sandboxSetting(botId), computer: this.sandboxComputer(), provider, policy, ...(runner ? { runner } : {}), entries } + // How far held commands reach, for the Sandbox dialog's summary: what the subagent rule measures, in its words. + const reachOf = (held: BotSandboxPolicy | undefined, of: BotSandboxTarget): BotSandboxReach | undefined => { + if (held?.kind !== 'held') return undefined + const hold = this.sandboxes.reach(botId, of) + return hold ? { reads: hold.reads, servers: hold.network && !hold.publicOnly } : undefined + } + const work = reachOf(policy, target) + const runs = runner ? reachOf(runner, { runner: 'mousse' }) : undefined + const reach = work || runs ? { ...(work ? { work } : {}), ...(runs ? { runner: runs } : {}) } : undefined + return { setting: this.sandboxSetting(botId), computer: this.sandboxComputer(), provider, policy, ...(runner ? { runner } : {}), entries, ...(reach ? { reach } : {}) } } /** @@ -4579,7 +4593,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if ('stale' in result) throw new BotEngineError('stale', 'This setting changed on another device. Look again, then change it.', { setting: result.stale }) if (result.changed) { const after = result.setting - const tighter = (before.sandbox === 'off' && after.sandbox === 'on') || (after.sandbox === 'on' && before.network.kind === 'open' && after.network.kind === 'blocked') + const tighter = (before.sandbox === 'off' && after.sandbox === 'on') || (after.sandbox === 'on' && !botSandboxNetworkWidens(before.network.kind, after.network.kind)) this.sandboxCards.delete(botId) this.sandboxes.recheck() this.releaseChatProcess(botId) @@ -10706,15 +10720,15 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { * Publish a new bot and set up its home thread and files folder. Pressing Create bot approves * the starter grant. Built-in bots wait for an owner message and start with an empty chat. */ - createBot(definition: BotDefinition, firstTurn?: { key: string; input: string }): void { + createBot(definition: BotDefinition, firstTurn?: { key: string; input: string }, sandbox?: Omit): void { if (this.store.registry(definition.id)) throw new BotEngineError('bot_exists', 'A bot with that id exists already.') const revision = this.definitionCall(() => this.host.definitions.publishRevision(definition)) this.host.definitions.save(revision) this.store.db.transaction(() => { this.store.ensureRegistry(definition.id) - // A new bot's commands run as its owner's own threads' do until the owner turns the sandbox on + // New bot's Sandbox step (`sandbox`), else off, running commands as its owner's own threads do // (docs/plans/bot-sandbox-setting.md, "Defaults"). - this.store.initSandboxSetting(definition.id, BOT_SANDBOX_DEFAULT) + this.store.initSandboxSetting(definition.id, sandbox ?? BOT_SANDBOX_DEFAULT) this.store.setPublished(definition.id, revision.revision!) if (!isBuiltInBot(revision)) { if (firstTurn) this.store.recordCreation(definition.id, firstTurn.key, firstTurn.input) diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index 2306cffe5..35fb38baa 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -1,4 +1,4 @@ -import type { BotSandboxNetwork, BotSandboxView } from '../../../shared/bots/personal/sandbox' +import type { BotSandboxNetwork, BotSandboxView, NewBotSandbox } from '../../../shared/bots/personal/sandbox' import { BOT_OFFER_REFUSALS, BOT_OFFERS_REPORTED, MAX_OFFERS_KEPT_PER_HOUR, OFFERED_ROW_PREFIX, OFFER_ALLOWED_DROPPED_LINE, isOffersTaken, isRunToken, offeredRowText, type BotOfferDelivered, type BotOfferOutcome, type BotOfferRecipient, type BotOfferRefusal } from '../../../shared/bots/personal/offers' import type { BotOfferAccessStore } from '../definitions/BotOfferAccessStore' import { PageChecks } from '../pageChecks' @@ -488,9 +488,10 @@ export class BotChatService { * before rows sends one `model` by name (on every row), and one from before picks none (by usage). * `access`: which devices reach it (New bot's Devices step, or the device that made it). Absent, this computer alone; * an older app's Everywhere (`all`) is this computer alone too. It is saved before the bot is published, so a device - * outside it never lists the bot, not even for a moment; a repeat that finds the bot made changes nothing. + * outside it never lists the bot, not even for a moment; a repeat that finds the bot made changes nothing. `sandbox`: New + * bot's Sandbox step, written with the bot, before its first turn; absent, the default. */ - async create(input: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess }): Promise<{ bot: BotSummary }> { + async create(input: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; sandbox?: NewBotSandbox }): Promise<{ bot: BotSummary }> { const access = input.access ? newBotAccessOf(input.access) : DEFAULT_BOT_DEVICE_ACCESS if (input.access) { const problem = botDeviceAccessProblem(access) @@ -557,7 +558,7 @@ export class BotChatService { // which the next start takes off (`BotDeviceAccessStore.dropBots`); a retry makes the bot under a new id. const held = this.holdNewBot(botId, access) try { - this.engine.createBot(definition, { key, input: firstMessagePrompt(description, !named.chosen) }) + this.engine.createBot(definition, { key, input: firstMessagePrompt(description, !named.chosen) }, input.sandbox ? { sandbox: input.sandbox.sandbox, network: { kind: input.sandbox.network.kind } } : undefined) } catch (error) { // Not published: its choice goes too. Published but a later step failed: the choice stays with the bot. if (held && !this.store.registry(botId)) { @@ -1355,7 +1356,7 @@ export class BotChatService { const pick = slots[row] return pick && !isPinned(pick) ? [[row, pick.model]] : [] })) as Partial> - const { last: _last, reachOnCreate: _reach, devices: _devices, ...offered } = choices + const { last: _last, reachOnCreate: _reach, sandboxOnCreate: _sandbox, devices: _devices, ...offered } = choices const images = this.options.images ? { image: shownPick(this.engine.imagePick(botId)), images: this.options.images.usage(botId) } : {} // The custom slots, their picks shown as the rows' are: never what the sign-in was. const custom = this.engine.customSlots(botId).map((slot) => ({ name: slot.name, pick: shownPick(slot.pick)!, ...(slot.description ? { description: slot.description } : {}) })) @@ -1406,6 +1407,7 @@ export class BotChatService { ...imageChoices, ...(last ? { last: { talk: offeredNow(last.talk), light: offeredNow(last.light), medium: offeredNow(last.medium), hard: offeredNow(last.hard) } } : {}), ...(this.options.deviceAccess ? { reachOnCreate: true as const } : {}), + sandboxOnCreate: true, ...(devices.length ? { devices } : {}), computer: 'this_computer', computers: this.computerChoices('new') diff --git a/src/mms/bots/registerMethods.ts b/src/mms/bots/registerMethods.ts index c322ce704..5d5718eaa 100644 --- a/src/mms/bots/registerMethods.ts +++ b/src/mms/bots/registerMethods.ts @@ -1,4 +1,4 @@ -import { isBotSandboxNetwork, type BotSandboxNetwork } from '../../shared/bots/personal/sandbox' +import { isBotSandboxNetwork, isNewBotSandbox, type BotSandboxNetwork, type NewBotSandbox } from '../../shared/bots/personal/sandbox' import { BOT_ASK_ANSWERS, BOT_WEB_PICTURE_PIECE_BYTES, MAX_BOT_CHAT_ATTACHMENTS, MAX_BOT_CHAT_PAGE, MAX_BOT_CHAT_TEXT, type BotAskAnswer, type BotChatAttachment, type BotsPersonalV2Method } from '../../shared/bots/personal/methods' import { BOT_FILE_MAX_WIDTH, BOT_FILE_MIN_WIDTH } from '../../shared/bots/personal/remoteFiles' import { MAX_BOT_CUSTOM_SLOT_DESCRIPTION, MAX_BOT_DESCRIPTION_CHARS, MAX_BOT_MODEL_CHARS, MAX_BOT_NAME_CHARS, MAX_BOT_SYSTEM_TEXT_BYTES, type BotModelPick, type BotModelSlots, type BotSchedule } from '../../shared/bots/personal/definition' @@ -102,6 +102,8 @@ function validate(method: BotsPersonalV2Method, value: unknown): Params { if (p.image !== undefined) imagePick(p.image) // New bot's Devices step: this computer alone, or with the devices ticked (`all`, from an older app, is this computer). if (p.access !== undefined && !isNewBotAccess(p.access)) throw new DomainRpcError('invalid_params', 'A new bot reaches this computer, and the devices picked for it') + // New bot's Sandbox step: on or off, with a network the owner can choose now. + if (p.sandbox !== undefined && !isNewBotSandbox(p.sandbox)) throw new DomainRpcError('invalid_params', 'sandbox is { sandbox: on or off, network: { kind: blocked, public or direct } }') break case 'bots.facePicture.save': if (!isFacePictureKey(p.key)) throw new DomainRpcError('invalid_params', 'A face picture key is 1 to 512 printable characters') @@ -222,7 +224,7 @@ function validate(method: BotsPersonalV2Method, value: unknown): Params { break case 'bots.sandbox.set': if (p.sandbox !== undefined && p.sandbox !== 'on' && p.sandbox !== 'off') throw new DomainRpcError('invalid_params', 'sandbox is on or off') - if (p.network !== undefined && !(isBotSandboxNetwork(p.network) && Object.keys(p.network as object).length === 1)) throw new DomainRpcError('invalid_params', 'network is { kind: blocked } or { kind: open }') + if (p.network !== undefined && !(isBotSandboxNetwork(p.network) && Object.keys(p.network as object).length === 1)) throw new DomainRpcError('invalid_params', 'network is { kind: blocked }, { kind: public } or { kind: direct }') if (p.expectedRevision !== undefined && !(Number.isInteger(p.expectedRevision) && (p.expectedRevision as number) >= 1)) throw new DomainRpcError('invalid_params', 'expectedRevision is a revision number') if (p.sandbox === undefined && p.network === undefined) throw new DomainRpcError('invalid_params', 'Give sandbox, network or both') break @@ -247,7 +249,7 @@ async function handle(method: BotsPersonalV2Method, p: Params, bots: BotChatServ const botId = p.botId as string switch (method) { case 'bots.personal.list': return bots.list() - case 'bots.create': return bots.create({ look: p.look as BotLook, ...(typeof p.name === 'string' && p.name.trim() ? { name: p.name } : {}), description: p.description as string, clientRequestId: p.clientRequestId as string, ...(typeof p.model === 'string' ? { model: p.model.trim() } : {}), ...(p.slots !== undefined ? { slots: p.slots as BotModelSlots } : {}), ...(p.image !== undefined ? { image: p.image as BotModelPick } : {}), ...(p.access !== undefined ? { access: p.access as NewBotAccess } : {}) }) + case 'bots.create': return bots.create({ look: p.look as BotLook, ...(typeof p.name === 'string' && p.name.trim() ? { name: p.name } : {}), description: p.description as string, clientRequestId: p.clientRequestId as string, ...(typeof p.model === 'string' ? { model: p.model.trim() } : {}), ...(p.slots !== undefined ? { slots: p.slots as BotModelSlots } : {}), ...(p.image !== undefined ? { image: p.image as BotModelPick } : {}), ...(p.access !== undefined ? { access: p.access as NewBotAccess } : {}), ...(p.sandbox !== undefined ? { sandbox: p.sandbox as NewBotSandbox } : {}) }) case 'bots.get': return bots.get(botId) case 'bots.update': return bots.update(botId, { ...(p.name !== undefined ? { name: p.name as string } : {}), ...(p.look !== undefined ? { look: p.look as BotLook } : {}), ...(p.description !== undefined ? { description: p.description as string | null } : {}) }) case 'bots.systemInstructions.get': return bots.systemInstructionsGet(botId) diff --git a/src/mms/bots/sandbox/BotSandboxResolver.ts b/src/mms/bots/sandbox/BotSandboxResolver.ts index 3b3ff329c..8c6fac8e6 100644 --- a/src/mms/bots/sandbox/BotSandboxResolver.ts +++ b/src/mms/bots/sandbox/BotSandboxResolver.ts @@ -1,5 +1,5 @@ import type { BotCommandHold } from '../../../shared/bots/personal/subagentHold' -import { BOT_SANDBOX_RUNTIME_NAMES, type BotSandboxLaunch, type BotSandboxNetwork, type BotSandboxPolicy, type BotSandboxRuntime, type BotSandboxSetting, type BotSandboxUnavailable } from '../../../shared/bots/personal/sandbox' +import { BOT_SANDBOX_RUNTIME_NAMES, type BotSandboxGivenNetwork, type BotSandboxLaunch, type BotSandboxNetwork, type BotSandboxNetworkKind, type BotSandboxPolicy, type BotSandboxRuntime, type BotSandboxSetting, type BotSandboxUnavailable } from '../../../shared/bots/personal/sandbox' /** * How a runtime runs a bot's commands in a sandbox on this computer (`HarnessDriver.botSandbox`, and Mousse's own runner @@ -7,18 +7,23 @@ import { BOT_SANDBOX_RUNTIME_NAMES, type BotSandboxLaunch, type BotSandboxNetwor */ export interface BotSandboxSupport { runtime: BotSandboxRuntime + /** + * The networks it gives held commands (`gives`), and which of them a saved `open` means here (`open`). The resolver + * makes any other choice unavailable (`network_mode`), and hands the probe, `reach` and the launch only what it gives. + */ + networks: { gives: readonly BotSandboxNetworkKind[]; open: Exclude } /** * A real start of the sandbox here with `network`, through the launcher's own program, PATH and environment: undefined * when it started, else why not. Must not throw. */ - probe(network: BotSandboxNetwork): Promise + probe(network: BotSandboxGivenNetwork): Promise /** * Why it can't hold commands here at all, without starting anything (the OS, the runtime, the owner's settings for the * bot's own work: Codex's command rules): undefined when it might. */ - unsupported?(network: BotSandboxNetwork, bot?: BotSandboxBot): BotSandboxUnavailable | undefined + unsupported?(network: BotSandboxGivenNetwork, bot?: BotSandboxBot): BotSandboxUnavailable | undefined /** How far a held command reaches here (for the subagent hold rule). */ - reach(network: BotSandboxNetwork): BotCommandHold + reach(network: BotSandboxGivenNetwork): BotCommandHold /** Held commands can still read other files (Codex on Windows). */ readsAll?: boolean /** @@ -61,7 +66,7 @@ export class BotSandboxResolver { folder?(botId: string): string | undefined }) {} - private keyOf(support: BotSandboxSupport, network: BotSandboxNetwork): string { + private keyOf(support: BotSandboxSupport, network: BotSandboxGivenNetwork): string { return `${support.runtime}\u0000${support.key}\u0000${network.kind}` } @@ -71,11 +76,12 @@ export class BotSandboxResolver { const support = this.deps.support(target) const early = this.decided(botId, setting, support, launch) if (early) return early - const key = this.keyOf(support!, setting.network) + const network = givenNetwork(setting.network, support!) + const key = this.keyOf(support!, network) if (!this.started.has(key)) { let probe = this.probing.get(key) if (!probe) { - probe = support!.probe(setting.network).catch((error: unknown) => ({ reason: 'start_failed', provider: BOT_SANDBOX_RUNTIME_NAMES[support!.runtime], repair: 'none', detail: error instanceof Error ? error.message : String(error) }) as BotSandboxUnavailable) + probe = support!.probe(network).catch((error: unknown) => ({ reason: 'start_failed', provider: BOT_SANDBOX_RUNTIME_NAMES[support!.runtime], repair: 'none', detail: error instanceof Error ? error.message : String(error) }) as BotSandboxUnavailable) this.probing.set(key, probe) void probe.finally(() => this.probing.delete(key)) } @@ -100,18 +106,24 @@ export class BotSandboxResolver { const support = this.deps.support(target) const early = this.decided(botId, setting, support, launch) if (early) return early - const failure = this.failed.get(this.keyOf(support!, setting.network)) + const network = givenNetwork(setting.network, support!) + const failure = this.failed.get(this.keyOf(support!, network)) if (failure) return { kind: 'unavailable', revision: setting.revision, ...failure } - return { kind: 'held', revision: setting.revision, network: { ...setting.network }, ...(support!.readsAll ? { readsAll: true as const } : {}) } + return { kind: 'held', revision: setting.revision, network, ...(support!.readsAll ? { readsAll: true as const } : {}) } } - /** Off, or a launcher with no sandbox here: decided without a probe. */ + /** Off, a launcher with no sandbox here, or a network it can't give: decided without a probe. */ private decided(botId: string, setting: BotSandboxSetting, support: BotSandboxSupport | undefined, _launch: BotSandboxLaunch): BotSandboxPolicy | undefined { if (setting.sandbox === 'off') return { kind: 'open', revision: setting.revision } if (!support) return { kind: 'unavailable', revision: setting.revision, reason: 'start_failed', provider: 'This provider', repair: 'none' } const folder = this.deps.folder?.(botId) - const unsupported = support.unsupported?.(setting.network, folder !== undefined ? { folder } : {}) - return unsupported ? { kind: 'unavailable', revision: setting.revision, ...unsupported } : undefined + const network = givenNetwork(setting.network, support) + const unsupported = support.unsupported?.(network, folder !== undefined ? { folder } : {}) + if (unsupported) return { kind: 'unavailable', revision: setting.revision, ...unsupported } + // Never a wider or narrower network in place of the one chosen. + if (!support.networks.gives.includes(network.kind)) + return { kind: 'unavailable', revision: setting.revision, reason: 'network_mode', provider: BOT_SANDBOX_RUNTIME_NAMES[support.runtime], network: network.kind, repair: 'none' } + return undefined } /** @@ -125,7 +137,7 @@ export class BotSandboxResolver { // are read again at each resolve for the bot's own folder (`unsupported`), so another bot on the launcher never // reads them, and the bot itself reads them gone once they are. if (unavailable.reason === 'command_rules') return - const key = this.keyOf(support, this.deps.setting(botId).network) + const key = this.keyOf(support, givenNetwork(this.deps.setting(botId).network, support)) this.started.delete(key) this.failed.set(key, unavailable) } @@ -139,7 +151,7 @@ export class BotSandboxResolver { const setting = this.deps.setting(botId) const support = this.deps.support(target) if (this.decided(botId, setting, support, 'work')) return true - const key = this.keyOf(support!, setting.network) + const key = this.keyOf(support!, givenNetwork(setting.network, support!)) return this.started.has(key) || this.failed.has(key) } @@ -150,6 +162,12 @@ export class BotSandboxResolver { /** How far a held command of `target` reaches here, for the subagent hold rule; undefined for an unknown launcher. */ reach(botId: string, target: BotSandboxTarget): BotCommandHold | undefined { - return this.deps.support(target)?.reach(this.deps.setting(botId).network) + const support = this.deps.support(target) + return support?.reach(givenNetwork(this.deps.setting(botId).network, support)) } } + +/** The network `support` is asked to give for the owner's choice: a saved `open` is what it meant there. */ +export function givenNetwork(network: BotSandboxNetwork, support: Pick): BotSandboxGivenNetwork { + return { kind: network.kind === 'open' ? support.networks.open : network.kind } +} diff --git a/src/mms/bots/sandbox/claudeSupport.ts b/src/mms/bots/sandbox/claudeSupport.ts index ce52d64a8..2f3d3f272 100644 --- a/src/mms/bots/sandbox/claudeSupport.ts +++ b/src/mms/bots/sandbox/claudeSupport.ts @@ -1,5 +1,5 @@ import { readFileSync } from 'node:fs' -import { botSandboxOsName, type BotSandboxNetwork, type BotSandboxPackage, type BotSandboxUnavailable } from '../../../shared/bots/personal/sandbox' +import { botSandboxOsName, type BotSandboxGivenNetwork, type BotSandboxPackage, type BotSandboxUnavailable } from '../../../shared/bots/personal/sandbox' import type { BotSandboxSupport } from './BotSandboxResolver' import { sharedBotConnectProxy } from './connectProxy' import { SANDBOX_EXEC } from './mousseRunner' @@ -37,7 +37,7 @@ export function windowsDriveMounted(read: () => string = () => readFileSync('/pr * bot-sandbox-setting.md): Seatbelt on macOS, bubblewrap and socat on Linux and WSL 2, none on Windows. The probe * starts what Claude Code starts, with the entry's own PATH (Claude Code looks `bwrap` and `socat` up there, never in * the extra folders Mousse searches for programs): a harmless command in bubblewrap, or under `sandbox-exec`. With the - * network open it also starts Mousse's proxy (`sharedBotConnectProxy`), which the sandbox's `network.httpProxyPort` + * public web it also starts Mousse's proxy (`sharedBotConnectProxy`), which the sandbox's `network.httpProxyPort` * names. `lockedEvidence`: a locked entry holds commands in the sandbox only with evidence for the Claude Code version * it runs here. */ @@ -59,8 +59,8 @@ export function claudeSandboxSupport(input: { const run = input.run ?? runProbe const proxy = input.proxy ?? sharedBotConnectProxy /** The proxy of an open network starts, or why the sandbox can't use it. */ - const proxyStarts = async (network: BotSandboxNetwork): Promise => { - if (network.kind !== 'open') return undefined + const proxyStarts = async (network: BotSandboxGivenNetwork): Promise => { + if (network.kind !== 'public') return undefined try { await proxy() return undefined @@ -70,6 +70,8 @@ export function claudeSandboxSupport(input: { } return { runtime: 'claude', + // Its sandbox reaches the network only through a proxy: Mousse's, which takes public addresses only. + networks: { gives: ['blocked', 'public'], open: 'public' }, key: `${platform}\u0000${env.PATH ?? env.Path ?? ''}\u0000${input.cliPath ?? ''}`, unsupported: () => (platform === 'linux' || platform === 'darwin' ? undefined : { reason: 'unsupported_os', provider: CLAUDE_SANDBOX_PROVIDER, os: botSandboxOsName(platform), repair: 'none' }), probe: async (network) => { @@ -92,8 +94,8 @@ export function claudeSandboxSupport(input: { }, // Linux: the system's folders and the bot's are readable, and /tmp is shared; macOS: everything but the home folder. reach: (network) => platform === 'linux' - ? { reads: 0, writes: 0, network: network.kind === 'open', sharedTemp: true } - : { reads: 1, writes: 0, network: network.kind === 'open' } + ? { reads: 0, writes: 0, network: network.kind !== 'blocked', publicOnly: true, sharedTemp: true } + : { reads: 1, writes: 0, network: network.kind !== 'blocked', publicOnly: true } } } diff --git a/src/mms/bots/sandbox/mousseRunner.ts b/src/mms/bots/sandbox/mousseRunner.ts index 464c88a20..10db3800e 100644 --- a/src/mms/bots/sandbox/mousseRunner.ts +++ b/src/mms/bots/sandbox/mousseRunner.ts @@ -113,9 +113,11 @@ export function bubblewrapArgs( input: MousseRunnerFolders & { network: BotSandboxNetwork }, fs: { exists(path: string): boolean; link(path: string): string | undefined } = { exists: existsSync, link: symbolicLink } ): string[] { - const args = ['--die-with-parent', '--new-session', ...(input.network.kind === 'blocked' ? ['--unshare-net'] : []), '--unshare-pid', '--unshare-ipc', '--unshare-uts'] + // This computer's network only for Direct (or a saved `open`, which is Direct here): anything else gets none. + const host = input.network.kind === 'direct' || input.network.kind === 'open' + const args = ['--die-with-parent', '--new-session', ...(host ? [] : ['--unshare-net']), '--unshare-pid', '--unshare-ipc', '--unshare-uts'] const special = new Set(['/proc', '/dev', '/sys', '/tmp']) - for (const folder of [...LINUX_SYSTEM_FOLDERS.filter((path) => !special.has(path)), ...LINUX_RUN_KEPT_OPEN, ...(input.network.kind === 'open' ? LINUX_RESOLVER_FOLDERS : [])]) { + for (const folder of [...LINUX_SYSTEM_FOLDERS.filter((path) => !special.has(path)), ...LINUX_RUN_KEPT_OPEN, ...(host ? LINUX_RESOLVER_FOLDERS : [])]) { if (!fs.exists(folder)) continue const target = fs.link(folder) if (target !== undefined) args.push('--symlink', target, folder) @@ -169,7 +171,7 @@ export function seatbeltProfile(input: { writable: readonly string[]; readable: ...(mine.length ? [`(allow file-read* ${mine.map((path) => `(subpath ${sbString(path)})`).join(' ')})`] : []), '(deny file-write*)', `(allow file-write* (literal "/dev/null") (literal "/dev/zero") (literal "/dev/dtracehelper") (regex #"^/dev/tty") (regex #"^/dev/fd/")${input.writable.map((path) => ` (subpath ${sbString(path)})`).join('')})`, - ...(input.network.kind === 'blocked' ? ['(deny network-outbound (remote ip))', '(deny network-inbound (local ip))', '(deny network-bind (local ip))', '(deny network-outbound (literal "/private/var/run/mDNSResponder"))'] : []) + ...(input.network.kind !== 'direct' && input.network.kind !== 'open' ? ['(deny network-outbound (remote ip))', '(deny network-inbound (local ip))', '(deny network-bind (local ip))', '(deny network-outbound (literal "/private/var/run/mDNSResponder"))'] : []) ] return lines.join('\n') } diff --git a/src/mms/bots/sandbox/runnerSupport.ts b/src/mms/bots/sandbox/runnerSupport.ts index 5428729be..3514fdd3a 100644 --- a/src/mms/bots/sandbox/runnerSupport.ts +++ b/src/mms/bots/sandbox/runnerSupport.ts @@ -1,4 +1,4 @@ -import type { BotSandboxNetwork, BotSandboxRuntime } from '../../../shared/bots/personal/sandbox' +import type { BotSandboxGivenNetwork, BotSandboxRuntime } from '../../../shared/bots/personal/sandbox' import { botSandboxOsName } from '../../../shared/bots/personal/sandbox' import type { BotSandboxSupport } from './BotSandboxResolver' import { probeMousseRunner } from './mousseRunner' @@ -16,13 +16,15 @@ export function mousseRunnerSupport(input: { platform: NodeJS.Platform; env: Nod const provider = runtime === 'pi' ? 'Pi' : 'Mousse' return { runtime, + // No proxy route yet: the network is none, or this computer's as it is. + networks: { gives: ['blocked', 'direct'], open: 'direct' }, key: `${platform}\u0000${env.PATH ?? env.Path ?? ''}`, unsupported: () => (platform === 'linux' || platform === 'darwin' ? undefined : { reason: 'unsupported_os', provider, os: botSandboxOsName(platform), repair: 'none' }), - probe: async (network: BotSandboxNetwork) => { + probe: async (network: BotSandboxGivenNetwork) => { const failed = await probeMousseRunner({ platform, env, network, ...(input.run ? { run: input.run } : {}) }) return failed ? { ...failed, provider } : undefined }, // Linux: the system's folders and the bot's only; macOS: everything but the home folder, as Claude Code's Seatbelt. - reach: (network) => ({ reads: platform === 'linux' ? 0 : 1, writes: 0, network: network.kind === 'open' }) + reach: (network) => ({ reads: platform === 'linux' ? 0 : 1, writes: 0, network: network.kind !== 'blocked' }) } } diff --git a/src/mms/bridge/remote/RemoteBots.ts b/src/mms/bridge/remote/RemoteBots.ts index e8fd04ed4..cd4c29fa2 100644 --- a/src/mms/bridge/remote/RemoteBots.ts +++ b/src/mms/bridge/remote/RemoteBots.ts @@ -12,7 +12,7 @@ import { MAX_CHOICE_LABEL_CHARS } from '../../../shared/bots/personal/questions' import type { BotLook } from '../../../shared/bots/personal/look' import { BOT_ASK_ANSWERS, MAX_BOT_CHAT_ATTACHMENTS, MAX_BOT_CHAT_PAGE, type BotAskAnswer, type BotRunsOnChoices, type BotsPersonalV2Api } from '../../../shared/bots/personal/methods' import { BOT_PERSON_KEY, REMOTE_BOT_METHOD_NAMES, remoteBotLevel, remoteBotMethod, type RemoteBotMethod } from '../../../shared/bots/personal/methodTable' -import { isBotSandboxNetwork, type BotSandboxNetwork } from '../../../shared/bots/personal/sandbox' +import { isBotSandboxNetwork, isNewBotSandbox, type BotSandboxNetwork, type NewBotSandbox } from '../../../shared/bots/personal/sandbox' import { botLevelReaches, type BotLevel } from '../../../shared/net/local' import { BOT_FULL_TRUST_PERMISSION } from '../../../shared/bots/personal/manifest' import type { BotChatService } from '../../bots/chat/BotChatService' @@ -356,7 +356,7 @@ export function validateRemoteBotParams(method: RemoteBotMethod, value: unknown) if (p[BOT_PERSON_KEY] !== 'person') throw new NetError('forbidden', 'Only a person at a Mousse window reads or edits this.', { details: { reason: 'person_only' } }) break - // About → Can use → Sandbox commands: a person at a Mousse window only, as for the system instructions. + // About → Sandbox: a person at a Mousse window only, as for the system instructions. case 'bots.sandbox.set': if (p.sandbox !== undefined) ok(p.sandbox === 'on' || p.sandbox === 'off') if (p.network !== undefined) ok(isBotSandboxNetwork(p.network) && Object.keys(p.network as object).length === 1) @@ -382,6 +382,7 @@ export function validateRemoteBotParams(method: RemoteBotMethod, value: unknown) if (p.slots !== undefined) ok(modelRowsProblem(p.slots, { all: true }) === undefined) if (p.image !== undefined) ok(imagePickOf(p.image)) if (p.access !== undefined) ok(botDeviceAccessProblem(p.access) === undefined) + if (p.sandbox !== undefined) ok(isNewBotSandbox(p.sandbox)) break case 'bots.update': ok(p.name !== undefined || p.look !== undefined || p.description !== undefined) @@ -1466,6 +1467,7 @@ export function remoteBotMethods(options: { clientRequestId: p.clientRequestId as string, ...(p.slots !== undefined ? { slots: p.slots as BotModelSlots } : {}), ...(p.image !== undefined ? { image: p.image as BotModelPick } : {}), + ...(p.sandbox !== undefined ? { sandbox: p.sandbox as NewBotSandbox } : {}), access }) remember(context.execution, bot.id) diff --git a/src/mms/harness/drivers/antigravity.ts b/src/mms/harness/drivers/antigravity.ts index 57953de7b..28d5a489c 100644 --- a/src/mms/harness/drivers/antigravity.ts +++ b/src/mms/harness/drivers/antigravity.ts @@ -42,6 +42,7 @@ export function antigravityBotSandbox(platform: NodeJS.Platform = process.platfo const none: BotSandboxUnavailable = { reason: 'unsupported_os', provider: 'Antigravity', os: botSandboxOsName(platform), repair: 'none' } return { runtime: 'antigravity', + networks: { gives: [], open: 'direct' }, key: platform, unsupported: () => none, probe: async () => none, diff --git a/src/mms/harness/pi/engine.ts b/src/mms/harness/pi/engine.ts index 6a1aca2b2..c5a7d7a20 100644 --- a/src/mms/harness/pi/engine.ts +++ b/src/mms/harness/pi/engine.ts @@ -124,7 +124,8 @@ export function piCommandSandbox(bot: Pick = new Set(['missing_packages', 'wsl1', 'userns_blocked', 'start_failed']) diff --git a/src/mms/harness/pi/extension/shell.ts b/src/mms/harness/pi/extension/shell.ts index 37c5781ca..e8a2aeb65 100644 --- a/src/mms/harness/pi/extension/shell.ts +++ b/src/mms/harness/pi/extension/shell.ts @@ -302,7 +302,7 @@ export function botBashOperations(options: { if (!sandbox) throw new Error(BOT_BASH_NO_SANDBOX) if (sandbox.kind === 'unavailable') throw new Error(sandbox.refusal) if (sandbox.kind === 'open') return options.open.exec(command, cwd, exec) - const policy = { kind: 'held' as const, revision: 0, network: { kind: sandbox.network } } + const policy = { kind: 'held' as const, revision: 0, network: { kind: sandbox.network === 'open' ? 'direct' as const : 'blocked' as const } } const wrap = (argv: string[], from: string) => mousseHeldSpawn(policy, argv, { cwd: from, writable: sandbox.writable, readOnly: sandbox.readOnly }, platform, options.env ?? process.env) let head = Buffer.alloc(0) const onData = (data: Buffer) => { diff --git a/src/mms/harness/vendors/codex/botSandbox.ts b/src/mms/harness/vendors/codex/botSandbox.ts index 8c4ee671a..1587d8afd 100644 --- a/src/mms/harness/vendors/codex/botSandbox.ts +++ b/src/mms/harness/vendors/codex/botSandbox.ts @@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { parse } from 'smol-toml' -import { botSandboxOsName, type BotSandboxNetwork, type BotSandboxUnavailable } from '../../../../shared/bots/personal/sandbox' +import { botSandboxOsName, type BotSandboxGivenNetwork, type BotSandboxUnavailable } from '../../../../shared/bots/personal/sandbox' import type { BotSandboxSupport } from '../../../bots/sandbox/BotSandboxResolver' import { linuxStartFailure, runProbe } from '../../../bots/sandbox/probe' import type { CliLaunch } from '../../cliConfig' @@ -58,6 +58,8 @@ export function codexBotSandboxSupport(input: { const windows = platform === 'win32' return { runtime: 'codex', + // Codex's own sandbox switches the network on or off: there is no proxy route to give the public web only. + networks: { gives: ['blocked', 'direct'], open: 'direct' }, key: program ? [platform, program.launch.command, ...program.launch.args, program.env.PATH ?? program.env.Path ?? '', program.env.CODEX_HOME ?? '', ...codexConfigOverrideArgs(program.args)].join('\u0000') : `${platform}\u0000none`, ...(windows ? { readsAll: true } : {}), unsupported: (_network, bot) => { @@ -86,7 +88,7 @@ export function codexBotSandboxSupport(input: { } }, // Linux and macOS: the system's folders and the bot's; Windows: every file the account can read. Writes: the bot's. - reach: (network) => ({ reads: windows ? 3 : 0, writes: 0, network: network.kind === 'open' }) + reach: (network) => ({ reads: windows ? 3 : 0, writes: 0, network: network.kind !== 'blocked' }) } } @@ -96,12 +98,12 @@ export function codexBotSandboxSupport(input: { * `workspaceWrite` sandbox does) and writing `dir`. The network as the owner set it. `overrides`: the app-server's own config * overrides (`codexConfigOverrideArgs`), before the profile's, so the probe loads the config a bot's commands run under. */ -export function codexSandboxProbeArgs(input: { platform: NodeJS.Platform; dir: string; network: BotSandboxNetwork; codexPackage?: string; overrides?: readonly string[] }): string[] { +export function codexSandboxProbeArgs(input: { platform: NodeJS.Platform; dir: string; network: BotSandboxGivenNetwork; codexPackage?: string; overrides?: readonly string[] }): string[] { const windows = input.platform === 'win32' const profile = codexBotProfile( { base: windows ? ':root' : ':minimal', readable: !windows && input.codexPackage ? [input.codexPackage] : [], closed: windows ? [] : [...CODEX_BOT_DENIED, ...(input.platform === 'darwin' ? CODEX_MACOS_DENIED : [])] }, [input.dir], - input.network.kind === 'open' + input.network.kind === 'direct' ) const command = windows ? ['cmd.exe', '/d', '/c', 'exit 0'] : ['true'] return ['sandbox', ...(input.overrides ?? []), '-P', CODEX_BOT_PROFILE, '-c', `permissions.${CODEX_BOT_PROFILE}=${inlineToml(profile)}`, '-C', input.dir, '--', ...command] diff --git a/src/mms/harness/vendors/codex/childPolicy.ts b/src/mms/harness/vendors/codex/childPolicy.ts index 253127ce9..3a1379835 100644 --- a/src/mms/harness/vendors/codex/childPolicy.ts +++ b/src/mms/harness/vendors/codex/childPolicy.ts @@ -140,7 +140,7 @@ export function codexBotSandbox(bot: Partial - const commandsAt = (detail?.permissions ?? []).reduce((at, item, index) => (COMMANDS_ROW.test(item.title) ? index : at), -1) + // The Sandbox row, under Run commands (at the end without one); its dialog holds Approvals, Full commands' switch. + const sandbox = (surface = false) => surface + ?
+ : + const permissions = (detail?.permissions ?? []).filter((item) => !FULL_COMMANDS_ROW.test(item.title)) + const commandsAt = permissions.reduce((at, item, index) => (COMMANDS_ROW.test(item.title) ? index : at), -1) // What the bot may use and which devices reach it are changed here: while the panel is open a theme's CSS is off // (its colors stay), so it cannot relabel them. @@ -547,7 +550,7 @@ export function BotAboutPanel({ bot, inPanel = false }: { bot: BotSummary; inPan else void store().setPermission(bot.id, BOT_FULL_TRUST_PERMISSION, false) }} /> } - {detail.permissions.map((item, index) => { + {permissions.map((item, index) => { const off = item.mark ?? (item.gone ? 'Gone from Mousse' : undefined) return +} diff --git a/src/renderer/components/bots/BotSandboxItem.tsx b/src/renderer/components/bots/BotSandboxItem.tsx new file mode 100644 index 000000000..0e99caef9 --- /dev/null +++ b/src/renderer/components/bots/BotSandboxItem.tsx @@ -0,0 +1,23 @@ +import type { ReactNode } from 'react' + +/** + * One row of the Sandbox dialog: its name left, and on the right either its value (what holds now, its details in the + * tooltip) or its one control. `dimmed`: it doesn't apply now (the sandbox is off); `warn`: something can't start. + */ +export function BotSandboxItem({ title, value, tip, control, dimmed = false, warn = false, testId, titleId }: { + title: ReactNode + value?: ReactNode + tip?: string + control?: ReactNode + dimmed?: boolean + warn?: boolean + testId?: string + titleId?: string +}) { + return
+
{title}
+
+ {control ?? {value}} +
+
+} diff --git a/src/renderer/components/bots/BotSandboxRows.tsx b/src/renderer/components/bots/BotSandboxRows.tsx deleted file mode 100644 index 35b0555ef..000000000 --- a/src/renderer/components/bots/BotSandboxRows.tsx +++ /dev/null @@ -1,241 +0,0 @@ -import { useEffect, type ComponentType, type ReactNode } from 'react' -import { create } from 'zustand' -import { Globe, Shield } from '../../lib/icons' -import type { BotSummary } from '../../../shared/bots/personal/chat' -import { - BOT_SANDBOX_INSTALL, BOT_SANDBOX_LABEL, BOT_SANDBOX_NETWORK_LABEL, BOT_SANDBOX_TURN_OFF, BOT_SANDBOX_WAITING, - botSandboxCardPolicy, botSandboxCardTitle, botSandboxNetworkLine, botSandboxProblem, botSandboxStatusLine, type BotSandboxCard, type BotSandboxPolicy, type BotSandboxNetwork, type BotSandboxView -} from '../../../shared/bots/personal/sandbox' -import { botsClient, useBotsStore } from '../../stores/botsStore' -import { useBotTerminals } from '../../stores/botTerminalsStore' -import { errorText } from '../../services/personalBotsClient' -import { Switch } from '../settings/SettingsRow' -import { botSetupBlock } from './botSetup' - -/** - * A bot's command sandbox (docs/plans/bot-sandbox-setting.md) as the owner sees it: the two switches in About → Can use, - * and the card Mousse posts in the chat when the sandbox can't start there. Both read one view per bot from the bot's - * computer (`bots.sandbox.get`), so a change in one shows in the other. Install what's missing opens the owner's terminal - * on the bot's computer with the command typed, not run: the owner presses Enter and signs in to `sudo` there; when that - * terminal ends or closes, the sandbox is checked again. - */ - -interface BotSandboxState { - /** What each bot's computer last said. */ - views: Readonly> - /** Why the last change failed, by bot. */ - errors: Readonly> - /** A change or a check on its way, by bot: the switches wait for it. */ - busy: Readonly> - /** The terminal Install what's missing opened, by bot, until it ends or closes. */ - installing: Readonly> - /** - * The bot's computer gave no install command for this card's launcher (`installKey`): Install isn't offered again - * there. Kept per card, so a stale card never hides Install on another launcher's card or in About. - */ - noInstall: Readonly> - /** Reads the view again; `recheck` starts the sandbox again first. A failed read leaves what was shown. */ - load(botId: string, recheck?: boolean): Promise - /** Changes a switch (`revision`: refused as stale when the setting moved since it was read; then it is read again). */ - set(botId: string, change: { sandbox?: 'on' | 'off'; network?: BotSandboxNetwork }, revision?: boolean): Promise - /** - * Install what's missing, on the bot's computer. `entry`: the launcher of the card Install was pressed on - * (`BotSandboxCard.entry`); `card`: that card's own key (`installKey`), under which "nothing to install" is kept. - */ - install(botId: string, entry?: string, card?: string): Promise -} - -/** - * Where Install was pressed: the bot (About), or one card (`card`: its message and place in it). A later card for the - * same launcher, posted when its package went missing again, is another card and offers Install again. - */ -export function installKey(botId: string, card?: string): string { - return card === undefined ? botId : `${botId}\u0000${card}` -} - -const without = (record: Readonly>, key: string): Record => { - const { [key]: _gone, ...rest } = record - return rest -} - -/** Reads in flight by bot: one at a time, and none answers over a change on its way. */ -const reading = new Map>() -const saving = new Map() - -export const useBotSandbox = create((set, get) => ({ - views: {}, - errors: {}, - busy: {}, - installing: {}, - noInstall: {}, - load(botId, recheck = false) { - const running = reading.get(botId) - if (running && !recheck) return running - const read = botsClient().sandbox(botId, recheck).then( - (view) => { if (!saving.get(botId)) set((state) => ({ views: { ...state.views, [botId]: view } })) }, - () => {} - ).finally(() => { if (reading.get(botId) === read) reading.delete(botId) }) - reading.set(botId, read) - return read - }, - async set(botId, change, revision = false) { - const before = get().views[botId] - const expected = revision && before ? { expectedRevision: before.setting.revision } : {} - saving.set(botId, (saving.get(botId) ?? 0) + 1) - set((state) => ({ - busy: { ...state.busy, [botId]: true }, - errors: without(state.errors, botId), - // The switch moves at once; turned off, commands run on the owner's path from now on. - ...(before ? { - views: { - ...state.views, - [botId]: { - ...before, - setting: { ...before.setting, ...change }, - ...(change.sandbox === 'off' ? { policy: { kind: 'open' as const, revision: before.policy.revision } } : {}) - } - } - } : {}) - })) - let stale = false - try { - const view = await botsClient().setSandbox(botId, { ...change, ...expected }) - set((state) => ({ views: { ...state.views, [botId]: view } })) - } catch (cause) { - stale = (cause as { code?: unknown } | null)?.code === 'stale' - set((state) => ({ - views: before ? { ...state.views, [botId]: before } : state.views, - ...(stale ? {} : { errors: { ...state.errors, [botId]: errorText(cause) } }) - })) - } finally { - saving.set(botId, (saving.get(botId) ?? 1) - 1) - set((state) => ({ busy: without(state.busy, botId) })) - } - // Someone changed it meanwhile (another window): what it is now shows. - if (stale) await get().load(botId) - }, - async install(botId, entry, card) { - if (get().installing[botId] || get().busy[botId]) return - set((state) => ({ busy: { ...state.busy, [botId]: true }, errors: without(state.errors, botId) })) - let command: string | undefined - try { - command = (await botsClient().sandboxInstall(botId, entry)).command - } catch (cause) { - set((state) => ({ busy: without(state.busy, botId), errors: { ...state.errors, [botId]: errorText(cause) } })) - return - } - set((state) => ({ busy: without(state.busy, botId) })) - if (!command) { - set((state) => ({ noInstall: { ...state.noInstall, [card ?? installKey(botId)]: true } })) - return - } - const node = useBotsStore.getState().bots.find((bot) => bot.id === botId)?.lives?.node ?? null - const terminal = useBotTerminals.getState().open(botId, node, { type: command, front: true }) - set((state) => ({ installing: { ...state.installing, [botId]: terminal } })) - // Its shell ended (the install ran, or the owner left it) or the owner closed its tab: check again. - const stop = useBotTerminals.subscribe((terminals) => { - const shown = terminals.terminals[terminal] - if (shown && shown.state !== 'ended') return - stop() - set((state) => ({ installing: without(state.installing, botId) })) - void get().load(botId, true) - }) - } -})) - -/** Whether the view says commands can't start, and Install can fix it from here. */ -function repairs(policy: BotSandboxPolicy, noInstall: boolean): { unavailable: boolean; install: boolean } { - return { unavailable: policy.kind === 'unavailable', install: policy.kind === 'unavailable' && policy.repair === 'install' && !noInstall } -} - -/** Turn off sandbox for this bot and Install what's missing (only where a package fixes it), as neutral buttons. */ -function Repairs({ botId, install, blocked, entry, card }: { botId: string; install: boolean; blocked: string | undefined; entry?: string; card?: string }) { - const busy = useBotSandbox((s) => Boolean(s.busy[botId])) - const installing = useBotSandbox((s) => Boolean(s.installing[botId])) - const store = useBotSandbox.getState - return - - {install ? : null} - -} - -type RowComponent = ComponentType<{ - icon?: ComponentType<{ size?: number; strokeWidth?: number }> - title: ReactNode - desc?: ReactNode - className?: string - titleTip?: string - testId?: string - children?: ReactNode -}> - -/** - * About → Can use: Sandbox commands and, under it, Allow network for sandboxed commands, each a switch with what it means - * now. Read when the section opens and again whenever the bot's detail does (`refresh`). Greyed with why for a bot this - * window can't set up (`botSetupBlock`); nothing while the bot's computer hasn't answered. - */ -export function BotSandboxRows({ bot, open, refresh, Row, surface = false }: { bot: Pick; open: boolean; refresh: unknown; Row: RowComponent; surface?: boolean }) { - const view = useBotSandbox((s) => s.views[bot.id]) - const error = useBotSandbox((s) => s.errors[bot.id]) - const busy = useBotSandbox((s) => Boolean(s.busy[bot.id])) - const noInstall = useBotSandbox((s) => Boolean(s.noInstall[installKey(bot.id)])) - const blocked = botSetupBlock(bot) - const away = Boolean(bot.lives?.offline) - useEffect(() => { if (open && !away) void useBotSandbox.getState().load(bot.id) }, [bot.id, open, away, refresh]) - if (!view) return null - // The launcher that can't start (the work's provider, else Mousse's runner for background and secret commands). - const shown = botSandboxProblem(view) ?? view.policy - const { unavailable, install } = repairs(shown, noInstall) - const network = botSandboxNetworkLine(view) - const on = view.setting.sandbox === 'on' - const store = useBotSandbox.getState - const rows = <> - - {botSandboxStatusLine(view)} - {unavailable ? : null} - {error ? {error} : null} - } - className="bot-sandbox-row"> - void store().set(bot.id, { sandbox: next ? 'on' : 'off' }, true)} /> - - {network.text}} - className={`bot-sandbox-row indent${on ? '' : ' is-off'}`}> - void store().set(bot.id, { network: { kind: next ? 'open' : 'blocked' } }, true)} /> - - - // A bot with nothing else under Can use: the rows on a surface of their own. - return surface ?
{rows}
: rows -} - -/** - * The card Mousse posts in the bot's chat when its sandbox can't start: what is wrong, that the work waits, what the - * sandbox printed under Details, and the two buttons. It reads what the sandbox is now: once it starts or is turned off, - * the card keeps its reason and says what holds now instead of the buttons. - */ -export function BotSandboxCardRow({ botId, card, cardKey }: { botId: string; card: BotSandboxCard; cardKey?: string }) { - // This card's own "nothing to install" (`installKey`): by its message and place, else by its launcher. - const remembered = installKey(botId, cardKey ?? card.entry ?? '') - const bot = useBotsStore((s) => s.bots.find((entry) => entry.id === botId)) - const view = useBotSandbox((s) => s.views[botId]) - const error = useBotSandbox((s) => s.errors[botId]) - const noInstall = useBotSandbox((s) => Boolean(s.noInstall[remembered])) - const away = Boolean(bot?.lives?.offline) - useEffect(() => { if (!away) void useBotSandbox.getState().load(botId) }, [botId, away]) - const blocked = bot ? botSetupBlock(bot) : undefined - // Until the bot's computer answers, the card stands as it was posted. - // The launcher this card was posted for, as it is now. - const now = view ? botSandboxCardPolicy(view, card) : undefined - const settled = now !== undefined && now.kind !== 'unavailable' - const install = now ? repairs(now, noInstall).install : card.repair === 'install' && !noInstall - return
-

{botSandboxCardTitle(card.computer)}

-

{card.text}

-

{settled ? botSandboxStatusLine({ computer: view!.computer, policy: now! }) : BOT_SANDBOX_WAITING}

- {card.detail ?
Details
{card.detail}
: null} - {settled ? null : } - {error ?

{error}

: null} -
-} diff --git a/src/renderer/components/bots/BotSandboxSettings.tsx b/src/renderer/components/bots/BotSandboxSettings.tsx new file mode 100644 index 000000000..224191899 --- /dev/null +++ b/src/renderer/components/bots/BotSandboxSettings.tsx @@ -0,0 +1,255 @@ +import { useEffect, useId, useMemo, useRef, useState } from 'react' +import { createPortal } from 'react-dom' +import { ChevronRight, Shield } from '../../lib/icons' +import type { BotDetail, BotSummary } from '../../../shared/bots/personal/chat' +import type { SecretEntryView } from '../../../shared/secretRequests' +import { + BOT_SANDBOX_INSTALL, BOT_SANDBOX_LABEL, BOT_SANDBOX_NETWORK_KINDS, BOT_SANDBOX_NETWORK_NAMES, BOT_SANDBOX_NETWORK_TIPS, BOT_SANDBOX_TURN_OFF, BOT_SANDBOX_WAITING, + botSandboxCardActions, botSandboxCardPolicy, botSandboxCardTitle, botSandboxProblem, botSandboxReachLines, botSandboxReasonText, botSandboxState, + type BotSandboxCard, type BotSandboxCardAction, type BotSandboxGivenNetwork, type BotSandboxNetwork, type BotSandboxNetworkKind, type BotSandboxPolicy, type BotSandboxReachLine +} from '../../../shared/bots/personal/sandbox' +import { useBotsStore } from '../../stores/botsStore' +import { installKey, useBotSandbox } from '../../stores/botSandboxStore' +import { createSecretsClient } from '../../services/secretsClient' +import { scaleMotionMs } from '../../lib/motion' +import { Modal } from '../ui/Modal' +import { Segmented, Switch } from '../settings/SettingsRow' +import { RemoveButton } from '../settings/IconButtons' +import { BotSandboxFiles } from './BotSandboxFiles' +import { BotSandboxItem } from './BotSandboxItem' +import { botSetupBlock } from './botSetup' + +/** + * A bot's command sandbox in About (docs/plans/bot-sandbox-setting.md): one Sandbox row with its state, which opens a + * dialog on the modal surface holding every setting (on or off, files, network, local servers, secrets, approvals) and + * a summary of what commands reach now, read from the bot's computer (`bots.sandbox.get`: the same result launches, + * cards and the bot's system text use). New bot's Sandbox step shows the same controls (`BotSandboxControls`). The card + * Mousse posts in the chat when the sandbox can't start (`BotSandboxCardRow`) offers what the bot's computer can do. + */ + +/** The modal surface's close (modal-surface.css), before Animation speed scales it. */ +const CLOSE_MS = 120 + +/** About's permission row the Approvals choice switches: Full commands, asked for on a card. */ +export const FULL_COMMANDS_ROW = /^run full commands$/i + +const OFF_TIP = 'Off: commands run like your own threads. Bot permissions, approvals and secret masking still apply.' + +/** The switch's name: the dialog and the step are already called Sandbox. */ +export const BOT_SANDBOX_SWITCH = 'Limit commands' + +/** The servers line for a choice not made yet (New bot): what the network gives on every launcher. */ +function serversText(on: boolean, network: BotSandboxNetwork['kind']): { text: string; tip: string } { + if (!on) return { text: 'Like your own threads', tip: 'The sandbox is off.' } + return network === 'direct' || network === 'open' + ? { text: 'Reachable on this computer', tip: 'Servers its commands start can be reached from this computer.' } + : { text: 'Inside only', tip: 'Servers its commands start stay inside the sandbox.' } +} + +/** + * On or off, Files, Network and Local servers: the Sandbox dialog's settings, and New bot's Sandbox step. `reach`: the + * summary from the bot's computer, for a made bot; New bot has none. `blocked`: why nothing can change here (tooltip). + * `botId`: the made bot, handed to the Files section; New bot has none. + */ +export function BotSandboxControls({ value, onChange, busy = false, blocked, reach, botId }: { + value: { sandbox: 'on' | 'off'; network: BotSandboxNetwork } + onChange(change: { sandbox?: 'on' | 'off'; network?: BotSandboxGivenNetwork }): void + busy?: boolean + blocked?: string + reach?: readonly BotSandboxReachLine[] + botId?: string +}) { + const networkId = useId() + const on = value.sandbox === 'on' + const locked = busy || Boolean(blocked) + const kind = value.network.kind + const servers = reach?.find((line) => line.id === 'servers') + // A made bot whose launchers can't start runs no server at all; New bot (no summary) says what the choice gives. + const shownServers = servers ? { text: servers.text, tip: servers.tip ?? '' } + : reach && on ? { text: "Commands can't start", tip: 'See what commands reach below.', warn: true } + : serversText(on, kind) + // A network saved before the choice was split shows no choice picked: its tooltip says what it gives. + const saved = kind === 'open' ? 'Saved before Public web and Direct were separate choices. Pick one to change it.' : undefined + return <> + onChange({ sandbox: next ? 'on' : 'off' })} />} /> + line.id === 'files') ? { line: reach.find((line) => line.id === 'files')! } : {})} /> + value={kind} ariaLabelledBy={networkId} disabled={locked || !on} + options={BOT_SANDBOX_NETWORK_KINDS.map((option) => ({ value: option, label: BOT_SANDBOX_NETWORK_NAMES[option], title: BOT_SANDBOX_NETWORK_TIPS[option] }))} + onChange={(next) => { if (next !== 'open') onChange({ network: { kind: next } }) }} />} /> + + +} + +/** About → Can use: the one Sandbox row, its state on the right; it opens the Sandbox dialog. */ +export function BotSandboxRow({ bot, open, refresh, detail }: { bot: Pick; open: boolean; refresh: unknown; detail: BotDetail | undefined }) { + const view = useBotSandbox((s) => s.views[bot.id]) + const [shown, setShown] = useState(false) + const blocked = botSetupBlock(bot) + const away = Boolean(bot.lives?.offline) + useEffect(() => { if (open && !away) void useBotSandbox.getState().load(bot.id) }, [bot.id, open, away, refresh]) + if (!view) return null + const state = botSandboxState(view) + return <> +
+ +
{BOT_SANDBOX_LABEL}
+
+ +
+
+ {shown ? createPortal( setShown(false)} />, document.body) : null} + +} + +/** The secrets the bot may use (given in its chat, or a saved one given to it there); none from another computer, where they are kept. */ +function useBotSecrets(homeThreadId: string | undefined, local: boolean): SecretEntryView[] | undefined { + const [entries, setEntries] = useState(undefined) + useEffect(() => { + if (!local || !homeThreadId) return + let live = true + createSecretsClient(window.mousse?.platformRequest).list().then((all) => { if (live) setEntries(all.filter((entry) => entry.threadId === homeThreadId || entry.threads?.includes(homeThreadId))) }, () => {}) + return () => { live = false } + }, [homeThreadId, local]) + return entries +} + +/** A secret's rule for commands, in a few words, and its whole line for the tooltip. */ +function secretRule(entry: SecretEntryView): { text: string; tip: string } { + if (entry.binding?.unavailable) return { text: 'Bound, service unavailable', tip: 'It is bound to a service this computer no longer knows.' } + if (entry.binding) return { text: `Only ${entry.binding.service ?? entry.binding.host}, read only`, tip: `Sent only to ${entry.binding.host}, for reading. Never given to a command.` } + return { text: 'One command at a time', tip: 'Given to one command at a time, as a variable or a private file, and masked in what it prints.' } +} + +/** + * The Sandbox dialog: every setting of the bot's command sandbox on its computer, then what commands reach now. Changes + * save at once on the bot's computer; the summary is read back from there. + */ +export function BotSandboxDialog({ bot, detail, onClose }: { bot: Pick; detail: BotDetail | undefined; onClose(): void }) { + const view = useBotSandbox((s) => s.views[bot.id]) + const busy = useBotSandbox((s) => Boolean(s.busy[bot.id])) + const error = useBotSandbox((s) => s.errors[bot.id]) + const noInstall = useBotSandbox((s) => Boolean(s.noInstall[installKey(bot.id)])) + const [closing, setClosing] = useState(false) + const timer = useRef(undefined) + useEffect(() => () => window.clearTimeout(timer.current), []) + const close = () => { + if (closing) return + setClosing(true) + timer.current = window.setTimeout(onClose, scaleMotionMs(CLOSE_MS)) + } + const blocked = botSetupBlock(bot) + const secrets = useBotSecrets(bot.homeThreadId, !bot.lives) + const full = detail?.permissions.find((item) => FULL_COMMANDS_ROW.test(item.title)) + const approvalsId = useId() + const reach = useMemo(() => (view ? botSandboxReachLines(view) : []), [view]) + if (!view) return null + const store = useBotSandbox.getState + const problem = botSandboxProblem(view) + const summary = reach.filter((line) => line.id !== 'servers') + return +

On {view.computer}

+
+ void store().set(bot.id, change, true)} /> + {secrets !== undefined && <> + {secrets.length + ? secrets.map((entry) => { + const rule = secretRule(entry) + return + }) + : } + } + {bot.lives ? : null} + value={full.enabled ? 'full' : 'auto'} ariaLabelledBy={approvalsId} disabled={Boolean(blocked)} + options={[{ value: 'auto', label: 'Auto', title: 'Destructive commands ask you first.' }, { value: 'full', label: 'Full', title: 'Any command runs without asking, destructive ones too.' }]} + onChange={(next) => void useBotsStore.getState().setPermission(bot.id, full.id, next === 'full')} /> + {/* Full commands can be taken away here, as its row in About offered (one Allow everything gives can't). */} + {full.builtIn || full.fromFullTrust ? null : void useBotsStore.getState().revokePermission(bot.id, full.id)} />} + : Auto} /> +
+

What commands reach

+
+ {summary.map((line) => )} +
+ {problem ?

{botSandboxReasonText(problem)}

: null} + {problem ? : null} + {error ?

{error}

: null} +
+} + +/** + * The buttons for a launcher that can't start, as the bot's computer can act on them now (`botSandboxCardActions`): + * Repair (install what's missing, or start it again) and Turn off this limit. Allow once and Keep allowing need a + * launch Mousse holds and can let through; `onAllow` is where they will act, and until a caller passes it they never + * show. + */ +export function BotSandboxActions({ botId, policy, noInstall, blocked, entry, card, onAllow }: { + botId: string + /** The card's own key (`installKey`), under which "nothing to install" is kept; the bot's in the dialog. */ + card?: string + policy: Extract + noInstall: boolean + blocked: string | undefined + entry?: string + onAllow?: (action: Extract) => void +}) { + const busy = useBotSandbox((s) => Boolean(s.busy[botId])) + const installing = useBotSandbox((s) => Boolean(s.installing[botId])) + const install = policy.repair === 'install' && !noInstall + const actions = botSandboxCardActions(policy, { install, held: Boolean(onAllow) }) + const store = useBotSandbox.getState + const off = busy || Boolean(blocked) + return + {actions.map((action) => { + switch (action) { + case 'repair': + return + case 'allow_once': + case 'keep_allowing': + return + case 'turn_off': + return + } + })} + +} + +/** + * The card Mousse posts in the bot's chat when its sandbox can't start: what is wrong, that the work waits, what the + * sandbox printed under Details, and what can be done. It reads what the launcher it names runs with now: once that + * starts or the sandbox is turned off, the card keeps its reason and says what holds now instead of the buttons. + */ +export function BotSandboxCardRow({ botId, card, cardKey }: { botId: string; card: BotSandboxCard; cardKey?: string }) { + // This card's own "nothing to install" (`installKey`): by its message and place, else by its launcher. + const remembered = installKey(botId, cardKey ?? card.entry ?? '') + const bot = useBotsStore((s) => s.bots.find((entry) => entry.id === botId)) + const view = useBotSandbox((s) => s.views[botId]) + const error = useBotSandbox((s) => s.errors[botId]) + const noInstall = useBotSandbox((s) => Boolean(s.noInstall[remembered])) + const away = Boolean(bot?.lives?.offline) + useEffect(() => { if (!away) void useBotSandbox.getState().load(botId) }, [botId, away]) + const blocked = bot ? botSetupBlock(bot) : undefined + // Until the bot's computer answers, the card stands as it was posted. + const now = view ? botSandboxCardPolicy(view, card) : undefined + const settled = now !== undefined && now.kind !== 'unavailable' + const policy: Extract = now?.kind === 'unavailable' + ? now + : { kind: 'unavailable', revision: 0, reason: card.reason, provider: card.provider ?? '', repair: card.repair } + return
+

{botSandboxCardTitle(card.computer)}

+

{now?.kind === 'unavailable' ? botSandboxReasonText(now) : card.text}

+

{settled ? (now.kind === 'open' ? 'The sandbox is off now. Commands run like your own threads.' : 'The sandbox starts now.') : BOT_SANDBOX_WAITING}

+ {card.detail ?
Details
{card.detail}
: null} + {settled ? null : } + {error ?

{error}

: null} +
+} diff --git a/src/renderer/components/bots/NewBotDialog.tsx b/src/renderer/components/bots/NewBotDialog.tsx index c27880ffd..70f5381ae 100644 --- a/src/renderer/components/bots/NewBotDialog.tsx +++ b/src/renderer/components/bots/NewBotDialog.tsx @@ -16,12 +16,13 @@ import { Select } from '../ui/Select' import { BotLookPicker } from './face/BotLookPicker' import { BOT_DEVICES_TIP } from '../../../shared/bots/personal/deviceAccess' import { BotDeviceSwitches, accessOf } from './BotDevices' +import { BotSandboxControls } from './BotSandboxSettings' import { OWNER_NAME_MAX, ownerNameFieldDue } from '../../../shared/ownerAddress' import { claimOwnerNameField, ownerNameRefusal, saveSetupOwnerName, useOwnerAddress } from '../../lib/ownerAddress' import '../../styles/chats.css' import '../../styles/bots.css' -const STEP_LABELS: Record = { look: 'Look', about: 'What it does', runsOn: 'Runs on', devices: 'Devices' } +const STEP_LABELS: Record = { look: 'Look', about: 'What it does', runsOn: 'Runs on', sandbox: 'Sandbox', devices: 'Devices' } /** The Look step's face: larger than Change look's, with the tiles still eight to a row at this width. */ const LOOK_PREVIEW_SIZE = 150 const FOCUSABLE = 'input:not(:disabled), textarea:not(:disabled), button:not(:disabled), [tabindex="0"]' @@ -135,7 +136,8 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { // Devices only when the owner has another device (phones too) and the service can save the choice. On another // computer, this one (`caller` in its list) always reaches the bot, so it has no switch. const otherDevices = choices?.reachOnCreate ? (choices.devices ?? []).filter((device) => !device.caller) : [] - const steps: NewBotStep[] = choices === null ? ['look', 'about'] : ['look', 'about', 'runsOn', ...(otherDevices.length ? ['devices' as const] : [])] + // Sandbox only where the bot's computer takes it on create (`sandboxOnCreate`): an older one refuses the key. + const steps: NewBotStep[] = choices === null ? ['look', 'about'] : ['look', 'about', 'runsOn', ...(choices?.sandboxOnCreate ? ['sandbox' as const] : []), ...(otherDevices.length ? ['devices' as const] : [])] // A step this service has no room for (Runs on, left open before an older service answered) shows as the last one. const step = steps.includes(draft.step) ? draft.step : steps[steps.length - 1]! const index = steps.indexOf(step) @@ -174,6 +176,8 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { // that are still offered. const offered = new Set(otherDevices.map((device) => device.node)) const access = choices?.reachOnCreate ? accessOf(state.newBotDraft.devices.filter((node) => offered.has(node))) : null + // The Sandbox step, only to a service that takes it. + const sandbox = choices?.sandboxOnCreate ? state.newBotDraft.sandbox : null // The name first, so the new bot's greeting already uses it, and only while the field shows: the service saves it // only while no name is set, so a name saved since stays. The bot is made whether or not it was saved; a name not // saved (refused, or a name set elsewhere meanwhile) is said in the new chat. @@ -183,7 +187,7 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { const refused = ownerNameRefusal(failure) nameNotSaved = refused ? `: ${refused}` : '' }) - const bot = await state.create({ look: state.newBotDraft.look ?? look, description, ...(name ? { name } : {}), ...(slots ? { slots } : model ? { model } : {}), ...(image ? { image } : {}), ...(access ? { access } : {}), ...(node ? { node } : {}) }) + const bot = await state.create({ look: state.newBotDraft.look ?? look, description, ...(name ? { name } : {}), ...(slots ? { slots } : model ? { model } : {}), ...(image ? { image } : {}), ...(access ? { access } : {}), ...(sandbox ? { sandbox } : {}), ...(node ? { node } : {}) }) if (bot && onCreated) onCreated(bot) else if (bot) await useChatsStore.getState().openBot(bot.id) // Refused because a pick is gone: Runs on (where the store returned) offers what is there now, and that row is empty. @@ -223,6 +227,10 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { onPick={(keys, pick) => setNewBotDraft({ slots: { ...(draft.slots ?? EMPTY_ROWS), ...Object.fromEntries(keys.map((key) => [key, pick])) } })} onOneWork={() => { const rows = draft.slots ?? EMPTY_ROWS; setNewBotDraft({ slots: { ...rows, light: rows.medium, hard: rows.medium } }) }} /> : null} } + {step === 'sandbox' &&
+ {home ?

On {home}

: null} + setNewBotDraft({ sandbox: { ...draft.sandbox, ...change } })} /> +
} {step === 'devices' &&

Devices that reach it

, active: boole if (!isTopDialog(dialog) || answeredEscapes.has(event)) return if (event.key === 'Escape') { event.preventDefault(); answeredEscapes.add(event); closeRef.current(); return } if (event.key !== 'Tab') return - const items = focusables(dialog, FOCUSABLE) + // Sequential tab stops only: a radio group's unchosen options (tabIndex -1) are reached with the arrow keys. + const items = focusables(dialog, FOCUSABLE).filter((item) => item.tabIndex >= 0) if (!items.length) { event.preventDefault(); return } const index = items.indexOf(document.activeElement as HTMLElement) const outside = index === -1 && !dialog.contains(document.activeElement) diff --git a/src/renderer/services/personalBotsClient.ts b/src/renderer/services/personalBotsClient.ts index 004e00faa..83e1787c6 100644 --- a/src/renderer/services/personalBotsClient.ts +++ b/src/renderer/services/personalBotsClient.ts @@ -10,6 +10,7 @@ import type { BotTransferResult } from '../../shared/bots/personal/transfer' import type { PlatformRequestApi } from '../../shared/platform' import type { BotDeviceAccess, BotDevicesView, NewBotAccess } from '../../shared/bots/personal/deviceAccess' import type { BotMark, BotMarksApi, BotMarksByRef } from '../../shared/bots/personal/marks' +import type { NewBotSandbox } from '../../shared/bots/personal/sandbox' /** * The Bot UI's methods (`bots.personal.v2`, Bot Phase 1 §5.11) over the host's profile-bound @@ -55,7 +56,7 @@ export interface PersonalBotsClient { * step (this computer alone when it is not shown), sent only to a service whose choices carry `reachOnCreate`. * `node`: made on that other computer (New bot's "Lives on"); its answer names the bot by a qualified id. */ - create(input: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; node?: string }): Promise + create(input: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; sandbox?: NewBotSandbox; node?: string }): Promise get(botId: string): Promise /** `description`: the bot's prompt, as the owner edits it in About; null resets it. An older service refuses it. */ update(botId: string, change: { name?: string; look?: BotLook; description?: string | null }): Promise @@ -166,8 +167,8 @@ export function createPersonalBotsClient(transport: PlatformRequestApi): Persona webPicture: (botId, messageId, src, offset, width) => call('bots.chat.webPicture', { botId, messageId, src, ...(offset ? { offset } : {}), ...(width ? { width } : {}) }), marks: async () => (await transport.request('bots.marks.list', {})).marks, setMark: async (botId, mark, on) => (await transport.request('bots.marks.set', { botId, mark, on })).marks, - create: async ({ look, name, description, clientRequestId, model, slots, image, access, node }) => - (await call('bots.create', { look, description, clientRequestId, ...(name ? { name } : {}), ...(slots ? { slots } : model ? { model } : {}), ...(image ? { image } : {}), ...(access ? { access } : {}), ...(node ? { node } : {}) })).bot, + create: async ({ look, name, description, clientRequestId, model, slots, image, access, sandbox, node }) => + (await call('bots.create', { look, description, clientRequestId, ...(name ? { name } : {}), ...(slots ? { slots } : model ? { model } : {}), ...(image ? { image } : {}), ...(access ? { access } : {}), ...(sandbox ? { sandbox } : {}), ...(node ? { node } : {}) })).bot, get: (botId) => call('bots.get', { botId }), systemInstructions: (botId) => call('bots.systemInstructions.get', { botId }), setSystemInstructions: (botId, text) => call('bots.systemInstructions.set', { botId, text }), diff --git a/src/renderer/stores/botSandboxStore.ts b/src/renderer/stores/botSandboxStore.ts new file mode 100644 index 000000000..a2eb3ef0c --- /dev/null +++ b/src/renderer/stores/botSandboxStore.ts @@ -0,0 +1,156 @@ +import { create } from 'zustand' +import type { BotSandboxGivenNetwork, BotSandboxView } from '../../shared/bots/personal/sandbox' +import { botsClient, useBotsStore } from './botsStore' +import { useBotTerminals } from './botTerminalsStore' +import { errorText } from '../services/personalBotsClient' + +/** + * A bot's command sandbox (docs/plans/bot-sandbox-setting.md) as the owner sees it: the Sandbox row and dialog in About, + * and the card Mousse posts in the chat when the sandbox can't start there. All read one view per bot from the bot's + * computer (`bots.sandbox.get`), so a change in one shows in the others. Repair, where a package fixes it, opens the owner's terminal + * on the bot's computer with the command typed, not run: the owner presses Enter and signs in to `sudo` there; when that + * terminal ends or closes, the sandbox is checked again. + */ + +interface BotSandboxState { + /** What each bot's computer last said. */ + views: Readonly> + /** Why the last change failed, by bot. */ + errors: Readonly> + /** A change or a check on its way, by bot: the switches wait for it. */ + busy: Readonly> + /** The terminal Install what's missing opened, by bot, until it ends or closes. */ + installing: Readonly> + /** + * The bot's computer gave no install command for this card's launcher (`installKey`): Install isn't offered again + * there. Kept per card, so a stale card never hides Install on another launcher's card or in the dialog. + */ + noInstall: Readonly> + /** Reads the view again; `recheck` starts the sandbox again first. A failed read leaves what was shown. */ + load(botId: string, recheck?: boolean): Promise + /** Changes a switch (`revision`: refused as stale when the setting moved since it was read; then it is read again). */ + set(botId: string, change: { sandbox?: 'on' | 'off'; network?: BotSandboxGivenNetwork }, revision?: boolean): Promise + /** + * Repair: with `install`, a terminal on the bot's computer with the command that adds what is missing; else the sandbox + * is started again. `entry`: the launcher of the card Repair was pressed on (`BotSandboxCard.entry`). + */ + repair(botId: string, install: boolean, entry?: string, card?: string): Promise + /** + * Install what's missing, on the bot's computer. `entry`: the launcher of the card Install was pressed on + * (`BotSandboxCard.entry`); `card`: that card's own key (`installKey`), under which "nothing to install" is kept. + */ + install(botId: string, entry?: string, card?: string): Promise +} + +/** + * Where Install was pressed: the bot (the dialog), or one card (`card`: its message and place in it). A later card for the + * same launcher, posted when its package went missing again, is another card and offers Install again. + */ +export function installKey(botId: string, card?: string): string { + return card === undefined ? botId : `${botId}\u0000${card}` +} + +const without = (record: Readonly>, key: string): Record => { + const { [key]: _gone, ...rest } = record + return rest +} + +/** Reads in flight by bot: one at a time, and none answers over a change on its way. */ +const reading = new Map>() +const saving = new Map() +/** Changes by bot, counted: a read started before a change never answers over what the change showed. */ +const changes = new Map() + +export const useBotSandbox = create((set, get) => ({ + views: {}, + errors: {}, + busy: {}, + installing: {}, + noInstall: {}, + load(botId, recheck = false) { + const running = reading.get(botId) + if (running && !recheck) return running + const before = changes.get(botId) ?? 0 + const read = botsClient().sandbox(botId, recheck).then( + (view) => { if (!saving.get(botId) && (changes.get(botId) ?? 0) === before) set((state) => ({ views: { ...state.views, [botId]: view } })) }, + () => {} + ).finally(() => { if (reading.get(botId) === read) reading.delete(botId) }) + reading.set(botId, read) + return read + }, + async set(botId, change, revision = false) { + const before = get().views[botId] + const expected = revision && before ? { expectedRevision: before.setting.revision } : {} + saving.set(botId, (saving.get(botId) ?? 0) + 1) + changes.set(botId, (changes.get(botId) ?? 0) + 1) + set((state) => ({ + busy: { ...state.busy, [botId]: true }, + errors: without(state.errors, botId), + // The switch moves at once; turned off, commands run on the owner's path from now on. + ...(before ? { + views: { + ...state.views, + [botId]: { + ...before, + setting: { ...before.setting, ...change }, + ...(change.sandbox === 'off' ? { policy: { kind: 'open' as const, revision: before.policy.revision } } : {}) + } + } + } : {}) + })) + let stale = false + try { + const view = await botsClient().setSandbox(botId, { ...change, ...expected }) + set((state) => ({ views: { ...state.views, [botId]: view } })) + } catch (cause) { + stale = (cause as { code?: unknown } | null)?.code === 'stale' + set((state) => ({ + views: before ? { ...state.views, [botId]: before } : state.views, + ...(stale ? {} : { errors: { ...state.errors, [botId]: errorText(cause) } }) + })) + } finally { + saving.set(botId, (saving.get(botId) ?? 1) - 1) + set((state) => ({ busy: without(state.busy, botId) })) + } + // Someone changed it meanwhile (another window): what it is now shows. + if (stale) await get().load(botId) + }, + async repair(botId, install, entry, card) { + if (install) return get().install(botId, entry, card) + if (get().busy[botId]) return + set((state) => ({ busy: { ...state.busy, [botId]: true }, errors: without(state.errors, botId) })) + try { + await get().load(botId, true) + } finally { + set((state) => ({ busy: without(state.busy, botId) })) + } + }, + async install(botId, entry, card) { + if (get().installing[botId] || get().busy[botId]) return + set((state) => ({ busy: { ...state.busy, [botId]: true }, errors: without(state.errors, botId) })) + let command: string | undefined + try { + command = (await botsClient().sandboxInstall(botId, entry)).command + } catch (cause) { + set((state) => ({ busy: without(state.busy, botId), errors: { ...state.errors, [botId]: errorText(cause) } })) + return + } + set((state) => ({ busy: without(state.busy, botId) })) + if (!command) { + set((state) => ({ noInstall: { ...state.noInstall, [card ?? installKey(botId)]: true } })) + return + } + const node = useBotsStore.getState().bots.find((bot) => bot.id === botId)?.lives?.node ?? null + const terminal = useBotTerminals.getState().open(botId, node, { type: command, front: true }) + set((state) => ({ installing: { ...state.installing, [botId]: terminal } })) + // Its shell ended (the install ran, or the owner left it) or the owner closed its tab: check again. + const stop = useBotTerminals.subscribe((terminals) => { + const shown = terminals.terminals[terminal] + if (shown && shown.state !== 'ended') return + stop() + set((state) => ({ installing: without(state.installing, botId) })) + void get().load(botId, true) + }) + } +})) + diff --git a/src/renderer/stores/botsStore.ts b/src/renderer/stores/botsStore.ts index 804bab9c3..f1eab536a 100644 --- a/src/renderer/stores/botsStore.ts +++ b/src/renderer/stores/botsStore.ts @@ -8,6 +8,7 @@ import type { BotLook } from '../../shared/bots/personal/look' import type { BotMemoryEntry } from '../../shared/bots/personal/memory' import type { BotModelPick, BotModelSlots } from '../../shared/bots/personal/definition' import type { NewBotAccess } from '../../shared/bots/personal/deviceAccess' +import { BOT_SANDBOX_DRAFT_DEFAULT, type NewBotSandbox } from '../../shared/bots/personal/sandbox' import { withMark, noMarks, type BotMark, type BotMarksByRef } from '../../shared/bots/personal/marks' import { DEFAULT_BOT_FILTER, type BotListFilter, type BotStateFilter } from '../lib/botList' import { attachmentTooLargeText } from '../../shared/bots/personal/attachments' @@ -114,14 +115,16 @@ export interface NewBotDraft { * bot is made on this computer while that field shows. */ ownerName: string + /** The Sandbox step: off by default, with the public web once turned on. Sent only to a service that takes it. */ + sandbox: NewBotSandbox /** The step New bot shows, so closing and reopening returns to it. */ step: NewBotStep /** The owner typed or picked something: a click beside the dialog no longer closes it. */ touched: boolean } -/** New bot's steps: the look, what it does (name and sentence), where it runs, and (with other devices) which reach it. */ -export type NewBotStep = 'look' | 'about' | 'runsOn' | 'devices' -const EMPTY_NEW_BOT: NewBotDraft = { look: null, name: '', description: '', model: null, slots: null, image: null, devices: [], node: null, ownerName: '', step: 'look', touched: false } +/** New bot's steps: the look, what it does (name and sentence), where it runs, its sandbox, and (with other devices) which reach it. */ +export type NewBotStep = 'look' | 'about' | 'runsOn' | 'sandbox' | 'devices' +const EMPTY_NEW_BOT: NewBotDraft = { look: null, name: '', description: '', model: null, slots: null, image: null, devices: [], node: null, ownerName: '', sandbox: BOT_SANDBOX_DRAFT_DEFAULT, step: 'look', touched: false } /** * The step that can fix a refused create: a model no longer offered is Runs on's, a name or sentence the service @@ -288,7 +291,7 @@ interface BotsState { * One create at a time: a second call while one is on its way gets the same answer. `node`: made on that other * computer (New bot's "Lives on"), where this one has Full bot access. */ - create(input: { look: BotLook; name?: string; description: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; node?: string }): Promise + create(input: { look: BotLook; name?: string; description: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; sandbox?: NewBotSandbox; node?: string }): Promise update(botId: string, change: { name?: string; look?: BotLook }): Promise /** * The owner edits the bot's prompt in About (its description; null: back to the default). Its next turn works under diff --git a/src/renderer/styles/bots.css b/src/renderer/styles/bots.css index 7f2cca8b3..12425164f 100644 --- a/src/renderer/styles/bots.css +++ b/src/renderer/styles/bots.css @@ -500,7 +500,7 @@ button.bot-image:focus-visible > img { opacity: 0.82; } .bot-sandbox-state.is-bad { color: var(--danger, var(--text-secondary)); } .bot-sandbox-detail { margin-top: 4px; color: var(--text-secondary); } .bot-sandbox-detail > summary { cursor: pointer; width: fit-content; } -.bot-sandbox-detail > pre { margin: 4px 0 0; max-height: 160px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-family: var(--font-mono, monospace); font-size: 11.5px; } +.bot-sandbox-detail-text { margin: 4px 0 0; max-height: 160px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; } .bot-sandbox-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; } /* Asking for something, inside the bot's message; the approval look (#590). */ @@ -659,13 +659,28 @@ html[data-theme] .app .bot-chat-pane::after { content: ''; position: absolute; i .bot-about-value { font-size: var(--settings-fs-small); white-space: nowrap; font-variant-numeric: tabular-nums; color: var(--text-primary); } .bot-about-permission.is-off .settings-item-lead, .bot-about-permission.is-off .settings-item-title { opacity: .55; } .bot-about-permission .settings-item-desc { -webkit-line-clamp: 1; } -/* Sandbox commands and its network switch: the whole line, a warning when commands can't start, then its buttons. */ -.bot-about .bot-sandbox-row .settings-item-desc { display: flex; flex-direction: column; gap: 2px; -webkit-line-clamp: unset; } -.bot-sandbox-line.is-warn { color: var(--warning); } -.bot-sandbox-line.is-bad { color: var(--danger, var(--warning)); } -.bot-sandbox-line.is-dimmed, .bot-sandbox-row.is-off .settings-item-lead, .bot-sandbox-row.is-off .settings-item-title { opacity: .55; } -.bot-about .bot-sandbox-actions { margin-top: var(--space-4); } -.bot-about .bot-sandbox-actions .settings-btn { height: var(--settings-control-h); padding: 0 var(--space-8); border-radius: var(--ui-control-radius); font-size: 12px; } +/* About's one Sandbox row: its state on the right, opening the Sandbox dialog. */ +.bot-sandbox-open { display: inline-flex; align-items: center; gap: 4px; height: var(--settings-control-h, 28px); padding: 0 6px 0 var(--space-8, 8px); border-radius: 7px; font-size: var(--settings-fs-small, 12.5px); color: var(--text-secondary); white-space: nowrap; transition: color .15s, background-color .15s; } +.bot-sandbox-open:hover, .bot-sandbox-open:focus-visible { color: var(--text-primary); background: var(--ui-hover); } +.bot-sandbox-open .is-warn { color: var(--warning); } + +/* The Sandbox dialog, on the modal surface: rows flat on it (no inner surface), one quiet heading before the summary. + Portaled to the body, so it carries the settings tokens itself (.settings-scope's values). */ +.bot-sandbox-dialog .modal { width: 560px; } +.bot-sandbox-dialog, .bot-new-sandbox { --space-4: 4px; --space-8: 8px; --space-12: 12px; --space-16: 16px; --space-24: 24px; --settings-row-y: 10px; --settings-control-h: 28px; --settings-fs-row: 13.5px; --settings-fs-small: 12.5px; } +.modal-body > p.bot-sandbox-where, .bot-sandbox-where { margin: -4px 0 8px; font-size: 12.5px; color: var(--text-secondary); } +.bot-sandbox-section > .settings-item:first-child { border-top: 0; } +.bot-sandbox-item .settings-item-title { font-size: 13.5px; } +.bot-sandbox-item.is-dimmed :is(.settings-item-title, .bot-sandbox-value) { opacity: .55; } +.bot-sandbox-item .settings-item-control { min-width: 0; } +.bot-sandbox-value { font-size: 12.5px; color: var(--text-secondary); text-align: right; white-space: pre-line; overflow-wrap: anywhere; } +.bot-sandbox-value.is-warn { color: var(--warning); } +.modal-body > h4.bot-sandbox-heading { margin: 20px 0 2px; font-size: 13px; font-weight: 600; color: var(--text-primary); } +.bot-sandbox-dialog .bot-sandbox-actions { margin-top: 12px; } +.bot-sandbox-actions .settings-btn { height: 28px; padding: 0 10px; border-radius: var(--ui-control-radius, 8px); font-size: 12px; } +.modal-body > p.bot-sandbox-error { margin: 8px 0 0; font-size: 12.5px; color: var(--danger); } +.modal-body > p.bot-sandbox-problem { margin: 12px 0 0; font-size: 12.5px; color: var(--text-secondary); } +.bot-new-sandbox .bot-sandbox-where { margin: 0 0 4px; } /* Context: the composer's context bar and breakdown, laid open. */ .bot-about .bot-about-context { flex-direction: column; align-items: stretch; justify-content: flex-start; gap: var(--space-8); } @@ -1059,3 +1074,4 @@ html[data-theme='blacksphere-plus'] .chat-list-row:not(.active):hover { backgrou /* Move bot dialog: destination picker sits cleanly above the confirmation copy. */ .bot-transfer-row { display: flex; flex-direction: column; gap: 6px; margin-bottom: 12px; } .bot-transfer-row .ui-select { width: 100%; } +.bot-sandbox-approvals { display: inline-flex; align-items: center; gap: 4px; } diff --git a/src/shared/bots/personal/methodTable.ts b/src/shared/bots/personal/methodTable.ts index 90f1701eb..dbe9b32ce 100644 --- a/src/shared/bots/personal/methodTable.ts +++ b/src/shared/bots/personal/methodTable.ts @@ -111,10 +111,10 @@ export const BOT_METHODS = { 'bots.personal.list': { level: 'use', local: chat([]) }, 'bots.create': { level: 'full', - local: chat(['look', 'name', 'description', 'clientRequestId', 'model', 'slots', 'image', 'access']), + local: chat(['look', 'name', 'description', 'clientRequestId', 'model', 'slots', 'image', 'access', 'sandbox']), // 2: `reach` (`RemoteBotReach`). 3: the rows, the Images row and the Devices step of New bot "Lives on" (`slots`, - // `image`, `access`), each as the bot's computer offers them. - remote: writes(['look', 'description', 'clientRequestId'], ['name', 'reach', 'slots', 'image', 'access'], 3) + // `image`, `access`), each as the bot's computer offers them. 4: its Sandbox step (`sandbox`). + remote: writes(['look', 'description', 'clientRequestId'], ['name', 'reach', 'slots', 'image', 'access', 'sandbox'], 4) }, 'bots.get': { level: 'use', local: chat(['botId']), remote: reads(['botId']) }, // 2: `description`, the bot's instructions as About edits them. diff --git a/src/shared/bots/personal/methods.ts b/src/shared/bots/personal/methods.ts index 94cffcb6a..d1c86f83d 100644 --- a/src/shared/bots/personal/methods.ts +++ b/src/shared/bots/personal/methods.ts @@ -7,7 +7,7 @@ import type { BotPickReason } from './modelSlots' import type { BotMemoryEntry, BotMemoryForgetResult, BotMemoryListing } from './memory' import type { LlmProviderOption } from '../../settings' import type { BotDeviceChoice, NewBotAccess } from './deviceAccess' -import type { BotSandboxNetwork, BotSandboxView } from './sandbox' +import type { BotSandboxNetwork, BotSandboxView, NewBotSandbox } from './sandbox' /** * An answer to an ask card (`bots.asks.answer`): Allow, Not now, or Allow once, which only a destructive command's card @@ -82,6 +82,8 @@ export interface BotRunsOnChoices { * which refuses the key, so the app sends none there. */ reachOnCreate?: true + /** The service takes `sandbox` on `bots.create` (New bot's Sandbox step). Absent from an older service, which refuses the key. */ + sandboxOnCreate?: true /** * The owner's other devices (phones too), for New bot's Devices step, which shows only when there is at least one: a * new bot reaches this computer alone plus the ones ticked there. Absent when there are none, from `bots.model.get`, @@ -226,9 +228,10 @@ export interface BotsPersonalV2Api { * service whose choices carry `imageProviders`. `access`: which devices reach the new bot (New bot's Devices step), * saved before the bot is listed anywhere; sent only to a service whose choices carry `reachOnCreate`. Absent, or * `all` from an older app, this computer alone. `node` (a window only): made on that other computer of the owner's, - * New bot's "Lives on", routed there; it always reaches this computer too. + * New bot's "Lives on", routed there; it always reaches this computer too. `sandbox`: New bot's Sandbox step, written with + * the bot so its first turn already runs under it; sent only to a service whose choices carry `sandboxOnCreate`. */ - 'bots.create': { params: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; node?: string }; result: { bot: BotSummary } } + 'bots.create': { params: { look: BotLook; name?: string; description: string; clientRequestId: string; model?: string; slots?: BotModelSlots; image?: BotModelPick; access?: NewBotAccess; sandbox?: NewBotSandbox; node?: string }; result: { bot: BotSummary } } 'bots.get': { params: { botId: string }; result: BotDetail } /** * Renames the bot, changes its look, or (`description`) edits its prompt in About: the description it works under from diff --git a/src/shared/bots/personal/sandbox.ts b/src/shared/bots/personal/sandbox.ts index 931a2c8aa..9f24d90e2 100644 --- a/src/shared/bots/personal/sandbox.ts +++ b/src/shared/bots/personal/sandbox.ts @@ -1,12 +1,48 @@ /** * A personal bot's command sandbox (docs/plans/bot-sandbox-setting.md, docs/bots.md "Command sandbox"): the owner's two - * switches in About → Can use, what one launch of the bot's commands runs with once they are read on the bot's computer + * settings in About → Sandbox, what one launch of the bot's commands runs with once they are read on the bot's computer * (`BotSandboxPolicy`), and every word the owner and the bot are told about it. Types and pure functions only, * browser-safe. */ -/** What sandboxed commands may reach of the network. Typed, so a list of sites can be added later. */ -export type BotSandboxNetwork = { kind: 'blocked' } | { kind: 'open' } +/** + * What a launcher gives sandboxed commands of the network: none (`blocked`); the public web only, through Mousse's + * proxy, which refuses this computer, the local network and every other special-purpose address (`public`); or this + * computer's network as it is (`direct`). + */ +export type BotSandboxNetworkKind = 'blocked' | 'public' | 'direct' + +/** A network a launcher gives (`BotSandboxNetworkKind`). Typed, so a list of sites can be added later. */ +export type BotSandboxGivenNetwork = { kind: BotSandboxNetworkKind } + +/** + * The owner's network choice for sandboxed commands: one of `BotSandboxNetworkKind`, or `open`, the network on as it was + * saved before the choice was split, which each launcher gives its own way (`BotSandboxSupport.networks.open`): the + * public web on Claude Code, this computer's network on Codex and Mousse's runner. A new choice is never `open`. + */ +export type BotSandboxNetwork = BotSandboxGivenNetwork | { kind: 'open' } + +/** The network choices the owner picks from, in order. */ +export const BOT_SANDBOX_NETWORK_KINDS: readonly BotSandboxNetworkKind[] = Object.freeze(['blocked', 'public', 'direct']) + +/** A network choice's name, as the owner picks it. */ +export const BOT_SANDBOX_NETWORK_NAMES: Readonly> = Object.freeze({ blocked: 'Blocked', public: 'Public web', direct: 'Direct' }) + +/** What each network choice gives, for its tooltip. */ +export const BOT_SANDBOX_NETWORK_TIPS: Readonly> = Object.freeze({ + blocked: 'No network for commands.', + public: 'Public internet sites only, such as GitHub, git, npm and pip. Not this computer or your local network.', + direct: "This computer's network as it is, your local network and services on this computer included." +}) + +/** + * Whether going from `before` to `after` leaves what runs under `before` as it may run now. Only a change from Blocked + * does: any other change can make a launcher's network narrower, or unavailable where it can't give the new choice + * (Public web to Direct on Claude Code), so what runs under the old one stops. + */ +export function botSandboxNetworkWidens(before: BotSandboxNetwork['kind'], after: BotSandboxNetwork['kind']): boolean { + return before === after || before === 'blocked' +} /** * The owner's setting for one bot, kept on the bot's computer (`bot_sandbox` in `bots.db`): whether its commands run in a @@ -26,6 +62,23 @@ export interface BotSandboxSetting { */ export const BOT_SANDBOX_DEFAULT: Omit = Object.freeze({ sandbox: 'off', network: Object.freeze({ kind: 'open' }) }) +/** New bot's Sandbox step: whether the new bot's commands run in a sandbox, and its network (`bots.create`'s `sandbox`). */ +export interface NewBotSandbox { + sandbox: 'on' | 'off' + network: BotSandboxGivenNetwork +} + +/** New bot's Sandbox step starts here: off, with the public web once it is turned on. */ +export const BOT_SANDBOX_DRAFT_DEFAULT: Readonly = Object.freeze({ sandbox: 'off', network: Object.freeze({ kind: 'public' }) }) + +/** Whether `value` is New bot's Sandbox step as the app sends it: exactly the two keys, and a network the owner can choose now. */ +export function isNewBotSandbox(value: unknown): value is NewBotSandbox { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false + const input = value as Record + return Object.keys(input).length === 2 && (input.sandbox === 'on' || input.sandbox === 'off') && + isBotSandboxNetworkChoice(input.network) && Object.keys(input.network as object).length === 1 +} + /** The kind of launch a policy is read for: a main work turn, a chat turn, a background command, a secret command, a subagent. */ export type BotSandboxLaunch = 'work' | 'chat' | 'watcher' | 'secret' | 'subagent' @@ -63,8 +116,8 @@ export interface BotSandboxUnavailable { os?: string /** The packages that fix it, for `missing_packages`. */ missing?: readonly BotSandboxPackage[] - /** For `network_mode`: the network setting that can't be given. */ - network?: BotSandboxNetwork['kind'] + /** For `network_mode`: the network choice that can't be given. */ + network?: BotSandboxNetworkKind /** What the sandbox printed when it failed to start (`start_failed`), for the card's details. Never shown to the bot. */ detail?: string /** `install`: a package fixes it, and Install what's missing opens a terminal to add it. */ @@ -83,10 +136,10 @@ export interface BotSandboxUnavailable { */ export type BotSandboxPolicy = | { kind: 'open'; revision: number } - | { kind: 'held'; revision: number; network: BotSandboxNetwork; readsAll?: true } + | { kind: 'held'; revision: number; network: BotSandboxGivenNetwork; readsAll?: true } | ({ kind: 'unavailable'; revision: number } & BotSandboxUnavailable) -/** About → Can use's view of the sandbox, read on the bot's computer (`bots.sandbox.get`). */ +/** About → Sandbox's view of the sandbox, read on the bot's computer (`bots.sandbox.get`). */ export interface BotSandboxView { setting: BotSandboxSetting /** The bot's computer, by name. */ @@ -102,6 +155,16 @@ export interface BotSandboxView { runner?: BotSandboxPolicy /** What each launcher the bot has a card for runs with now, by entry (`BotSandboxCard.entry`), the work's and the runner's included. */ entries?: Record + /** How far held commands reach here: the work's (`policy`) and the runner's (`runner`), each while held. */ + reach?: { work?: BotSandboxReach; runner?: BotSandboxReach } +} + +/** How far a launcher's held commands reach on this computer, for the Sandbox dialog's summary. */ +export interface BotSandboxReach { + /** 0: the system's folders and the bot's; 1: everything but the home folder; 2–3: every file the account reads. */ + reads: 0 | 1 | 2 | 3 + /** Servers its commands start can be reached from outside the sandbox. */ + servers: boolean } /** The launcher that can't start now, the work's first, then Mousse's runner: what About shows and repairs. */ @@ -124,11 +187,12 @@ export function botSandboxCardPolicy(view: Pick): string { - const { policy } = view - if (policy.kind === 'open') return 'Commands run like they do in your own threads. Bot permissions and approvals still apply.' - if (policy.kind === 'unavailable') return `On, but commands can't start on ${view.computer}. ${botSandboxReasonText(policy)}` - // The work's commands start; Mousse's runner, which runs background and secret commands, can't. - if (view.runner?.kind === 'unavailable') return `On, but background and secret commands can't start on ${view.computer}. ${botSandboxReasonText(view.runner)}` - return policy.readsAll ? 'Commands can change files only in allowed folders. They can still read other files.' : 'Commands can change files only in allowed folders.' +/** The Sandbox row's value in About: Off, On with its network, or that commands can't start. */ +export function botSandboxState(view: Pick): { text: string; warn: boolean } { + if (view.setting.sandbox === 'off') return { text: 'Off', warn: false } + if (botSandboxProblem(view)) return { text: "On · Can't start", warn: true } + const network = view.setting.network.kind + return { text: `On · ${network === 'open' ? 'Network on' : BOT_SANDBOX_NETWORK_NAMES[network]}`, warn: false } +} + +/** The name of Mousse's runner's commands in the summary. */ +export const BOT_SANDBOX_RUNNER_NAME = 'Background commands' + +/** One row of the Sandbox dialog's summary of what commands reach. `warn`: a launcher can't start. */ +export interface BotSandboxReachLine { + id: 'commands' | 'files' | 'network' | 'servers' + label: string + text: string + tip?: string + warn?: true +} + +/** What one launcher's commands reach, row by row, or why they can't start. */ +type LauncherReach = { name: string } & ({ problem: string } | { files: string; filesTip: string; network: string; servers: string }) + +function launcherReach(name: string, policy: BotSandboxPolicy, reach: BotSandboxReach | undefined): LauncherReach { + if (policy.kind === 'unavailable') return { name, problem: botSandboxReasonText(policy) } + if (policy.kind === 'open') return { name, files: 'Like your own threads', filesTip: 'The sandbox is off for these commands.', network: 'Like your own threads', servers: 'Like your own threads' } + const reads = policy.readsAll ? 3 : reach?.reads ?? 0 + const read = reads === 0 ? 'system files' : reads === 1 ? 'all but your home folder' : 'every file' + return { + name, + files: reads === 0 ? 'Its folders only' : `Changes its folders, reads ${read}`, + filesTip: `Commands change files only in the bot's folders. They read ${reads === 0 ? "its folders and the system's" : read}.`, + network: BOT_SANDBOX_NETWORK_NAMES[policy.network.kind], + servers: reach?.servers ? 'Reachable on this computer' : 'Inside only' + } } -/** About's status line under Allow network for sandboxed commands; `dimmed` when it doesn't apply now. */ -export function botSandboxNetworkLine(view: Pick): { text: string; dimmed: boolean } { - const { setting, policy } = view - if (setting.sandbox === 'off') return { text: 'Applies when the sandbox is on.', dimmed: true } - if (policy.kind === 'unavailable' && policy.reason === 'network_mode') return { text: `Not available with ${policy.provider} here. ${botSandboxReasonText(policy)}`, dimmed: true } - return setting.network.kind === 'open' - ? { text: 'Sandboxed commands can use the network.', dimmed: false } - : { text: "Sandboxed commands can't use the network.", dimmed: false } +/** + * The Sandbox dialog's summary: in plain words, what the bot's commands reach now, read from the same result launches + * use (`BotSandboxView`). Off: one row. On: files, network and local servers, each naming a launcher only where the + * work's provider and Mousse's runner (background and secret commands) differ; a launcher that can't start says so. + */ +export function botSandboxReachLines(view: Pick): BotSandboxReachLine[] { + if (view.setting.sandbox === 'off') return [{ id: 'commands', label: 'Commands', text: 'Like your own threads', tip: 'Bot permissions, approvals and secret masking still apply.' }] + const launchers = [launcherReach(view.provider, view.policy, view.reach?.work), ...(view.runner ? [launcherReach(BOT_SANDBOX_RUNNER_NAME, view.runner, view.reach?.runner)] : [])] + const lines: BotSandboxReachLine[] = [] + const broken = launchers.filter((launcher): launcher is Extract => 'problem' in launcher) + for (const launcher of broken) lines.push({ id: 'commands', label: launchers.length > 1 ? launcher.name : 'Commands', text: "Can't start", tip: launcher.problem, warn: true }) + const held = launchers.filter((launcher): launcher is Exclude => !('problem' in launcher)) + const row = (id: 'files' | 'network' | 'servers', label: string, pick: (launcher: (typeof held)[number]) => string, tip?: (launcher: (typeof held)[number]) => string) => { + if (!held.length) return + const texts = held.map(pick) + const same = texts.every((text) => text === texts[0]) + // One line per launcher where they differ. + const text = same || held.length === 1 ? texts[0]! : held.map((launcher, index) => `${launcher.name}: ${texts[index]}`).join('\n') + const tips = tip ? [...new Set(held.map(tip))] : [] + lines.push({ id, label, text, ...(tips.length ? { tip: tips.join(' ') } : {}) }) + } + row('files', 'Files', (launcher) => launcher.files, (launcher) => launcher.filesTip) + row('network', 'Network', (launcher) => launcher.network) + row('servers', 'Local servers', (launcher) => launcher.servers) + const network = lines.find((line) => line.id === 'network') + if (network && view.setting.network.kind === 'open') network.tip = 'Saved before Public web and Direct were separate choices. Pick one to change it.' + return lines +} + +/** A network in words, for the bot: what its commands get. */ +function networkWords(network: BotSandboxGivenNetwork): string { + return network.kind === 'blocked' ? "can't use the network" : network.kind === 'public' ? 'can reach public internet sites only' : "can use this computer's network" } /** The bot's system line on its sandbox, under "What your owner allows now", when it may run commands. */ export function botSandboxSystemLine(policy: BotSandboxPolicy, computer: string): string { if (policy.kind === 'open') return "- Your command sandbox is off. Commands run like your owner's own. Your permissions and approvals still apply." if (policy.kind === 'unavailable') - return `- Your command sandbox can't start on ${computer}: ${clause(botSandboxReasonText(policy))}. Commands can't run now. Point your owner to "${BOT_SANDBOX_TURN_OFF}" on the card or in About → Can use, and to "${BOT_SANDBOX_INSTALL}" when the card shows it. Never tell them to type install commands or restart Mousse.` - return policy.network.kind === 'open' - ? '- Your command sandbox is on. Commands can change files only in allowed folders and can use the network.' - : `- Your command sandbox is on. Commands can change files only in allowed folders and can't use the network. If a command needs the network, tell your owner they can turn on "${BOT_SANDBOX_NETWORK_LABEL}" in About → Can use. Don't work around it.` + return `- Your command sandbox can't start on ${computer}: ${clause(botSandboxReasonText(policy))}. Commands can't run now. Point your owner to "${BOT_SANDBOX_TURN_OFF}" on the card or under ${BOT_SANDBOX_WHERE}, and to "${BOT_SANDBOX_INSTALL}" when the card shows it. Never tell them to type install commands or restart Mousse.` + return policy.network.kind !== 'blocked' + ? `- Your command sandbox is on. Commands can change files only in allowed folders and ${networkWords(policy.network)}.` + : `- Your command sandbox is on. Commands can change files only in allowed folders and can't use the network. If a command needs the network, tell your owner they can choose a network under ${BOT_SANDBOX_WHERE}. Don't work around it.` } /** @@ -206,7 +323,7 @@ export function botSandboxSystemLine(policy: BotSandboxPolicy, computer: string) export function botSandboxRefusal(unavailable: BotSandboxUnavailable, computer: string): string { const reason = clause(botSandboxReasonText(unavailable)) const install = unavailable.repair === 'install' ? ` To keep the sandbox on, choose **${BOT_SANDBOX_INSTALL}**. I'll check again on my next turn.` : '' - return `This command did not run: your command sandbox can't start on ${computer}. Tell your owner: "I couldn't run commands on ${computer}: ${reason}. Choose **${BOT_SANDBOX_TURN_OFF}** on the card or in About → Can use.${install}" Don't retry the command in this turn.` + return `This command did not run: your command sandbox can't start on ${computer}. Tell your owner: "I couldn't run commands on ${computer}: ${reason}. Choose **${BOT_SANDBOX_TURN_OFF}** on the card or under ${BOT_SANDBOX_WHERE}.${install}" Don't retry the command in this turn.` } /** The card Mousse posts in the bot's chat when its sandbox can't start: one per reason until it starts or is turned off. */ @@ -255,9 +372,38 @@ export function isBotSandboxCard(value: unknown): value is BotSandboxCard { (card.repair === 'install' || card.repair === 'none') && (card.detail === undefined || typeof card.detail === 'string') } -/** Whether `value` is a saved network choice. */ +/** Whether `value` is a saved network choice (`open` included, as saved before the choice was split). */ export function isBotSandboxNetwork(value: unknown): value is BotSandboxNetwork { - return Boolean(value) && typeof value === 'object' && ((value as { kind?: unknown }).kind === 'blocked' || (value as { kind?: unknown }).kind === 'open') + const kind = value && typeof value === 'object' ? (value as { kind?: unknown }).kind : undefined + return kind === 'blocked' || kind === 'public' || kind === 'direct' || kind === 'open' +} + +/** Whether `value` is a network choice the owner can make now: never `open`, which only an older choice keeps. */ +export function isBotSandboxNetworkChoice(value: unknown): value is BotSandboxGivenNetwork { + return isBotSandboxNetwork(value) && value.kind !== 'open' +} + +/** + * What the owner can do on a card of a command the sandbox stopped: + * - `repair`: install what's missing (a terminal with the command typed) or start the sandbox again; + * - `turn_off`: turn this bot's sandbox off; + * - `allow_once` / `keep_allowing`: let the one stopped launch through, or keep allowing what it needed. These need a + * launch Mousse holds and can let through, which only Mousse's own command runner can do; no card offers them yet. + */ +export type BotSandboxCardAction = 'repair' | 'allow_once' | 'keep_allowing' | 'turn_off' + +/** Reasons a fresh start may clear without installing anything (the owner fixed it, or it failed once). */ +const RECHECKABLE: ReadonlySet = new Set(['start_failed', 'command_rules', 'userns_blocked', 'missing_packages']) + +/** + * The buttons a card shows for `policy` now, in order: only what the bot's computer can do. `install`: Install has a + * command to offer (`repair: 'install'`, and the computer gave one). `held`: a stopped launch the card can let through + * (none yet: Allow once and Keep allowing come with Mousse's command runner). + */ +export function botSandboxCardActions(policy: BotSandboxPolicy, options: { install: boolean; held?: boolean }): BotSandboxCardAction[] { + if (policy.kind !== 'unavailable') return [] + const repair = options.install || RECHECKABLE.has(policy.reason) + return [...(repair ? ['repair' as const] : []), ...(options.held ? ['allow_once' as const, 'keep_allowing' as const] : []), 'turn_off'] } /** The runtime's name in the owner's words. */ diff --git a/src/shared/bots/personal/subagentHold.ts b/src/shared/bots/personal/subagentHold.ts index 4c4ba59ae..d828304c0 100644 --- a/src/shared/bots/personal/subagentHold.ts +++ b/src/shared/bots/personal/subagentHold.ts @@ -38,6 +38,8 @@ export interface BotCommandHold { reads: 0 | 1 | 2 | 3 writes: 0 | 1 | 2 network: boolean + /** Its network is the public web only (through Mousse's proxy), not this computer's network. */ + publicOnly?: boolean /** Restricted Claude Code on Linux also opens /tmp, which Codex closes. */ sharedTemp?: boolean } @@ -57,7 +59,7 @@ export function commandReach(hold: BotRuntimeHold | undefined): BotCommandHold | export function commandsWithin(sub: BotCommandHold | 'none', work: BotCommandHold | 'none'): boolean { if (sub === 'none') return true if (work === 'none') return false - return sub.reads <= work.reads && sub.writes <= work.writes && (!sub.network || work.network) && (!sub.sharedTemp || work.sharedTemp === true || work.reads > 0) + return sub.reads <= work.reads && sub.writes <= work.writes && (!sub.network || (work.network && (!work.publicOnly || sub.publicOnly === true))) && (!sub.sharedTemp || work.sharedTemp === true || work.reads > 0) } /** diff --git a/src/shared/secretRequests.ts b/src/shared/secretRequests.ts index 4e40b1a30..803e8bdfc 100644 --- a/src/shared/secretRequests.ts +++ b/src/shared/secretRequests.ts @@ -58,6 +58,8 @@ export interface SecretEntryView { expiresAt?: string /** The thread that asked for it. */ threadId?: string + /** Every thread that may use it by name: the one that asked, and any it was given to later (Use saved). */ + threads?: string[] threadTitle?: string createdAt?: string lastUsedAt?: string diff --git a/tests/bots/botMethodTable.test.ts b/tests/bots/botMethodTable.test.ts index 326528208..d204b8e79 100644 --- a/tests/bots/botMethodTable.test.ts +++ b/tests/bots/botMethodTable.test.ts @@ -99,7 +99,7 @@ describe('the bot method table', () => { // About → System instructions: setting the bot up, from a person's window only. 'bots.systemInstructions.get': 'full', 'bots.systemInstructions.set': 'full', - // About → Can use → Sandbox commands: setting the bot up; changes from a person's window only. + // About → Sandbox: setting the bot up; changes from a person's window only. 'bots.sandbox.get': 'full', 'bots.sandbox.set': 'full', 'bots.sandbox.install': 'full', diff --git a/tests/bots/botSandboxSetting.test.ts b/tests/bots/botSandboxSetting.test.ts index 93b2a97b7..a8059e4ee 100644 --- a/tests/bots/botSandboxSetting.test.ts +++ b/tests/bots/botSandboxSetting.test.ts @@ -81,8 +81,8 @@ describe("a bot's command sandbox setting", () => { it("each turn's commands run as the setting says, and the bot is told which", async () => { const held = await work('held') - expect(held.prepared.authority.sandbox).toMatchObject({ computer: 'Laptop', policy: { kind: 'held', network: { kind: 'open' } } }) - expect(held.prepared.instructions).toContain('Your command sandbox is on. Commands can change files only in allowed folders and can use the network.') + expect(held.prepared.authority.sandbox).toMatchObject({ computer: 'Laptop', policy: { kind: 'held', network: { kind: 'public' } } }) + expect(held.prepared.instructions).toContain('Your command sandbox is on. Commands can change files only in allowed folders and can reach public internet sites only.') await finish(f, held.payload, 'completed', { text: 'Done.' }) await f.bots.service.sandboxSet(botId, { sandbox: 'off' }) const open = await work('open') @@ -240,6 +240,33 @@ describe("a bot's command sandbox setting", () => { expect(await call('bots.sandbox.get', { botId })).toMatchObject({ setting: { revision: 3 } }) }) + it("New bot's Sandbox step is written with the bot, before its first turn, here and from another device; an old `open` or a stray key is refused", async () => { + const domains = new DomainHandlerRegistry() + registerPersonalBotMethods(domains, () => f.bots.service) + const window = { connection: { id: 'c', binding: { profileId: 'p1', epoch: 1 }, capabilities: new Set(), clientType: 'gui' } } as unknown as HandlerContext + const create = (key: string, sandbox: unknown) => domains.dispatch(window, 'bots.create', { look: { colour: 'teal', accessory: 'cap' }, description: 'Watch the build.', clientRequestId: key, sandbox }) as Promise<{ bot: { id: string } }> + const made = await create('sb-1', { sandbox: 'on', network: { kind: 'direct' } }) + expect(f.store.sandboxSetting(made.bot.id)).toEqual({ sandbox: 'on', network: { kind: 'direct' }, revision: 1 }) + // Its first turn reads it: the chat turn that says hello already runs under it. + const first = f.store.listActivations(made.bot.id).find((activation) => activation.lane === 'chat')! + expect((await start(f, first.id)).prepared.authority.sandbox.policy).toMatchObject({ kind: 'held', network: { kind: 'direct' }, revision: 1 }) + for (const sandbox of [{ sandbox: 'on', network: { kind: 'open' } }, { sandbox: 'on' }, { sandbox: 'on', network: { kind: 'public' }, extra: 1 }]) + await expect(create(`sb-bad-${JSON.stringify(sandbox)}`, sandbox)).rejects.toMatchObject({ code: 'invalid_params' }) + + // Another device's New bot: its step reaches the bot's computer as it was set (the devices it reaches are not this test's). + const service = f.bots.service + const port = new Proxy(service, { get: (target, key) => key === 'create' ? (input: Parameters[0]) => { const { access: _access, ...rest } = input; return service.create(rest) } : Reflect.get(target, key, target) }) + const methods = remoteBotMethods({ bots: () => port, reach: { level: () => 'full', canReach: () => true } }) + const row = methods.find((each) => each.method === 'bots.create')! + const caller = { caller: { node: 'n_laptop', user: 'u' } } as unknown as RpcContext + const params = row.validate!({ look: { colour: 'teal', accessory: 'cap' }, description: 'Watch the build.', clientRequestId: 'sb-remote', sandbox: { sandbox: 'on', network: { kind: 'blocked' } } }) + row.authorize?.(params, caller) + await row.authorizeNew?.(params, caller) + const remote = await row.handle(params, caller) as { bot: { id: string } } + expect(f.store.sandboxSetting(remote.bot.id.split(':').at(-1)!)).toMatchObject({ sandbox: 'on', network: { kind: 'blocked' } }) + expect(() => row.validate!({ look: { colour: 'teal', accessory: 'cap' }, description: 'x', clientRequestId: 'sb-r2', sandbox: { sandbox: 'on', network: { kind: 'open' } } })).toThrow() + }) + it('Install what is missing: the distribution\'s own package manager, for the packages missing; none where none is known', () => { const os = (text: string) => () => text expect(sandboxInstallCommand(['socat'], os('ID=ubuntu\nID_LIKE=debian\n'))).toBe('sudo apt-get install -y socat') diff --git a/tests/bots/botSubagentRuntimes.test.ts b/tests/bots/botSubagentRuntimes.test.ts index 94c7550fd..c2e969ecb 100644 --- a/tests/bots/botSubagentRuntimes.test.ts +++ b/tests/bots/botSubagentRuntimes.test.ts @@ -115,9 +115,9 @@ describe('a subagent on another runtime, through the real drivers', () => { it("the drivers say how far a bot's held commands reach here: Claude Code's Seatbelt on macOS reads all but the home folder, Codex's profile only the system's and the bot's", () => { expect(harness.botSandbox('claude')).toMatchObject({ runtime: 'claude' }) - expect(harness.botSandbox('claude')!.reach({ kind: 'blocked' })).toEqual({ reads: 1, writes: 0, network: false }) + expect(harness.botSandbox('claude')!.reach({ kind: 'blocked' })).toEqual({ reads: 1, writes: 0, network: false, publicOnly: true }) expect(harness.botSandbox('codex')).toMatchObject({ runtime: 'codex' }) - expect(harness.botSandbox('codex')!.reach({ kind: 'open' })).toEqual({ reads: 0, writes: 0, network: true }) + expect(harness.botSandbox('codex')!.reach({ kind: 'direct' })).toEqual({ reads: 0, writes: 0, network: true }) expect(harness.botSandbox('claude:unknown')).toBeUndefined() }) diff --git a/tests/bots/botWorkSubagentsHold.test.ts b/tests/bots/botWorkSubagentsHold.test.ts index 534cdf826..8e84e8579 100644 --- a/tests/bots/botWorkSubagentsHold.test.ts +++ b/tests/bots/botWorkSubagentsHold.test.ts @@ -46,7 +46,7 @@ describe('a subagent on another entry is never held less tightly than its work', const own = { pick: { ...PI }, name: { name: 'Some Model', entry: 'OpenRouter' } } /** How each entry sandboxes the bot's commands here: its runtime and how far a held command reaches. */ const support = (runtime: BotSandboxSupport['runtime'], reach: Omit, hostedSearch?: BotSandboxSupport['hostedSearch']): BotSandboxSupport => - ({ runtime, key: runtime, probe: async () => undefined, reach: (network) => ({ ...reach, network: network.kind === 'open' }), ...(hostedSearch ? { hostedSearch } : {}) }) + ({ runtime, key: runtime, networks: { gives: ['blocked', 'public', 'direct'], open: 'direct' }, probe: async () => undefined, reach: (network) => ({ ...reach, network: network.kind !== 'blocked' }), ...(hostedSearch ? { hostedSearch } : {}) }) /** Claude Code's sandbox on Linux: the system's folders and the bot's; and an entry whose commands read everything. */ const TIGHT = support('claude', { reads: 0, writes: 0, sharedTemp: true }) const LOOSE = support('pi', { reads: 3, writes: 0 }) diff --git a/tests/bots/sandbox/claudeSupport.test.ts b/tests/bots/sandbox/claudeSupport.test.ts index a96b77d0f..c52ea6359 100644 --- a/tests/bots/sandbox/claudeSupport.test.ts +++ b/tests/bots/sandbox/claudeSupport.test.ts @@ -10,10 +10,10 @@ import type { ProbeRun } from '../../../src/mms/bots/sandbox/probe' import { claudeCodeDriver } from '../../../src/mms/harness/drivers/claudeCode' import { decodeInstanceConfig } from '../../../src/mms/harness/driver' import { instanceEnv } from '../../../src/mms/harness/env' -import type { BotSandboxNetwork } from '../../../src/shared/bots/personal/sandbox' +import type { BotSandboxGivenNetwork } from '../../../src/shared/bots/personal/sandbox' -const BLOCKED: BotSandboxNetwork = { kind: 'blocked' } -const OPEN: BotSandboxNetwork = { kind: 'open' } +const BLOCKED: BotSandboxGivenNetwork = { kind: 'blocked' } +const OPEN: BotSandboxGivenNetwork = { kind: 'public' } /** A Linux computer whose PATH is `/usr/bin` and whose programs are `files`. */ function linux(files: string[], options: { run?: ProbeRun; wsl1?: boolean; proxy?: () => Promise; windowsDrive?: boolean } = {}) { @@ -32,7 +32,7 @@ function linux(files: string[], options: { run?: ProbeRun; wsl1?: boolean; proxy } describe('claudeSandboxSupport: what a probe finds', () => { - const rows: Array<{ name: string; files: string[]; network: BotSandboxNetwork; run?: ProbeRun; wsl1?: boolean; windowsDrive?: boolean; proxy?: () => Promise; expected: Record | undefined; started?: boolean; proxied?: boolean }> = [ + const rows: Array<{ name: string; files: string[]; network: BotSandboxGivenNetwork; run?: ProbeRun; wsl1?: boolean; windowsDrive?: boolean; proxy?: () => Promise; expected: Record | undefined; started?: boolean; proxied?: boolean }> = [ { name: 'WSL 1', files: ['/usr/bin/bwrap', '/usr/bin/socat'], network: BLOCKED, wsl1: true, expected: { reason: 'wsl1', provider: 'Claude Code', repair: 'none' }, started: false }, // WSL 2 with a Windows drive mounted: Claude Code's sandbox fails every command there (checked by hand). { name: 'WSL 2 with a Windows drive mounted', files: ['/usr/bin/bwrap', '/usr/bin/socat'], network: OPEN, windowsDrive: true, expected: { reason: 'start_failed', detail: CLAUDE_WSL_WINDOWS_DRIVE }, started: false, proxied: false }, @@ -91,8 +91,8 @@ describe('claudeSandboxSupport: what a probe finds', () => { }) it('reach and key: what a held command reaches here, and a new PATH or program probes again', () => { - expect(claudeSandboxSupport({ platform: 'linux', env: { PATH: '/usr/bin' } }).reach(OPEN)).toEqual({ reads: 0, writes: 0, network: true, sharedTemp: true }) - expect(claudeSandboxSupport({ platform: 'darwin', env: { PATH: '/usr/bin' } }).reach(BLOCKED)).toEqual({ reads: 1, writes: 0, network: false }) + expect(claudeSandboxSupport({ platform: 'linux', env: { PATH: '/usr/bin' } }).reach(OPEN)).toEqual({ reads: 0, writes: 0, network: true, publicOnly: true, sharedTemp: true }) + expect(claudeSandboxSupport({ platform: 'darwin', env: { PATH: '/usr/bin' } }).reach(BLOCKED)).toEqual({ reads: 1, writes: 0, network: false, publicOnly: true }) const keys = new Set([ claudeSandboxSupport({ platform: 'linux', env: { PATH: '/usr/bin' } }).key, claudeSandboxSupport({ platform: 'linux', env: { PATH: '/usr/bin:/usr/local/bin' } }).key, diff --git a/tests/bots/sandbox/networkChoice.test.ts b/tests/bots/sandbox/networkChoice.test.ts new file mode 100644 index 000000000..d49fc9720 --- /dev/null +++ b/tests/bots/sandbox/networkChoice.test.ts @@ -0,0 +1,91 @@ +/** + * The owner's network choice for a bot's sandboxed commands (Blocked, Public web, Direct, and `open` as saved before the + * choice was split), as each launcher's resolver result gives it: what a launch runs with, and the choices a launcher + * can't give, which are unavailable rather than swapped for a wider or narrower one. The probes are hand-authored + * starts that succeed; they prove Mousse's side only. + * + * The inputs (test-the-claim §4): + * - launchers: Claude Code (Mousse's public-only proxy), Codex (its own network switch), Mousse's runner; + * - choices: blocked, public, direct, and a saved `open`; + * - changes between choices, for what stops running commands (tighter) and what doesn't (wider). + */ +import { describe, expect, it } from 'vitest' +import { BotSandboxResolver, type BotSandboxSupport } from '../../../src/mms/bots/sandbox/BotSandboxResolver' +import { claudeSandboxSupport } from '../../../src/mms/bots/sandbox/claudeSupport' +import { mousseRunnerSupport } from '../../../src/mms/bots/sandbox/runnerSupport' +import { bubblewrapArgs } from '../../../src/mms/bots/sandbox/mousseRunner' +import { codexBotSandboxSupport, type CodexSandboxProgram } from '../../../src/mms/harness/vendors/codex/botSandbox' +import { botSandboxNetworkWidens, type BotSandboxNetwork, type BotSandboxPolicy } from '../../../src/shared/bots/personal/sandbox' +import { commandsWithin } from '../../../src/shared/bots/personal/subagentHold' + +const ok = async () => ({ code: 0, output: '' }) +const program: CodexSandboxProgram = { launch: { path: '/opt/codex/bin/codex', command: '/opt/codex/bin/codex', args: [] }, env: { PATH: '/usr/bin' }, args: [], codexPackage: '/opt/codex' } +const LAUNCHERS: Record = { + claude: claudeSandboxSupport({ platform: 'darwin', env: { PATH: '/usr/bin' }, run: ok, proxy: async () => ({ port: 1 }) }), + codex: codexBotSandboxSupport({ platform: 'darwin', program, run: ok }), + runner: mousseRunnerSupport({ platform: 'darwin', env: { PATH: '/usr/bin' }, run: ok }) +} + +async function resolve(launcher: string, network: BotSandboxNetwork): Promise { + const resolver = new BotSandboxResolver({ setting: () => ({ sandbox: 'on', network, revision: 4 }), support: () => LAUNCHERS[launcher] }) + return resolver.resolve('bot-1', { runner: 'mousse' }, 'work') +} + +const held = (kind: 'blocked' | 'public' | 'direct') => ({ kind: 'held', network: { kind } }) +const cannot = (provider: string, network: 'public' | 'direct') => ({ kind: 'unavailable', reason: 'network_mode', provider, network, repair: 'none' }) + +describe('what each launcher gives for the network chosen', () => { + it.each<[string, BotSandboxNetwork['kind'], object]>([ + ['claude', 'blocked', held('blocked')], + ['claude', 'public', held('public')], + // Its sandbox reaches the network only through a proxy: never this computer's network in its place. + ['claude', 'direct', cannot('Claude Code', 'direct')], + // Saved before the split: what it meant there, the public web through Mousse's proxy. + ['claude', 'open', held('public')], + ['codex', 'blocked', held('blocked')], + // No proxy route: never the whole network in place of the public web. + ['codex', 'public', cannot('Codex', 'public')], + ['codex', 'direct', held('direct')], + ['codex', 'open', held('direct')], + ['runner', 'blocked', held('blocked')], + ['runner', 'public', cannot('Mousse', 'public')], + ['runner', 'direct', held('direct')], + ['runner', 'open', held('direct')] + ])('%s, %s', async (launcher, kind, expected) => { + expect(await resolve(launcher, { kind })).toMatchObject({ revision: 4, ...expected }) + }) + + it("the runner's own launch never opens this computer's network for anything but Direct", () => { + const folders = { cwd: '/home/me/bot', writable: ['/home/me/bot'], readOnly: [] } + expect(bubblewrapArgs('true', { ...folders, network: { kind: 'public' } }, { exists: () => false, link: () => undefined })).toContain('--unshare-net') + expect(bubblewrapArgs('true', { ...folders, network: { kind: 'direct' } }, { exists: () => false, link: () => undefined })).not.toContain('--unshare-net') + }) + + it('a subagent on this computer\'s network is never within work held to the public web', () => { + const publicWeb = LAUNCHERS.claude!.reach({ kind: 'public' }) + const direct = LAUNCHERS.codex!.reach({ kind: 'direct' }) + expect(commandsWithin({ ...direct, reads: 0 }, { ...publicWeb, reads: 1 })).toBe(false) + expect(commandsWithin({ ...publicWeb, reads: 0 }, { ...direct, reads: 1 })).toBe(true) + }) +}) + +describe('which changes of the network stop what runs under the old one', () => { + it.each<[BotSandboxNetwork['kind'], BotSandboxNetwork['kind'], boolean]>([ + // From Blocked, nothing that runs loses anything. + ['blocked', 'public', true], + ['blocked', 'direct', true], + ['blocked', 'open', true], + ['public', 'public', true], + // Any other change can narrow a launcher, or leave it unable to give the new choice (Public web to Direct on + // Claude Code), so what runs under the old one stops. + ['public', 'direct', false], + ['public', 'blocked', false], + ['direct', 'public', false], + ['direct', 'blocked', false], + ['open', 'direct', false], + ['open', 'public', false], + ['open', 'blocked', false] + ])('%s to %s leaves what runs: %s', (before, after, widens) => { + expect(botSandboxNetworkWidens(before, after)).toBe(widens) + }) +}) diff --git a/tests/bots/sandboxSupport.ts b/tests/bots/sandboxSupport.ts index ae6a7da43..269b664c9 100644 --- a/tests/bots/sandboxSupport.ts +++ b/tests/bots/sandboxSupport.ts @@ -2,14 +2,16 @@ import type { BotSandboxSupport } from '../../src/mms/bots/sandbox/BotSandboxRes import type { BotStore } from '../../src/mms/bots/store/BotStore' /** - * A provider entry whose command sandbox starts here (hand-authored): what the bot tests' harness answers for every - * entry, so a bot with the sandbox on runs commands held, as on a computer where the sandbox starts. + * A provider entry whose command sandbox starts here with any network (hand-authored): what the bot tests' harness + * answers for every entry, so a bot with the sandbox on runs commands held, as on a computer where the sandbox starts. + * A saved `open` is the public web on it, as on Claude Code. */ export const STARTING_SANDBOX: BotSandboxSupport = Object.freeze({ runtime: 'claude', key: 'test', + networks: Object.freeze({ gives: Object.freeze(['blocked', 'public', 'direct'] as const), open: 'public' as const }), probe: async () => undefined, - reach: (network) => ({ reads: 0, writes: 0, network: network.kind === 'open' }) + reach: (network) => ({ reads: 0, writes: 0, network: network.kind !== 'blocked' }) }) /** diff --git a/tests/harness/botSubagentHoldReal.test.ts b/tests/harness/botSubagentHoldReal.test.ts index 19ee1bca3..c77a60e4e 100644 --- a/tests/harness/botSubagentHoldReal.test.ts +++ b/tests/harness/botSubagentHoldReal.test.ts @@ -75,7 +75,7 @@ describe(`a subagent on the other runtime is held as its work is, on the real bi // What the drivers say here: Claude Code's sandbox starts (bubblewrap and socat on PATH; /tmp shared); Codex's // profile reads the system's and the bot's folders, and switches its search off. f.host.harness.botSandbox = (instanceId) => (instanceId === 'claude' - ? { ...STARTING_SANDBOX, runtime: 'claude', key: 'claude', reach: (network) => ({ reads: 0, writes: 0, network: network.kind === 'open', sharedTemp: true }) } + ? { ...STARTING_SANDBOX, runtime: 'claude', key: 'claude', reach: (network) => ({ reads: 0, writes: 0, network: network.kind !== 'blocked', sharedTemp: true }) } : { ...STARTING_SANDBOX, runtime: 'codex', key: 'codex', hostedSearch: 'off_without_web' }) f.candidates = [selection[work]] await f.bots.reconcileOnStartup() diff --git a/tests/harness/codexBotSandbox.test.ts b/tests/harness/codexBotSandbox.test.ts index ba87acc0c..98ab74be4 100644 --- a/tests/harness/codexBotSandbox.test.ts +++ b/tests/harness/codexBotSandbox.test.ts @@ -39,7 +39,7 @@ describe("Codex's sandbox for a bot's commands, as the resolver reads it", () => it('a probe starts a harmless command through the entry\'s own Codex, under a profile like the bot\'s, with the network as set, in a folder of its own removed afterwards', async () => { const { run, calls } = runner({ code: 0, output: '' }) const support = codexBotSandboxSupport({ platform: 'linux', program, run }) - expect(await support.probe({ kind: 'open' })).toBeUndefined() + expect(await support.probe({ kind: 'direct' })).toBeUndefined() expect(await support.probe({ kind: 'blocked' })).toBeUndefined() const [open, blocked] = calls expect(open).toMatchObject({ program: '/opt/codex/bin/codex', env: program.env, dirExisted: true }) @@ -71,7 +71,7 @@ describe("Codex's sandbox for a bot's commands, as the resolver reads it", () => const ordinary = codexBotSandboxSupport({ platform: 'win32', program, run, readConfig: () => undefined }) expect(await ordinary.probe({ kind: 'blocked' })).toEqual({ reason: 'network_mode', provider: 'Codex', network: 'blocked', repair: 'none' }) expect(calls).toEqual([]) - expect(await ordinary.probe({ kind: 'open' })).toBeUndefined() + expect(await ordinary.probe({ kind: 'direct' })).toBeUndefined() expect(calls[0]!.args.slice(calls[0]!.args.indexOf('--'))).toEqual(['--', 'cmd.exe', '/d', '/c', 'exit 0']) expect(calls[0]!.args[calls[0]!.args.indexOf('-c') + 1]).toContain('":root" = "read"') const elevated = codexBotSandboxSupport({ platform: 'win32', program, run, readConfig: () => '[windows]\nsandbox = "elevated"\n' }) @@ -122,12 +122,12 @@ describe("Codex's sandbox for a bot's commands, as the resolver reads it", () => it('without starting anything: no sandbox on another system, nothing to start without Codex, none on Windows (where a failed command would run again outside it); how far a held command reaches', () => { expect(codexBotSandboxSupport({ platform: 'aix', program }).unsupported!({ kind: 'blocked' })).toMatchObject({ reason: 'unsupported_os', provider: 'Codex' }) - const onWindows = codexBotSandboxSupport({ platform: 'win32', program }).unsupported!({ kind: 'open' }) + const onWindows = codexBotSandboxSupport({ platform: 'win32', program }).unsupported!({ kind: 'direct' }) expect(onWindows).toMatchObject({ reason: 'unsandboxed_retry', provider: 'Codex', repair: 'none' }) expect(botSandboxReasonText(onWindows!)).toBe("Codex can't keep a failed command from running again outside the sandbox on Windows.") expect(codexBotSandboxSupport({ platform: 'linux', program: undefined }).unsupported!({ kind: 'blocked' })).toMatchObject({ reason: 'start_failed', provider: 'Codex' }) - expect(codexBotSandboxSupport({ platform: 'darwin', program }).unsupported!({ kind: 'open' })).toBeUndefined() - expect(codexBotSandboxSupport({ platform: 'linux', program }).reach({ kind: 'open' })).toEqual({ reads: 0, writes: 0, network: true }) + expect(codexBotSandboxSupport({ platform: 'darwin', program }).unsupported!({ kind: 'direct' })).toBeUndefined() + expect(codexBotSandboxSupport({ platform: 'linux', program }).reach({ kind: 'direct' })).toEqual({ reads: 0, writes: 0, network: true }) expect(codexBotSandboxSupport({ platform: 'darwin', program }).reach({ kind: 'blocked' })).toEqual({ reads: 0, writes: 0, network: false }) const windows = codexBotSandboxSupport({ platform: 'win32', program }) expect(windows.reach({ kind: 'blocked' })).toEqual({ reads: 3, writes: 0, network: false }) @@ -148,9 +148,9 @@ describe("the Codex driver's sandbox for an entry", () => { driver.create({ builtIn: true, instanceId: 'codex', config: {} } as unknown as DriverContext) const support = driver.botSandbox!({}, {} as InstanceEnv, 'codex') expect(support.runtime).toBe('codex') - expect(support.unsupported!({ kind: 'open' })).toBeUndefined() + expect(support.unsupported!({ kind: 'direct' })).toBeUndefined() expect(support.key).toContain('/opt/codex/bin/codex') - expect(driver.botSandbox!({}, {} as InstanceEnv, 'codex:other').unsupported!({ kind: 'open' })).toMatchObject({ reason: 'start_failed' }) + expect(driver.botSandbox!({}, {} as InstanceEnv, 'codex:other').unsupported!({ kind: 'direct' })).toMatchObject({ reason: 'start_failed' }) }) }) @@ -159,11 +159,11 @@ describe("Codex's sandbox with the owner's Codex command rules", () => { let rules: string[] = ['/home/me/.codex/rules/default.rules'] const program = { launch: { command: '/opt/codex/bin/codex', args: [] }, env: { PATH: '/usr/bin' }, args: [], rules: () => rules } const support = codexBotSandboxSupport({ platform: 'linux', program }) - const unavailable = support.unsupported!({ kind: 'open' }) + const unavailable = support.unsupported!({ kind: 'direct' }) expect(unavailable).toMatchObject({ reason: 'command_rules', provider: 'Codex', repair: 'none' }) expect(botSandboxReasonText(unavailable!)).toBe("Codex can't keep commands in the sandbox while you have Codex command rules.") rules = [] - expect(support.unsupported!({ kind: 'open' })).toBeUndefined() + expect(support.unsupported!({ kind: 'direct' })).toBeUndefined() }) }) @@ -203,7 +203,7 @@ describe.skipIf(!LIVE)(`the real Codex sandbox here (${LIVE ?? 'set MOUSSE_CODEX const home = mkdtempSync(join(tmpdir(), 'mousse-codex-home-')) try { const live: CodexSandboxProgram = { launch: { path: LIVE!, command: LIVE!, args: [] }, env: { ...process.env, CODEX_HOME: home }, args: [] } - expect(await codexBotSandboxSupport({ platform: process.platform, program: live }).probe({ kind: 'open' })).toBeUndefined() + expect(await codexBotSandboxSupport({ platform: process.platform, program: live }).probe({ kind: 'direct' })).toBeUndefined() } finally { rmSync(home, { recursive: true, force: true }) } @@ -223,7 +223,7 @@ describe.skipIf(!LIVE)(`the real Codex sandbox here (${LIVE ?? 'set MOUSSE_CODEX const env = { ...process.env, CODEX_HOME: home, GH_TOKEN: 'gh-secret' } const owner = parse(policy) as Record const shell = codexBotShellEnvironment(lockedEnv({ platform: process.platform, base: env, driver: 'codex', credential: 'unknown', scratch: dir }), owner) - const probe = codexSandboxProbeArgs({ platform: process.platform, dir, network: { kind: 'open' } }) + const probe = codexSandboxProbeArgs({ platform: process.platform, dir, network: { kind: 'direct' } }) const command = process.platform === 'win32' ? ['cmd.exe', '/d', '/c', 'set'] : ['env'] const run = spawnSync(LIVE!, ['sandbox', ...codexConfigArgs(shell), ...probe.slice(1, probe.indexOf('--')), '--', ...command], { env, encoding: 'utf8', windowsHide: true, timeout: 30_000 }) const result = { code: run.status, output: `${run.stdout}\n${run.stderr}` } diff --git a/tests/renderer/botAboutPanel.test.ts b/tests/renderer/botAboutPanel.test.ts index 66db97558..10fe83b04 100644 --- a/tests/renderer/botAboutPanel.test.ts +++ b/tests/renderer/botAboutPanel.test.ts @@ -19,7 +19,7 @@ import type { BotSandboxView } from '../../src/shared/bots/personal/sandbox' const { BotAboutPanel, nextRunText, reminderWhenText } = await import('../../src/renderer/components/bots/BotAboutPanel') const { setBotsClient, useBotsStore } = await import('../../src/renderer/stores/botsStore') const { BotDialogs } = await import('../../src/renderer/components/bots/BotDialogs') -const { useBotSandbox } = await import('../../src/renderer/components/bots/BotSandboxRows') +const { useBotSandbox } = await import('../../src/renderer/stores/botSandboxStore') let root: Root let host: HTMLElement @@ -728,21 +728,28 @@ describe("the bot's system instructions in About", () => { }) }) -describe('the command sandbox in About → Can use', () => { +describe('the command sandbox in About', () => { afterEach(() => useBotSandbox.setState(useBotSandbox.getInitialState(), true)) - const held = (network: 'open' | 'blocked', revision = 1): BotSandboxView => ({ - setting: { sandbox: 'on', network: { kind: network }, revision }, computer: 'Desk', provider: 'Claude Code', policy: { kind: 'held', revision, network: { kind: network } } + const held = (network: BotSandboxView['setting']['network']['kind'], revision = 1, over: Partial = {}): BotSandboxView => ({ + setting: { sandbox: 'on', network: { kind: network }, revision }, computer: 'Desk', provider: 'Claude Code', + policy: { kind: 'held', revision, network: { kind: network === 'open' ? 'public' : network } }, ...over }) + const off = (revision = 1): BotSandboxView => ({ setting: { sandbox: 'off', network: { kind: 'public' }, revision }, computer: 'Desk', provider: 'Claude Code', policy: { kind: 'open', revision } }) const unavailable = (over: Partial>): BotSandboxView => ({ setting: { sandbox: 'on', network: { kind: 'blocked' }, revision: 3 }, computer: 'Ubuntu box', provider: 'Claude Code', policy: { kind: 'unavailable', revision: 3, reason: 'missing_packages', provider: 'Claude Code', missing: ['socat'], repair: 'install', ...over } }) - const row = (testId: string) => host.querySelector(`[data-testid="${testId}"]`)! - const line = (testId: string) => row(testId).querySelector('.settings-item-desc > span')?.textContent - const toggle = (label: string) => host.querySelector(`[role="switch"][aria-label="${label}"]`)! + const dialog = () => document.querySelector('[role="dialog"][aria-labelledby], [role="dialog"][aria-label="Sandbox"]') + const inDialog = (label: string) => [...dialog()!.querySelectorAll('button')].find((element) => element.getAttribute('aria-label') === label || element.textContent === label) + const sandboxSwitch = () => dialog()!.querySelector('[role="switch"][aria-label="Limit commands"]')! + const choice = (name: string) => [...dialog()!.querySelectorAll('[role="radio"]')].find((element) => element.textContent === name)! + const picked = (testId: string) => dialog()!.querySelector(`[data-testid="${testId}"] [role="radio"][aria-checked="true"]`)?.textContent ?? null + /** The summary as a person reads it: each row's name and what it says. */ + const summary = () => [...dialog()!.querySelectorAll('[data-testid="bot-sandbox-reach"] .settings-item')].map((item) => `${item.querySelector('.settings-item-title')!.textContent}: ${item.querySelector('.bot-sandbox-value')!.textContent}`) + const state = () => host.querySelector('[data-testid="bot-sandbox"] .bot-sandbox-open')!.textContent const sets = () => fake.calls.filter(([name]) => name === 'setSandbox') - /** About shown afresh, as when another bot's About opens: nothing read before is kept. */ + const open = async () => click(host.querySelector('[data-testid="bot-sandbox"] .bot-sandbox-open')!) async function again(current = bot) { act(() => root.unmount()) root = createRoot(host) @@ -750,75 +757,121 @@ describe('the command sandbox in About → Can use', () => { await show(current) } - it('sits under Run commands; each switch saves its own change, and the network switch keeps its value while the sandbox is off', async () => { - fake.details.b1!.permissions.splice(1, 0, { id: 'sh', enabled: true, title: 'run commands', note: '', grantedAt: AT }) - fake.sandboxes.b1 = held('blocked') + it('is one Sandbox row under Run commands, with its state; Full commands moves into its dialog', async () => { + fake.details.b1!.permissions.splice(1, 0, { id: 'sh', enabled: true, title: 'run commands', note: '', grantedAt: AT }, { id: 'full', enabled: false, title: 'run full commands', note: '', grantedAt: AT }) + fake.sandboxes.b1 = off() await show() - expect(rows('Can use')).toEqual(['Use files on this computer', 'Run commands', 'Sandbox commands', 'Allow network for sandboxed commands', 'Use the pdf skill']) - expect(line('bot-sandbox')).toBe('Commands can change files only in allowed folders.') - expect(line('bot-sandbox-network')).toBe("Sandboxed commands can't use the network.") - - await click(toggle('Allow network for sandboxed commands')) - expect(sets()).toEqual([['setSandbox', 'b1', { network: { kind: 'open' }, expectedRevision: 1 }]]) - expect(line('bot-sandbox-network')).toBe('Sandboxed commands can use the network.') - - await click(toggle('Sandbox commands')) - expect(sets().at(-1)).toEqual(['setSandbox', 'b1', { sandbox: 'off', expectedRevision: 2 }]) - expect(toggle('Sandbox commands').getAttribute('aria-checked')).toBe('false') - expect(line('bot-sandbox')).toBe('Commands run like they do in your own threads. Bot permissions and approvals still apply.') - expect(line('bot-sandbox-network')).toBe('Applies when the sandbox is on.') - expect(toggle('Allow network for sandboxed commands').disabled).toBe(true) - expect(toggle('Allow network for sandboxed commands').getAttribute('aria-checked')).toBe('true') - - await click(toggle('Sandbox commands')) - expect(sets().at(-1)).toEqual(['setSandbox', 'b1', { sandbox: 'on', expectedRevision: 3 }]) - expect(toggle('Allow network for sandboxed commands').disabled).toBe(false) + expect(rows('Can use')).toEqual(['Use files on this computer', 'Run commands', 'Sandbox', 'Use the pdf skill']) + expect(state()).toBe('Off') + fake.sandboxes.b1 = held('public') + await again() + expect(state()).toBe('On · Public web') }) - it('a bot without a commands row has them at the end; a service without the switch shows none', async () => { - fake.sandboxes.b1 = held('open') + it('the dialog names the computer and saves each change there; the network keeps its choice while the sandbox is off', async () => { + fake.sandboxes.b1 = off() await show() - expect(rows('Can use')).toEqual(['Use files on this computer', 'Use the pdf skill', 'Sandbox commands', 'Allow network for sandboxed commands']) - delete fake.sandboxes.b1 - await again() - expect(rows('Can use')).toEqual(['Use files on this computer', 'Use the pdf skill']) + await open() + expect(dialog()!.textContent).toContain('On Desk') + expect(picked('bot-sandbox-network')).toBe('Public web') + expect(choice('Direct').disabled).toBe(true) + + await click(sandboxSwitch()) + expect(sets()).toEqual([['setSandbox', 'b1', { sandbox: 'on', expectedRevision: 1 }]]) + expect(state()).toBe('On · Public web') + await click(choice('Direct')) + expect(sets().at(-1)).toEqual(['setSandbox', 'b1', { network: { kind: 'direct' }, expectedRevision: 2 }]) + expect(state()).toBe('On · Direct') + + await click(sandboxSwitch()) + expect(sets().at(-1)).toEqual(['setSandbox', 'b1', { sandbox: 'off', expectedRevision: 3 }]) + expect(picked('bot-sandbox-network')).toBe('Direct') + expect(summary()).toEqual(['Commands: Like your own threads']) + }) + + it('a network saved before the split shows no choice picked, and the summary says what each launcher gives', async () => { + fake.sandboxes.b1 = held('open', 1, { + runner: { kind: 'held', revision: 1, network: { kind: 'direct' } }, + reach: { work: { reads: 1, servers: false }, runner: { reads: 0, servers: true } } + }) + await show() + expect(state()).toBe('On · Network on') + await open() + expect(picked('bot-sandbox-network')).toBeNull() + expect(summary()).toEqual([ + 'Files: Claude Code: Changes its folders, reads all but your home folder\nBackground commands: Its folders only', + 'Network: Claude Code: Public web\nBackground commands: Direct' + ]) + expect(dialog()!.querySelector('[data-testid="bot-sandbox-servers"] .bot-sandbox-value')!.textContent).toBe('Claude Code: Inside only\nBackground commands: Reachable on this computer') }) - it("can't start: the reason in the line, Turn off and Install what's missing; without a package that fixes it, Turn off alone", async () => { + it("can't start: the summary says so, with Repair and Turn off this limit; without a fix, Turn off this limit alone", async () => { fake.sandboxes.b1 = unavailable({}) await show() - expect(line('bot-sandbox')).toBe("On, but commands can't start on Ubuntu box. Claude Code needs socat to start sandboxed commands.") - expect(button("Install what's missing")).toBeTruthy() - await click(button('Turn off sandbox for this bot')) + expect(state()).toBe("On · Can't start") + await open() + expect(summary()).toEqual(["Commands: Can't start"]) + expect(inDialog('Repair')).toBeTruthy() + await click(inDialog('Turn off this limit')) expect(sets()).toEqual([['setSandbox', 'b1', { sandbox: 'off' }]]) - expect(button('Turn off sandbox for this bot')).toBeUndefined() - expect(line('bot-sandbox')).toBe('Commands run like they do in your own threads. Bot permissions and approvals still apply.') + expect(inDialog('Turn off this limit')).toBeUndefined() + expect(state()).toBe('Off') fake.sandboxes.b1 = unavailable({ reason: 'wsl1', missing: undefined, repair: 'none' }) await again() - expect(line('bot-sandbox')).toBe("On, but commands can't start on Ubuntu box. This computer uses WSL 1. The sandbox needs WSL 2.") - expect(button('Turn off sandbox for this bot')).toBeTruthy() - expect(button("Install what's missing")).toBeUndefined() + await open() + expect(inDialog('Turn off this limit')).toBeTruthy() + expect(inDialog('Repair')).toBeUndefined() }) - it("Install what's missing with no command from the bot's computer opens nothing and stops offering it", async () => { + it("Repair with no install command from the bot's computer opens nothing, then checks again instead", async () => { fake.sandboxes.b1 = unavailable({}) await show() - await click(button("Install what's missing")) + await open() + await click(inDialog('Repair')) expect(fake.calls).toContainEqual(['sandboxInstall', 'b1']) - expect(button("Install what's missing")).toBeUndefined() - expect(button('Turn off sandbox for this bot')).toBeTruthy() + await click(inDialog('Repair')) + expect(fake.calls).toContainEqual(['sandbox', 'b1', true]) + expect(fake.calls.filter(([name]) => name === 'sandboxInstall')).toHaveLength(1) + }) + + it('Approvals switches Full commands: Auto asks before destructive commands, Full does not', async () => { + fake.details.b1!.permissions.push({ id: 'full', enabled: false, title: 'run full commands', note: '', grantedAt: AT }) + fake.sandboxes.b1 = off() + await show() + await open() + expect(picked('bot-sandbox-approvals')).toBe('Auto') + await click(choice('Full')) + expect(fake.calls).toContainEqual(['setPermission', 'b1', 'full', true]) + // Its row in About could take it away; the dialog still can. + await click(inDialog('Remove Full commands')) + expect(fake.calls).toContainEqual(['revokePermission', 'b1', 'full']) + }) + + it("lists the secrets the bot may use with each one's rule: one given in its chat, and a saved one given to it there", async () => { + const home = { ...bot, homeThreadId: 'home-b1' } + fake.details.b1 = { ...fake.details.b1!, summary: home } + ;(window.mousse as unknown as { platformRequest: unknown }).platformRequest = { request: async () => ({ secrets: [ + { name: 'GITHUB_TOKEN', keep: 'saved', threadId: 'home-b1', binding: { service: 'GitHub', host: 'api.github.com', readOnly: true } }, + { name: 'NPM_TOKEN', keep: 'saved', threadId: 'other', threads: ['other', 'home-b1'] }, + { name: 'SOMEONE_ELSES', keep: 'saved', threadId: 'other' } + ] }) } + fake.sandboxes.b1 = off() + await show(home) + await open() + const secrets = [...dialog()!.querySelectorAll('[data-testid="bot-sandbox-secret"]')].map((item) => `${item.querySelector('.settings-item-title')!.textContent}: ${item.querySelector('.bot-sandbox-value')!.textContent}`) + expect(secrets).toEqual(['GITHUB_TOKEN: Only GitHub, read only', 'NPM_TOKEN: One command at a time']) }) it('a change another window made meanwhile is shown as it is now, not as an error', async () => { fake.sandboxes.b1 = held('blocked') await show() - fake.sandboxes.b1 = { ...held('blocked', 2), setting: { sandbox: 'off', network: { kind: 'blocked' }, revision: 2 }, policy: { kind: 'open', revision: 2 } } - await click(toggle('Allow network for sandboxed commands')) + await open() + fake.sandboxes.b1 = off(2) + await click(choice('Public web')) await act(async () => {}) - expect(toggle('Sandbox commands').getAttribute('aria-checked')).toBe('false') - expect(toggle('Allow network for sandboxed commands').getAttribute('aria-checked')).toBe('false') - expect(row('bot-sandbox').querySelector('[role="alert"]')).toBeNull() + expect(sandboxSwitch().getAttribute('aria-checked')).toBe('false') + expect(dialog()!.querySelector('[role="alert"]')).toBeNull() }) it("is greyed with why for a bot this window can't set up", async () => { @@ -826,8 +879,9 @@ describe('the command sandbox in About → Can use', () => { fake.sandboxes[there.id] = unavailable({}) fake.details[there.id] = { ...fake.details.b1!, summary: there } await show(there) - expect(toggle('Sandbox commands').disabled).toBe(true) - expect(toggle('Sandbox commands').parentElement!.getAttribute('title')).toBe('Needs Full bot access on Studio Mac') - expect(button('Turn off sandbox for this bot')!.disabled).toBe(true) + await open() + expect(sandboxSwitch().disabled).toBe(true) + expect(sandboxSwitch().parentElement!.getAttribute('title')).toBe('Needs Full bot access on Studio Mac') + expect(inDialog('Turn off this limit')!.disabled).toBe(true) }) -}) \ No newline at end of file +}) diff --git a/tests/renderer/botSandboxChat.test.ts b/tests/renderer/botSandboxChat.test.ts index 0d45fc5ea..eba456338 100644 --- a/tests/renderer/botSandboxChat.test.ts +++ b/tests/renderer/botSandboxChat.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom /** * The card Mousse posts in a bot's chat when its command sandbox can't start (docs/plans/bot-sandbox-setting.md): why, - * that the work waits, what the sandbox printed, Turn off sandbox for this bot, and Install what's missing, which opens + * that the work waits, what the sandbox printed, Turn off this limit, and Repair, which opens * the owner's terminal on the bot's computer with the command typed but not run, and checks again when it ends. */ import { act, createElement, Fragment } from 'react' @@ -41,7 +41,7 @@ const ChatWorkspace = () => createElement(Fragment, null, createElement(ChatPane const { useChatsStore } = await import('../../src/renderer/stores/chatsStore') const { setBotsClient, useBotsStore } = await import('../../src/renderer/stores/botsStore') const { useBotTerminals } = await import('../../src/renderer/stores/botTerminalsStore') -const { useBotSandbox } = await import('../../src/renderer/components/bots/BotSandboxRows') +const { useBotSandbox } = await import('../../src/renderer/stores/botSandboxStore') const { clearBotLiveReplies } = await import('../../src/renderer/stores/botLiveReplies') const { useComputersStore, NO_COMPUTERS } = await import('../../src/renderer/lib/computers') @@ -140,7 +140,7 @@ describe("the chat's sandbox card", () => { await act(async () => useChatsStore.getState().openBot('inbox')) await settle() expect(lines().at(-1)).toBe("This bot's work is waiting. Mousse checks again on the next turn.") - expect(button('Turn off sandbox for this bot', card()!)).toBeDefined() + expect(button('Turn off this limit', card()!)).toBeDefined() }) it("with the sandbox off, a card of another provider entry settles too, though the view has no state of that entry", async () => { @@ -152,11 +152,11 @@ describe("the chat's sandbox card", () => { await act(async () => root.render(createElement(ChatWorkspace))) await act(async () => useChatsStore.getState().openBot('inbox')) await settle() - expect(lines().at(-1)).toBe('Commands run like they do in your own threads. Bot permissions and approvals still apply.') - expect(button('Turn off sandbox for this bot', card()!)).toBeUndefined() + expect(lines().at(-1)).toBe('The sandbox is off now. Commands run like your own threads.') + expect(button('Turn off this limit', card()!)).toBeUndefined() }) - it("Install what's missing on a card of another provider entry asks for that entry's packages", async () => { + it("Repair on a card of another provider entry asks for that entry's packages", async () => { const second: Extract = { ...unavailable, provider: 'Claude Code' } // The work's entry starts; the second entry (a subagent's) misses socat. fake.sandboxes.inbox = { ...started, entries: { claude: started.policy, 'claude:second': second } } @@ -167,12 +167,12 @@ describe("the chat's sandbox card", () => { await act(async () => root.render(createElement(ChatWorkspace))) await act(async () => useChatsStore.getState().openBot('inbox')) await settle() - await click(button("Install what's missing", card()!)) + await click(button('Repair', card()!)) expect(fake.calls).toContainEqual(['sandboxInstall', 'inbox', 'claude:second']) expect(created).toEqual([{ botId: 'inbox' }]) }) - it("Install is decided per card: a stale card whose launcher has nothing to install hides its own Install, never another card's", async () => { + it("Install is decided per card: a stale card whose launcher has nothing to install checks again instead, and another card still installs", async () => { const old: Extract = { ...unavailable, provider: 'Claude Code' } const second: Extract = { ...unavailable, provider: 'Claude Code' } // The old card's launcher has no state in the view (stands as posted); the second entry still misses socat. @@ -189,14 +189,18 @@ describe("the chat's sandbox card", () => { const cards = () => [...host.querySelectorAll('[data-testid="bot-sandbox-card"]')] // The old card's launcher was repaired already: its computer has nothing to install. fake.installCommand = undefined - await click(button("Install what's missing", cards()[0]!)) + await click(button('Repair', cards()[0]!)) expect(fake.calls).toContainEqual(['sandboxInstall', 'inbox', 'claude:old']) - expect(button("Install what's missing", cards()[0]!)).toBeUndefined() - // The second card still offers it. - expect(button("Install what's missing", cards()[1]!)).toBeDefined() + // Its Repair now starts the sandbox again instead of installing. + await click(button('Repair', cards()[0]!)) + expect(fake.calls.filter(([name, , entry]) => name === 'sandboxInstall' && entry === 'claude:old')).toHaveLength(1) + expect(fake.calls).toContainEqual(['sandbox', 'inbox', true]) + // The second card still installs. + await click(button('Repair', cards()[1]!)) + expect(fake.calls).toContainEqual(['sandboxInstall', 'inbox', 'claude:second']) }) - it("a new card for a launcher whose package went missing again offers Install, though an older card of it had nothing to install", async () => { + it("a new card for a launcher whose package went missing again installs, though an older card of it had nothing to install", async () => { const second: Extract = { ...unavailable, provider: 'Claude Code' } // The older card's launcher has no state in the view (it stands as posted). fake.sandboxes.inbox = { ...started, entries: { claude: started.policy } } @@ -207,10 +211,11 @@ describe("the chat's sandbox card", () => { await act(async () => useChatsStore.getState().openBot('inbox')) await settle() const cards = () => [...host.querySelectorAll('[data-testid="bot-sandbox-card"]')] - // Repaired already: nothing to install, and that card stops offering it. + // Repaired already: nothing to install, and that card's Repair checks again from then on. fake.installCommand = undefined - await click(button("Install what's missing", cards()[0]!)) - expect(button("Install what's missing", cards()[0]!)).toBeUndefined() + await click(button('Repair', cards()[0]!)) + await click(button('Repair', cards()[0]!)) + expect(fake.calls.filter(([name]) => name === 'sandboxInstall')).toHaveLength(1) // Its package goes missing again and a new card for the same launcher is posted: it offers Install. fake.sandboxes.inbox = { ...started, entries: { claude: started.policy, 'claude:second': second } } fake.chats.inbox = [...fake.chats.inbox, { seq: 2, id: 'bm_sandbox_2', at: AT, author: 'bot', kind: 'notice', text: '', chips: [], cards: [botSandboxCard(second, 'Ubuntu box', 'claude:second')] }] @@ -218,7 +223,9 @@ describe("the chat's sandbox card", () => { await act(async () => useBotSandbox.getState().load('inbox')) await settle() expect(cards()).toHaveLength(2) - expect(button("Install what's missing", cards()[1]!)).toBeDefined() + fake.installCommand = 'sudo apt-get install -y socat' + await click(button('Repair', cards()[1]!)) + expect(fake.calls.filter(([name]) => name === 'sandboxInstall')).toHaveLength(2) }) it("a card of Mousse's runner keeps its buttons while the runner can't start, though the work's provider can", async () => { @@ -230,7 +237,7 @@ describe("the chat's sandbox card", () => { 'Mousse has no command sandbox on Windows.', "This bot's work is waiting. Mousse checks again on the next turn." ]) - expect(button('Turn off sandbox for this bot', card()!)).toBeDefined() + expect(button('Turn off this limit', card()!)).toBeDefined() }) it('says why, that the work waits, and what the sandbox printed; Turn off turns it off and the card says what holds now', async () => { @@ -241,12 +248,12 @@ describe("the chat's sandbox card", () => { 'Claude Code needs socat to start sandboxed commands.', "This bot's work is waiting. Mousse checks again on the next turn." ]) - expect(card()!.querySelector('details pre')?.textContent).toBe('bwrap: setting up uid map: Permission denied') - expect(button("Install what's missing", card()!)).toBeTruthy() - await click(button('Turn off sandbox for this bot', card()!)) + expect(card()!.querySelector('details .bot-sandbox-detail-text')?.textContent).toBe('bwrap: setting up uid map: Permission denied') + expect(button('Repair', card()!)).toBeTruthy() + await click(button('Turn off this limit', card()!)) expect(fake.calls.filter(([name]) => name === 'setSandbox')).toEqual([['setSandbox', 'inbox', { sandbox: 'off' }]]) - expect(lines().at(-1)).toBe('Commands run like they do in your own threads. Bot permissions and approvals still apply.') - expect(button('Turn off sandbox for this bot', card()!)).toBeUndefined() + expect(lines().at(-1)).toBe('The sandbox is off now. Commands run like your own threads.') + expect(button('Turn off this limit', card()!)).toBeUndefined() }) it("offers Turn off alone where no package fixes it", async () => { @@ -255,21 +262,21 @@ describe("the chat's sandbox card", () => { await open(inbox, wsl1) expect(lines()[1]).toBe('This computer uses WSL 1. The sandbox needs WSL 2.') expect(card()!.querySelector('details')).toBeNull() - expect(button('Turn off sandbox for this bot', card()!)).toBeTruthy() - expect(button("Install what's missing", card()!)).toBeUndefined() + expect(button('Turn off this limit', card()!)).toBeTruthy() + expect(button('Repair', card()!)).toBeUndefined() }) - it("Install what's missing opens a terminal on the bot's computer with the command typed but not run, and checks again when it ends", async () => { + it("Repair opens a terminal on the bot's computer with the command typed but not run, and checks again when it ends", async () => { const there = summary('n_ubuntu:inbox', { name: 'Inbox helper', lives: { node: MAC, name: 'Ubuntu box', level: 'full' } }) fake.sandboxes[there.id] = waiting fake.installCommand = COMMAND await open(there) - await click(button("Install what's missing", card()!)) + await click(button('Repair', card()!)) expect(fake.calls).toContainEqual(['sandboxInstall', there.id]) expect(created).toEqual([{ botId: there.id, node: MAC }]) // Its tab comes to the front of the side panel. expect(tabs()).toEqual(['Terminal · Ubuntu box']) - expect(button("Install what's missing", card()!)!.disabled).toBe(true) + expect(button('Repair', card()!)!.disabled).toBe(true) // Typed once the shell shows its prompt, without Enter: the owner runs it and signs in to sudo there. expect(written).toEqual([]) await act(async () => output?.({ ptyId: 'pty-1', data: 'me@ubuntu:~$ ' })) @@ -282,20 +289,20 @@ describe("the chat's sandbox card", () => { await act(async () => exited?.({ ptyId: 'pty-1' })) await settle() expect(fake.calls.filter(([name]) => name === 'sandbox').at(-1)).toEqual(['sandbox', there.id, true]) - expect(lines().at(-1)).toBe('Commands can change files only in allowed folders.') - expect(button("Install what's missing", card()!)).toBeUndefined() + expect(lines().at(-1)).toBe('The sandbox starts now.') + expect(button('Repair', card()!)).toBeUndefined() }) it('closing the install terminal before it ends checks again too', async () => { fake.sandboxes.inbox = waiting fake.installCommand = COMMAND await open() - await click(button("Install what's missing", card()!)) + await click(button('Repair', card()!)) expect(created).toEqual([{ botId: 'inbox' }]) expect(tabs()).toEqual(['Terminal']) await click(button('Close Terminal')) expect(fake.calls.filter(([name]) => name === 'sandbox').at(-1)).toEqual(['sandbox', 'inbox', true]) // Still missing: the card offers it again. - expect(button("Install what's missing", card()!)!.disabled).toBe(false) + expect(button('Repair', card()!)!.disabled).toBe(false) }) }) diff --git a/tests/renderer/botSandboxStore.test.ts b/tests/renderer/botSandboxStore.test.ts new file mode 100644 index 000000000..931015e44 --- /dev/null +++ b/tests/renderer/botSandboxStore.test.ts @@ -0,0 +1,35 @@ +// @vitest-environment jsdom +/** + * The window's view of a bot's sandbox (`useBotSandbox`): a read that started before the owner's change never puts the + * older setting back once it answers, so the next change carries the revision the window showed last. + */ +import { afterEach, expect, it } from 'vitest' +import { setBotsClient } from '../../src/renderer/stores/botsStore' +import { useBotSandbox } from '../../src/renderer/stores/botSandboxStore' +import type { BotSandboxView } from '../../src/shared/bots/personal/sandbox' + +const view = (revision: number, kind: 'blocked' | 'public'): BotSandboxView => ({ + setting: { sandbox: 'on', network: { kind }, revision }, computer: 'Desk', provider: 'Claude Code', policy: { kind: 'held', revision, network: { kind } } +}) + +afterEach(() => { + setBotsClient(null) + useBotSandbox.setState(useBotSandbox.getInitialState(), true) +}) + +it('a read that answers after a change keeps the change', async () => { + let answer: (value: BotSandboxView) => void = () => {} + const sets: unknown[] = [] + setBotsClient({ + sandbox: () => new Promise((done) => { answer = done }), + setSandbox: async (_botId: string, change: unknown) => { sets.push(change); return view(2, 'public') } + } as never) + useBotSandbox.setState({ views: { b1: view(1, 'blocked') } }) + const read = useBotSandbox.getState().load('b1') + await useBotSandbox.getState().set('b1', { network: { kind: 'public' } }, true) + answer(view(1, 'blocked')) + await read + expect(useBotSandbox.getState().views.b1!.setting).toMatchObject({ revision: 2, network: { kind: 'public' } }) + await useBotSandbox.getState().set('b1', { network: { kind: 'blocked' } }, true) + expect(sets.at(-1)).toEqual({ network: { kind: 'blocked' }, expectedRevision: 2 }) +}) diff --git a/tests/renderer/newBotDialog.test.ts b/tests/renderer/newBotDialog.test.ts index cb1dd9b54..afb34ee76 100644 --- a/tests/renderer/newBotDialog.test.ts +++ b/tests/renderer/newBotDialog.test.ts @@ -264,8 +264,29 @@ describe('New bot', () => { await click(createButton()) await act(async () => {}) expect(creates()[0]![1]).not.toHaveProperty('access') + expect(creates()[0]![1]).not.toHaveProperty('sandbox') }) + it('with a home that takes it, a Sandbox step after Runs on: off at first, and what is set there goes with the create', async () => { + vi.mocked(fake.client.modelChoices).mockImplementation(async () => ({ models: [{ model: 'sonnet', label: 'Claude · sonnet' }], computer: 'this_computer', computers: [{ id: 'this_computer', name: 'Desk' }], sandboxOnCreate: true })) + await open([]) + await toRunsOn('Remind me to water the plants.') + expect(stepLabels()).toEqual(['Look', 'What it does', 'Runs on', 'Sandbox']) + await click(nextButton()) + expect(stepNow()).toBe('sandbox') + const sandbox = () => dialog()!.querySelector('[role="switch"][aria-label="Limit commands"]')! + const choice = (name: string) => [...dialog()!.querySelectorAll('[data-testid="bot-sandbox-network"] [role="radio"]')].find((element) => element.textContent === name)! + expect(sandbox().getAttribute('aria-checked')).toBe('false') + expect(choice('Public web').getAttribute('aria-checked')).toBe('true') + expect(choice('Blocked').disabled).toBe(true) + await click(sandbox()) + await click(choice('Blocked')) + await click(createButton()) + await act(async () => {}) + expect(creates()[0]![1]).toMatchObject({ sandbox: { sandbox: 'on', network: { kind: 'blocked' } } }) + }) + + it('says so on Runs on when the picked model is gone by Create bot, and shows it as not available now', async () => { await open([]) await toRunsOn('Remind me to water the plants.') diff --git a/tests/run/codexAdapter.test.ts b/tests/run/codexAdapter.test.ts index 8912e401f..5d39dd459 100644 --- a/tests/run/codexAdapter.test.ts +++ b/tests/run/codexAdapter.test.ts @@ -2625,10 +2625,10 @@ describe('a bot turn on Codex', () => { * `codex` is in the test home, so its package is the folder above), writing the bot's folders; Windows keeps * workspace-write. */ - function heldStart(network: 'blocked' | 'open', folders: { files: string; docs: string; scratch: string }): TranscriptFrame[] { + function heldStart(network: 'blocked' | 'direct', folders: { files: string; docs: string; scratch: string }): TranscriptFrame[] { const writable = [folders.docs, folders.files, folders.scratch] const codexPackage = dirname(realpathSync.native(home)) - const profile = { filesystem: { ':minimal': 'read', ':root': 'deny', ...macDenied(process.platform), [join(home, 'ref')]: 'read', [codexPackage]: 'read', ...homebrew(process.platform), ...Object.fromEntries(writable.map((root) => [root, 'write'])) }, network: { enabled: network === 'open' } } + const profile = { filesystem: { ':minimal': 'read', ':root': 'deny', ...macDenied(process.platform), [join(home, 'ref')]: 'read', [codexPackage]: 'read', ...homebrew(process.platform), ...Object.fromEntries(writable.map((root) => [root, 'write'])) }, network: { enabled: network === 'direct' } } if (process.platform !== 'win32') return [ out({ id: 5, method: 'thread/start', params: { approvalPolicy: 'untrusted', permissions: CODEX_BOT_PROFILE, model: 'gpt-x', modelProvider: 'openai', config: { ...BOT_FEATURES, [`permissions.${CODEX_BOT_PROFILE}`]: profile, ...botEnv(folders.scratch, process.platform, true), model_provider: 'openai' } } }), @@ -2642,18 +2642,18 @@ describe('a bot turn on Codex', () => { config: { ...BOT_FEATURES, 'sandbox_workspace_write.writable_roots': writable, - 'sandbox_workspace_write.network_access': network === 'open', + 'sandbox_workspace_write.network_access': network === 'direct', 'sandbox_workspace_write.exclude_tmpdir_env_var': true, 'sandbox_workspace_write.exclude_slash_tmp': true, ...botEnv(folders.scratch), model_provider: 'openai' } })), - ...turnStart(6, 'go', 'turn-1', { sandboxPolicy: { type: 'workspaceWrite', writableRoots: writable, networkAccess: network === 'open', excludeTmpdirEnvVar: true, excludeSlashTmp: true } }) + ...turnStart(6, 'go', 'turn-1', { sandboxPolicy: { type: 'workspaceWrite', writableRoots: writable, networkAccess: network === 'direct', excludeTmpdirEnvVar: true, excludeSlashTmp: true } }) ] } - it.each(['blocked', 'open'] as const)('with "run commands" and the network %s: every command allowed by the grant with no question, never one outside the sandbox (a retry, an escalation with its justification, one asking for more permissions); its own profile (Linux, macOS) or workspace-write (Windows) over exactly its own folders, with that network', async (network) => { + it.each(['blocked', 'direct'] as const)('with "run commands" and the network %s: every command allowed by the grant with no question, never one outside the sandbox (a retry, an escalation with its justification, one asking for more permissions); its own profile (Linux, macOS) or workspace-write (Windows) over exactly its own folders, with that network', async (network) => { const { bot, files, docs, scratch } = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: network } }) const replay = transport([ ...handshake(), @@ -2761,7 +2761,7 @@ describe('a bot turn on Codex', () => { ] as const it.each(rulesRows)("the owner's Codex rules, with the sandbox on: $name", async ({ place, layer, text: rules, held }) => { const failed: BotSandboxUnavailable[] = [] - const { bot, files, docs, scratch } = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'open' } }, (unavailable) => failed.push(unavailable)) + const { bot, files, docs, scratch } = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'direct' } }, (unavailable) => failed.push(unavailable)) const dotCodex = join(home, 'project', '.codex') const folder = place === 'home' ? home : dotCodex mkdirSync(join(folder, 'rules'), { recursive: true }) @@ -2774,7 +2774,7 @@ describe('a bot turn on Codex', () => { ...handshake(), out({ id: 4, method: 'config/read', params: { includeLayers: true } }), inn({ id: 4, result: { config: { mcp_servers: {} }, layers } }), - ...(held ? heldStart('open', { files, docs, scratch }) : [...threadStart(5, threadParams({ config: { ...NO_COMMANDS, model_provider: 'openai' } })), ...turnStart(6, `${line}\n\ngo`)]), + ...(held ? heldStart('direct', { files, docs, scratch }) : [...threadStart(5, threadParams({ config: { ...NO_COMMANDS, model_provider: 'openai' } })), ...turnStart(6, `${line}\n\ngo`)]), ...message('msg-1', ['Done']), completed('completed') ]) @@ -2787,8 +2787,8 @@ describe('a bot turn on Codex', () => { // About and the probe read the rules a thread of that bot would load: on one Codex entry, a project the owner trusts // that one bot works in marks only that bot's sandbox unavailable, whichever bot's thread started last. it("About reads each bot's own Codex rules: one bot's project rules don't reach another bot on the same entry", async () => { - const a = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'open' } }, () => {}, 'files-a') - const b = realBot(['read'], { kind: 'held', revision: 1, network: { kind: 'open' } }, undefined, 'files-b') + const a = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'direct' } }, () => {}, 'files-a') + const b = realBot(['read'], { kind: 'held', revision: 1, network: { kind: 'direct' } }, undefined, 'files-b') const dotCodex = join(home, 'project', '.codex') mkdirSync(join(dotCodex, 'rules'), { recursive: true }) const file = join(dotCodex, 'rules', 'default.rules') @@ -2816,10 +2816,10 @@ describe('a bot turn on Codex', () => { await adapter.startTurn(input({ prompt: 'go', threadId: 'thread-2', runId: 'run-2', attemptId: 'attempt-2', cwd: b.scratch }), recordingSink(), control(), { ...host(), bot: b.bot }) replay.assertDone() const support = codexBotSandboxSupport({ platform: 'linux', program: codex.botSandboxProgram() }) - expect(support.unsupported!({ kind: 'open' }, { folder: a.files })).toMatchObject({ reason: 'command_rules', detail: expect.stringContaining(file) }) - expect(support.unsupported!({ kind: 'open' }, { folder: b.files })).toBeUndefined() + expect(support.unsupported!({ kind: 'direct' }, { folder: a.files })).toMatchObject({ reason: 'command_rules', detail: expect.stringContaining(file) }) + expect(support.unsupported!({ kind: 'direct' }, { folder: b.files })).toBeUndefined() // A bot no thread has read yet: the system and user configs' rules only. - expect(support.unsupported!({ kind: 'open' }, { folder: join(home, 'files-c') })).toBeUndefined() + expect(support.unsupported!({ kind: 'direct' }, { folder: join(home, 'files-c') })).toBeUndefined() }) // Codex gives a command every variable of its own process unless the thread's `shell_environment_policy` says @@ -2881,7 +2881,7 @@ describe('a bot turn on Codex', () => { it('a command whose sandbox failed to start is reported once as the sandbox failing, never a command that only failed on its own', async () => { const failures: BotSandboxUnavailable[] = [] - const { bot, files, docs, scratch } = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'open' } }, (unavailable) => failures.push(unavailable)) + const { bot, files, docs, scratch } = realBot(['read', 'shell'], { kind: 'held', revision: 1, network: { kind: 'direct' } }, (unavailable) => failures.push(unavailable)) // What the sandbox prints when it can't start, on this platform (Codex 0.162.1's helper and the sandboxes it runs). const failedStart = process.platform === 'linux' ? 'bwrap: setting up uid map: Permission denied' @@ -2895,7 +2895,7 @@ describe('a bot turn on Codex', () => { const replay = transport([ ...handshake(), ...setupRead(4), - ...heldStart('open', { files, docs, scratch }), + ...heldStart('direct', { files, docs, scratch }), // A command's own failures: a sign-in GitHub refused, a name that did not resolve. ...ran('gh-1', 'gh: Bad credentials (HTTP 401)', 1), ...ran('curl-1', 'curl: (6) Could not resolve host: api.github.com', 6), diff --git a/tests/secrets/secretVault.test.ts b/tests/secrets/secretVault.test.ts index f24cfe1ce..be928928a 100644 --- a/tests/secrets/secretVault.test.ts +++ b/tests/secrets/secretVault.test.ts @@ -235,7 +235,7 @@ describe('the secrets a thread asked for', () => { await give('t1', 'day') expect(readFileSync(join(home, 'secrets', 'meta.json'), 'utf8')).not.toContain(VALUE) expect(JSON.stringify(vault.list())).not.toContain(VALUE) - expect(vault.list()).toEqual([{ name: 'API_TOKEN', keep: 'day', label: 'API token', expiresAt: '2026-11-16T10:00:00.000Z', threadId: 't1', createdAt: '2026-11-15T10:00:00.000Z' }]) + expect(vault.list()).toEqual([{ name: 'API_TOKEN', keep: 'day', label: 'API token', expiresAt: '2026-11-16T10:00:00.000Z', threadId: 't1', threads: ['t1'], createdAt: '2026-11-15T10:00:00.000Z' }]) }) it('never overwrites another secret: a taken name gets the next free one, and the agent is told that name', async () => { diff --git a/tests/subagentProviderPolicy.test.ts b/tests/subagentProviderPolicy.test.ts index af20d3dcd..721cba17a 100644 --- a/tests/subagentProviderPolicy.test.ts +++ b/tests/subagentProviderPolicy.test.ts @@ -77,7 +77,7 @@ describe('policy table: permission decisions', () => { const writableRoots = ['/home/me/site', '/p/files/b1', '/p/scratch/a'] const SHELL = new Set(['read', 'shell'] as const) const READ = new Set(['read'] as const) - const held = (network: 'open' | 'blocked') => ({ policy: { kind: 'held' as const, revision: 3, network: { kind: network } } }) + const held = (network: 'direct' | 'blocked') => ({ policy: { kind: 'held' as const, revision: 3, network: { kind: network } } }) const open = { policy: { kind: 'open' as const, revision: 4 } } const unavailable = { policy: { kind: 'unavailable' as const, revision: 5, reason: 'start_failed' as const, provider: 'Codex', repair: 'none' as const } } const workspaceWrite = (networkAccess: boolean) => ({ @@ -89,14 +89,14 @@ describe('policy table: permission decisions', () => { const OPEN = { approvalPolicy: 'untrusted', sandbox: 'danger-full-access', sandboxPolicy: { type: 'dangerFullAccess' } } it.each([ ['held, network blocked, Linux', SHELL, held('blocked'), 'linux', PROFILE, { [`permissions.${CODEX_BOT_PROFILE}`]: { network: { enabled: false } } }], - ['held, network open, macOS', SHELL, held('open'), 'darwin', PROFILE, { [`permissions.${CODEX_BOT_PROFILE}`]: { network: { enabled: true } } }], + ['held, network direct, macOS', SHELL, held('direct'), 'darwin', PROFILE, { [`permissions.${CODEX_BOT_PROFILE}`]: { network: { enabled: true } } }], ['held, network blocked, Windows', SHELL, held('blocked'), 'win32', workspaceWrite(false), { 'sandbox_workspace_write.network_access': false, 'sandbox_workspace_write.writable_roots': writableRoots }], - ['held, network open, Windows', SHELL, held('open'), 'win32', workspaceWrite(true), { 'sandbox_workspace_write.network_access': true }], + ['held, network direct, Windows', SHELL, held('direct'), 'win32', workspaceWrite(true), { 'sandbox_workspace_write.network_access': true }], ['off (open), Linux', SHELL, open, 'linux', OPEN, {}], ['off (open), Windows', SHELL, open, 'win32', OPEN, {}], ['unavailable', SHELL, unavailable, 'linux', SUPERVISED, { 'features.shell_tool': false, 'features.unified_exec': false }], ['no sandbox given', SHELL, undefined, 'linux', SUPERVISED, { 'features.shell_tool': false, 'features.unified_exec': false }], - ['without "run commands", held', READ, held('open'), 'linux', SUPERVISED, { 'features.shell_tool': false, 'features.unified_exec': false }], + ['without "run commands", held', READ, held('direct'), 'linux', SUPERVISED, { 'features.shell_tool': false, 'features.unified_exec': false }], ['without "run commands", off', READ, open, 'win32', SUPERVISED, { 'features.shell_tool': false, 'features.unified_exec': false }] ] as const)('a bot turn with commands %s', (_name, tools, sandbox, platform, policy, config) => { const codex = codexBotSandbox({ tools, workspace, ...(sandbox ? { sandbox } : {}) }, { platform, codexPackage: '/opt/codex' }) @@ -128,7 +128,7 @@ describe('policy table: permission decisions', () => { const key = (tools: ReadonlySet, policy: BotSandboxPolicy) => codexBotSandboxKey(codexBotSandbox({ tools, workspace, sandbox: { policy } }, { platform: 'win32' })) const keys = [ key(SHELL, held('blocked').policy), - key(SHELL, held('open').policy), + key(SHELL, held('direct').policy), key(SHELL, { ...held('blocked').policy, revision: 9 }), key(SHELL, open.policy), key(SHELL, { ...open.policy, revision: 6 }),