Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

Merge remote-tracking branch 'origin/main' into feat/mcp-followup

Asyfdzaky8b7252b41a14
diff --cc DECISIONS.md
index 1f1927c0,c8a28bfe..94ed10a6
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@@ -289,9 -289,22 +289,27 @@@
- **Consequence**: Owners can use the MCP ecosystem without a hand-written capability per integration. Every third-party call is visible in Ask Me mode unless the owner named the tool in `autoApprove`. The cost is a prompt per call for servers the owner hasn't pre-approved, even under Allow All. That is deliberate. Maintenance owned by Mercury:
- Any new place that filters tools by name (plan mode, members, bots, sub-agents) must decide how it treats the `mcp__` prefix.
- Text from an MCP server (descriptions, results, errors) is untrusted input and must never be used to make a permission decision.
- - Resources, prompts, sampling, OAuth, images in results, bot access and the 2026-07-28 protocol (`versionNegotiation: 'auto'`) are follow-ups.
+ - Resources, prompts, sampling, OAuth, bot access and the 2026-07-28 protocol (`versionNegotiation: 'auto'`) are follow-ups.
+- **Follow-up after the #207 review**:
+ - **One approval rule for plugin and MCP tools: trust follows origin.** Allow All, internal-turn grants and a tool's own "read-only" claim apply only to code Mercury vouches for: built-in tools and plugins installed from the catalog with a matching checksum (`verified`). Tools from code the owner brings in from elsewhere (every MCP server, and plugins installed from a path, URL or GitHub) always ask, and skip the prompt only when the owner named them exactly (`tools.autoApprove` for MCP, or a scheduled task's `allow_tools`, which the owner approves when the task is created) or answered **Always** for that tool in that chat. MCP tools and verified plugins already follow this rule; unverified plugins still follow the normal modes until the plugin tool path enforces it.
+ - **Owner prompts can't be answered by a channel's own Allow All.** MCP tool calls, shell commands that change MCP setup, and writes to `mercury.yaml`, `permissions.yaml` and `.env` ask with `alwaysAsk`. The web channel, which serves the terminal attached to the background service, the web dashboard and Mercury Cloud, used to answer every prompt itself in an Allow All session; it now shows these.
+ - **Mercury Cloud: configuration stays local.** Cloud relays chats to the owner's own Mercury (they arrive through `WebChannel`), so Cloud chats can use MCP tools with the same prompts. Cloud has no command to add, enable or change servers, and `${env:}` secrets never leave the local `.env`. Configuring servers from Cloud would let a remote control start local processes, so it needs its own trust design and issue.
+ - **Shared call wrapper: yes, in stages.** The plugin runtime is also an MCP-over-stdio client, and the two keep separate copies of the same steps, which have drifted. The approval preview shows plugin arguments cut to 400 characters without redaction, and MCP arguments redacted, start and end, up to 4,000. Results are capped at 100,000 characters for plugins and 32 KB for MCP, and plugin results aren't redacted. One module will own the approval preview, timeouts, the result cap, redaction, image handling and error text for both. Image handling is already shared (`src/capabilities/tool-images.ts`); the rest follows once those differences are settled.
+
+ ## ADR-030: Mercury Desktop — a Tauri shell around the one dashboard, over a versioned API
+
+ - **Context**: Mercury had one interface outside the terminal: the React dashboard the runtime serves on loopback, behind a cookie login. Users asked for a desktop app (and later phone apps) that can attach to the Mercury on their computer, install one when there is none, and connect to Mercuries elsewhere — a home machine, a server, Termux, Mercury Cloud — side by side. Research covered Hermes Desktop (Electron, separate gateway, connections registry), OpenClaw (native Swift menu-bar app over a gateway), Claude Desktop (Electron plus a hidden VM; 9 processes/1.2 GB idle on Windows reported), the ChatGPT/Codex apps (native Mac app, Electron Codex, merged in 2026), and Tauri 2 versus Electron.
+ - **Decision**:
+ - **Shell.** Tauri 2 (`apps/desktop`): a Rust shell of a few hundred lines around the platform webview, one process plus the runtime. It owns what a tab cannot — window and tray, the OS keychain, finding and starting the runtime on this computer, deep links, updates. Everything the user looks at is the same React dashboard (`ui/`), imported as source through the `@` alias and built with Vite; `resolve.dedupe` keeps one React. Routing is a hash router: a bundled app has no server-side fallback. Phones get native apps later; they share the API, not the UI.
+ - **Monorepo.** Desktop under `apps/desktop`, dashboard stays in `ui/`, runtime in `src/`. Release tags per package (`v1.x` runtime, `desktop-v0.x` app, `optimus-v0.x` plugin). The desktop updater polls `https://mercuryagent.sh/desktop/latest.json`, published from `website/static/desktop/` like the plugin catalog, because GitHub's "latest release" can only point at one package.
+ - **Contract.** Two numbers: the package version (display) and `API_VERSION` in `/api/health` (compatibility), with `features` flags for additive changes. A client declares the range it understands; outside it, the user is told which side to update and can open the runtime-served dashboard, which always matches. `docs/api-contract.md` is the ledger; no runtime release without a row.
+ - **Credentials.** Three kinds, one guard (`src/web/middleware.ts`): the web session (any peer, cookie or Bearer), the attach token (loopback only, per boot — the desktop app attaches to a local runtime with it, zero typing), and device tokens (`mdt_<id>_<secret>`, any peer, long-lived, one per device, hashed at rest in `~/.mercury/devices.json`, constant-time compare, revocable one at a time). `POST /api/auth/token` exchanges the password for one; `mercury devices add|list|revoke` manages them. The app keeps a device token in the OS keychain, never in a file it owns, and never keeps the password.
+ - **Cross-origin.** `/api/*` sends CORS headers for the desktop webview origins and `web.corsOrigins`; never a wildcard, never credentials. Event streams from a hosted client are `fetch()`+Bearer with an EventSource-shaped wrapper, because EventSource cannot send a header.
+ - **Install from the app.** "Install Mercury here" downloads the matching runtime release from GitHub (binary for this CPU plus `web.tar.gz`), verifies both against `checksums.txt`, installs into `~/.mercury/bin` the way `install.sh` does, then runs `mercury setup --headless`, `mercury service install` and `mercury start`. The runtime is not bundled inside the app: that would add ~90 MB per platform, tie every app release to a runtime release, and duplicate the updater. The one loss is an offline first install.
+ - **Local runtime.** The app never supervises the daemon itself; `mercury service` (launchd, systemd user unit, Task Scheduler, Termux boot) already does, and the app reuses it. Closing the window hides to the tray; Quit lives in the tray.
+ - **Alternatives considered**:
+ - Electron: same architecture, but a bundled Chromium per app (≈150 MB download, 300–500 MB idle, several processes). The UI is already a web app with no need for Chromium-only APIs.
+ - Loading the runtime-served dashboard URL in the window instead of bundling the UI: always version-matched and no CORS, but no offline first run, native integration only through remote-page IPC, and cookie auth that cannot be shared across connections. Kept as the fallback path when versions disagree.
+ - Password login from the app on every launch: no revocation per device, and the password would have to be stored.
+ - Exposing `/api/health` to unauthenticated remote peers for discovery: rejected; the runtime stays invisible (404) without a credential, and pairing returns the same contract fields.
+ - **Consequence**: One UI codebase for the web dashboard and the desktop app; the dashboard must keep working in both homes (same-origin cookie, and Bearer from a shell), so no new `window.location` navigation or raw `EventSource` in `ui/` — use `lib/connection.ts` and `lib/sse.ts`. Every API change is judged against the contract rules. The runtime still binds loopback only; remote access means a tunnel, VPN or reverse proxy, which is a later decision with its own ADR. Follow-ups: bundled runtime as a sidecar (install from the app), signed updater artifacts, notifications with actions, the macOS notch capsule, QR pairing over `mercury://`, and the cockpit redesign in `ui/`.
diff --cc src/channels/web.test.ts
index b506115e,a8bde99a..d4235da5
--- a/src/channels/web.test.ts
+++ b/src/channels/web.test.ts
@@@ -155,36 -155,26 +155,58 @@@ describe('WebChannel durable streaming'
await expect(channel.askPermission('Write file?', 'request-allowed')).resolves.toBe('yes');
});
+
+ it('still asks in an allow-all session when the prompt must always ask', async () => {
+ const channel = new WebChannel('Mercury');
+ const events: Array<{ type: string; data?: Record<string, unknown> }> = [];
+ channel.setSessionPermissionMode('session-allowed', 'allow-all');
+ channel.emitCloudMessage('work', 'request-allowed', 'session-allowed', 'conversation-1', undefined, (event) => {
+ events.push(event);
+ return true;
+ });
+
+ const decision = channel.askPermission('MCP tool call', 'request-allowed', { alwaysAsk: true });
+ const id = events.find((event) => event.type === 'permission_request')?.data?.id as string;
+ expect(id).toBeTruthy();
+ expect(channel.resolveApproval(id, 'no', 'request-allowed')).toBe(true);
+ await expect(decision).resolves.toBe('no');
+ });
+
+ it('still asks under the global bypass when the prompt must always ask', async () => {
+ const channel = new WebChannel('Mercury');
+ const events: Array<{ type: string; data?: Record<string, unknown> }> = [];
+ channel.setBypassPermissions(true);
+ channel.emitCloudMessage('work', 'request-bypass', 'session-bypass', 'conversation-1', undefined, (event) => {
+ events.push(event);
+ return true;
+ });
+
+ await expect(channel.askPermission('Write file?', 'request-bypass')).resolves.toBe('yes');
+ const decision = channel.askPermission('MCP tool call', 'request-bypass', { alwaysAsk: true });
+ const id = events.find((event) => event.type === 'permission_request')?.data?.id as string;
+ expect(channel.resolveApproval(id, 'yes', 'request-bypass')).toBe(true);
+ await expect(decision).resolves.toBe('yes');
+ });
});
+
+ describe('WebChannel plan checklist', () => {
+ it('sends the plan only to that conversation and keeps it for reopening', async () => {
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const { PlanStore } = await import('../core/plan.js');
+ const channel = new WebChannel('Mercury');
+ channel.plans = new PlanStore(join(mkdtempSync(join(tmpdir(), 'mercury-webplan-')), 'plans.json'));
+ const seen: Record<string, string[]> = { a: [], b: [] };
+ for (const id of ['a', 'b']) {
+ channel.addSSEClient({ enqueue: (v: Uint8Array) => seen[id].push(new TextDecoder().decode(v)), close() {} } as unknown as ReadableStreamDefaultController, id);
+ }
+ channel.sendPlan([{ label: 'Research', status: 'active' }, { label: 'Write', status: 'pending' }], 'a');
+ expect(seen.a.join('')).toContain('event: plan');
+ expect(seen.a.join('')).toContain('"label":"Research"');
+ expect(seen.b.join('')).not.toContain('event: plan');
+ expect(channel.plans.get('a')?.steps).toHaveLength(2);
+ channel.sendPlan([{ label: 'x', status: 'nonsense' }], 'a');
+ expect(channel.plans.get('a')?.steps[0].label).toBe('Research');
+ });
+ });
diff --cc src/channels/web.ts
index 19b83b62,40bea138..54142774
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@@ -237,16 -325,17 +325,17 @@@ export class WebChannel extends BaseCha
this.broadcast({ type: 'thinking', data: { targetId: _targetId } });
}
- async askPermission(prompt: string, _targetId?: string): Promise<string> {
- if (this.isPermissionBypassed(_targetId)) return 'yes';
+ async askPermission(prompt: string, _targetId?: string, options?: { alwaysAsk?: boolean }): Promise<string> {
+ if (!options?.alwaysAsk && this.isPermissionBypassed(_targetId)) return 'yes';
if (!this.hasInteractiveTarget(_targetId)) return 'no';
const id = `perm_${randomUUID()}`;
- this.broadcast({
+ const event: ChatEvent = {
type: 'permission_request',
data: { id, prompt, options: ['yes', 'always', 'no'], targetId: _targetId },
- });
-
- return this.waitForInteraction(id, 'permission', ['yes', 'always', 'no'], _targetId, 'no');
+ };
+ const pending = this.waitForInteraction(id, 'permission', ['yes', 'always', 'no'], _targetId, 'no', event);
+ this.broadcast(event);
+ return pending;
}
async askToContinue(question: string, _targetId?: string): Promise<boolean> {