Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(attach): /code from the attach TUI hands the terminal to Mercury Code (1.3.2)
Salman Qureshif16707a312d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91002336..774dab86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## 1.3.2 — hotfix: /code from the default launch++- **`/code` works again from `mercury`.** Since 1.3.1 the default launch attaches to the daemon, and `/code` typed there was forwarded to the daemon's web channel — which has no terminal to switch into — so it printed "Programming mode: Off". The attach TUI now hands the terminal to Mercury Code (`/code` or `/code <dir>`), exactly what `mercury code` does; the runtime keeps running in the background. `/code plan|auto|off` inside the attach TUI explain where to run them.+## 1.3.1 — Steady MercuryThe release where Mercury stays out of your way. One process runs the fleet and your channels; the terminal just attaches to it — instantly. Bots do real work, deliver files you can find, stay online without burning tokens, and can be run from a phone. The 1.3.1 "Honest Mercury" line (chat that answers, "done" that means verified, security fixes) was never published on its own and ships here.diff --git a/README.md b/README.mdindex e95db629..8d814775 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@</p><p align="center">- <strong>🔖 Current Stable: v1.3.1 — Steady Mercury</strong>+ <strong>🔖 Current Stable: v1.3.2 — Steady Mercury</strong></p><p align="center">diff --git a/package-lock.json b/package-lock.jsonindex 9a2c2465..52f576c7 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,13 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.3.1",+ "version": "1.3.2","lockfileVersion": 2,"requires": true,"packages": {"": {"name": "@cosmicstack/mercury-agent",- "version": "1.3.1",+ "version": "1.3.2",+ "hasInstallScript": true,"license": "MIT","dependencies": {"@ai-sdk/anthropic": "^3.0.71",diff --git a/package.json b/package.jsonindex c133d0f1..9edb5fe8 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@cosmicstack/mercury-agent",- "version": "1.3.1",+ "version": "1.3.2","description": "Soul-driven AI agent with Second Brain memory, permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.","type": "module","main": "dist/index.js",diff --git a/src/cli/attach.ts b/src/cli/attach.tsindex 6c19476f..e7546bfe 100644--- a/src/cli/attach.ts+++ b/src/cli/attach.ts@@ -394,7 +394,8 @@ export interface AttachRunOptions {exitOnFailure?: boolean;}-export type AttachResult = 'attached' | 'unavailable' | 'unhealthy';+/** 'code' = the user asked for Mercury Code; MERCURY_BOOT_CODE is set and the caller boots the terminal runtime. */+export type AttachResult = 'attached' | 'unavailable' | 'unhealthy' | 'code';/*** Entry point for `mercury attach` (and the auto-attach path when a second@@ -464,12 +465,26 @@ export async function runAttach(opts: AttachRunOptions = {}): Promise<AttachResu}}+ let handoff: { kind: 'code'; dir?: string } | null = null;const instance = render(React.createElement(AttachTui, {client,pid: target.pid,onExit: () => {},+ onHandoff: (h) => { handoff = h; },}));await instance.waitUntilExit();+ if (handoff) {+ const h: { kind: 'code'; dir?: string } = handoff;+ const { resolve } = await import('node:path');+ const { existsSync, statSync } = await import('node:fs');+ const dir = h.dir ? resolve(h.dir.replace(/^~(?=$|[\\/])/, process.env.HOME ?? '')) : '';+ if (dir && !(existsSync(dir) && statSync(dir).isDirectory())) {+ console.log(chalk.yellow(` Not a directory: ${dir} — opening Mercury Code here instead.`));+ }+ process.env.MERCURY_BOOT_CODE = dir && existsSync(dir) ? dir : '1';+ console.log(chalk.dim(' Opening Mercury Code in this terminal (the runtime keeps running in the background)…'));+ return 'code';+ }console.log(chalk.dim(` Detached. Runtime still running${target.pid ? ` (PID ${target.pid})` : ''} — \`mercury stop\` stops it.`));return 'attached';}\ No newline at end of filediff --git a/src/index.ts b/src/index.tsindex 1049c262..4f2788e6 100644--- a/src/index.ts+++ b/src/index.ts@@ -76,7 +76,7 @@ import { getManual } from './utils/manual.js';import { ask, InputClosedError } from './cli/ask.js';import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';import { runUninstall } from './cli/uninstall.js';-import { runAttach } from './cli/attach.js';+import { runAttach, type AttachResult } from './cli/attach.js';import { installService, uninstallService, showServiceStatus, isServiceInstalled, pinDaemonPathOnWindows, serviceDrift } from './cli/service.js';import { detectInkPatch, describeInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';import { runWithWatchdog } from './cli/watchdog.js';@@ -2229,8 +2229,22 @@ async function configure(existingConfig?: MercuryConfig): Promise<void> {* Auto-attach entry for launch paths that found a "running" runtime. Attach,* or — when the runtime proved unresponsive — heal it and boot fresh.*/+/**+ * Attach, and if the user asks for Mercury Code from inside the attach TUI,+ * boot it here: runAgent() beside the live daemon is a terminal for the+ * main agent only (ADR-024) and honours MERCURY_BOOT_CODE.+ */+async function attachOrCode(opts?: Parameters<typeof runAttach>[0]): Promise<AttachResult> {+ const result = await runAttach(opts);+ if (result === 'code') {+ await runAgent();+ return 'attached';+ }+ return result;+}+async function attachOrHeal(): Promise<void> {- const result = await runAttach();+ const result = await attachOrCode();if (result === 'attached') return;if (result !== 'unhealthy') { process.exitCode = 1; return; }await healRuntimeAndBoot();@@ -2253,7 +2267,7 @@ async function bootDaemonThenAttach(): Promise<void> {await runAgent();return;}- const result = await runAttach();+ const result = await attachOrCode();if (result === 'attached') return;// The daemon came up but we could not attach (web disabled, port taken):// a terminal for the main agent only — runAgent() sees the live daemon@@ -3871,7 +3885,7 @@ program.command('attach').description('Attach this terminal to an already-running Mercury runtime (chat + live streaming)').action(async () => {- await runAttach({ exitOnFailure: true });+ await attachOrCode({ exitOnFailure: true });});programdiff --git a/src/ui/attach-handoff.test.ts b/src/ui/attach-handoff.test.tsnew file mode 100644index 00000000..4bc52a9d--- /dev/null+++ b/src/ui/attach-handoff.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { parseAttachHandoff } from './attach-handoff.js';++/**+ * Regression: after ADR-024 `mercury` attaches by default, and `/code` typed+ * in the attach TUI was forwarded to the daemon's web channel — which has no+ * terminal to switch into — so it printed "Programming mode: Off" and+ * Mercury Code was unreachable from the default launch.+ */+describe('attach TUI hand-off for /code', () => {+ it('/code and /code <dir> hand the terminal to Mercury Code', () => {+ expect(parseAttachHandoff('/code')).toEqual({ kind: 'code' });+ expect(parseAttachHandoff(' /code ')).toEqual({ kind: 'code' });+ expect(parseAttachHandoff('/code ~/projects/x')).toEqual({ kind: 'code', dir: '~/projects/x' });+ expect(parseAttachHandoff('/code .')).toEqual({ kind: 'code', dir: '.' });+ });++ it('mode words are explained locally, never forwarded as a no-op', () => {+ expect(parseAttachHandoff('/code plan')?.kind).toBe('notice');+ expect(parseAttachHandoff('/code off')?.kind).toBe('notice');+ });++ it('everything else is forwarded as before', () => {+ expect(parseAttachHandoff('/codex')).toBeNull();+ expect(parseAttachHandoff('/bots')).toBeNull();+ expect(parseAttachHandoff('hello')).toBeNull();+ });++ it('the launcher boots Mercury Code when the attach TUI hands off', () => {+ const index = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.ts'), 'utf8').replace(/\r\n/g, '\n');+ expect(index).toContain("if (result === 'code') {");+ expect(index.match(/await attachOrCode\(/g)?.length ?? 0).toBeGreaterThanOrEqual(3);+ expect(index).not.toMatch(/const result = await runAttach\(\);\n\s*if \(result === 'attached'\) return;/);+ });+});diff --git a/src/ui/attach-handoff.ts b/src/ui/attach-handoff.tsnew file mode 100644index 00000000..c228274c--- /dev/null+++ b/src/ui/attach-handoff.ts@@ -0,0 +1,24 @@+/**+ * Commands the attach TUI must NOT forward to the daemon because they need+ * the in-process terminal (ADR-024 left `mercury` attaching by default).+ * `/code [dir]` hands the terminal over to Mercury Code — the same boot+ * `mercury code [dir]` performs — instead of toggling a mode flag on the+ * daemon's web channel and printing "Programming mode: Off".+ */+export type AttachHandoff =+ | { kind: 'code'; dir?: string }+ | { kind: 'notice'; text: string };++const CODE_MODE_WORDS = new Set(['plan', 'auto', 'off', 'diff', 'status', 'on']);++export function parseAttachHandoff(text: string): AttachHandoff | null {+ const trimmed = text.trim();+ const m = trimmed.match(/^\/code(?:\s+(.+))?$/);+ if (!m) return null;+ const arg = (m[1] ?? '').trim();+ if (!arg) return { kind: 'code' };+ if (CODE_MODE_WORDS.has(arg.toLowerCase())) {+ return { kind: 'notice', text: `Mercury Code runs in the terminal — send /code to open it, then /code ${arg} inside it.` };+ }+ return { kind: 'code', dir: arg };+}diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsxindex 26b8242e..87161df4 100644--- a/src/ui/attach-tui.tsx+++ b/src/ui/attach-tui.tsx@@ -1,4 +1,5 @@import React from 'react';+import { parseAttachHandoff } from './attach-handoff.js';import { Box, Text, Spacer, Static, useApp, useInput } from 'ink';import type { AttachClient, AttachEvent, AttachThread } from '../cli/attach.js';import { renderMarkdown } from '../utils/markdown.js';@@ -116,7 +117,7 @@ function AttachPromptView({ prompt, activeIdx }: { prompt: AttachPrompt; activeI);}-export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid: number | null; onExit: () => void }): React.ReactNode {+export function AttachTui({ client, pid, onExit, onHandoff }: { client: AttachClient; pid: number | null; onExit: () => void; onHandoff?: (handoff: { kind: 'code'; dir?: string }) => void }): React.ReactNode {const { exit } = useApp();const [phase, setPhase] = React.useState<'pick' | 'chat'>('pick');@@ -306,6 +307,10 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:const sendInput = React.useCallback(async (text: string) => {if (!thread || !text.trim()) return;+ // Mercury Code needs this terminal, not the daemon's web channel.+ const handoff = parseAttachHandoff(text);+ if (handoff?.kind === 'notice') { setNotice(handoff.text); return; }+ if (handoff?.kind === 'code') { onHandoff?.(handoff); exit(); return; }const id = `a_local_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;setHistory((prev) => [...prev, { id, role: 'user', content: text }]);setStreaming(true);@@ -318,7 +323,7 @@ export function AttachTui({ client, pid, onExit }: { client: AttachClient; pid:if (!thread.id && result.sessionId) {setThread({ ...thread, id: result.sessionId, alias: 'session', title: 'New session' });}- }, [client, thread]);+ }, [client, thread, onHandoff, exit]);const resolvePrompt = React.useCallback(async (value: string) => {const active = prompt;