Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(chat): hand-off prompt to Mercury Code for coding tasks (time-weighted)
Salman Qureshi86f58adee66c
diff --git a/src/channels/choice-prompt-timeout.test.ts b/src/channels/choice-prompt-timeout.test.tsnew file mode 100644index 00000000..143a41bc--- /dev/null+++ b/src/channels/choice-prompt-timeout.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { CLIChannel } from './cli.js';++const agentSrc = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'core', 'agent.ts'), 'utf8');++/**+ * Time-weighted prompts: an unanswered question must be answered FOR the user+ * (default = No) and the visible prompt box must disappear — the request flow+ * is never left blocked on input nobody will give.+ */+describe('choice prompt timeout / dismissal', () => {+ it('resolveChoicePromptWithDefault resolves a pending choice prompt and clears it', async () => {+ const channel = new CLIChannel();+ const pending = channel.presentChoicePrompt('Proceed?', [+ { value: '0', label: 'Yes' },+ { value: '1', label: 'No' },+ ]);+ // The prompt is visible while pending.+ expect(channel.getTuiState().permissionPrompt).not.toBeNull();++ channel.resolveChoicePromptWithDefault('1');++ expect(await pending).toBe('1');+ expect(channel.getTuiState().permissionPrompt).toBeNull();+ });++ it('is a no-op when no prompt is pending', () => {+ const channel = new CLIChannel();+ expect(() => channel.resolveChoicePromptWithDefault('0')).not.toThrow();+ expect(channel.getTuiState().permissionPrompt).toBeNull();+ });++ it('agent: the hand-off prompt continues the work on BOTH answers (non-blocking)', () => {+ // The timeout default index must be the "No" choice.+ expect(agentSrc).toMatch(/MERCURY_CODE_HANDOFF_TIMEOUT_MS,\s*\n\s*1, \/\/ time-weighted default: No/);+ // Yes → Mercury Code + continue; No → normal chat. Either way the+ // original message is queued and processed (never dropped, never blocked).+ expect(agentSrc).toContain('promptMercuryCodeHandoff');+ expect(agentSrc).toMatch(/promptMercuryCodeHandoff\(channel: CLIChannel[\s\S]*?this\.queueMessage\(msg, workKey\);\s*\n\s*this\.processQueue\(\);/s);+ });+});\ No newline at end of filediff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 60a8c2ae..868a2fcb 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -1437,6 +1437,19 @@ export class CLIChannel extends BaseChannel {});}+ /**+ * Resolve a pending choice prompt with a default value (timeout / dismissal).+ * Time-weighted prompts use this so an unanswered question is answered FOR+ * the user and the box disappears instead of lingering forever.+ */+ resolveChoicePromptWithDefault(value: string): void {+ if (!this.state.permissionPrompt) return;+ const resolver = this.permissionResolver;+ this.permissionResolver = null;+ this.update({ permissionPrompt: null });+ resolver?.(value);+ }+async askToContinue(question: string, _targetId?: string): Promise<boolean> {return new Promise((resolve) => {this.permissionResolver = (val) => {diff --git a/src/core/agent.ts b/src/core/agent.tsindex 040e2c22..2ff7db6a 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -404,6 +404,33 @@ function looksResearchy(text: string): boolean {return temporal.test(t) || deep.test(t) || factual.test(t);}+/** No answer to the Mercury Code hand-off prompt is treated as "keep chatting". */+export const MERCURY_CODE_HANDOFF_TIMEOUT_MS = 45_000;++/**+ * Coding-shaped task detector for the Mercury Code hand-off prompt.+ * Conservative — only messages that clearly describe build/repair work on a+ * codebase match (build/repair verbs + code artifacts, source-file paths,+ * shell/package-manager commands, or fenced code). Conceptual chat questions+ * about code ("what is a pointer", "explain recursion") never match, so the+ * prompt stays rare.+ */+export function looksLikeCodingTask(text: string): boolean {+ const t = text.toLowerCase();+ if (t.length < 16 || t.startsWith('/')) return false;++ // Concept-chat noise never prompts.+ const chatNoise = /\b(what is|what's|whats|who is|explain|difference between|meaning of|how does|how do)\b/;+ if (chatNoise.test(t)) return false;++ const intent = /\b(implement|refactor|write|create|build|develop|add|fix|debug|migrate|restructure|scaffold|optimize|clean up|cleanup)\b/;+ const artifact = /\b(code|function|method|class|component|module|feature|endpoint|api|route|handler|script|library|package|bug|regression|test suite|codebase|repository|repo|app|application|plugin|migration|schema|database|service|ui|frontend|backend)\b/;+ const pathOrCommand = /(^|[\s"'(])[\w./@~-]+\.(ts|tsx|js|jsx|py|rs|go|java|kt|rb|php|c|cpp|cs|swift|sh)\b|\b(npm|pnpm|yarn|pip|cargo|git|docker|make|gradle|mvn)\s+\w+/;+ const fence = /```/;++ return (intent.test(t) && artifact.test(t)) || pathOrCommand.test(t) || fence.test(t);+}+export class Agent {readonly lifecycle: Lifecycle;readonly scheduler: Scheduler;@@ -578,10 +605,86 @@ export class Agent {return;}+ // Mercury Code hand-off: in the normal chat TUI, a coding-shaped task may+ // belong in the coding TUI. Ask once; no answer within the timeout is+ // treated as "No" and the request proceeds in normal chat — never blocked.+ // The research prompt above takes precedence when both match (the message+ // returned there already).+ if (isUserMessage && !inMercuryCode && promptChannel instanceof CLIChannel && looksLikeCodingTask(trimmed)) {+ this.promptMercuryCodeHandoff(promptChannel, msg, workKey).catch((err) => {+ logger.warn({ err: err.message }, 'Mercury Code hand-off prompt failed — proceeding with normal message');+ this.queueMessage(msg, workKey);+ this.processQueue();+ });+ return;+ }++ this.queueMessage(msg, workKey);+ this.processQueue();+ }++ /**+ * Mercury Code hand-off: in the normal chat TUI, a coding-shaped task may be+ * better served by the full-screen coding TUI. Ask ONCE with a timeout — an+ * unanswered prompt resolves to "keep chatting" after+ * MERCURY_CODE_HANDOFF_TIMEOUT_MS so the request is never left blocked.+ * Only the CLI TUI is prompted (Mercury Code is a terminal surface; other+ * channels just keep chatting).+ */+ private async promptMercuryCodeHandoff(channel: CLIChannel, msg: ChannelMessage, workKey?: string): Promise<void> {+ const choice = await this.presentChoiceWithTimeout(+ 'This looks like a coding task. Open it in Mercury Code (full-screen coding TUI — plan + build in one flow)?',+ ['Yes — switch to Mercury Code and continue there', 'No — continue in normal chat'],+ msg.channelId,+ msg.channelType,+ MERCURY_CODE_HANDOFF_TIMEOUT_MS,+ 1, // time-weighted default: No+ );++ if (choice.startsWith('Yes')) {+ const cwd = this.capabilities.getCwd();+ const entered = channel.enterMercuryCode(cwd, channel.getTuiState().version || 'dev');+ if (entered.ok) {+ this.programmingMode.setAuto();+ this.programmingMode.setProjectContext(cwd);+ channel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());+ await channel.send('Mercury Code active (AUTO) — continuing your request here.', msg.channelId).catch(() => {});+ } else {+ await channel.send(`Could not open Mercury Code (${entered.message}) — continuing in normal chat.`, msg.channelId).catch(() => {});+ }+ }this.queueMessage(msg, workKey);this.processQueue();}+ /**+ * presentChoice with a time-weighted default: if the user does not answer+ * within `timeoutMs`, the fallback choice wins and the work continues; a+ * later answer is discarded. The visible prompt is dismissed on timeout so+ * it never lingers waiting for input nobody will give.+ */+ private async presentChoiceWithTimeout(+ question: string,+ choices: string[],+ channelId: string,+ channelType: string,+ timeoutMs: number,+ fallbackIndex: number,+ ): Promise<string> {+ const fallback = choices[fallbackIndex];+ const channel = this.channels.get(channelType as any);+ const timeoutPromise = new Promise<string>((resolve) => {+ setTimeout(() => {+ if (channel instanceof CLIChannel) channel.resolveChoicePromptWithDefault(String(fallbackIndex));+ resolve(fallback);+ }, timeoutMs);+ });+ return Promise.race([+ this.presentChoice(question, choices, channelId, channelType).catch(() => fallback),+ timeoutPromise,+ ]);+ }+private queueMessage(message: ChannelMessage, workKey?: string): void {if (workKey && this.queuedWorkKeys.has(workKey)) return;this.messageQueue.push({ message, workKey });diff --git a/src/core/coding-task-detect.test.ts b/src/core/coding-task-detect.test.tsnew file mode 100644index 00000000..da77b997--- /dev/null+++ b/src/core/coding-task-detect.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';+import { MERCURY_CODE_HANDOFF_TIMEOUT_MS, looksLikeCodingTask } from './agent.js';++/**+ * The chat → Mercury Code hand-off prompt keys on this detector. It must be+ * conservative: coding-shaped build/repair work prompts, concept chat and+ * short chatter never do.+ */+describe('looksLikeCodingTask', () => {+ it('matches build/repair work on a codebase', () => {+ expect(looksLikeCodingTask('fix the bug in the auth module')).toBe(true);+ expect(looksLikeCodingTask('build a download manager app')).toBe(true);+ expect(looksLikeCodingTask('add a login feature to the app')).toBe(true);+ expect(looksLikeCodingTask('refactor the database layer and clean up the schema')).toBe(true);+ expect(looksLikeCodingTask('implement the /health endpoint')).toBe(true);+ });++ it('matches source-file paths and package commands', () => {+ expect(looksLikeCodingTask('please look at src/core/agent.ts and clean it up')).toBe(true);+ expect(looksLikeCodingTask('npm install is failing in my repo')).toBe(true);+ expect(looksLikeCodingTask('git status shows broken tests in tests/app.py')).toBe(true);+ });++ it('never prompts for concept chat or greetings', () => {+ expect(looksLikeCodingTask('what is a pointer in C')).toBe(false);+ expect(looksLikeCodingTask('explain how recursion works')).toBe(false);+ expect(looksLikeCodingTask('who is the creator of javascript')).toBe(false);+ expect(looksLikeCodingTask('hello!')).toBe(false);+ expect(looksLikeCodingTask('how do I?')).toBe(false);+ expect(looksLikeCodingTask('/code')).toBe(false);+ });++ it('is time-weighted: the hand-off prompt has a bounded timeout', () => {+ expect(MERCURY_CODE_HANDOFF_TIMEOUT_MS).toBeGreaterThanOrEqual(30_000);+ expect(MERCURY_CODE_HANDOFF_TIMEOUT_MS).toBeLessThanOrEqual(60_000);+ });+});\ No newline at end of file