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.

fix(chat): research prompt only when the owner wants research; Quick answer first

Salman Qureshi35c5c16b5c8d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c9454205..de38d0e4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@
- **Search never depends on the model.** Results come only from Mercury's own search tools, never from a provider's built-in web search, so search works the same with every model.
- **You can see what happened.** Every result ends with the trail, for example `Searched: Brave: blocked (HTTP 429) → DuckDuckGo: 5 results`, so "nothing found" and "everything was blocked" read differently.
+### Chat
+- **The research prompt asks only when you want research.** It used to fire on words ("latest", "recent", "explain", "today's news"), so "convert the latest epub" or "explain how my build works and fix it" got a research question. The words now only decide whether to check; one short model call decides whether you asked for an in-depth, multi-source write-up. Instructions, quick questions and today's news never get the prompt, and a failed or slow check means no prompt.
+- **Quick answer comes first.** The picker starts on "Quick answer", so an accidental Enter never starts a long research run.
+
## 1.4.1 — Mercury learns how you work, saves its own skills, and searches again
### Owner Model: Mercury learns how to work with you (ADR-026)
diff --git a/src/channels/choice-prompt-timeout.test.ts b/src/channels/choice-prompt-timeout.test.ts
index 70a54a71..7206e247 100644
--- a/src/channels/choice-prompt-timeout.test.ts
+++ b/src/channels/choice-prompt-timeout.test.ts
@@ -59,7 +59,9 @@ describe('choice prompt timeout / dismissal', () => {
// timeout — an unanswered question held the chat message indefinitely.
// It must use the same time-weighted contract, defaulting to Quick answer.
expect(agentSrc).toMatch(/promptResearchMode[\s\S]*?this\.presentChoiceWithTimeout\(/s);
- expect(agentSrc).toMatch(/MERCURY_CODE_HANDOFF_TIMEOUT_MS,\s*\n\s*1, \/\/ unanswered = Quick answer/);
+ expect(agentSrc).toMatch(/MERCURY_CODE_HANDOFF_TIMEOUT_MS,\s*\n\s*0, \/\/ unanswered = Quick answer/);
+ // Quick answer is listed first, so the picker starts on it.
+ expect(agentSrc).toMatch(/\['Quick answer \(normal conversation\)', 'Full research mode/);
});
it('enterMercuryCode tears down a stranded bot chat (no parked sends afterwards)', async () => {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 8a07be1d..32a5fa7e 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -40,6 +40,7 @@ import { getTelegramHelp, getDiscordHelp, getSlackHelp } from '../utils/manual.j
import { WebChannel } from '../channels/web.js';
import type { ArrowSelectOption } from '../utils/arrow-select.js';
import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';
+import { classifyResearchIntent } from './research-intent.js';
import type { SpotifyClient } from '../spotify/client.js';
import { normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';
import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../spotify/ui.js';
@@ -911,20 +912,41 @@ export class Agent {
const isUserMessage = msg.channelType !== 'internal' && msg.senderId !== 'system' && !trimmed.startsWith('/');
const promptChannel = this.channels.getChannelForMessage(msg);
const inMercuryCode = promptChannel instanceof CLIChannel && promptChannel.getTuiState().mercuryCode != null;
+ // The word filter only decides whether to ask the model; the model
+ // decides whether the owner actually wants a research article. An
+ // instruction ("do X with the latest file") or a quick question never
+ // gets the prompt, and a failed or slow check means no prompt.
if (isUserMessage && !inMercuryCode && !this.researchMode.isActive() && looksResearchy(trimmed)) {
- this.promptResearchMode(msg, workKey).catch((err) => {
- logger.warn({ err: err.message }, 'Research-mode prompt failed — proceeding with normal message');
- this.queueMessage(msg, workKey);
- this.processQueue();
+ void this.wantsResearch(trimmed).then((wanted) => {
+ if (!wanted) {
+ this.routeIncoming(msg, workKey, trimmed, isUserMessage, inMercuryCode, promptChannel);
+ return;
+ }
+ this.promptResearchMode(msg, workKey).catch((err) => {
+ logger.warn({ err: err.message }, 'Research-mode prompt failed — proceeding with normal message');
+ this.queueMessage(msg, workKey);
+ this.processQueue();
+ });
});
return;
}
+ this.routeIncoming(msg, workKey, trimmed, isUserMessage, inMercuryCode, promptChannel);
+ }
+
+ /** After the research check: the Mercury Code hand-off, then the queue. */
+ private routeIncoming(
+ msg: ChannelMessage,
+ workKey: string | undefined,
+ trimmed: string,
+ isUserMessage: boolean,
+ inMercuryCode: boolean,
+ promptChannel: ReturnType<ChannelRegistry['getChannelForMessage']>,
+ ): void {
// 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).
+ // The research prompt takes precedence when both match.
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');
@@ -1066,6 +1088,22 @@ export class Agent {
});
}
+ /** One small model call: does this message ask for a full research article? */
+ private async wantsResearch(text: string): Promise<boolean> {
+ let model: ReturnType<ReturnType<ProviderRegistry['getDefault']>['getModelInstance']>;
+ try {
+ model = this.learningProviders().getDefault().getModelInstance();
+ } catch {
+ return false;
+ }
+ const verdict = await classifyResearchIntent(text, async (system, user) => {
+ const result = await generateText({ model, system, messages: [{ role: 'user', content: user }], maxOutputTokens: 8 });
+ return result.text;
+ });
+ logger.debug({ verdict }, 'Research intent');
+ return verdict === 'research';
+ }
+
private async promptResearchMode(msg: ChannelMessage, workKey?: string): Promise<void> {
const channel = this.channels.getChannelForMessage(msg);
if (!channel) {
@@ -1080,14 +1118,16 @@ export class Agent {
// Time-weighted default (same contract as the Mercury Code hand-off): an
// unanswered prompt must never hold a chat message hostage. No answer
// within the window → "Quick answer", nothing remembered, and the next
- // research-shaped question asks again.
+ // research-shaped question asks again. Quick answer is listed FIRST, so
+ // the picker starts on it and an accidental Enter never starts a long
+ // research run.
const choice = await this.presentChoiceWithTimeout(
`This looks like a research question. ${explanation}\n\nHow do you want to proceed?`,
- ['Full research mode (deep, multi-source article)', 'Quick answer (normal conversation)'],
+ ['Quick answer (normal conversation)', 'Full research mode (deep, multi-source article)'],
msg.channelId,
msg.channelType,
MERCURY_CODE_HANDOFF_TIMEOUT_MS,
- 1, // unanswered = Quick answer (not remembered — nobody chose)
+ 0, // unanswered = Quick answer (not remembered — nobody chose)
);
if (choice.toLowerCase().startsWith('full')) {
diff --git a/src/core/research-intent.test.ts b/src/core/research-intent.test.ts
new file mode 100644
index 00000000..5b6eff0e
--- /dev/null
+++ b/src/core/research-intent.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { RESEARCH_INTENT_SYSTEM, classifyResearchIntent, parseResearchIntent } from './research-intent.js';
+
+describe('research intent', () => {
+ it('only a clear RESEARCH verdict counts', () => {
+ expect(parseResearchIntent('RESEARCH')).toBe('research');
+ expect(parseResearchIntent('research.')).toBe('research');
+ expect(parseResearchIntent(' Research\nbecause they asked for a report')).toBe('research');
+ expect(parseResearchIntent('NORMAL')).toBe('normal');
+ expect(parseResearchIntent('It could be research')).toBe('normal');
+ expect(parseResearchIntent('')).toBe('normal');
+ });
+
+ it('asks the model with the intent prompt and the message', async () => {
+ const seen: string[] = [];
+ const verdict = await classifyResearchIntent('Write me an in-depth report on the history of solar power', async (system, user) => {
+ seen.push(system, user);
+ return 'RESEARCH';
+ });
+ expect(verdict).toBe('research');
+ expect(seen[0]).toBe(RESEARCH_INTENT_SYSTEM);
+ expect(seen[1]).toBe('Write me an in-depth report on the history of solar power');
+ });
+
+ it('a failing or slow model never triggers the prompt', async () => {
+ expect(await classifyResearchIntent('x', async () => { throw new Error('rate limited'); })).toBe('normal');
+ expect(await classifyResearchIntent('x', () => new Promise((r) => setTimeout(() => r('RESEARCH'), 200)), 20)).toBe('normal');
+ });
+
+ it('the prompt tells the model that instructions and quick questions are NORMAL', () => {
+ expect(RESEARCH_INTENT_SYSTEM).toMatch(/instructions to do something/);
+ expect(RESEARCH_INTENT_SYSTEM).toMatch(/today's news/);
+ expect(RESEARCH_INTENT_SYSTEM).toMatch(/exactly one word: RESEARCH or NORMAL/);
+ });
+});
diff --git a/src/core/research-intent.ts b/src/core/research-intent.ts
new file mode 100644
index 00000000..235bdaf3
--- /dev/null
+++ b/src/core/research-intent.ts
@@ -0,0 +1,53 @@
+/**
+ * Does the owner want a full research article, or just an answer / a task
+ * done? Words alone can't tell: "do X with the latest file" and "what's the
+ * latest on X" both say "latest". The cheap word filter (looksResearchy in
+ * agent.ts) decides whether to ask at all; this asks the model.
+ *
+ * Anything unclear, slow or failing counts as NORMAL: a missed research
+ * prompt costs nothing (the owner can type /research), a wrong one interrupts
+ * a request with a question nobody asked for.
+ */
+
+export const RESEARCH_INTENT_SYSTEM = `You decide whether a chat message asks for a full research report.
+
+Answer RESEARCH only when the person explicitly wants an in-depth, multi-source write-up on a topic: a report, an article, a deep dive, a comprehensive overview, a comparison study, a literature review.
+
+Answer NORMAL for everything else, including:
+- instructions to do something (convert, fix, send, open, install, write code, edit a file), even if the task needs a web search;
+- quick factual questions, prices, definitions, "who is", "when is";
+- today's news or headlines, weather, scores;
+- conversation, opinions, follow-ups.
+
+Reply with exactly one word: RESEARCH or NORMAL.`;
+
+export type ResearchIntent = 'research' | 'normal';
+
+/** The model's verdict; anything but a clear RESEARCH is NORMAL. */
+export function parseResearchIntent(text: string): ResearchIntent {
+ const first = text.trim().split(/\s+/)[0]?.replace(/[^a-z]/gi, '').toUpperCase() ?? '';
+ return first === 'RESEARCH' ? 'research' : 'normal';
+}
+
+/**
+ * Ask the model, within `timeoutMs`. `generate` runs one small completion
+ * with the given system prompt and user text and returns its text.
+ */
+export async function classifyResearchIntent(
+ message: string,
+ generate: (system: string, user: string) => Promise<string>,
+ timeoutMs = 6000,
+): Promise<ResearchIntent> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const verdict = await Promise.race([
+ generate(RESEARCH_INTENT_SYSTEM, message.slice(0, 2000)),
+ new Promise<string>((resolve) => { timer = setTimeout(() => resolve('NORMAL'), timeoutMs); }),
+ ]);
+ return parseResearchIntent(verdict);
+ } catch {
+ return 'normal';
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}