Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: add workspace management features with file tree navigation, git integration, and TUI enhancements
Salman Qureshi00f442a61f98
diff --git a/README.md b/README.mdindex fd11b559..94d9d86a 100644--- a/README.md+++ b/README.md@@ -39,7 +39,7 @@ npm i -g @cosmicstack/mercury-agentmercury```-First run triggers the setup wizard — enter your name, an API key, and optionally a Telegram bot token. Takes 30 seconds.+First run triggers the setup wizard (name, provider, optional Telegram). After setup, Mercury opens the Ink TUI startup screen and asks for your permission mode (`Ask Me` or `Allow All`) before chat starts.To reconfigure later (change keys, name, settings):@@ -115,7 +115,7 @@ In daemon mode, Telegram becomes your primary channel — CLI is log-only since| `mercury restart` | Restart the background process || `mercury stop` | Stop a background process || `mercury logs` | View recent daemon logs |-| `mercury doctor` | Reconfigure (Enter to keep current values) |+| `mercury doctor` | Reconfigure setup (name, providers, channels, permissions defaults) || `mercury setup` | Re-run the setup wizard || `mercury status` | Show config and daemon status || `mercury help` | Show full manual |@@ -149,6 +149,9 @@ Type these during a conversation — they don't consume API tokens. Work on both| `/budget reset` | Reset usage to zero || `/budget set <n>` | Change daily token budget || `/permissions` | Change permission mode (Ask Me / Allow All) |+| `/view` | Toggle progress view (balanced/detailed) |+| `/view balanced` | Set compact progress view |+| `/view detailed` | Set full progress view || `/tasks` | List scheduled tasks || `/memory` | View and manage second brain memory || `/unpair` | Telegram: reset all access |@@ -170,7 +173,7 @@ Type these during a conversation — they don't consume API tokens. Work on both| Channel | Features ||---------|----------|-| **CLI** | Readline prompt, arrow-key command menus, real-time text streaming with markdown re-rendering, permission mode picker |+| **CLI** | Ink TUI, startup permission mode picker, interactive permission prompts (arrow keys + Enter; Y/N/A shortcuts), progress views (balanced/detailed), real-time streaming || **Telegram** | HTML formatting, editable streaming messages, file uploads, typing indicators, multi-user access with admin/member roles |### Telegram Accessdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex c7f8099a..ba1bd220 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -21,7 +21,7 @@ npm i -g @cosmicstack/mercury-agentmercury```-首次运行会启动配置向导。你需要输入姓名、模型 API Key,并可选择配置 Telegram Bot Token。之后如需重新配置:+首次运行会启动配置向导(姓名、模型、可选 Telegram)。完成后会进入 Ink TUI 启动画面,并在进入聊天前让你选择权限模式(`Ask Me` / `Allow All`)。之后如需重新配置:```bashmercury doctor@@ -76,7 +76,7 @@ mercury status # 查看运行状态| `mercury restart` | 重启后台进程 || `mercury stop` | 停止后台进程 || `mercury logs` | 查看近期日志 |-| `mercury doctor` | 重新配置,回车保留现有值 |+| `mercury doctor` | 重新配置 Mercury(姓名、Provider、频道、权限默认项) || `mercury setup` | 重新运行配置向导 || `mercury status` | 查看配置和守护进程状态 || `mercury help` | 查看完整手册 |@@ -110,6 +110,9 @@ mercury status # 查看运行状态| `/budget reset` | 将用量重置为零 || `/budget set <n>` | 修改每日 Token 预算 || `/permissions` | 修改权限模式 |+| `/view` | 切换进度视图(balanced/detailed) |+| `/view balanced` | 使用精简进度视图 |+| `/view detailed` | 使用详细进度视图 || `/tasks` | 列出定时任务 || `/memory` | 查看和管理 Second Brain 记忆 || `/unpair` | Telegram:重置所有访问 |@@ -131,7 +134,7 @@ mercury status # 查看运行状态| 渠道 | 能力 ||------|------|-| CLI | Readline 提示符、方向键命令菜单、实时文本流、Markdown 重渲染、权限模式选择 |+| CLI | Ink TUI、启动权限模式选择、交互式权限审批(方向键 + Enter,支持 Y/N/A 快捷键)、balanced/detailed 进度视图、实时文本流 || Telegram | HTML 格式化、可编辑流式消息、文件上传、输入状态、多用户访问和管理员/成员角色 |### Telegram 访问模型diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 07cf80ab..a861375b 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -1,10 +1,13 @@import React from 'react';import { render } from 'ink';+import fs from 'node:fs';+import path from 'node:path';+import { execSync } from 'node:child_process';import type { ChannelMessage } from '../types/channel.js';import { BaseChannel, type PermissionMode } from './base.js';import { logger } from '../utils/logger.js';import { formatToolStep, formatToolResult } from '../utils/tool-label.js';-import type { ChatMessage, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, AppMode } from '../ui/types.js';+import type { ChatMessage, ToolStep, PermissionPromptState, SidebarSection, SkillInfo, SubAgentInfo, ProviderInfo, TokenInfo, AppMode, WorkspaceState, WorkspaceTreeNode, WorkspaceGitFile } from '../ui/types.js';import { TuiApp } from '../ui/App.js';export interface TuiState {@@ -24,6 +27,7 @@ export interface TuiState {programmingMode: import('../core/programming-mode.js').ProgrammingModeState;projectContext: string | null;permissionMode: PermissionMode;+ workspace: WorkspaceState | null;}const defaultState: TuiState = {@@ -43,6 +47,7 @@ const defaultState: TuiState = {programmingMode: 'off',projectContext: null,permissionMode: 'ask-me',+ workspace: null,};export class CLIChannel extends BaseChannel {@@ -119,10 +124,38 @@ export class CLIChannel extends BaseChannel {this.update({ mode: 'chat' });return;}- if (trimmed === '/code' || trimmed === '/coding') {+ if (trimmed === '/coding') {this.update({ mode: 'coding' });return;}+ if (trimmed === '/workspace' || trimmed === '/ws') {+ this.update({ mode: this.state.workspace?.active ? 'workspace' : 'coding' });+ return;+ }+ if (trimmed === '/ws up') {+ this.moveWorkspaceSelection(-1);+ return;+ }+ if (trimmed === '/ws down') {+ this.moveWorkspaceSelection(1);+ return;+ }+ if (trimmed === '/ws open-selected') {+ this.toggleOrSelectWorkspaceNode();+ return;+ }+ if (trimmed === '/ws close-file') {+ this.closeWorkspaceFile();+ return;+ }+ if (trimmed === '/ws collapse') {+ this.collapseWorkspaceNode();+ return;+ }+ if (trimmed === '/ws expand') {+ this.expandWorkspaceNode();+ return;+ }if (trimmed === '/menu' || trimmed === '/m') {this.update({ mode: 'menu' });return;@@ -413,6 +446,216 @@ export class CLIChannel extends BaseChannel {this.update({ mode });}+ setProgrammingStatus(mode: import('../core/programming-mode.js').ProgrammingModeState, projectContext: string | null): void {+ this.update({ programmingMode: mode, projectContext });+ }++ openWorkspace(rawPath: string): { ok: boolean; message: string } {+ const target = path.resolve(rawPath.replace(/^~(?=$|\/)/, process.env.HOME || '~'));+ if (!fs.existsSync(target)) return { ok: false, message: `Workspace path does not exist: ${target}` };+ if (!fs.statSync(target).isDirectory()) return { ok: false, message: `Workspace path is not a directory: ${target}` };++ const workspace = this.buildWorkspaceState(target, undefined, 'Workspace opened');+ this.update({ workspace, mode: 'workspace', projectContext: target });+ return { ok: true, message: `Workspace opened: ${target}` };+ }++ refreshWorkspace(): void {+ if (!this.state.workspace?.active) return;+ const selectedPath = this.state.workspace.selectedPath ?? undefined;+ const workspace = this.buildWorkspaceState(this.state.workspace.rootPath, selectedPath, 'Workspace refreshed');+ this.update({ workspace });+ }++ stageWorkspaceFile(filePath: string): { ok: boolean; message: string } {+ if (!this.state.workspace?.active) return { ok: false, message: 'No active workspace.' };+ const root = this.state.workspace.rootPath;+ try {+ const rel = filePath === 'all' ? '.' : filePath;+ execSync(`git add ${this.quoteArg(rel)}`, { cwd: root, stdio: 'pipe' });+ this.refreshWorkspace();+ return { ok: true, message: rel === '.' ? 'Staged all changes.' : `Staged: ${rel}` };+ } catch (err: any) {+ return { ok: false, message: `Stage failed: ${err?.message || String(err)}` };+ }+ }++ undoWorkspaceFile(filePath: string): { ok: boolean; message: string } {+ if (!this.state.workspace?.active) return { ok: false, message: 'No active workspace.' };+ const root = this.state.workspace.rootPath;+ try {+ execSync(`git checkout -- ${this.quoteArg(filePath)}`, { cwd: root, stdio: 'pipe' });+ this.refreshWorkspace();+ return { ok: true, message: `Reverted: ${filePath}` };+ } catch (err: any) {+ return { ok: false, message: `Undo failed: ${err?.message || String(err)}` };+ }+ }++ commitWorkspace(message: string): { ok: boolean; message: string } {+ if (!this.state.workspace?.active) return { ok: false, message: 'No active workspace.' };+ const root = this.state.workspace.rootPath;+ if (!message.trim()) return { ok: false, message: 'Commit message is required.' };+ const body = `${message.trim()}\n\nCo-authored-by: Mercury <[email protected]>`;+ try {+ execSync(`git commit -m ${this.quoteArg(body)}`, { cwd: root, stdio: 'pipe' });+ this.refreshWorkspace();+ return { ok: true, message: 'Commit created with Mercury co-author.' };+ } catch (err: any) {+ return { ok: false, message: `Commit failed: ${err?.message || String(err)}` };+ }+ }++ getWorkspace(): WorkspaceState | null {+ return this.state.workspace;+ }++ private quoteArg(v: string): string {+ return `'${v.replace(/'/g, `'\\''`)}'`;+ }++ private moveWorkspaceSelection(delta: number): void {+ if (!this.state.workspace?.active) return;+ const next = Math.max(0, Math.min(this.state.workspace.nodes.length - 1, this.state.workspace.selectedIndex + delta));+ const node = this.state.workspace.nodes[next];+ this.update({+ workspace: {+ ...this.state.workspace,+ selectedIndex: next,+ selectedPath: node?.path || null,+ },+ });+ }++ private toggleOrSelectWorkspaceNode(): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ const node = ws.nodes[ws.selectedIndex];+ if (!node) return;+ if (!node.isDir) {+ const preview = this.readFilePreview(node.path);+ this.update({ workspace: { ...ws, selectedPath: node.path, openedFilePath: node.path, openedFilePreview: preview, lastAction: `Opened file: ${node.path}` } });+ return;+ }+ const expanded = !node.expanded;+ this.rebuildWorkspaceWithExpansion(node.path, expanded);+ }++ private collapseWorkspaceNode(): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ const node = ws.nodes[ws.selectedIndex];+ if (!node?.isDir) return;+ if (!node.expanded) return;+ this.rebuildWorkspaceWithExpansion(node.path, false);+ }++ private expandWorkspaceNode(): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ const node = ws.nodes[ws.selectedIndex];+ if (!node?.isDir) return;+ if (node.expanded) return;+ this.rebuildWorkspaceWithExpansion(node.path, true);+ }++ private rebuildWorkspaceWithExpansion(nodePath: string, expand: boolean): void {+ const ws = this.state.workspace;+ if (!ws) return;+ const expandedSet = new Set(ws.nodes.filter((n) => n.isDir && n.expanded).map((n) => n.path));+ if (expand) expandedSet.add(nodePath);+ else expandedSet.delete(nodePath);+ const workspace = this.buildWorkspaceState(ws.rootPath, ws.selectedPath || undefined, ws.lastAction, expandedSet);+ this.update({ workspace });+ }++ private buildWorkspaceState(rootPath: string, selectedPath?: string, lastAction = '', preExpanded?: Set<string>): WorkspaceState {+ const expanded = preExpanded || new Set<string>([rootPath]);+ const nodes = this.buildTreeNodes(rootPath, expanded, 0);+ const selectedIndex = Math.max(0, nodes.findIndex((n) => n.path === selectedPath));+ const selectedNode = nodes[selectedIndex] || nodes[0] || null;+ const { files, branch, stagedCount, unstagedCount } = this.readGitState(rootPath);+ return {+ active: true,+ rootPath,+ nodes,+ selectedIndex,+ selectedPath: selectedNode?.path || null,+ openedFilePath: this.state.workspace?.openedFilePath || null,+ openedFilePreview: this.state.workspace?.openedFilePreview || [],+ gitFiles: files,+ stagedCount,+ unstagedCount,+ branch,+ lastAction,+ };+ }++ closeWorkspaceFile(): void {+ const ws = this.state.workspace;+ if (!ws?.active) return;+ this.update({ workspace: { ...ws, openedFilePath: null, openedFilePreview: [], lastAction: 'Closed file preview' } });+ }++ private readFilePreview(filePath: string): string[] {+ try {+ const raw = fs.readFileSync(filePath, 'utf-8');+ return raw.split('\n').slice(0, 80);+ } catch {+ return ['(Unable to read file preview)'];+ }+ }++ private buildTreeNodes(dir: string, expanded: Set<string>, depth: number): WorkspaceTreeNode[] {+ const nodes: WorkspaceTreeNode[] = [];+ const id = `${dir}:${depth}`;+ const isExpanded = expanded.has(dir);+ nodes.push({ id, name: depth === 0 ? path.basename(dir) || dir : path.basename(dir), path: dir, depth, isDir: true, expanded: isExpanded });+ if (!isExpanded) return nodes;+ let entries: fs.Dirent[] = [];+ try {+ entries = fs.readdirSync(dir, { withFileTypes: true });+ } catch {+ return nodes;+ }+ const sorted = entries+ .filter((e) => e.name !== '.git' && e.name !== 'node_modules')+ .sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));+ for (const entry of sorted.slice(0, 200)) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ nodes.push(...this.buildTreeNodes(full, expanded, depth + 1));+ } else {+ nodes.push({ id: `${full}:${depth + 1}`, name: entry.name, path: full, depth: depth + 1, isDir: false });+ }+ }+ return nodes;+ }++ private readGitState(rootPath: string): { files: WorkspaceGitFile[]; branch: string; stagedCount: number; unstagedCount: number } {+ try {+ const branch = execSync('git branch --show-current', { cwd: rootPath, stdio: 'pipe' }).toString().trim() || 'detached';+ const out = execSync('git status --porcelain', { cwd: rootPath, stdio: 'pipe' }).toString();+ const files: WorkspaceGitFile[] = out+ .split('\n')+ .map((line) => line.trimEnd())+ .filter(Boolean)+ .map((line) => {+ const x = line[0] || ' ';+ const y = line[1] || ' ';+ const rel = line.slice(3).trim();+ const staged = x !== ' ' && x !== '?';+ const status = `${x}${y}`.trim() || '??';+ return { path: rel, staged, status };+ });+ const stagedCount = files.filter((f) => f.staged).length;+ const unstagedCount = files.length - stagedCount;+ return { files, branch, stagedCount, unstagedCount };+ } catch {+ return { files: [], branch: 'not-a-git-repo', stagedCount: 0, unstagedCount: 0 };+ }+ }+initSplash(agentName: string, version: string): void {this.update({ agentName, version, mode: 'splash' });}diff --git a/src/core/agent.ts b/src/core/agent.tsindex d19112ea..d83809d3 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1,4 +1,5 @@import { generateText, streamText, stepCountIs } from 'ai';+import path from 'node:path';import type { ChannelMessage, ChannelType } from '../types/channel.js';import type { ProviderRegistry } from '../providers/registry.js';import type { Identity } from '../soul/identity.js';@@ -545,6 +546,11 @@ export class Agent {return;}+ if (await this.handleWorkspaceNaturalLanguage(trimmed, msg.channelType, msg.channelId)) {+ this.lifecycle.transition('idle');+ return;+ }+if (this.tokenBudget.isOverBudget()) {const channel = this.channels.getChannelForMessage(msg);if (channel && msg.channelType !== 'internal') {@@ -1737,26 +1743,81 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userif (cmd.startsWith('/code')) {const rawArgs = trimmed.slice('/code'.length).trim().toLowerCase();+ const cliChannel = channelType === 'cli' && channel instanceof CLIChannel ? channel : null;- if (!rawArgs || rawArgs === 'status') {+ if (!rawArgs) {+ if (cliChannel) {+ const choice = await this.presentChoice(+ 'Code mode: open workspace IDE now?',+ ['Yes, open current workspace', 'No, keep classic coding mode'],+ channelId,+ channelType,+ );+ if (choice.toLowerCase().startsWith('yes')) {+ const current = this.capabilities.getCwd();+ const opened = cliChannel.openWorkspace(current);+ if (opened.ok) {+ this.capabilities.permissions.addTempScope(current, true, true);+ this.programmingMode.setExecute();+ this.programmingMode.setProjectContext(current);+ cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send(`${opened.message}\nWorkspace IDE mode enabled.`, channelId);+ return true;+ }+ await channel.send(opened.message, channelId);+ return true;+ }+ }+ await channel.send(this.programmingMode.getStatusText(), channelId);+ return true;+ }++ if (rawArgs === 'status') {await channel.send(this.programmingMode.getStatusText(), channelId);return true;}+ if (rawArgs === 'workspace' || rawArgs === 'ws') {+ if (!cliChannel) {+ await channel.send('Workspace IDE mode is currently available in CLI only.', channelId);+ return true;+ }+ const current = this.capabilities.getCwd();+ const opened = cliChannel.openWorkspace(current);+ if (opened.ok) {+ this.programmingMode.setExecute();+ cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send(`${opened.message}\nWorkspace IDE mode enabled.`, channelId);+ } else {+ await channel.send(opened.message, channelId);+ }+ return true;+ }+if (rawArgs === 'plan') {this.programmingMode.setPlan();+ if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());await channel.send('Programming mode: **Plan**\nI will explore, analyze, and present a plan before writing any code. Use `/code execute` to switch to execution.', channelId);return true;}if (rawArgs === 'execute' || rawArgs === 'exec') {this.programmingMode.setExecute();+ if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());await channel.send('Programming mode: **Execute**\nI will implement the plan step by step, verifying with builds/tests. Use `/code off` to exit.', channelId);return true;}+ if (rawArgs === 'build') {+ this.programmingMode.setExecute();+ if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send('Programming mode: **Build**\nExecution mode is active for implementation/build tasks.', channelId);+ return true;+ }+if (rawArgs === 'off' || rawArgs === 'exit') {this.programmingMode.setOff();+ if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());await channel.send('Programming mode: **Off**\nBack to normal conversation mode.', channelId);return true;}@@ -1764,11 +1825,81 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userif (rawArgs === 'toggle') {const newState = this.programmingMode.toggle();const labels: Record<string, string> = { off: 'Off', plan: 'Plan', execute: 'Execute' };+ if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());await channel.send(`Programming mode: **${labels[newState]}**`, channelId);return true;}- await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code off, /code toggle', channelId);+ await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code build, /code workspace, /code off, /code toggle', channelId);+ return true;+ }++ if (cmd.startsWith('/ws') || cmd.startsWith('/workspace')) {+ const cliChannel = channelType === 'cli' && channel instanceof CLIChannel ? channel : null;+ if (!cliChannel) {+ await channel.send('Workspace IDE mode is currently available in CLI only.', channelId);+ return true;+ }++ const base = cmd.startsWith('/workspace') ? '/workspace' : '/ws';+ const rawArgs = trimmed.slice(base.length).trim();+ const rawLower = rawArgs.toLowerCase();++ if (!rawArgs || rawLower === 'status') {+ const ws = cliChannel.getWorkspace();+ await channel.send(ws?.active ? `Workspace active: ${ws.rootPath}` : 'No active workspace. Use `/ws open <path>`.', channelId);+ return true;+ }++ if (rawLower.startsWith('open ')) {+ const target = rawArgs.slice(5).trim();+ const opened = cliChannel.openWorkspace(target);+ if (opened.ok) {+ this.capabilities.setCwd(path.resolve(target.replace(/^~(?=$|\/)/, process.env.HOME || '~')));+ this.capabilities.permissions.addTempScope(this.capabilities.getCwd(), true, true);+ this.programmingMode.setExecute();+ this.programmingMode.setProjectContext(this.capabilities.getCwd());+ cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send(`${opened.message}\nWorkspace IDE is ready.`, channelId);+ } else {+ await channel.send(opened.message, channelId);+ }+ return true;+ }++ if (rawLower === 'refresh') {+ cliChannel.refreshWorkspace();+ await channel.send('Workspace refreshed.', channelId);+ return true;+ }++ if (rawLower.startsWith('stage ')) {+ const fileArg = rawArgs.slice(6).trim();+ const result = cliChannel.stageWorkspaceFile(fileArg || 'all');+ await channel.send(result.message, channelId);+ return true;+ }++ if (rawLower.startsWith('commit ')) {+ const message = rawArgs.slice(7).trim();+ const result = cliChannel.commitWorkspace(message);+ await channel.send(result.message, channelId);+ return true;+ }++ if (rawLower.startsWith('undo ')) {+ const fileArg = rawArgs.slice(5).trim();+ const result = cliChannel.undoWorkspaceFile(fileArg);+ await channel.send(result.message, channelId);+ return true;+ }++ if (rawLower === 'help') {+ await channel.send('Workspace commands:\n`/ws open <path>`\n`/ws refresh`\n`/ws stage <file|all>`\n`/ws commit <message>`\n`/ws undo <file>`\n`/ws status`', channelId);+ return true;+ }++ await channel.send('Unknown workspace command. Use `/ws help`.', channelId);return true;}@@ -2162,6 +2293,33 @@ Always specify owner and repo parameters on GitHub tools. The user's GitHub userreturn false;}+ private async handleWorkspaceNaturalLanguage(content: string, channelType: string, channelId: string): Promise<boolean> {+ const channel = this.channels.get(channelType as any);+ if (!channel || channelType !== 'cli' || !(channel instanceof CLIChannel)) return false;++ const lower = content.toLowerCase();+ if (!lower.includes('workspace')) return false;+ if (!(lower.includes('open') || lower.includes('use') || lower.includes('enter'))) return false;++ const pathMatch = content.match(/(?:open|use|workspace)\s+(?:at\s+|in\s+)?([^,.;]+)$/i);+ const targetRaw = (pathMatch?.[1] || '').trim();+ const target = targetRaw && !targetRaw.startsWith('workspace') ? targetRaw : this.capabilities.getCwd();+ const opened = channel.openWorkspace(target);+ if (!opened.ok) {+ await channel.send(opened.message, channelId);+ return true;+ }++ const resolved = path.resolve(target.replace(/^~(?=$|\/)/, process.env.HOME || '~'));+ this.capabilities.setCwd(resolved);+ this.capabilities.permissions.addTempScope(resolved, true, true);+ this.programmingMode.setExecute();+ this.programmingMode.setProjectContext(resolved);+ channel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send(`Workspace opened from conversation intent: ${resolved}`, channelId);+ return true;+ }+private async openCliCommandMenu(channel: CLIChannel, channelId: string): Promise<void> {const ctx = this.capabilities.getChatCommandContext();if (!ctx) return;diff --git a/src/index.ts b/src/index.tsindex 8c4a5eda..2bc9b169 100644--- a/src/index.ts+++ b/src/index.ts@@ -58,12 +58,11 @@ function hr() {}const MERCURY_ASCII = [- ' __ _____________ ________ ________ __',- ' / |/ / ____/ __ \\/ ____/ / / / __ \\/ < /',- ' / /|_/ / __/ / /_/ / / / / / / /_/ /\\ / ',- ' / / / / /___/ _, _/ /___/ /_/ / _, _/ / / ',- '/_/ /_/_____/_/ |_|\\____/\\____/_/ |_| /_/ ',-].filter(l => l.trim());+ ' /\\_/\\ ',+ ' =( o.o )= ',+ ' > ^ < ',+ ' * ',+].filter((l) => l.trim());function banner() {console.log('');@@ -71,7 +70,8 @@ function banner() {console.log(chalk.bold.cyan(` ${line}`));}console.log('');- console.log(chalk.white(' an AI agent for personal tasks'));+ console.log(chalk.bold.cyan(' MERCURY'));+ console.log(chalk.white(' Your soul-driven AI agent'));console.log(chalk.dim(` v${pkgVersion} · by Cosmic Stack · mercury.cosmicstack.org`));console.log('');}@@ -82,7 +82,8 @@ function splashScreen() {console.log(chalk.bold.cyan(` ${line}`));}console.log('');- console.log(chalk.dim(' an AI agent for personal tasks'));+ console.log(chalk.bold.cyan(' MERCURY'));+ console.log(chalk.dim(' Your soul-driven AI agent'));console.log(chalk.cyan(' by Cosmic Stack'));console.log(chalk.dim(' mercury.cosmicstack.org'));console.log('');@@ -1424,7 +1425,7 @@ programprogram.command('doctor')- .description('Reconfigure Mercury — change keys, name, settings (Enter to keep current)')+ .description('Reconfigure Mercury setup (name, providers, channels, permissions defaults)').action(async () => {if (isSetupComplete()) {await configure(loadConfig());diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 0443b33c..02747145 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -74,6 +74,11 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCliconst [inputHistory, setInputHistory] = React.useState<string[]>([]);const [historyIndex, setHistoryIndex] = React.useState<number>(-1);const [historyDraft, setHistoryDraft] = React.useState<string>('');+ const [workspacePane, setWorkspacePane] = React.useState<'files' | 'details' | 'git'>('files');+ const [detailCursor, setDetailCursor] = React.useState(0);+ const [gitCursor, setGitCursor] = React.useState(0);+ const [workspaceLeaderActive, setWorkspaceLeaderActive] = React.useState(false);+ const workspaceLeaderTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);const slashCommands = React.useMemo(() => ['/help',@@ -83,6 +88,8 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli'/code','/code plan','/code execute',+ '/code build',+ '/code workspace','/code off','/spotify','/budget',@@ -92,6 +99,12 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli'/view','/view balanced','/view detailed',+ '/ws',+ '/ws open ',+ '/ws refresh',+ '/ws stage all',+ '/ws commit ',+ '/ws help',], []);const slashSuggestions = React.useMemo(() => {@@ -152,6 +165,8 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli}, [state.permissionPrompt]);useInput((ch, key) => {+ const keyChar = (ch || (key as any)?.name || '').toLowerCase();+if (ch === '\u0003' || (key.ctrl && ((key as any).name === 'c' || ch?.toLowerCase?.() === 'c'))) {onExit();return;@@ -247,6 +262,76 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyClireturn;}+ if (state.mode === 'workspace') {+ if (!key.ctrl && !key.meta && ch === ';' && input.length === 0) {+ setWorkspaceLeaderActive(true);+ if (workspaceLeaderTimeoutRef.current) clearTimeout(workspaceLeaderTimeoutRef.current);+ workspaceLeaderTimeoutRef.current = setTimeout(() => {+ setWorkspaceLeaderActive(false);+ workspaceLeaderTimeoutRef.current = null;+ }, 1600);+ return;+ }++ if (workspaceLeaderActive) {+ if (workspaceLeaderTimeoutRef.current) {+ clearTimeout(workspaceLeaderTimeoutRef.current);+ workspaceLeaderTimeoutRef.current = null;+ }+ setWorkspaceLeaderActive(false);++ if (keyChar === 'f') {+ setWorkspacePane('files');+ return;+ }+ if (keyChar === 'd') {+ setWorkspacePane('details');+ return;+ }+ if (keyChar === 'g') {+ setWorkspacePane('git');+ return;+ }+ if (keyChar === 'c') {+ onInput('/ws close-file');+ return;+ }++ if (key.escape) {+ return;+ }+ }++ if (key.upArrow) {+ if (workspacePane === 'files') onInput('/ws up');+ else if (workspacePane === 'details') setDetailCursor((i) => Math.max(0, i - 1));+ else setGitCursor((i) => Math.max(0, i - 1));+ return;+ }+ if (key.downArrow) {+ if (workspacePane === 'files') onInput('/ws down');+ else if (workspacePane === 'details') setDetailCursor((i) => Math.min(3, i + 1));+ else setGitCursor((i) => Math.min((state.workspace?.gitFiles.length || 1) - 1, i + 1));+ return;+ }+ if (key.leftArrow) {+ if (workspacePane === 'files') onInput('/ws collapse');+ return;+ }+ if (key.rightArrow) {+ if (workspacePane === 'files') onInput('/ws expand');+ return;+ }+ if (key.return && !input.trim()) {+ if (workspacePane === 'files') onInput('/ws open-selected');+ else if (workspacePane === 'git') {+ const picked = state.workspace?.gitFiles[gitCursor];+ if (picked) onInput(`/ws stage ${picked.path}`);+ }+ return;+ }+ }+if (state.mode === 'splash') return;if ((ch === 'v' || ch === 'V') && !state.permissionPrompt) {@@ -319,6 +404,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli}if (key.ctrl || key.meta) return;+if (ch && ch.length === 1 && !key.escape) {setInput((prev) => prev + ch);}@@ -377,7 +463,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli);}- const showInput = !state.permissionPrompt && !state.isThinking && (state.mode === 'chat' || state.mode === 'coding');+ const showInput = !state.permissionPrompt && !state.isThinking && (state.mode === 'chat' || state.mode === 'coding' || state.mode === 'workspace');return (<Box flexDirection="column" flexGrow={1}>@@ -385,6 +471,7 @@ export function TuiApp({ state, onInput, onPermissionResolve, onExit, spotifyCli{state.mode === 'spotify' ? <SpotifyBody activeIdx={spotifyIdx} nowPlaying={spotifyNow} /> : null}{state.mode === 'menu' ? <MenuBody menuIdx={menuIdx} /> : null}{state.mode === 'coding' ? <CodingBody state={state} /> : null}+ {state.mode === 'workspace' ? <WorkspaceBody state={state} workspacePane={workspacePane} detailCursor={detailCursor} gitCursor={gitCursor} workspaceLeaderActive={workspaceLeaderActive} /> : null}{state.mode === 'chat' ? (<ChatBody state={state} />) : null}@@ -500,6 +587,89 @@ function CodingBody({ state }: { state: TuiState }) {);}+function WorkspaceBody({ state, workspacePane, detailCursor, gitCursor, workspaceLeaderActive }: { state: TuiState; workspacePane: 'files' | 'details' | 'git'; detailCursor: number; gitCursor: number; workspaceLeaderActive: boolean }) {+ const ws = state.workspace;+ if (!ws?.active) {+ return (+ <Box flexDirection="column" flexGrow={1} paddingX={1}>+ <Text color="yellow">Workspace mode is not active.</Text>+ <Text dimColor>Use /ws open <path> or type: open workspace /path/to/project</Text>+ </Box>+ );+ }++ const selectedNode = ws.nodes[ws.selectedIndex];+ const selectedRel = selectedNode ? selectedNode.path.replace(ws.rootPath + '/', '') : '';++ return (+ <Box flexDirection="column" flexGrow={1}>+ <Box paddingX={1}>+ <Text color="gray">Workspace: </Text><Text color="cyan">{ws.rootPath}</Text>+ <Text color="gray"> | Branch: </Text><Text color="magenta">{ws.branch}</Text>+ <Text color="gray"> | Pane: </Text><Text color="white">{workspacePane.toUpperCase()}</Text>+ {workspaceLeaderActive ? <Text color="yellow"> [;] pending: F/D/G/C</Text> : null}+ </Box>+ <Box paddingX={1}><Text color="gray">{'═'.repeat(118)}</Text></Box>+ <Box flexDirection="row" flexGrow={1}>+ <Box flexDirection="column" width={40} paddingX={1}>+ <Text bold color={workspacePane === 'files' ? 'white' : 'cyan'}>EXPLORER {workspacePane === 'files' ? '●' : '○'}</Text>+ <Text color="gray">{'─'.repeat(36)}</Text>+ {ws.nodes.slice(0, 300).map((node, idx) => {+ const isSelected = idx === ws.selectedIndex;+ const prefix = node.isDir ? (node.expanded ? '▾' : '▸') : ' ';+ const indent = ' '.repeat(Math.max(0, node.depth * 2));+ return (+ <Text key={node.id} color={isSelected ? 'white' : 'gray'}>+ {isSelected ? '›' : ' '} {indent}{prefix} {node.name}+ </Text>+ );+ })}+ </Box>+ <Box><Text color="gray">│</Text></Box>+ <Box flexDirection="column" flexGrow={1} paddingX={1}>+ <Text bold color={workspacePane === 'details' ? 'white' : 'cyan'}>EDITOR {workspacePane === 'details' ? '●' : '○'}</Text>+ <Text color="gray">{'─'.repeat(40)}</Text>+ <Text color={detailCursor === 0 ? 'white' : undefined}>Selected: <Text color="yellow">{selectedRel || ws.rootPath}</Text></Text>+ <Text color={detailCursor === 1 ? 'white' : undefined}>Mode: <Text color={state.programmingMode === 'execute' ? 'green' : 'yellow'}>{state.programmingMode.toUpperCase()}</Text></Text>+ <Text color={detailCursor === 2 ? 'white' : undefined}>Prompt lane: Mercury chat input is active below.</Text>+ {ws.lastAction ? <Text dimColor>Last: {ws.lastAction}</Text> : null}+ <Text color="gray">{'─'.repeat(40)}</Text>+ <Text bold color="cyan">File Preview</Text>+ {ws.openedFilePath ? <Text color="yellow">{ws.openedFilePath}</Text> : <Text dimColor>No open file. Select in Files and press Enter.</Text>}+ {ws.openedFilePreview.slice(0, 24).map((line, i) => (+ <Text key={`${i}:${line.slice(0, 10)}`} dimColor>{String(i + 1).padStart(3, ' ')} {line}</Text>+ ))}+ {state.toolSteps.length > 0 && <ToolStepsView steps={state.toolSteps} viewMode={state.viewMode} />}+ {state.subAgents.length > 0 ? <AgentPanelView agents={state.subAgents} /> : <Text dimColor>No sub-agents active. Mercury shows active prompts/tools here.</Text>}+ <Box marginTop={1}><Text dimColor>Focus: F Files · D Details · G Git · C close file</Text></Box>+ </Box>+ <Box><Text color="gray">│</Text></Box>+ <Box flexDirection="column" width={44} paddingX={1}>+ <Text bold color={workspacePane === 'git' ? 'white' : 'cyan'}>SOURCE CONTROL {workspacePane === 'git' ? '●' : '○'}</Text>+ <Text color="gray">{'─'.repeat(40)}</Text>+ <Text>Staged: <Text color="green">{ws.stagedCount}</Text> · Unstaged: <Text color="yellow">{ws.unstagedCount}</Text></Text>+ <Text color="gray">{'─'.repeat(40)}</Text>+ {ws.gitFiles.length === 0 ? <Text dimColor>Clean working tree</Text> : ws.gitFiles.slice(0, 40).map((f, i) => (+ <Text key={f.path} color={i === gitCursor ? 'white' : (f.staged ? 'green' : 'yellow')}>{i === gitCursor ? '›' : ' '} {f.staged ? '●' : '○'} {f.status} {f.path}</Text>+ ))}+ <Box marginTop={1} flexDirection="column">+ <Text dimColor>/ws stage all</Text>+ <Text dimColor>/ws stage <file></Text>+ <Text dimColor>/ws commit <message></Text>+ <Text dimColor>/ws undo <file></Text>+ <Text dimColor>/ws refresh</Text>+ <Text dimColor>Enter in Git pane stages selected file</Text>+ </Box>+ </Box>+ </Box>+ <Box paddingX={1}><Text color="gray">{'═'.repeat(118)}</Text></Box>+ <Box paddingX={1}>+ <Text dimColor>Shortcuts: ; then F/D/G/C · Tree: ↑↓ navigate, ← collapse, → expand, Enter open · Git: Enter stage selected</Text>+ </Box>+ </Box>+ );+}+function MenuBody({ menuIdx }: { menuIdx: number }) {const menuOptions: Array<{ label: string; mode: AppMode; icon: string }> = [{ label: 'Status', mode: 'menu', icon: '📊' },diff --git a/src/ui/types.ts b/src/ui/types.tsindex 0afd887b..0d37d84b 100644--- a/src/ui/types.ts+++ b/src/ui/types.ts@@ -2,7 +2,37 @@ import type { ProgrammingModeState } from '../core/programming-mode.js';import type { SubAgentStatus } from '../types/agent.js';import type { PermissionMode } from '../channels/base.js';-export type AppMode = 'splash' | 'chat' | 'coding' | 'spotify' | 'menu';+export type AppMode = 'splash' | 'chat' | 'coding' | 'workspace' | 'spotify' | 'menu';++export interface WorkspaceTreeNode {+ id: string;+ name: string;+ path: string;+ depth: number;+ isDir: boolean;+ expanded?: boolean;+}++export interface WorkspaceGitFile {+ path: string;+ staged: boolean;+ status: string;+}++export interface WorkspaceState {+ active: boolean;+ rootPath: string;+ nodes: WorkspaceTreeNode[];+ selectedIndex: number;+ selectedPath: string | null;+ openedFilePath: string | null;+ openedFilePreview: string[];+ gitFiles: WorkspaceGitFile[];+ stagedCount: number;+ unstagedCount: number;+ branch: string;+ lastAction: string;+}export interface ChatMessage {id: string;@@ -75,6 +105,7 @@ export interface MercuryAppState {version: string;isThinking: boolean;permissionPrompt: PermissionPromptState | null;+ workspace: WorkspaceState | null;}export interface PermissionPromptState {@@ -82,4 +113,4 @@ export interface PermissionPromptState {message: string;options?: Array<{ value: string; label: string }>;resolve: (value: string | boolean) => void;-}\ No newline at end of file+}diff --git a/src/utils/manual.ts b/src/utils/manual.tsindex d1e8aa3b..14fe8339 100644--- a/src/utils/manual.ts+++ b/src/utils/manual.ts@@ -119,6 +119,9 @@ export function getManual(): string {['/tools', 'List currently loaded tools'],['/skills', 'List installed skills'],['/permissions', 'Change permission mode (Ask Me / Allow All)'],+ ['/view', 'Toggle progress view (balanced/detailed)'],+ ['/view balanced', 'Set compact progress view'],+ ['/view detailed', 'Set full progress view'],['/tasks', 'List scheduled tasks'],['/memory', 'View and manage second brain memory'],['/stream', 'Toggle text streaming on/off (Telegram)'],@@ -133,8 +136,15 @@ export function getManual(): string {['/code', 'Show programming mode status'],['/code plan', 'Switch to plan mode (analyze, present options, no coding)'],['/code execute', 'Switch to execute mode (implement plan step by step)'],+ ['/code build', 'Alias of execute mode for build-focused coding'],+ ['/code workspace', 'Open current directory in workspace IDE mode'],['/code off', 'Exit programming mode'],['/code toggle', 'Cycle through: off → plan → execute → off'],+ ['/ws open <path>', 'Open a workspace directory in IDE mode'],+ ['/ws refresh', 'Refresh file tree + git status panel'],+ ['/ws stage <file|all>', 'Stage a file or all changes'],+ ['/ws commit <message>', 'Commit staged changes (Mercury co-authored)'],+ ['/ws undo <file>', 'Revert file changes with git checkout -- <file>'],['/halt', 'Emergency: stop all agents + clear queue'],['/stop', 'Stop all agents + clear queue + release locks + clear task board'],['/reset', 'Full reset: stop all + clear context (requires confirmation)'],@@ -159,9 +169,10 @@ export function getManual(): string {const perms = ['Commands are blocked (never run), auto-approved, or need approval.',- 'Say "always" when prompted to permanently approve a command type.',+ 'Use interactive approval prompts: ↑/↓ + Enter (or Y/N/A shortcuts).',+ 'Choose "Always" when prompted to permanently approve a command type.','Edit ~/.mercury/permissions.yaml to customize manually.',- 'File access is scoped — new paths need approval (y/n/always).',+ 'File access is scoped — new paths need approval (Yes/No/Always).','At session start, choose "Ask Me" (confirm each action) or "Allow All" (auto-approve everything).','Scheduled tasks always run in Allow All mode.',];