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 branch 'feat/p2-argv-lane' into release/1.3.1-p2

Salman Qureshid6f6b7949ed5
diff --cc src/core/agent.ts
index abb80eef,7b979ab9..f1af3962
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@@ -3632,1045 -4798,2822 +3633,1045 @@@ export class Agent
msg.channelId,
).catch((e) => logger.warn({ e }, 'channel send failed'));
}
- const verifyText = (result.text || '').trim();
- if (verifyText && verifyText !== '(no text response)') messages.push({ role: 'assistant', content: verifyText });
- messages.push({ role: 'user', content: verificationPrompt(msg.content) });
- const verifyProvider = usedProvider
- ? (providersForAttempt.find((p) => p.name === usedProvider!.name && p.getModel() === usedProvider!.model) ?? providersForAttempt[0])
- : providersForAttempt[0];
- if (verifyProvider) {
- lastRoundSteps = 0;
- try {
- const round = await this.runInlineContinuationRound({
- messages,
- systemPrompt,
- volatileSystem,
- provider: verifyProvider,
- maxOutputTokens: effectiveMaxOutputTokens,
- maxSteps: effectiveMaxSteps,
- abortController: loopAbortController,
- channel,
- channelId: msg.channelId,
- // Verification must produce evidence, not prose about evidence.
- forceFirstTool: true,
- onStep: async (toolCalls, toolResults) => {
- this.completedStepCount++;
- lastRoundSteps++;
- lastStepHadToolCalls = !!(toolCalls && toolCalls.length > 0);
- const cliChVerify = this.channels.get('cli');
- if (cliChVerify instanceof CLIChannel) cliChVerify.bumpLiveActivitySteps();
- if (toolCalls && toolResults && toolCalls.length > 0) {
- hasCompletedTool = true;
- noteToolSteps(toolCalls, toolResults);
- for (let i = 0; i < toolCalls.length; i++) {
- const tc = toolCalls[i];
- executeTurnToolsUsed.add(tc.toolName);
- if (tc.toolName === 'run_command') {
- const cmd = (tc.input as any)?.command;
- if (typeof cmd === 'string') {
- executeCommandsRun.push(cmd);
- if (VERIFICATION_COMMAND_PATTERN.test(cmd)) {
- const vResult = (toolResults[i] as any)?.result ?? toolResults[i];
- const vText = typeof vResult === 'string' ? vResult : JSON.stringify(vResult ?? '');
- recordVerification(cmd, vText);
- }
- }
- }
- recordExecuteToolResult(tc.toolName, (toolResults[i] as any)?.result ?? toolResults[i]);
- this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, (toolResults[i] as any)?.result ?? toolResults[i]);
- this.maybeRecordPlanProgress(channel, tc.toolName, tc.input);
- loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);
- }
- }
- },
- });
- if (round.text.trim()) result = { text: round.text, usage: round.usage, reasoning: round.reasoning };
- cliResponseStreamed = channel instanceof CLIChannel;
- } catch (verifyErr: any) {
- logger.warn({ err: verifyErr?.message || String(verifyErr) }, 'Verification continuation failed; keeping original response');
- }
- }
- }
-
- // ── Final verdict: a step-budget stop past the continuation bound is
- // an honest pause, never a completion banner. ──
- const pauseHonestly = async (banner: string, reason: string): Promise<void> => {
- logger.warn({ banner, task: msg.content.slice(0, 120) }, 'Completion contract: pausing task honestly');
- this.markProgress('Task paused');
- this.pushLiveActivity('Paused', 'completion contract');
- if (this.currentWorkKey) {
- this.workLedger.markPaused(this.currentWorkKey, reason);
- }
- if (channel && msg.channelType !== 'internal') {
- // Persistent banner, deferred text flushed first (see TaskSurface.pause).
- await surface.pause(`${banner}\n\n_/trace ${traceId}_`);
- if (this.currentWorkKey) this.workLedger.markDelivered(this.currentWorkKey);
- }
- this.lifecycle.transition('idle');
- };
-
- if (!loopAbortController.signal.aborted && turnEnd() === 'steps-exhausted') {
- logger.warn({ steps: lastRoundSteps, budget: effectiveMaxSteps }, 'Step budget exhausted past continuation bound — pausing task honestly');
- await pauseHonestly(
- STEPS_PAUSED_BANNER,
- 'Step budget reached with work pending. Send "continue" to resume with a fresh budget.',
- );
- return;
- }
-
- // Narration-guard exhaustion: after all forced continuation rounds the
- // turn STILL contains zero mutating work (rounds failed on flaky
- // providers, or the model kept narrating). That must never read as
- // "Task complete" — pause and let "continue" re-engage.
- if (
- !loopAbortController.signal.aborted
- && this.programmingMode.isExecute()
- && !responseAsksUser(result.text || '')
- && shouldForceExecuteContinuation({
- taskText: msg.content,
- hasApprovedPlan: this.programmingMode.getLastPlan() != null,
- toolsUsed: executeTurnToolsUsed,
- toolsSucceeded: executeToolSucceeded,
- })
- ) {
- logger.warn({ task: msg.content.slice(0, 120), blocker: lastGuardToolFailure }, 'Narration guard exhausted (both cycles) — pausing instead of completing');
- const blockerNote = lastGuardToolFailure
- ? `\n\nWhat blocked it: ${lastGuardToolFailure}`
- : '';
- await pauseHonestly(
- WORK_NOT_STARTED_BANNER + blockerNote,
- `No implementation work was performed across two guard cycles.${lastGuardToolFailure ? ` Last blocker: ${lastGuardToolFailure}` : ''} Send "continue" to resume with tools.`,
- );
- return;
- }
-
- // Verification failed or is stale: in execute mode, a build/test/
- // typecheck ran but did not pass, or passed and was then followed by
- // more edits. Either way there is no evidence the work is correct —
- // that is an honest pause, never a "Task complete" banner.
- if (
- !loopAbortController.signal.aborted
- && this.programmingMode.isExecute()
- && lastVerification != null
- && !verifiedAfterLastMutation()
- && !responseAsksUser(result.text || '')
- ) {
- const stale = lastVerification.ok;
- logger.warn({ verification: lastVerificationNote, stale }, 'Completion contract: verification failed or stale — pausing instead of completing');
- await pauseHonestly(
- `${VERIFICATION_FAILED_BANNER}\n\nLast check: ${lastVerificationNote}${stale ? ' (ran before the latest changes)' : ''}`,
- `Verification ${stale ? 'is stale' : 'failed'}: ${lastVerificationNote}. Send "continue" to resume.`,
- );
- return;
- }
-
- // Recompute AFTER the guard: the continuation's output (not the
- // original narration) must be what reaches the session store, the
- // work ledger, and the final delivery.
- const finalText = (result.text || '').trim() || '(no text response)';
-
- // Store plan output when in plan mode for later execution
- if (this.programmingMode.isPlan() && preGuardText !== '(no text response)') {
- this.programmingMode.storePlan(preGuardText);
- logger.info({ planLength: preGuardText.length }, 'Plan captured from plan-mode response');
- }
-
- this.tokenBudget.recordUsage({
- provider: usedProvider?.name ?? 'unknown',
- model: usedProvider?.model ?? 'unknown',
- inputTokens: result.usage?.inputTokens ?? 0,
- outputTokens: result.usage?.outputTokens ?? 0,
- totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
- channelType: msg.channelType,
- agentId: this.config.cloud.agentId || undefined,
- });
- logger.info({
- provider: usedProvider?.name,
- model: usedProvider?.model,
- inputTokens: result.usage?.inputTokens ?? 0,
- cachedInputTokens: result.usage?.cachedInputTokens ?? 0,
- outputTokens: result.usage?.outputTokens ?? 0,
- steps: this.completedStepCount,
- toolCalls: turnToolTrace.length,
- historyEntries: recentMemory.length,
- activeTools: activeTools?.length ?? 'all',
- elapsedMs: Date.now() - startTime,
- }, 'Turn usage');
- this.syncTokenInfoToCli();
-
- // Estimate tokens saved by Saver Mode (cap headroom + history trim).
- // Rough: (default_cap - actual_output) when capped, plus history-window delta.
- if (saverWasActive) {
- const actualOutput = result.usage?.outputTokens ?? 0;
- const outputHeadroom = Math.max(0, MODEL_OUTPUT_TOKEN_LIMIT - effectiveMaxOutputTokens);
- const outputSaved = Math.max(0, Math.min(outputHeadroom, MODEL_OUTPUT_TOKEN_LIMIT - actualOutput));
- // Rough proxy: each trimmed history message ~120 tokens average.
- const historyTrimMessages = Math.max(0, NORMAL_HISTORY_WINDOW - this.saverMode.adjustHistoryWindow(NORMAL_HISTORY_WINDOW));
- const historySaved = historyTrimMessages * 120;
- const estimated = outputSaved + historySaved;
- if (estimated > 0) {
- this.tokenBudget.recordSavings(estimated);
- this.syncSaverToCli();
- }
- }
-
- if (canonicalSessionId) {
- if (turnToolTrace.length > 0) {
- this.sessions.appendMessage(canonicalSessionId, {
- role: 'assistant',
- kind: TOOL_TRACE_KIND,
- content: formatToolTrace(turnToolTrace),
- externalMessageId: `${msg.id}:tools`,
- metadata: { channelType: msg.channelType, channelId: msg.channelId, toolCalls: turnToolTrace.length },
- });
- }
- this.sessions.appendMessage(canonicalSessionId, {
- role: 'assistant',
- content: finalText,
- externalMessageId: `${msg.id}:assistant`,
- tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
- reasoning: typeof result.reasoning === 'string'
- ? result.reasoning
- : result.reasoning
- ? JSON.stringify(result.reasoning)
- : undefined,
- metadata: {
- channelType: msg.channelType,
- channelId: msg.channelId,
- ...(typeof msg.metadata?.requestId === 'string' ? { requestId: msg.metadata.requestId } : {}),
- ...(usedProvider ? { provider: usedProvider.name, model: usedProvider.model } : {}),
- // Per-turn trace, shown by /trace <id>.
- traceId,
- elapsedMs: Date.now() - startTime,
- steps: this.completedStepCount,
- inputTokens: result.usage?.inputTokens ?? 0,
- cachedInputTokens: result.usage?.cachedInputTokens ?? 0,
- outputTokens: result.usage?.outputTokens ?? 0,
- ...(lastVerificationNote ? { verification: lastVerificationNote } : {}),
- },
- });
- if (msg.channelType !== 'internal' && msg.senderId !== 'system' && usedProvider) {
- this.scheduleSessionTitleGeneration(canonicalSessionId, usedProvider.name);
- }
- } else {
- this.shortTerm.add(msg.channelId, { id: msg.id, timestamp: msg.timestamp, role: 'user', content: msg.content });
- this.shortTerm.add(msg.channelId, {
- id: Date.now().toString(36), timestamp: Date.now(), role: 'assistant', content: finalText,
- tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0), reasoning: result.reasoning || undefined,
- });
- }
-
- this.episodic.record({
- type: 'message',
- summary: `User: ${msg.content.slice(0, 100)} | Agent: ${finalText.slice(0, 100)}`,
- channelType: msg.channelType,
- });
-
- if (msg.channelType !== 'internal') {
- this.extractMemory(msg.content, finalText).catch(err => {
- logger.warn({ err }, 'Memory extraction failed');
- });
- this.scheduleStatusVerbRefresh(channel, msg.content);
- }
-
- if (this.currentWorkKey) this.workLedger.markCompleted(this.currentWorkKey, finalText);
-
- if (channel && msg.channelType !== 'internal') {
- const elapsed = Date.now() - startTime;
- const stepCount = this.completedStepCount;
- const completionMeta = {
- provider: usedProvider?.name ?? 'unknown',
- model: usedProvider?.model ?? 'unknown',
- inputTokens: result.usage?.inputTokens ?? 0,
- outputTokens: result.usage?.outputTokens ?? 0,
- totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
- budgetUsed: this.tokenBudget.getDailyUsed(),
- budgetTotal: this.tokenBudget.getBudget(),
- budgetPercentage: this.tokenBudget.getUsagePercentage(),
- };
- const isMercuryCodeExecution = channel instanceof CLIChannel
- && channel.getTuiState().mode === 'mercury-code'
- && (channel.getTuiState().programmingMode === 'execute' || channel.getTuiState().programmingMode === 'auto');
- logger.info({ channelType: msg.channelType, targetId: msg.channelId, surface: surface.kind, traceId }, 'Delivering final response');
- await surface.done({
- finalText,
- elapsedMs: elapsed,
- stepCount,
- meta: completionMeta,
- verificationNote: lastVerificationNote || undefined,
- traceId,
- alreadyStreamed: !requiresFinalSend(msg.channelType, cliResponseStreamed),
- forceBanner: isMercuryCodeExecution,
- });
- this.markProgress();
- } else {
- logger.debug('Internal prompt processed, no channel response needed');
- }
-
-
- const awaitsCloudAck = msg.channelType === 'web'
- && typeof msg.metadata?.externalConversationId === 'string'
- && typeof msg.metadata?.requestId === 'string';
- if (this.currentWorkKey && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);
-
- this.lifecycle.transition('idle');
- } catch (err) {
- logger.error({ err }, 'Error handling message');
- const ledgerEntry = this.currentWorkKey ? this.workLedger.get(this.currentWorkKey) : undefined;
- if (this.currentWorkKey) {
- if (ledgerEntry?.status === 'completed') this.workLedger.markDeliveryError(this.currentWorkKey, err);
- else if (ledgerEntry?.status !== 'failed') {
- const errMsg = err instanceof Error ? err.message : String(err);
- this.workLedger.markFailed(
- this.currentWorkKey,
- err,
- `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`,
- );
- }
- }
- if (ledgerEntry?.status === 'completed') {
- logger.warn({ err, workKey: this.currentWorkKey }, 'Final response persisted but delivery did not complete; retaining for replay');
- return;
- }
- // Always notify the user — they should never have to re-prompt
- // to find out their task died.
- const catchChannel = this.channels.getChannelForMessage(msg);
- if (catchChannel && msg.channelType !== 'internal') {
- const errMsg = err instanceof Error ? err.message : String(err);
- try {
- const finalError = `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`;
- const delivered = catchChannel instanceof WebChannel ? catchChannel.sendError(finalError, msg.channelId) : true;
- if (!(catchChannel instanceof WebChannel)) await catchChannel.send(finalError, msg.channelId);
- const awaitsCloudAck = msg.channelType === 'web'
- && typeof msg.metadata?.externalConversationId === 'string'
- && typeof msg.metadata?.requestId === 'string';
- if (this.currentWorkKey && delivered && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);
- if (this.currentWorkKey && !delivered) this.workLedger.markDeliveryError(this.currentWorkKey, 'Terminal error delivery was not accepted');
- } catch (sendErr) {
- if (this.currentWorkKey) this.workLedger.markDeliveryError(this.currentWorkKey, sendErr);
- logger.warn({ sendErr }, 'Failed to notify user of handler error');
- }
- }
- // Write crash flag so next startup also reports the failure.
- try {
- const { writeCrashFlag } = await import('./crash-flag.js');
- writeCrashFlag({
- reason: `Unhandled agent error: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300),
- timestamp: Date.now(),
- activeTask: this.currentActivity || undefined,
- channelId: msg.channelId || undefined,
- channelType: msg.channelType || undefined,
- });
- } catch { /* best effort */ }
- this.lifecycle.transition('idle');
- } finally {
- clearInterval(memoryGuard);
- stallWatchdog.stop();
- stopHeartbeat();
- this.finalizeChannelTask(msg);
- this.currentMessage = null;
- this.currentAbort = null;
- this.currentAbortReason = null;
- this.currentActivity = '';
- this.completedStepCount = 0;
- this.stepNarrative = [];
- {
- const ch = this.channels.get('cli');
- if (ch instanceof CLIChannel) ch.clearLiveActivity();
- }
- if (isInternal) {
- this.capabilities.permissions.endTurnGrant();
- }
- this.capabilities.permissions.clearElevation();
- }
- }
-
- /**
- * Prompt caching: the system prompt is the large, stable prefix of every
- * model call (identity, skills, bot roster, guidelines; with ~50 tool
- * schemas it is roughly 10K tokens) and it is re-sent on every one of up
- * to 75 steps. Sending it as a system *message* carrying an Anthropic
- * cache_control marker lets Anthropic serve it from cache across steps
- * and turns; providers that do not know the option ignore it, and the
- * AI SDK treats a leading system message exactly like `system:`.
- */
- private withCachedSystem(systemPrompt: string, messages: unknown[], volatileSystem = ''): any[] {
- return [
- {
- role: 'system',
- content: systemPrompt,
- providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },
- },
- // Per-turn context lives in its own block AFTER the cache marker so it
- // never invalidates the stable prefix.
- ...(volatileSystem ? [{ role: 'system', content: volatileSystem }] : []),
- ...messages,
- ];
- }
-
- private buildSystemPrompt(): string {
- let prompt = this.identity.getSystemPrompt(this.config.identity);
- const skillContext = this.capabilities.getSkillContext();
- if (skillContext) {
- prompt += '\n\n' + skillContext;
- }
- // Mercury Bots: the main agent must know the fleet exists — what each
- // bot does, its live state, and how to dispatch to it. Without this the
- // conversational agent answers bot questions blindly.
- if (this.botManager) {
- prompt += this.botManager.getSystemPromptSection();
- }
- const programmingSuffix = this.programmingMode.getSystemPromptSuffix();
- if (programmingSuffix) {
- prompt += programmingSuffix;
- }
- const researchSuffix = this.researchMode.getSystemPromptSuffix();
- if (researchSuffix) {
- prompt += researchSuffix;
- }
- const budgetStatus = this.tokenBudget.getStatusText();
- prompt += '\n\n' + budgetStatus;
- if (this.tokenBudget.getUsagePercentage() > 70) {
- prompt += '\nBe concise to conserve tokens.';
- }
- const saverSuffix = this.saverMode.getSystemPromptSuffix();
- if (saverSuffix) {
- prompt += saverSuffix;
- }
-
- const now = new Date();
- const dateStr = now.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
- // Hour resolution on purpose: a minute-precise clock changed the system
- // prompt every turn and defeated prompt caching for the ~10K-token
- // prefix that follows. Tools report exact timestamps when it matters.
- const timeStr = `about ${now.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true })}`;
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- prompt += `\n\nEnvironment:\n- Date: ${dateStr}, ${timeStr} (${timezone})\n- Platform: ${process.platform}\n- Working directory: ${this.capabilities.getCwd()}`;
-
- prompt += `\n\n**Tool Usage Guidelines:**
-- Use write_file, create_file, and edit_file tools DIRECTLY to create and modify files. Do NOT create intermediary scripts (Python, bash, Node.js) whose sole purpose is to generate other files — you have native file tools for this.
-- Use run_command for: building, testing, installing dependencies, running the project, git operations, and other system tasks that require a shell.
-- Do NOT use run_command with echo/cat/tee/heredoc to write files. Use write_file or create_file instead.
-- Do NOT create one-time-use helper scripts. If the user asks you to create a file, create it directly with create_file or write_file.
-- When creating multiple files, call create_file or write_file for each one individually. Do not batch them into a script.`;
-
- if (this.userMemory) {
- const summary = this.userMemory.getSummary();
- prompt += `\n\nSecond Brain (SQLite-backed long-term memory) is ENABLED. You have ${summary.total} persistent memories about this user.`;
- prompt += `\nMemory types: identity, preference, goal, project, habit, decision, constraint, relationship, episode, reflection.`;
- prompt += `\n\nCRITICAL — Memory storage rules:`;
- prompt += `\n- ALL persistent user knowledge lives in the Second Brain SQLite database — this is the single source of truth.`;
- prompt += `\n- NEVER use create_file, write_file, edit_file, or any file tool to store memories, notes, facts, preferences, or brain data. Files are for code and documents, not for knowledge storage.`;
- prompt += `\n- New memories are extracted AUTOMATICALLY after each conversation turn. You do not need to ask the user if they want to save something.`;
- prompt += `\n- When the user explicitly asks you to "save/remember/note/keep this," use the save_memory tool to store it directly — no follow-up questions needed.`;
- prompt += `\n- When you need to actively recall something beyond auto-injected context (e.g. "do you remember...", "what do I know about..."), use the search_memory tool.`;
- prompt += `\n- Relevant memories are auto-injected before each message. You can reference them naturally (e.g. "I remember you prefer TypeScript").`;
- prompt += `\n- Users can manage memory with: /memory (overview, search, pause learning, clear).`;
- if (summary.learningPaused) {
- prompt += `\n\nLearning is currently PAUSED — no new memories will be extracted or saved until resumed.`;
- }
- } else {
- prompt += '\n\nSecond Brain is DISABLED. Basic long-term memory (text search over facts) is still active.';
- }
-
- // Notification routing guidance for tweet-notifier skill
- const skillNames = this.capabilities.getSkillContext();
- if (skillNames.includes('tweet-notifier')) {
- prompt += `\n\n**Tweet Notification System Available** — The tweet-notifier skill is installed.
-When you need to schedule tweets, manage approvals, or notify founders/supporters:
-1. Use the \`use_skill\` tool to invoke the \`tweet-notifier\` skill for detailed instructions
-2. The skill provides templates for scheduling tweets, notifying founders (via send_message), and alerting supporters (approved Telegram users)
-3. Key tools used by this system: schedule_task (for timing), send_message (for notifications to Telegram), save_memory (for tweet state tracking), search_memory (for checking existing tweets)
-4. Supporters are all approved Telegram users — send_message will reach them
-5. The founder (Optimus Prime) receives notifications via send_message (Telegram)`;
- }
-
- const toolNames = this.capabilities.getToolNames();
- const githubTools = ['create_pr', 'review_pr', 'list_issues', 'create_issue', 'github_api'];
- const hasGitHub = githubTools.some(t => toolNames.includes(t));
- if (hasGitHub) {
- let githubHint = '\n\nGitHub companion is active.';
- const { defaultOwner, defaultRepo } = this.config.github;
- if (defaultOwner && defaultRepo) {
- githubHint += ` Default repo: ${defaultOwner}/${defaultRepo}. Use this when the user doesn't specify a repo.`;
- }
-
- githubHint += `
-
-Available GitHub tools and when to use them:
-- git_add, git_commit, git_push: LOCAL git operations (stage, commit, push to a remote you have SSH/auth access to). All commits include "Co-authored-by: Mercury <[email protected]>".
-- create_pr: Create a pull request on GitHub. The head branch must already exist on the remote.
-- review_pr: Get PR details and optionally post a review comment.
-- list_issues, create_issue: Browse and file issues.
-- github_api: Raw GitHub API access. IMPORTANT USE CASES:
- - Push files directly to GitHub via PUT /repos/{owner}/{repo}/contents/{path} when git push fails due to auth. The body must include "message" and "content" (base64-encoded file content). This creates a commit on GitHub with Mercury as co-author.
- - Delete files via DELETE /repos/{owner}/{repo}/contents/{path} with a "message" and "sha" in the body.
- - Any other GitHub API operation not covered by the other tools.
-
-When the user asks to "push to GitHub" or "upload files" and git push fails, use github_api with PUT /repos/{owner}/{repo}/contents/{path} to push content directly through the API. This bypasses local git entirely.
-
-Always specify owner and repo parameters on GitHub tools. The user's GitHub username is ${this.config.github.username || 'not set'}.'`;
-
- prompt += githubHint;
- }
- return prompt;
- }
-
- async processInternalPrompt(prompt: string, channelId?: string, channelType?: string): Promise<void> {
- const syntheticMsg: ChannelMessage = {
- id: `internal-${Date.now().toString(36)}`,
- channelId: channelId || 'internal',
- channelType: (channelType || 'internal') as ChannelType,
- senderId: 'system',
- content: prompt,
- timestamp: Date.now(),
- };
- this.enqueueMessage(syntheticMsg);
- }
-
- private async handleScheduledTask(manifest: ScheduledTaskManifest): Promise<void> {
- // Bot routines run on the bot lane, never through the main agent loop
- // (BOTS-ARCHITECTURE.md §2.3 — cron lane).
- if (manifest.botId) {
- if (!this.botManager) {
- logger.warn({ task: manifest.id, botId: manifest.botId }, 'Bot routine fired but BotManager is not wired');
- return;
- }
- logger.info({ task: manifest.id, botId: manifest.botId }, 'Bot routine firing');
- const result = this.botManager.enqueue(manifest.botId, {
- trigger: 'cron',
- prompt: manifest.prompt || manifest.description,
- });
- if (!result.accepted) {
- logger.warn({ botId: manifest.botId, reasonCode: result.reasonCode }, 'Bot routine could not be enqueued');
- }
- return;
- }
- logger.info({ task: manifest.id, channel: manifest.sourceChannelType }, 'Processing scheduled task');
- try {
- const channel = manifest.sourceChannelType
- ? this.channels.get(manifest.sourceChannelType as ChannelType)
- : this.channels.getNotificationChannel();
-
- if (channel && manifest.sourceChannelType !== 'internal') {
- const skillInfo = manifest.skillName ? ` (${manifest.skillName})` : '';
- await channel.send(
- ` Scheduled task started${skillInfo}: ${manifest.description}\nAll actions auto-approved for this run.`,
- manifest.sourceChannelId,
- ).catch((e) => logger.warn({ e }, 'channel send failed'));
- }
-
- let prompt = manifest.prompt || '';
- if (manifest.skillName) {
- const skillHint = `Invoke the skill "${manifest.skillName}" using the use_skill tool and follow its instructions.`;
- prompt = prompt ? `${prompt} ${skillHint}` : `Scheduled task triggered. ${skillHint}`;
- }
- if (!prompt) {
- prompt = `Execute scheduled task: ${manifest.description}`;
- }
- await this.processInternalPrompt(prompt, manifest.sourceChannelId, manifest.sourceChannelType);
- } catch (err) {
- logger.error({ err, task: manifest.id }, 'Scheduled task execution failed');
- }
- }
-
- private async heartbeat(): Promise<void> {
- logger.debug('Heartbeat tick');
-
- const pruned = this.episodic.prune(7);
- if (pruned > 0) {
- logger.info({ pruned }, 'Episodic memory pruned');
- }
-
- if (this.userMemory) {
- try {
- const consolidation = this.userMemory.consolidate();
- if (consolidation.profileUpdated || consolidation.reflectionCount > 0) {
- logger.info({ consolidation }, 'Second brain consolidated');
- }
-
- const pruning = this.userMemory.prune();
- if (pruning.movedToSubconscious > 0 || pruning.hardDeleted > 0 || pruning.promoted > 0) {
- logger.info({ pruning }, 'Second brain pruned');
- }
- } catch (err) {
- logger.warn({ err }, 'Second brain heartbeat error');
- }
- }
-
- const notifications: string[] = [];
-
- const usagePct = this.tokenBudget.getUsagePercentage();
- if (usagePct >= 80) {
- notifications.push(`Token budget at ${Math.round(usagePct)}% — ${this.tokenBudget.getRemaining().toLocaleString()} tokens remaining today.`);
- }
-
- const pendingSchedules = this.scheduler.getManifests();
- const now = Date.now();
- for (const task of pendingSchedules) {
- if (task.delaySeconds && task.executeAt) {
- const executeAt = new Date(task.executeAt).getTime();
- const diffMin = Math.round((executeAt - now) / 60000);
- if (diffMin > 0 && diffMin <= 5) {
- notifications.push(`Task "${task.description}" fires in ${diffMin} minute${diffMin !== 1 ? 's' : ''}.`);
- }
- }
- }
-
- if (notifications.length > 0) {
- const channel = this.channels.getNotificationChannel();
- if (channel) {
- const msg = notifications.join('\n');
- try {
- await channel.send(msg, 'notification');
- } catch (err) {
- logger.warn({ err }, 'Failed to send heartbeat notification');
- }
- }
- }
- }
-
- private async extractMemory(userMessage: string, agentResponse: string): Promise<void> {
- if (!this.userMemory) return;
- if (this.userMemory.isLearningPaused()) return;
-
- const trivial = /^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|bye|goodbye|good morning|good evening)\b/i;
- if (trivial.test(userMessage.trim())) return;
-
- if (!this.tokenBudget.canAfford(800)) return;
-
- try {
- const provider = this.providers.getDefault();
- const result = await generateText({
- model: provider.getModelInstance(),
- system: `You extract structured memory from conversations. Output a JSON array of 0-3 memory candidates.
-
-Each candidate: { type, categories, summary (concise fact, 12-220 chars), detail (optional explanation), evidenceKind ("direct" if explicitly stated, "inferred" if deduced), confidence (0-1), importance (0-1), durability (0-1) }
-
-TYPE DEFINITIONS (pick the single most specific one):
-- identity: who the user IS — their name, role, job title, self-description
-- relationship: other people the user knows — MUST include the person's name in summary
-- preference: likes, dislikes, style choices, opinions
-- goal: aspirations, targets, things they want to achieve
-- project: specific ongoing work, initiatives, things being built
-- habit: routines, recurring behaviors, schedules
-- decision: choices made, commitments, selected approaches
-- constraint: limitations, rules they follow, things they avoid
-- episode: notable one-time events worth remembering
-
-CATEGORIES (pick 1-3 domain buckets that best fit this memory):
-- personal: the user's private life, non-work
-- health: medical, physical, mental wellbeing
-- family: family members, family relationships
-- work: job, professional, career
-- finance: money, spending, investments
-- technical: programming, tools, engineering
-- education: learning, study, courses
-- social: friends, social life, community
-- travel: trips, places, geography
-- general: anything that doesn't fit the above
-
-RULES:
-- Each semantic fact must appear EXACTLY ONCE. Never store the same information under multiple types.
-- If a fact is about someone else's role/relationship to the user, use "relationship" (not "identity").
-- "identity" is ONLY for the user themselves.
-- For relationships, always name the person: "Salman is user's co-developer" not "User works with a co-developer".
-- Only extract specific, durable, user-specific information.
-- Do NOT extract trivial observations, greetings, or assistant behavior.
-- "categories" must be an array of 1-3 lowercase strings from the list above. If none fit, suggest a new single-word lowercase category.
-- Output pure JSON array, no markdown fences.`,
- messages: [
- { role: 'user', content: `User: ${userMessage}\nAssistant: ${agentResponse}` },
- ],
- maxOutputTokens: 400,
- });
-
- this.tokenBudget.recordUsage({
- provider: provider.name,
- model: provider.getModel(),
- inputTokens: result.usage?.inputTokens ?? 0,
- outputTokens: result.usage?.outputTokens ?? 0,
- totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
- channelType: 'internal',
- agentId: this.config.cloud.agentId || undefined,
- });
- this.syncTokenInfoToCli();
-
- const text = result.text.trim();
- if (!text) return;
-
- let candidates: Array<{
- type: string;
- categories?: string[];
- summary: string;
- detail?: string;
- evidenceKind?: string;
- confidence: number;
- importance: number;
- durability: number;
- }>;
-
- try {
- const jsonStr = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
- const parsed = JSON.parse(jsonStr);
- // Handle both single object and array of objects
- candidates = Array.isArray(parsed) ? parsed : [parsed];
- } catch {
- const facts = text
- .split('\n')
- .map(l => l.replace(/^-\s*/, '').trim())
- // Skip JSON-like lines (key-value pairs, braces, brackets)
- .filter(f => f.length > 10 && f.length < 200 && !/^["{\[\]}]|":\s*"/.test(f));
- candidates = facts.slice(0, 3).map(f => ({
- type: 'preference',
- categories: ['general'],
- summary: f,
- confidence: 0.75,
- importance: 0.7,
- durability: 0.7,
- evidenceKind: 'inferred',
- }));
- }
-
- const validTypes = ['identity', 'preference', 'goal', 'project', 'habit', 'decision', 'constraint', 'relationship', 'episode'];
- const typed = candidates
- .filter(c => c.summary && c.summary.length >= 12 && c.summary.length <= 220)
- .filter(c => validTypes.includes(c.type))
- .map(c => {
- // Normalise categories: must be array of strings, 1-3, lowercase, trimmed.
- let cats: string[] = ['general'];
- if (Array.isArray(c.categories) && c.categories.length > 0) {
- const cleaned = c.categories
- .map((cat: unknown) => String(cat).trim().toLowerCase())
- .filter((cat: string) => cat.length > 0)
- .slice(0, 3);
- if (cleaned.length > 0) cats = cleaned;
- }
- return {
- type: c.type as any,
- categories: cats,
- summary: c.summary,
- detail: c.detail,
- evidenceKind: (c.evidenceKind === 'direct' ? 'direct' : 'inferred') as 'direct' | 'inferred',
- confidence: Math.min(1, Math.max(0, c.confidence ?? 0.7)),
- importance: Math.min(1, Math.max(0, c.importance ?? 0.7)),
- durability: Math.min(1, Math.max(0, c.durability ?? 0.7)),
- };
- });
-
- if (typed.length > 0) {
- const remembered = this.userMemory.remember(typed, 'conversation');
- if (remembered.length > 0) {
- logger.info({ count: remembered.length, types: remembered.map(r => r.type) }, 'Second brain memories stored');
- }
- }
- } catch (err) {
- logger.warn({ err }, 'Memory extraction error');
- }
- }
-
- /**
- * Mark all queued/running work as user-cancelled (terminal state).
- * Used by deliberate-stop paths (TUI Ctrl+C, /exit, SIGTERM) so the
- * next start does not auto-resume killed tasks. Crash recovery is
- * unaffected — this is only invoked on intentional exits.
- */
- cancelActiveWork(reason = 'Cancelled by the user.'): number {
- try {
- return this.workLedger.cancelActive(reason);
- } catch (error) {
- logger.warn({ error }, 'Failed to cancel active work');
- return 0;
- }
- }
-
- async shutdown(): Promise<void> {
- // Deliberate shutdown: never resume this work on restart.
- try { this.workLedger.cancelActive('Mercury was shut down.'); } catch { /* best effort */ }
- if (this.supervisor) {
- await this.supervisor.haltAll();
- }
- this.backgroundTasks.destroy();
- this.providers.destroy();
- await this.sleep();
- logger.info('Mercury has shut down');
- }
-
- /**
- * Notify all active channels with a message. Used before forced exits
- * (SIGTERM, crash, watchdog kill) so the user is never left wondering
- * what happened to their task.
- */
- async notifyAllChannels(message: string): Promise<void> {
- const active = this.channels.getActiveChannels();
- const sends = active.map((type) => {
- const ch = this.channels.get(type);
- if (!ch) return Promise.resolve();
- return ch.send(message).catch((e) => {
- logger.warn({ e, channel: type }, 'Failed to notify channel before exit');
- });
- });
- await Promise.allSettled(sends);
- }
-
- /**
- * AI self-check: ask the model itself whether repeated tool usage is productive or a loop.
- * Used in allow-all mode instead of prompting the user.
- * Returns true if the AI thinks it should continue, false if it should stop.
- */
- private async aiSelfCheck(context: {
- toolName: string;
- callCount: number;
- recentCalls: string[];
- taskDescription: string;
- }): Promise<boolean> {
- try {
- const provider = this.providers.getDefault();
- if (!provider) return true; // no provider = let it continue
-
- const selfCheckResult = await generateText({
- model: provider.getModelInstance(),
- system: `You are Mercury Autopilot, a monitoring system inside an AI coding agent. Your job is to determine whether repeated tool usage is productive iteration or a stuck loop.
-
-Productive patterns (CONTINUE):
-- Fetching multiple different URLs (e.g., scraping articles, reading docs)
-- Reading multiple different files to understand a codebase
-- Editing different sections of code across files
-- Running different commands (build, test, lint, deploy)
-- Creating multiple files for a project
-
-Stuck patterns (STOP):
-- Same exact call repeated with identical parameters
-- Retrying the same failing operation with minor variations
-- Reading the same file over and over
-- Running the same failing command repeatedly
-
-Respond with ONLY "CONTINUE" or "STOP" followed by a one-line reason.`,
- messages: [{
- role: 'user',
- content: `Tool "${context.toolName}" called ${context.callCount} times consecutively.
-
-User's task: ${context.taskDescription}
-
-Recent calls (newest last):
-${context.recentCalls.join('\n')}
-
-Is this productive iteration or a stuck loop?`,
- }],
- maxOutputTokens: 80,
- });
-
- const answer = (selfCheckResult.text || '').trim().toUpperCase();
- const shouldContinue = answer.startsWith('CONTINUE');
- logger.info({
- toolName: context.toolName,
- count: context.callCount,
- decision: shouldContinue ? 'continue' : 'stop',
- reason: selfCheckResult.text?.trim().slice(0, 120),
- }, 'Mercury Autopilot verdict');
- return shouldContinue;
- } catch (err) {
- logger.warn({ err }, 'Mercury Autopilot self-check failed — defaulting to continue');
- return true; // on failure, be permissive
- }
- }
-
- setSpotifyClient(client: SpotifyClient): void {
- this.spotifyClient = client;
- }
-
- async presentChoice(question: string, choices: string[], channelId: string, channelType: string): Promise<string> {
- const channel = this.channels.get(channelType as any);
-
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- const options = choices.map((label, i) => ({
- value: String(i),
- label,
- }));
-
- const selected = await channel.presentChoicePrompt(question, options);
- const index = parseInt(selected, 10);
- return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
- }
-
- if (channelType === 'web' && channel instanceof WebChannel) {
- const options = choices.map((label, i) => ({
- value: String(i),
- label,
- }));
-
- const selected = await channel.presentChoicePrompt(question, options, channelId);
- const index = parseInt(selected, 10);
- return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
- }
-
- if (channelType === 'telegram' && channel instanceof TelegramChannel) {
- const options = choices.map((label, i) => ({
- value: String(i),
- label,
- }));
-
- const selected = await channel.presentChoicePrompt(question, options, channelId);
- const index = parseInt(selected, 10);
- return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
- }
-
- await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
- return choices[0];
- }
-
- private async handleBudgetOverrideCLI(channel: import('../channels/base.js').Channel, msg: ChannelMessage): Promise<void> {
- const status = this.tokenBudget.getStatusText();
- await channel.send(
- `Token budget exceeded! ${status}\n\nChoose an option:\n 1 — Override (allow this one request)\n 2 — Reset usage to zero\n 3 — Set a new daily budget (current: ${this.tokenBudget.getBudget().toLocaleString()})\n 4 — Cancel\n\nOr use /budget override, /budget reset, /budget set <number> anytime.`,
- msg.channelId,
- );
- }
-
- async handleBudgetCommand(subcommand: string, channelType: string, channelId: string): Promise<void> {
- const channel = this.channels.get(channelType as any);
- if (!channel) return;
-
- const parts = subcommand.trim().split(/\s+/);
- const action = parts[0]?.toLowerCase();
-
- if (action === 'override' || action === '1') {
- this.tokenBudget.forceAllowNext();
- await channel.send('Budget override applied — your next request will proceed.', channelId);
- } else if (action === 'reset' || action === '2') {
- this.tokenBudget.resetUsage();
- this.syncTokenInfoToCli();
- await channel.send(`Usage reset to zero. ${this.tokenBudget.getStatusText()}`, channelId);
- } else if (action === 'set' || action === '3') {
- const newBudget = parseInt(parts[1], 10);
- if (isNaN(newBudget) || newBudget <= 0) {
- await channel.send('Please specify the new budget. Usage: `/budget set 100000` or type e.g. `3 100000`', channelId);
- return;
- }
- this.tokenBudget.setBudget(newBudget);
- this.syncTokenInfoToCli();
- await channel.send(`Daily budget updated to ${newBudget.toLocaleString()} tokens. ${this.tokenBudget.getStatusText()}`, channelId);
- } else if (action === 'cancel' || action === '4') {
- await channel.send(`Cancelled. ${this.tokenBudget.getStatusText()}`, channelId);
- } else if (!action || action === 'status') {
- await channel.send(this.tokenBudget.getStatusText(), channelId);
- } else {
- await channel.send(`Unknown budget command "${action}". Available: /budget, /budget override, /budget reset, /budget set <number>, /budget status`, channelId);
- }
- }
-
- /**
- * Handle the /saver slash command — Token Saver Mode controls.
- * Subcommands: (empty)|status|on|off|toggle|threshold <n>|auto on|off|routing on|off|stats
- */
- async handleSaverCommand(subcommand: string, channelType: string, channelId: string): Promise<void> {
- const channel = this.channels.get(channelType as any);
- if (!channel) return;
-
- const parts = subcommand.trim().split(/\s+/).filter(Boolean);
- const action = (parts[0] || '').toLowerCase();
- const arg = (parts[1] || '').toLowerCase();
-
- const showStatus = async () => {
- const text = this.saverMode.getStatusText(
- this.tokenBudget.getSavedLifetime(),
- this.tokenBudget.getSavedToday(),
- );
- const usagePct = Math.round(this.tokenBudget.getUsagePercentage());
- await channel.send(`${text}\nCurrent daily usage: ${usagePct}%`, channelId);
- this.syncSaverToCli();
- };
-
- if (!action || action === 'status' || action === 'stats') {
- await showStatus();
- return;
- }
-
- if (action === 'on' || action === 'enable') {
- this.saverMode.enable();
- await channel.send(
- '⚡ Token Saver Mode enabled. Responses will be terser, step limits lower, and history window shorter to conserve tokens.',
- channelId,
- );
- this.syncSaverToCli();
- return;
- }
-
- if (action === 'off' || action === 'disable') {
- this.saverMode.disable();
- await channel.send('Token Saver Mode disabled. Normal response settings restored.', channelId);
- this.syncSaverToCli();
- return;
- }
-
- if (action === 'toggle') {
- const next = this.saverMode.toggle();
- await channel.send(
- next === 'on'
- ? '⚡ Token Saver Mode enabled.'
- : 'Token Saver Mode disabled.',
- channelId,
- );
- this.syncSaverToCli();
- return;
- }
-
- if (action === 'threshold') {
- const n = parseInt(parts[1], 10);
- if (isNaN(n) || n < 0 || n > 100) {
- await channel.send('Usage: /saver threshold <0-100> — percentage of daily budget at which saver auto-engages. Set 0 to disable.', channelId);
- return;
- }
- this.saverMode.setAutoThreshold(n);
- await channel.send(
- n === 0
- ? 'Saver auto-engage disabled (threshold set to 0).'
- : `Saver auto-engage threshold set to ${n}% of daily budget.`,
- channelId,
- );
- return;
- }
-
- if (action === 'auto') {
- if (arg === 'on' || arg === 'enable') {
- this.saverMode.setAutoEnabled(true);
- await channel.send(`Saver auto-engage enabled (at ${this.saverMode.getAutoThreshold()}% usage).`, channelId);
- } else if (arg === 'off' || arg === 'disable') {
- this.saverMode.setAutoEnabled(false);
- await channel.send('Saver auto-engage disabled. Saver will only activate when you run /saver on.', channelId);
- this.syncSaverToCli();
- } else {
- await channel.send(
- `Saver auto-engage is currently ${this.saverMode.isAutoEnabled() ? 'ON' : 'OFF'} (threshold: ${this.saverMode.getAutoThreshold()}%).\nUse /saver auto on|off to change.`,
- channelId,
- );
- }
- return;
- }
-
- if (action === 'routing') {
- if (arg === 'on' || arg === 'enable') {
- this.saverMode.setRoutingEnabled(true);
- await channel.send('Saver cheap-provider routing enabled (when saver is active, cheaper providers will be preferred).', channelId);
- } else if (arg === 'off' || arg === 'disable') {
- this.saverMode.setRoutingEnabled(false);
- await channel.send('Saver cheap-provider routing disabled.', channelId);
- } else {
- await channel.send(`Saver cheap-provider routing is currently ${this.saverMode.isRoutingEnabled() ? 'ON' : 'OFF'}.\nUse /saver routing on|off to change.`, channelId);
- }
- return;
- }
-
- await channel.send(
- 'Unknown saver command. Available:\n' +
- ' /saver — show status and savings\n' +
- ' /saver on — manually enable\n' +
- ' /saver off — disable\n' +
- ' /saver toggle — flip on/off\n' +
- ' /saver threshold <0-100> — auto-engage threshold (default 75)\n' +
- ' /saver auto on|off — enable/disable auto-engagement\n' +
- ' /saver routing on|off — prefer cheap providers while active (opt-in)',
- channelId,
- );
- }
-
- /** Push the current saver state to the CLI status bar if present. */
- private syncSaverToCli(): void {
- const ch = this.channels.get('cli');
- if (ch && (ch as any).setSaverMode) {
- (ch as any).setSaverMode(
- this.saverMode.getState(),
- this.tokenBudget.getSavedToday(),
- this.tokenBudget.getSavedLifetime(),
- );
- }
- }
-
- private syncTokenInfoToCli(): void {
- const ch = this.channels.get('cli');
- if (ch && (ch as any).setTokenInfo) {
- (ch as any).setTokenInfo(
- this.tokenBudget.getDailyUsed(),
- this.tokenBudget.getBudget(),
- Math.round(this.tokenBudget.getUsagePercentage()),
- );
- }
- }
-
- private async handleSkillsSlashCommand(
- trimmed: string,
- channel: any,
- channelId: string,
- ctx: { skillNames: () => string[] },
- ): Promise<void> {
- const parts = trimmed.split(/\s+/).slice(1);
- const sub = (parts[0] || 'list').toLowerCase();
- const args = parts.slice(1);
- const arg = args.join(' ').trim();
-
- const { RegistryClient, isValidSkillId, searchFeed } = await import('../skills/registry.js');
- const { SkillStore } = await import('../skills/store.js');
- const registry = new RegistryClient();
- const store = new SkillStore({ registry });
-
- try {
- switch (sub) {
- case 'help':
- case '-h':
- case '--help': {
- await channel.send(
- [
- '**Mercury Skills — in-chat commands**',
- '',
- '`/skills` — list installed skills',
- '`/skills search <query>` — search the registry',
- '`/skills view <id>` — show details + registry URL',
- '`/skills install <id>` — install from the registry',
- '`/skills install <url>` — install raw SKILL.md from a URL',
- '`/skills remove <id>` — uninstall',
- '',
- 'Browse the full catalog at https://skills.mercuryagent.sh',
- ].join('\n'),
- channelId,
- );
- return;
- }
-
- case 'list': {
- const names = ctx.skillNames();
- if (names.length === 0) {
- await channel.send(
- 'No skills installed. Try `/skills search <query>` to browse https://skills.mercuryagent.sh.',
- channelId,
- );
- return;
- }
- const lines = [
- `**${names.length} skill${names.length > 1 ? 's' : ''} installed:**`,
- '',
- ...names.map((n) => `• ${n}`),
- '',
- '_Run `/skills search <query>` to find more on the registry._',
- ];
- await channel.send(lines.join('\n'), channelId);
- return;
- }
-
- case 'search':
- case 'find': {
- if (!arg) {
- await channel.send('Usage: `/skills search <query>`', channelId);
- return;
- }
- await channel.send(`🔍 Searching the registry for "${arg}"…`, channelId);
- const feed = await registry.getFeed();
- const scored = searchFeed(feed, arg, 5);
- if (scored.length === 0) {
- await channel.send(`No matches for "${arg}".`, channelId);
- return;
- }
- const lines = scored.map(({ skill }) =>
- [
- `• \`${skill.id}\` (v${skill.version})`,
- ` ${skill.description}`,
- ` ${registry.webUrl(skill.id)}`,
- ].join('\n'),
- );
- await channel.send(
- [
- `**Top ${scored.length} matches for "${arg}":**`,
- '',
- lines.join('\n\n'),
- '',
- 'Inspect one with `/skills view <id>`, install with `/skills install <id>`.',
- ].join('\n'),
- channelId,
- );
- return;
- }
-
- case 'view':
- case 'show':
- case 'info': {
- if (!arg) {
- await channel.send('Usage: `/skills view <category/slug>`', channelId);
- return;
- }
- if (!isValidSkillId(arg)) {
- await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
- return;
- }
- const detail = await registry.getSkill(arg);
- const author = detail.author ? `\n**Author:** ${detail.author}` : '';
- const tags = detail.tags?.length ? `\n**Tags:** ${detail.tags.join(', ')}` : '';
- await channel.send(
- [
- `**${detail.title}** (\`${detail.id}\`)`,
- `**Version:** ${detail.version}`,
- `**Category:** ${detail.category}${author}${tags}`,
- '',
- detail.description,
- '',
- `🔗 ${registry.webUrl(detail.id)}`,
- '',
- `Install with \`/skills install ${detail.id}\``,
- ].join('\n'),
- channelId,
- );
- return;
- }
-
- case 'install':
- case 'add': {
- if (!arg) {
- await channel.send('Usage: `/skills install <category/slug>` or `/skills install <url>`', channelId);
- return;
- }
- // URL install → delegate to the existing capability path
- if (/^https?:\/\//i.test(arg)) {
- const { SkillLoader } = await import('../skills/loader.js');
- const loader = new SkillLoader();
- await channel.send(`📦 Installing from \`${arg}\`…`, channelId);
- const installed = await loader.installFromUrl(arg);
- await channel.send(
- `✅ Installed \`${installed.name}\` from URL.\n${installed.skillDir}`,
- channelId,
- );
- return;
- }
- if (!isValidSkillId(arg)) {
- await channel.send('Invalid skill id. Expected `<category>/<slug>` or a `https://` URL.', channelId);
- return;
- }
- await channel.send(`📦 Installing \`${arg}\` from the registry…`, channelId);
- const result = await store.install(arg);
- const verb =
- result.status === 'already-installed'
- ? 'Already installed'
- : result.status === 'updated'
- ? 'Updated'
- : result.status === 'reinstalled'
- ? 'Reinstalled'
- : 'Installed';
- await channel.send(
- `✅ ${verb} \`${result.id}\` (v${result.version})\n🔗 ${registry.webUrl(result.id)}`,
- channelId,
- );
- return;
- }
-
- case 'remove':
- case 'rm':
- case 'delete':
- case 'uninstall': {
- if (!arg) {
- await channel.send('Usage: `/skills remove <category/slug>`', channelId);
- return;
- }
- if (!isValidSkillId(arg)) {
- await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
- return;
- }
- const removed = store.remove(arg);
- await channel.send(
- removed ? `🗑 Removed \`${arg}\`.` : `Skill \`${arg}\` is not installed.`,
- channelId,
- );
- return;
- }
-
- default:
- await channel.send(
- `Unknown subcommand \`${sub}\`. Try \`/skills help\`.`,
- channelId,
- );
- }
- } catch (err: any) {
- const msg = err?.message || 'Skill registry request failed';
- await channel.send(`⚠️ ${msg}`, channelId);
- }
- }
-
- private async handleChatCommand(content: string, channelType: string, channelId: string): Promise<boolean> {
- const trimmed = content.trim();
- const cmd = trimmed.toLowerCase();
- const channel = this.channels.get(channelType as any);
- if (!channel) return false;
-
- const ctx = this.capabilities.getChatCommandContext();
- if (!ctx) return false;
-
- if (cmd === '/sessions' || cmd.startsWith('/session')) {
- await this.handleSessionCommand(trimmed, channelType as ChannelType, channelId);
- return true;
- }
-
- // /new — fresh conversation context for this chat; memory is kept.
- // Unlike /reset this never halts agents, clears queues, or wipes state.
- if (cmd === '/new') {
- await this.handleSessionCommand('/session new', channelType as ChannelType, channelId);
- return true;
- }
-
- // /trace [id] — what happened in a turn: provider, tokens, timing,
- // verification, and every tool call. Answers "why did it do that?".
- if (cmd === '/trace' || cmd.startsWith('/trace ')) {
- await channel.send(this.renderTrace(channelType as ChannelType, channelId, trimmed.slice('/trace'.length).trim()), channelId);
- return true;
- }
-
- if (cmd === '/help') {
- const helpText = channelType === 'telegram' ? getTelegramHelp() : channelType === 'discord' ? getDiscordHelp() : channelType === 'slack' ? getSlackHelp() : ctx.manual();
- await channel.send(helpText, channelId);
- return true;
- }
-
- if (cmd === '/whatsnew' || cmd.startsWith('/whatsnew ')) {
- // Curated highlights for the running version — one friendly block,
- // exhaustive notes stay in CHANGELOG.md / the releases page.
- const runningVersion = channelType === 'cli' && channel instanceof CLIChannel
- ? (channel.getTuiState().version || 'dev')
- : 'dev';
- await channel.send(whatsNewText(runningVersion), channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
- return true;
- }
-
- if (cmd.startsWith('/update')) {
- const sub = trimmed.slice('/update'.length).trim().toLowerCase();
- if (sub === 'ignore') {
- const { latestSeenUpdate, ignoreUpdateVersion, getIgnoredUpdateVersion } = await import('../cli/update-notice.js');
- const runningVersion = channelType === 'cli' && channel instanceof CLIChannel
- ? (channel.getTuiState().version || 'dev')
- : 'dev';
- const target = latestSeenUpdate(runningVersion);
- if (!target) {
- await channel.send('Nothing to ignore — no update was offered for this version.', channelId);
- return true;
- }
- if (getIgnoredUpdateVersion() === target) {
- await channel.send(`Update to v${target} is already ignored.`, channelId);
- return true;
- }
- ignoreUpdateVersion(target);
- if (channel instanceof CLIChannel) channel.setUpdateAvailable(null);
- await channel.send(`Ignored — update notices for v${target} are silenced permanently. \`mercury upgrade\` in the terminal still works whenever you want it.`, channelId);
- return true;
- }
- await channel.send('Usage: `/update ignore` — permanently silence the offered update notice.', channelId);
- return true;
- }
-
- if (cmd === '/saver' || cmd.startsWith('/saver ')) {
- await this.handleSaverCommand(trimmed.slice('/saver'.length).trim(), channelType, channelId);
- return true;
- }
-
- if (cmd.startsWith('/bg')) {
- await this.handleBgCommand(trimmed, { content: trimmed, channelId, channelType: channelType as any, id: Date.now().toString(36), senderId: 'user', timestamp: Date.now() }, channel);
- return true;
- }
-
- if (cmd === '/progress' || cmd === '/still') {
- if (!this.processing || !this.currentMessage) {
- await channel.send('No active foreground task.', channelId);
- return true;
- }
- const elapsedSec = Math.round((Date.now() - this.currentMessage.timestamp) / 1000);
- const stepInfo = this.completedStepCount > 0 ? ` · step ${this.completedStepCount}/${MAX_STEPS}` : '';
- const narrative = formatNarrative(this.stepNarrative, this.currentActivity, 10);
- const narrativeBlock = narrative ? `\n${narrative}` : '';
- await channel.send(
- `⏳ Task in progress (${elapsedSec}s${stepInfo})${narrativeBlock}\nUse /bg current to move it to background.`,
- channelId,
- );
- return true;
- }
-
- if (cmd === '/exit' || cmd === '/quit') {
- await channel.send('Goodbye! Shutting down Mercury...', channelId);
- this.shutdown();
- return true;
- }
-
- if (cmd === '/permissions') {
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- const mode = await channel.askPermissionMode?.();
- if (mode === 'allow-all') {
- this.capabilities.permissions.setAutoApproveAll(true);
- this.capabilities.permissions.addTempScope('/', true, true);
- await channel.send('Allow All mode active for this session. All scopes, commands, and loops auto-approved. Resets on restart.', channelId);
- } else {
- this.capabilities.permissions.setAutoApproveAll(false);
- await channel.send('Ask Me mode active. Risky actions will prompt for confirmation.', channelId);
- }
- return true;
- }
- await channel.send('Use /permissions in CLI to switch permission mode. On Telegram, use the /permissions button or command.', channelId);
- return true;
- }
-
- if (cmd === '/status') {
- const config = ctx.config();
- const budget = ctx.tokenBudget();
- const saver = this.saverMode.getState();
- const saverLine = saver === 'off'
- ? `Saver: off (auto at ${this.saverMode.getAutoThreshold()}%)`
- : `Saver: ${saver.toUpperCase()} · saved today ~${this.tokenBudget.getSavedToday().toLocaleString()} tokens`;
- const lines = [
- `**${config.identity.name}** — Status`,
- `Owner: ${config.identity.owner || '(not set)'}`,
- `Provider: ${config.providers.default}`,
- `Telegram: ${config.channels.telegram.enabled ? 'enabled' : 'disabled'}`,
- `Telegram access: ${getTelegramAccessSummary(config)}`,
- `Discord: ${config.channels.discord.enabled ? 'enabled' : 'disabled'}`,
- `Discord access: ${getDiscordAccessSummary(config)}`,
- `Slack: ${config.channels.slack.enabled ? 'enabled' : 'disabled'}`,
- `Slack access: ${getSlackAccessSummary(config)}`,
- `Budget: ${budget.getStatusText()}`,
- saverLine,
- `Skills: ${ctx.skillNames().length > 0 ? ctx.skillNames().join(', ') : 'none'}`,
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
-
- if (cmd === '/models' || cmd === '/model' || cmd.startsWith('/models ') || cmd.startsWith('/model ')) {
- const base = cmd.startsWith('/model ') || cmd === '/model' ? '/model' : '/models';
- const rawArgs = trimmed.slice(base.length).trim();
- const activeProviders = getActiveProviders(this.config);
- const current = this.providers.getDefault();
-
- if (!rawArgs) {
- const lines = [
- '**Session Models**',
- '',
- ...activeProviders.map((p) => {
- const marker = p.name === current.name ? ' ← current' : '';
- return `• ${p.name} · ${p.model}${marker}`;
- }),
- '',
- 'Use `/models use <provider>` to switch the default (saved across restarts).',
- 'Use `mercury doctor` to add/configure models.',
- ];
- await channel.send(lines.join('\n'), channelId);
-
- if (channelType === 'cli' && channel instanceof CLIChannel && activeProviders.length > 1) {
- const choices = [
- ...activeProviders.map((p) => `${p.name} · ${p.model}${p.name === current.name ? ' (current)' : ''}`),
- 'Open doctor instructions',
- 'Keep current model',
- ];
- const picked = await this.presentChoice('Switch session model?', choices, channelId, channelType);
- if (picked === 'Open doctor instructions') {
- await channel.send('Run `mercury doctor` and update provider/model settings. Then restart Mercury to persist defaults.', channelId);
- return true;
- }
- if (picked === 'Keep current model') return true;
- const providerName = picked.split(' · ')[0].trim();
- if (providerName && providerName !== current.name) {
- const switched = await this.switchSessionProvider(providerName);
- await channel.send(switched.message, channelId);
- }
- }
- return true;
- }
-
- if (rawArgs === 'doctor' || rawArgs === 'add') {
- await channel.send('Use `mercury doctor` to add/configure models. Then use `/models` to switch active session model.', channelId);
- return true;
- }
-
- const target = rawArgs.replace(/^use\s+/i, '').trim();
- if (!target) {
- await channel.send('Usage: `/models` or `/models use <provider>`', channelId);
- return true;
- }
-
- const switched = await this.switchSessionProvider(target);
- await channel.send(switched.message, channelId);
- return true;
- }
-
- if (cmd === '/cloud' || cmd.startsWith('/cloud ')) {
- const cfg = ctx.config();
- if (!cfg.cloud.enabled || !cfg.cloud.jwt) {
- await channel.send('Mercury Cloud is not connected. Run `mercury cloud connect` to set it up.', channelId);
- return true;
- }
-
- const sub = trimmed.slice('/cloud'.length).trim();
-
- const ensureFreshToken = async (): Promise<string> => {
- try {
- const store = getCloudTokenStore();
- if (store) {
- return await store.rotateIfExpired();
- }
- const parts = cfg.cloud.jwt.split('.');
- if (parts.length === 3) {
- const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
- const exp = payload.exp * 1000;
- if (Date.now() > exp - 60_000 && cfg.cloud.refreshToken) {
- const { refreshToken } = await import('../cloud/pairing.js');
- const result = await refreshToken(cfg.cloud.apiUrl, cfg.cloud.refreshToken);
- cfg.cloud.jwt = result.jwt;
- cfg.cloud.refreshToken = result.refreshToken;
- cfg.providers.mercuryCloud.apiKey = result.jwt;
- const { saveConfig } = await import('../utils/config.js');
- saveConfig(cfg);
- this.config = cfg;
- return result.jwt;
- }
- }
- } catch {}
- return cfg.cloud.jwt;
- };
-
- if (!sub || sub === 'models' || sub === 'model') {
- try {
- const jwt = await ensureFreshToken();
- const res = await fetch(`${cfg.cloud.apiUrl}/v1/models`, {
- headers: { Authorization: `Bearer ${jwt}` },
- });
- if (!res.ok) {
- await channel.send(`Failed to fetch cloud models (HTTP ${res.status}). Your token may have expired — run \`mercury cloud login\`.`, channelId);
- return true;
- }
- const data = await res.json() as { data: Array<{ id: string; label: string; tier_required: string; context_window: number; available: boolean; is_branded?: boolean; discount_percent?: number }> };
- const models = data.data || [];
- if (models.length === 0) {
- await channel.send('No models available.', channelId);
- return true;
- }
-
- const currentModel = cfg.providers.mercuryCloud?.model || '—';
- const branded = models.filter((m) => m.is_branded);
- const raw = models.filter((m) => !m.is_branded);
-
- const formatModel = (m: typeof models[0]) => {
- const marker = m.id === currentModel ? ' ← current' : '';
- const lock = m.available ? '' : ' 🔒';
- const discount = m.discount_percent && m.discount_percent > 0 ? ` (${m.discount_percent}% off input)` : '';
- return `• ${m.id} · ${m.label} (${m.tier_required})${discount}${lock}${marker}`;
- };
-
- const lines = [
- '**Mercury Cloud Models**',
- '',
- '**Mercury Branded**',
- ...branded.map(formatModel),
- '',
- '**Direct Models**',
- ...raw.map(formatModel),
- '',
- 'Use `/cloud use <model-id>` to switch.',
- ];
- await channel.send(lines.join('\n'), channelId);
-
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- const availableModels = models.filter((m) => m.available);
- const choices = [
- ...availableModels.map((m) => `${m.id} · ${m.label}${m.id === currentModel ? ' (current)' : ''}`),
- 'Keep current model',
- ];
- if (availableModels.length <= 1) {
- await channel.send('Only one model available for your tier. Upgrade to unlock more.', channelId);
- return true;
- }
- const picked = await this.presentChoice('Switch cloud model?', choices, channelId, channelType);
- if (picked === 'Keep current model') return true;
- const modelId = picked.split(' · ')[0].trim();
- if (modelId) {
- cfg.providers.mercuryCloud.model = modelId;
- cfg.providers.mercuryCloud.enabled = true;
- cfg.providers.default = 'mercuryCloud';
- const { saveConfig } = await import('../utils/config.js');
- saveConfig(cfg);
- this.config = cfg;
- const provider = await createProvider(cfg.providers.mercuryCloud, getCloudTokenStore());
- this.providers.set('mercuryCloud', provider);
- this.providers.setDefault('mercuryCloud');
- updateCliProviderStatus(this.channels.get('cli'), 'mercuryCloud', modelId);
- await channel.send(`✓ Switched to **${modelId}**. Saved to config.`, channelId);
- }
- }
- } catch (err) {
- await channel.send(`Error fetching cloud models: ${(err as Error).message}`, channelId);
- }
- return true;
- }
-
- if (sub.startsWith('use ')) {
- const modelId = sub.slice(4).trim();
- if (!modelId) {
- await channel.send('Usage: `/cloud use <model-id>`', channelId);
- return true;
- }
- await ensureFreshToken();
- try {
- cfg.providers.mercuryCloud.model = modelId;
- cfg.providers.mercuryCloud.enabled = true;
- if (cfg.providers.default !== 'mercuryCloud') {
- cfg.providers.default = 'mercuryCloud';
+ const verifyText = (result.text || '').trim();
+ if (verifyText && verifyText !== '(no text response)') messages.push({ role: 'assistant', content: verifyText });
+ messages.push({ role: 'user', content: verificationPrompt(msg.content) });
+ const verifyProvider = usedProvider
+ ? (providersForAttempt.find((p) => p.name === usedProvider!.name && p.getModel() === usedProvider!.model) ?? providersForAttempt[0])
+ : providersForAttempt[0];
+ if (verifyProvider) {
+ lastRoundSteps = 0;
+ try {
+ const round = await this.runInlineContinuationRound({
+ messages,
+ systemPrompt,
+ volatileSystem,
+ provider: verifyProvider,
+ maxOutputTokens: effectiveMaxOutputTokens,
+ maxSteps: effectiveMaxSteps,
+ abortController: loopAbortController,
+ channel,
+ channelId: msg.channelId,
+ // Verification must produce evidence, not prose about evidence.
+ forceFirstTool: true,
+ onStep: continuationStepHandler,
+ });
+ if (round.text.trim()) result = { text: round.text, usage: round.usage, reasoning: round.reasoning, finishReason: round.finishReason };
+ cliResponseStreamed = channel instanceof CLIChannel;
+ } catch (verifyErr: any) {
+ logger.warn({ err: verifyErr?.message || String(verifyErr) }, 'Verification continuation failed; keeping original response');
}
- const { saveConfig } = await import('../utils/config.js');
- saveConfig(cfg);
- this.config = cfg;
- const provider = await createProvider(cfg.providers.mercuryCloud, getCloudTokenStore());
- this.providers.set('mercuryCloud', provider);
- this.providers.setDefault('mercuryCloud');
- updateCliProviderStatus(this.channels.get('cli'), 'mercuryCloud', modelId);
- await channel.send(`✓ Switched to **${modelId}**. Saved to config.`, channelId);
- } catch (err) {
- await channel.send(`Error switching model: ${(err as Error).message}`, channelId);
}
- return true;
}
- await channel.send('Usage: `/cloud models` to list, `/cloud use <model-id>` to switch', channelId);
- return true;
- }
-
- if (cmd === '/memory') {
- if (!this.userMemory) {
- const cfg = ctx.config();
- if (cfg.memory.secondBrain?.enabled === false) {
- await channel.send('Second brain is disabled in configuration.', channelId);
- } else {
- await channel.send('Second brain dependency issue: SQLite backend (better-sqlite3) is not available.', channelId);
+ // ── Final verdict: a step-budget stop past the continuation bound is
+ // an honest pause, never a completion banner. ──
+ const pauseHonestly = async (banner: string, reason: string): Promise<void> => {
+ logger.warn({ banner, task: msg.content.slice(0, 120) }, 'Completion contract: pausing task honestly');
+ this.markProgress('Task paused');
+ this.pushLiveActivity('Paused', 'completion contract');
+ if (this.currentWorkKey) {
+ this.workLedger.markPaused(this.currentWorkKey, reason);
}
- return true;
- }
-
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- await this.openCliMemoryMenu(channel, channelId);
- return true;
- }
+ if (channel && msg.channelType !== 'internal') {
+ // Persistent banner, deferred text flushed first (see TaskSurface.pause).
+ await surface.pause(`${banner}\n\n_/trace ${traceId}_`);
+ if (this.currentWorkKey) this.workLedger.markDelivered(this.currentWorkKey);
+ }
+ this.lifecycle.transition('idle');
+ };
- const choiceChannel = channel as typeof channel & { presentChoicePrompt?: (question: string, options: ArrowSelectOption[], targetId?: string) => Promise<string> };
- if (typeof choiceChannel.presentChoicePrompt === 'function') {
- await this.openMemoryChoiceMenu(choiceChannel, channelId);
- return true;
+ if (!loopAbortController.signal.aborted && turnEnd() === 'steps-exhausted') {
+ logger.warn({ steps: lastRoundSteps, budget: effectiveMaxSteps }, 'Step budget exhausted past continuation bound — pausing task honestly');
+ await pauseHonestly(
+ STEPS_PAUSED_BANNER,
+ 'Step budget reached with work pending. Send "continue" to resume with a fresh budget.',
+ );
+ return;
}
- await this.sendMemoryOverview(channel, channelId);
- return true;
- }
-
- if (cmd.startsWith('/telegram')) {
- if (channelType !== 'cli') {
- await channel.send('`/telegram` is only available from the Mercury CLI chat.', channelId);
- return true;
+ // Narration-guard exhaustion: after all forced continuation rounds the
+ // turn STILL contains zero mutating work (rounds failed on flaky
+ // providers, or the model kept narrating). That must never read as
+ // "Task complete" — pause and let "continue" re-engage.
+ if (
+ !loopAbortController.signal.aborted
+ && this.programmingMode.isExecute()
+ && !responseAsksUser(result.text || '')
+ && shouldForceExecuteContinuation({
+ taskText: msg.content,
+ hasApprovedPlan: this.programmingMode.getLastPlan() != null,
+ toolsUsed: executeTurnToolsUsed,
+ toolsSucceeded: executeToolSucceeded,
+ })
+ ) {
+ logger.warn({ task: msg.content.slice(0, 120), blocker: lastGuardToolFailure }, 'Narration guard exhausted (both cycles) — pausing instead of completing');
+ const blockerNote = lastGuardToolFailure
+ ? `\n\nWhat blocked it: ${lastGuardToolFailure}`
+ : '';
+ await pauseHonestly(
+ WORK_NOT_STARTED_BANNER + blockerNote,
+ `No implementation work was performed across two guard cycles.${lastGuardToolFailure ? ` Last blocker: ${lastGuardToolFailure}` : ''} Send "continue" to resume with tools.`,
+ );
+ return;
}
- const config = ctx.config();
- const rawSubcommand = trimmed.slice('/telegram'.length).trim();
- if (!rawSubcommand && channel instanceof CLIChannel) {
- await channel.withMenu(async (select) => {
- await this.openCliTelegramMenu(channel, channelId, select);
- });
- return true;
+ // Verification failed or is stale: in execute mode, a build/test/
+ // typecheck ran but did not pass, or passed and was then followed by
+ // more edits. Either way there is no evidence the work is correct —
+ // that is an honest pause, never a "Task complete" banner.
+ if (
+ !loopAbortController.signal.aborted
+ && this.programmingMode.isExecute()
+ && lastVerification != null
+ && !verifiedAfterLastMutation()
+ && !responseAsksUser(result.text || '')
+ ) {
+ const stale = lastVerification.ok;
+ logger.warn({ verification: lastVerificationNote, stale }, 'Completion contract: verification failed or stale — pausing instead of completing');
+ await pauseHonestly(
+ `${VERIFICATION_FAILED_BANNER}\n\nLast check: ${lastVerificationNote}${stale ? ' (ran before the latest changes)' : ''}`,
+ `Verification ${stale ? 'is stale' : 'failed'}: ${lastVerificationNote}. Send "continue" to resume.`,
+ );
+ return;
}
- const parts = rawSubcommand.split(/\s+/).filter(Boolean);
- const action = parts[0]?.toLowerCase() || 'help';
- const formatTelegramUser = (user: {
- userId: number;
- username?: string;
- firstName?: string;
- pairingCode?: string;
- }) => {
- const username = user.username ? ` (@${user.username})` : '';
- const firstName = user.firstName ? ` ${user.firstName}` : '';
- const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';
- return `${user.userId}${username}${firstName}${pairingCode}`;
- };
-
- const sendTelegramOverview = async () => {
- const lines = [
- '**Telegram Management**',
- '',
- `Access: ${getTelegramAccessSummary(config)}`,
- `Admins: ${config.channels.telegram.admins.length > 0 ? config.channels.telegram.admins.map(formatTelegramUser).join(', ') : 'none'}`,
- `Members: ${config.channels.telegram.members.length > 0 ? config.channels.telegram.members.map(formatTelegramUser).join(', ') : 'none'}`,
- `Pending: ${config.channels.telegram.pending.length > 0 ? config.channels.telegram.pending.map(formatTelegramUser).join(', ') : 'none'}`,
- '',
- 'Commands:',
- '• `/telegram pending`',
- '• `/telegram users`',
- '• `/telegram approve <pairing-code|user-id>`',
- '• `/telegram reject <user-id>`',
- '• `/telegram remove <user-id>`',
- '• `/telegram promote <user-id>`',
- '• `/telegram demote <user-id>`',
- '• `/telegram reset`',
- ];
- await channel.send(lines.join('\n'), channelId);
- };
-
- if (action === 'help' || action === 'status') {
- await sendTelegramOverview();
- return true;
- }
+ // Recompute AFTER the guard: the continuation's output (not the
+ // original narration) must be what reaches the session store, the
+ // work ledger, and the final delivery.
+ const finalText = (result.text || '').trim() || '(no text response)';
- if (action === 'pending') {
- const pending = getTelegramPendingRequests(config);
- const lines = [
- '**Telegram Pending Requests**',
- '',
- pending.length > 0 ? pending.map(formatTelegramUser).join('\n') : 'No pending Telegram requests.',
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
+ // Store plan output when in plan mode for later execution
+ if (this.programmingMode.isPlan() && preGuardText !== '(no text response)') {
+ this.programmingMode.storePlan(preGuardText);
+ logger.info({ planLength: preGuardText.length }, 'Plan captured from plan-mode response');
}
- if (action === 'users') {
- const approved = getTelegramApprovedUsers(config);
- const lines = [
- '**Telegram Approved Users**',
- '',
- `Admins: ${config.channels.telegram.admins.length > 0 ? config.channels.telegram.admins.map(formatTelegramUser).join(', ') : 'none'}`,
- `Members: ${config.channels.telegram.members.length > 0 ? config.channels.telegram.members.map(formatTelegramUser).join(', ') : 'none'}`,
- '',
- `Total approved: ${approved.length}`,
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
+ this.tokenBudget.recordUsage({
+ provider: usedProvider?.name ?? 'unknown',
+ model: usedProvider?.model ?? 'unknown',
+ inputTokens: result.usage?.inputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
+ channelType: msg.channelType,
+ agentId: this.config.cloud.agentId || undefined,
+ });
+ logger.info({
+ provider: usedProvider?.name,
+ model: usedProvider?.model,
+ inputTokens: result.usage?.inputTokens ?? 0,
+ cachedInputTokens: result.usage?.cachedInputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ steps: this.completedStepCount,
+ toolCalls: turnToolTrace.length,
+ historyEntries: recentMemory.length,
+ activeTools: activeTools?.length ?? 'all',
+ elapsedMs: Date.now() - startTime,
+ }, 'Turn usage');
+ this.syncTokenInfoToCli();
- if (action === 'approve') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/telegram approve <pairing-code|user-id>`', channelId);
- return true;
+ // Estimate tokens saved by Saver Mode (cap headroom + history trim).
+ // Rough: (default_cap - actual_output) when capped, plus history-window delta.
+ if (saverWasActive) {
+ const actualOutput = result.usage?.outputTokens ?? 0;
+ const outputHeadroom = Math.max(0, MODEL_OUTPUT_TOKEN_LIMIT - effectiveMaxOutputTokens);
+ const outputSaved = Math.max(0, Math.min(outputHeadroom, MODEL_OUTPUT_TOKEN_LIMIT - actualOutput));
+ // Rough proxy: each trimmed history message ~120 tokens average.
+ const historyTrimMessages = Math.max(0, NORMAL_HISTORY_WINDOW - this.saverMode.adjustHistoryWindow(NORMAL_HISTORY_WINDOW));
+ const historySaved = historyTrimMessages * 120;
+ const estimated = outputSaved + historySaved;
+ if (estimated > 0) {
+ this.tokenBudget.recordSavings(estimated);
+ this.syncSaverToCli();
}
+ }
- let approved = approveTelegramPendingRequestByPairingCode(config, value);
- let resultLabel = value;
-
- if (!approved) {
- const userId = Number(value);
- if (!isNaN(userId)) {
- approved = approveTelegramPendingRequest(config, userId, 'member');
- resultLabel = userId.toString();
- }
+ if (canonicalSessionId) {
+ if (turnToolTrace.length > 0) {
+ this.sessions.appendMessage(canonicalSessionId, {
+ role: 'assistant',
+ kind: TOOL_TRACE_KIND,
+ content: formatToolTrace(turnToolTrace),
+ externalMessageId: `${msg.id}:tools`,
+ metadata: { channelType: msg.channelType, channelId: msg.channelId, toolCalls: turnToolTrace.length },
+ });
}
-
- if (!approved) {
- await channel.send(`No pending Telegram request found for \`${resultLabel}\`.`, channelId);
- return true;
+ this.sessions.appendMessage(canonicalSessionId, {
+ role: 'assistant',
+ content: finalText,
+ externalMessageId: `${msg.id}:assistant`,
+ tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
+ reasoning: typeof result.reasoning === 'string'
+ ? result.reasoning
+ : result.reasoning
+ ? JSON.stringify(result.reasoning)
+ : undefined,
+ metadata: {
+ channelType: msg.channelType,
+ channelId: msg.channelId,
+ ...(typeof msg.metadata?.requestId === 'string' ? { requestId: msg.metadata.requestId } : {}),
+ ...(usedProvider ? { provider: usedProvider.name, model: usedProvider.model } : {}),
+ // Per-turn trace, shown by /trace <id>.
+ traceId,
+ elapsedMs: Date.now() - startTime,
+ steps: this.completedStepCount,
+ inputTokens: result.usage?.inputTokens ?? 0,
+ cachedInputTokens: result.usage?.cachedInputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ ...(lastVerificationNote ? { verification: lastVerificationNote } : {}),
+ },
+ });
+ if (msg.channelType !== 'internal' && msg.senderId !== 'system' && usedProvider) {
+ this.scheduleSessionTitleGeneration(canonicalSessionId, usedProvider.name);
}
-
- saveConfig(config);
- await channel.send(`Approved Telegram user ${formatTelegramUser(approved)}.`, channelId);
- return true;
+ } else {
+ this.shortTerm.add(msg.channelId, { id: msg.id, timestamp: msg.timestamp, role: 'user', content: msg.content });
+ this.shortTerm.add(msg.channelId, {
+ id: Date.now().toString(36), timestamp: Date.now(), role: 'assistant', content: finalText,
+ tokenCount: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0), reasoning: result.reasoning || undefined,
+ });
}
- if (action === 'reject') {
- const value = Number(parts[1]);
- if (isNaN(value)) {
- await channel.send('Usage: `/telegram reject <user-id>`', channelId);
- return true;
- }
-
- const rejected = rejectTelegramPendingRequest(config, value);
- if (!rejected) {
- await channel.send(`No pending Telegram request found for \`${value}\`.`, channelId);
- return true;
- }
+ this.episodic.record({
+ type: 'message',
+ summary: `User: ${msg.content.slice(0, 100)} | Agent: ${finalText.slice(0, 100)}`,
+ channelType: msg.channelType,
+ });
- saveConfig(config);
- await channel.send(`Rejected Telegram request for ${formatTelegramUser(rejected)}.`, channelId);
- return true;
+ if (msg.channelType !== 'internal') {
+ this.extractMemory(msg.content, finalText).catch(err => {
+ logger.warn({ err }, 'Memory extraction failed');
+ });
+ this.scheduleStatusVerbRefresh(channel, msg.content);
}
- if (action === 'remove') {
- const value = Number(parts[1]);
- if (isNaN(value)) {
- await channel.send('Usage: `/telegram remove <user-id>`', channelId);
- return true;
- }
-
- const removed = removeTelegramUser(config, value);
- if (!removed) {
- await channel.send(`No approved Telegram user found for \`${value}\`.`, channelId);
- return true;
- }
+ if (this.currentWorkKey) this.workLedger.markCompleted(this.currentWorkKey, finalText);
- saveConfig(config);
- await channel.send(`Removed Telegram access for ${formatTelegramUser(removed)}.`, channelId);
- return true;
+ if (channel && msg.channelType !== 'internal') {
+ const elapsed = Date.now() - startTime;
+ const stepCount = this.completedStepCount;
+ const completionMeta = {
+ provider: usedProvider?.name ?? 'unknown',
+ model: usedProvider?.model ?? 'unknown',
+ inputTokens: result.usage?.inputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
+ budgetUsed: this.tokenBudget.getDailyUsed(),
+ budgetTotal: this.tokenBudget.getBudget(),
+ budgetPercentage: this.tokenBudget.getUsagePercentage(),
+ };
+ const isMercuryCodeExecution = channel instanceof CLIChannel
+ && channel.getTuiState().mode === 'mercury-code'
+ && (channel.getTuiState().programmingMode === 'execute' || channel.getTuiState().programmingMode === 'auto');
+ logger.info({ channelType: msg.channelType, targetId: msg.channelId, surface: surface.kind, traceId }, 'Delivering final response');
+ await surface.done({
+ finalText,
+ elapsedMs: elapsed,
+ stepCount,
+ meta: completionMeta,
+ verificationNote: lastVerificationNote || undefined,
+ traceId,
+ alreadyStreamed: !requiresFinalSend(msg.channelType, cliResponseStreamed),
+ forceBanner: isMercuryCodeExecution,
+ });
+ this.markProgress();
+ } else {
+ logger.debug('Internal prompt processed, no channel response needed');
}
- if (action === 'promote') {
- const value = Number(parts[1]);
- if (isNaN(value)) {
- await channel.send('Usage: `/telegram promote <user-id>`', channelId);
- return true;
- }
-
- const promoted = promoteTelegramUserToAdmin(config, value);
- if (!promoted) {
- await channel.send(`No Telegram member found for \`${value}\`.`, channelId);
- return true;
- }
- saveConfig(config);
- await channel.send(`Promoted ${formatTelegramUser(promoted)} to Telegram admin.`, channelId);
- return true;
- }
+ const awaitsCloudAck = msg.channelType === 'web'
+ && typeof msg.metadata?.externalConversationId === 'string'
+ && typeof msg.metadata?.requestId === 'string';
+ if (this.currentWorkKey && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);
- if (action === 'demote') {
- const value = Number(parts[1]);
- if (isNaN(value)) {
- await channel.send('Usage: `/telegram demote <user-id>`', channelId);
- return true;
+ this.lifecycle.transition('idle');
+ } catch (err) {
+ logger.error({ err }, 'Error handling message');
+ const ledgerEntry = this.currentWorkKey ? this.workLedger.get(this.currentWorkKey) : undefined;
+ if (this.currentWorkKey) {
+ if (ledgerEntry?.status === 'completed') this.workLedger.markDeliveryError(this.currentWorkKey, err);
+ else if (ledgerEntry?.status !== 'failed') {
+ const errMsg = err instanceof Error ? err.message : String(err);
+ this.workLedger.markFailed(
+ this.currentWorkKey,
+ err,
+ `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`,
+ );
}
-
- const demoted = demoteTelegramAdmin(config, value);
- if (!demoted) {
- await channel.send('Could not demote that Telegram admin. Mercury must keep at least one admin.', channelId);
- return true;
+ }
+ if (ledgerEntry?.status === 'completed') {
+ logger.warn({ err, workKey: this.currentWorkKey }, 'Final response persisted but delivery did not complete; retaining for replay');
+ return;
+ }
+ // Always notify the user — they should never have to re-prompt
+ // to find out their task died.
+ const catchChannel = this.channels.getChannelForMessage(msg);
+ if (catchChannel && msg.channelType !== 'internal') {
+ const errMsg = err instanceof Error ? err.message : String(err);
+ try {
+ const finalError = `I encountered an unexpected error and couldn't finish: ${errMsg.slice(0, 200)}`;
+ const delivered = catchChannel instanceof WebChannel ? catchChannel.sendError(finalError, msg.channelId) : true;
+ if (!(catchChannel instanceof WebChannel)) await catchChannel.send(finalError, msg.channelId);
+ const awaitsCloudAck = msg.channelType === 'web'
+ && typeof msg.metadata?.externalConversationId === 'string'
+ && typeof msg.metadata?.requestId === 'string';
+ if (this.currentWorkKey && delivered && !awaitsCloudAck) this.workLedger.markDelivered(this.currentWorkKey);
+ if (this.currentWorkKey && !delivered) this.workLedger.markDeliveryError(this.currentWorkKey, 'Terminal error delivery was not accepted');
+ } catch (sendErr) {
+ if (this.currentWorkKey) this.workLedger.markDeliveryError(this.currentWorkKey, sendErr);
+ logger.warn({ sendErr }, 'Failed to notify user of handler error');
}
-
- saveConfig(config);
- await channel.send(`Demoted ${formatTelegramUser(demoted)} to Telegram member.`, channelId);
- return true;
}
-
- if (action === 'reset' || action === 'unpair') {
- config.channels.telegram.admins = [];
- config.channels.telegram.members = [];
- config.channels.telegram.pending = [];
- saveConfig(config);
- await channel.send('Telegram access reset. New users can send /start to begin pairing again.', channelId);
- return true;
+ // Write crash flag so next startup also reports the failure.
+ try {
+ const { writeCrashFlag } = await import('./crash-flag.js');
+ writeCrashFlag({
+ reason: `Unhandled agent error: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300),
+ timestamp: Date.now(),
+ activeTask: this.currentActivity || undefined,
+ channelId: msg.channelId || undefined,
+ channelType: msg.channelType || undefined,
+ });
+ } catch { /* best effort */ }
+ this.lifecycle.transition('idle');
+ } finally {
+ clearInterval(memoryGuard);
+ stallWatchdog.stop();
+ stopHeartbeat();
+ this.finalizeChannelTask(msg);
+ this.currentMessage = null;
+ this.currentAbort = null;
+ this.currentAbortReason = null;
+ this.currentActivity = '';
+ this.completedStepCount = 0;
+ this.stepNarrative = [];
+ {
+ const ch = this.channels.get('cli');
+ if (ch instanceof CLIChannel) ch.clearLiveActivity();
}
-
- await channel.send(
- `Unknown Telegram command "${action}". Try \`/telegram\`, \`/telegram pending\`, or \`/telegram users\`.`,
- channelId,
- );
- return true;
+ if (isInternal) {
- this.capabilities.permissions.setAutoApproveAll(false);
++ this.capabilities.permissions.endTurnGrant();
+ }
+ this.capabilities.permissions.clearElevation();
}
+ }
- if (cmd.startsWith('/discord')) {
- if (channelType !== 'cli') {
- await channel.send('`/discord` is only available from the Mercury CLI chat.', channelId);
- return true;
- }
+ /**
+ * Prompt caching: the system prompt is the large, stable prefix of every
+ * model call (identity, skills, bot roster, guidelines; with ~50 tool
+ * schemas it is roughly 10K tokens) and it is re-sent on every one of up
+ * to 75 steps. Sending it as a system *message* carrying an Anthropic
+ * cache_control marker lets Anthropic serve it from cache across steps
+ * and turns; providers that do not know the option ignore it, and the
+ * AI SDK treats a leading system message exactly like `system:`.
+ */
+ private withCachedSystem(systemPrompt: string, messages: unknown[], volatileSystem = ''): any[] {
+ return [
+ {
+ role: 'system',
+ content: systemPrompt,
+ providerOptions: { anthropic: { cacheControl: { type: 'ephemeral' } } },
+ },
+ // Per-turn context lives in its own block AFTER the cache marker so it
+ // never invalidates the stable prefix.
+ ...(volatileSystem ? [{ role: 'system', content: volatileSystem }] : []),
+ ...messages,
+ ];
+ }
- const config = ctx.config();
- const rawSubcommand = trimmed.slice('/discord'.length).trim();
- const parts = rawSubcommand.split(/\s+/).filter(Boolean);
- const action = parts[0]?.toLowerCase() || 'help';
- const formatDiscordUser = (user: {
- userId: string;
- username?: string;
- displayName?: string;
- pairingCode?: string;
- }) => {
- const username = user.username ? ` (@${user.username})` : '';
- const displayName = user.displayName ? ` ${user.displayName}` : '';
- const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';
- return `${user.userId}${username}${displayName}${pairingCode}`;
- };
+ /** Stable system prompt; assembly lives in core/system-prompt.ts. */
+ private buildSystemPrompt(): string {
+ const summary = this.userMemory ? this.userMemory.getSummary() : null;
+ return assembleSystemPrompt({
+ identityPrompt: this.identity.getSystemPrompt(this.config.identity),
+ skillContext: this.capabilities.getSkillContext(),
+ botSection: this.botManager ? this.botManager.getSystemPromptSection() : '',
+ programmingSuffix: this.programmingMode.getSystemPromptSuffix(),
+ researchSuffix: this.researchMode.getSystemPromptSuffix(),
+ budgetStatus: this.tokenBudget.getStatusText(),
+ budgetUsagePercentage: this.tokenBudget.getUsagePercentage(),
+ saverSuffix: this.saverMode.getSystemPromptSuffix(),
+ cwd: this.capabilities.getCwd(),
+ now: new Date(),
+ platform: process.platform,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ memorySummary: summary ? { total: summary.total, learningPaused: summary.learningPaused } : null,
+ toolNames: this.capabilities.getToolNames(),
+ github: this.config.github,
+ });
+ }
- const sendDiscordOverview = async () => {
- const lines = [
- '**Discord Management**',
- '',
- `Access: ${getDiscordAccessSummary(config)}`,
- `Admins: ${config.channels.discord.admins.length > 0 ? config.channels.discord.admins.map(formatDiscordUser).join(', ') : 'none'}`,
- `Members: ${config.channels.discord.members.length > 0 ? config.channels.discord.members.map(formatDiscordUser).join(', ') : 'none'}`,
- `Pending: ${config.channels.discord.pending.length > 0 ? config.channels.discord.pending.map(formatDiscordUser).join(', ') : 'none'}`,
- '',
- 'Commands:',
- '\u2022 `/discord pending`',
- '\u2022 `/discord users`',
- '\u2022 `/discord approve <pairing-code|user-id>`',
- '\u2022 `/discord reject <user-id>`',
- '\u2022 `/discord remove <user-id>`',
- '\u2022 `/discord reset`',
- ];
- await channel.send(lines.join('\n'), channelId);
- };
+ async processInternalPrompt(prompt: string, channelId?: string, channelType?: string): Promise<void> {
+ const syntheticMsg: ChannelMessage = {
+ id: `internal-${Date.now().toString(36)}`,
+ channelId: channelId || 'internal',
+ channelType: (channelType || 'internal') as ChannelType,
+ senderId: 'system',
+ content: prompt,
+ timestamp: Date.now(),
+ };
+ this.enqueueMessage(syntheticMsg);
+ }
- if (action === 'help' || action === 'status') {
- await sendDiscordOverview();
- return true;
+ private async handleScheduledTask(manifest: ScheduledTaskManifest): Promise<void> {
+ // Bot routines run on the bot lane, never through the main agent loop
+ // (BOTS-ARCHITECTURE.md §2.3 — cron lane).
+ if (manifest.botId) {
+ if (!this.botManager) {
+ logger.warn({ task: manifest.id, botId: manifest.botId }, 'Bot routine fired but BotManager is not wired');
+ return;
+ }
+ logger.info({ task: manifest.id, botId: manifest.botId }, 'Bot routine firing');
+ const result = this.botManager.enqueue(manifest.botId, {
+ trigger: 'cron',
+ prompt: manifest.prompt || manifest.description,
+ });
+ if (!result.accepted) {
+ logger.warn({ botId: manifest.botId, reasonCode: result.reasonCode }, 'Bot routine could not be enqueued');
}
+ return;
+ }
+ logger.info({ task: manifest.id, channel: manifest.sourceChannelType }, 'Processing scheduled task');
+ try {
+ const channel = manifest.sourceChannelType
+ ? this.channels.get(manifest.sourceChannelType as ChannelType)
+ : this.channels.getNotificationChannel();
- if (action === 'pending') {
- const pending = config.channels.discord.pending;
- const lines = [
- '**Discord Pending Requests**',
- '',
- pending.length > 0 ? pending.map(formatDiscordUser).join('\n') : 'No pending Discord requests.',
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
+ if (channel && manifest.sourceChannelType !== 'internal') {
+ const skillInfo = manifest.skillName ? ` (${manifest.skillName})` : '';
+ await channel.send(
+ ` Scheduled task started${skillInfo}: ${manifest.description}\nAll actions auto-approved for this run.`,
+ manifest.sourceChannelId,
+ ).catch((e) => logger.warn({ e }, 'channel send failed'));
}
- if (action === 'users') {
- const lines = [
- '**Discord Approved Users**',
- '',
- `Admins: ${config.channels.discord.admins.length > 0 ? config.channels.discord.admins.map(formatDiscordUser).join(', ') : 'none'}`,
- `Members: ${config.channels.discord.members.length > 0 ? config.channels.discord.members.map(formatDiscordUser).join(', ') : 'none'}`,
- '',
- `Total approved: ${config.channels.discord.admins.length + config.channels.discord.members.length}`,
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
+ let prompt = manifest.prompt || '';
+ if (manifest.skillName) {
+ const skillHint = `Invoke the skill "${manifest.skillName}" using the use_skill tool and follow its instructions.`;
+ prompt = prompt ? `${prompt} ${skillHint}` : `Scheduled task triggered. ${skillHint}`;
+ }
+ if (!prompt) {
+ prompt = `Execute scheduled task: ${manifest.description}`;
}
+ await this.processInternalPrompt(prompt, manifest.sourceChannelId, manifest.sourceChannelType);
+ } catch (err) {
+ logger.error({ err, task: manifest.id }, 'Scheduled task execution failed');
+ }
+ }
- if (action === 'approve') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/discord approve <pairing-code|user-id>`', channelId);
- return true;
- }
+ private async heartbeat(): Promise<void> {
+ logger.debug('Heartbeat tick');
- let approved = approveDiscordPendingRequestByPairingCode(config, value);
- let resultLabel = value;
+ const pruned = this.episodic.prune(7);
+ if (pruned > 0) {
+ logger.info({ pruned }, 'Episodic memory pruned');
+ }
- if (!approved) {
- approved = approveDiscordPendingRequest(config, value, 'member');
- resultLabel = value;
+ if (this.userMemory) {
+ try {
+ const consolidation = this.userMemory.consolidate();
+ if (consolidation.profileUpdated || consolidation.reflectionCount > 0) {
+ logger.info({ consolidation }, 'Second brain consolidated');
}
- if (!approved) {
- await channel.send(`No pending Discord request found for \`${resultLabel}\`.`, channelId);
- return true;
+ const pruning = this.userMemory.prune();
+ if (pruning.movedToSubconscious > 0 || pruning.hardDeleted > 0 || pruning.promoted > 0) {
+ logger.info({ pruning }, 'Second brain pruned');
}
-
- saveConfig(config);
- await channel.send(`Approved Discord user ${formatDiscordUser(approved)}.`, channelId);
- return true;
+ } catch (err) {
+ logger.warn({ err }, 'Second brain heartbeat error');
}
+ }
- if (action === 'reject') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/discord reject <user-id>`', channelId);
- return true;
- }
-
- const rejected = rejectDiscordPendingRequestConfig(config, value);
- if (!rejected) {
- await channel.send(`No pending Discord request found for \`${value}\`.`, channelId);
- return true;
- }
-
- saveConfig(config);
- await channel.send(`Rejected Discord request for ${formatDiscordUser(rejected)}.`, channelId);
- return true;
- }
+ const notifications: string[] = [];
- if (action === 'remove') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/discord remove <user-id>`', channelId);
- return true;
- }
+ const usagePct = this.tokenBudget.getUsagePercentage();
+ if (usagePct >= 80) {
+ notifications.push(`Token budget at ${Math.round(usagePct)}% — ${this.tokenBudget.getRemaining().toLocaleString()} tokens remaining today.`);
+ }
- const removed = removeDiscordUser(config, value);
- if (!removed) {
- await channel.send(`No approved Discord user found for \`${value}\`.`, channelId);
- return true;
+ const pendingSchedules = this.scheduler.getManifests();
+ const now = Date.now();
+ for (const task of pendingSchedules) {
+ if (task.delaySeconds && task.executeAt) {
+ const executeAt = new Date(task.executeAt).getTime();
+ const diffMin = Math.round((executeAt - now) / 60000);
+ if (diffMin > 0 && diffMin <= 5) {
+ notifications.push(`Task "${task.description}" fires in ${diffMin} minute${diffMin !== 1 ? 's' : ''}.`);
}
-
- saveConfig(config);
- await channel.send(`Removed Discord access for ${formatDiscordUser(removed)}.`, channelId);
- return true;
}
-
- if (action === 'reset' || action === 'unpair') {
- clearDiscordAccess(config);
- saveConfig(config);
- await channel.send('Discord access reset. New users can send /start in a DM to begin pairing again.', channelId);
- return true;
- }
-
- await channel.send(
- `Unknown Discord command "${action}". Try \`/discord\`, \`/discord pending\`, or \`/discord users\`.`,
- channelId,
- );
- return true;
}
- if (cmd.startsWith('/slack')) {
- if (channelType !== 'cli') {
- await channel.send('`/slack` is only available from the Mercury CLI chat.', channelId);
- return true;
+ if (notifications.length > 0) {
+ const channel = this.channels.getNotificationChannel();
+ if (channel) {
+ const msg = notifications.join('\n');
+ try {
+ await channel.send(msg, 'notification');
+ } catch (err) {
+ logger.warn({ err }, 'Failed to send heartbeat notification');
+ }
}
+ }
+ }
- const config = ctx.config();
- const rawSubcommand = trimmed.slice('/slack'.length).trim();
- const parts = rawSubcommand.split(/\s+/).filter(Boolean);
- const action = parts[0]?.toLowerCase() || 'help';
- const formatSlackUser = (user: {
- userId: string;
- userName?: string;
- displayName?: string;
- pairingCode?: string;
- }) => {
- const userName = user.userName ? ` (@${user.userName})` : '';
- const displayName = user.displayName ? ` ${user.displayName}` : '';
- const pairingCode = user.pairingCode ? ` [code: ${user.pairingCode}]` : '';
- return `${user.userId}${userName}${displayName}${pairingCode}`;
- };
-
- const sendSlackOverview = async () => {
- const lines = [
- '**Slack Management**',
- '',
- `Access: ${getSlackAccessSummary(config)}`,
- `Admins: ${config.channels.slack.admins.length > 0 ? config.channels.slack.admins.map(formatSlackUser).join(', ') : 'none'}`,
- `Members: ${config.channels.slack.members.length > 0 ? config.channels.slack.members.map(formatSlackUser).join(', ') : 'none'}`,
- `Pending: ${config.channels.slack.pending.length > 0 ? config.channels.slack.pending.map(formatSlackUser).join(', ') : 'none'}`,
- '',
- 'Commands:',
- '\u2022 `/slack pending`',
- '\u2022 `/slack users`',
- '\u2022 `/slack approve <pairing-code|user-id>`',
- '\u2022 `/slack reject <user-id>`',
- '\u2022 `/slack remove <user-id>`',
- '\u2022 `/slack reset`',
- ];
- await channel.send(lines.join('\n'), channelId);
- };
+ private async extractMemory(userMessage: string, agentResponse: string): Promise<void> {
+ if (!this.userMemory) return;
+ if (this.userMemory.isLearningPaused()) return;
- if (action === 'help' || action === 'status') {
- await sendSlackOverview();
- return true;
- }
+ const trivial = /^(hi|hello|hey|thanks|thank you|ok|okay|yes|no|bye|goodbye|good morning|good evening)\b/i;
+ if (trivial.test(userMessage.trim())) return;
- if (action === 'pending') {
- const pending = config.channels.slack.pending;
- const lines = [
- '**Slack Pending Requests**',
- '',
- pending.length > 0 ? pending.map(formatSlackUser).join('\n') : 'No pending Slack requests.',
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
+ if (!this.tokenBudget.canAfford(800)) return;
- if (action === 'users') {
- const lines = [
- '**Slack Approved Users**',
- '',
- `Admins: ${config.channels.slack.admins.length > 0 ? config.channels.slack.admins.map(formatSlackUser).join(', ') : 'none'}`,
- `Members: ${config.channels.slack.members.length > 0 ? config.channels.slack.members.map(formatSlackUser).join(', ') : 'none'}`,
- '',
- `Total approved: ${config.channels.slack.admins.length + config.channels.slack.members.length}`,
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
+ try {
+ const provider = this.providers.getDefault();
+ const result = await generateText({
+ model: provider.getModelInstance(),
+ system: `You extract structured memory from conversations. Output a JSON array of 0-3 memory candidates.
- if (action === 'approve') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/slack approve <pairing-code|user-id>`', channelId);
- return true;
- }
+Each candidate: { type, categories, summary (concise fact, 12-220 chars), detail (optional explanation), evidenceKind ("direct" if explicitly stated, "inferred" if deduced), confidence (0-1), importance (0-1), durability (0-1) }
- let approved = approveSlackPendingRequestByPairingCode(config, value);
- let resultLabel = value;
+TYPE DEFINITIONS (pick the single most specific one):
+- identity: who the user IS — their name, role, job title, self-description
+- relationship: other people the user knows — MUST include the person's name in summary
+- preference: likes, dislikes, style choices, opinions
+- goal: aspirations, targets, things they want to achieve
+- project: specific ongoing work, initiatives, things being built
+- habit: routines, recurring behaviors, schedules
+- decision: choices made, commitments, selected approaches
+- constraint: limitations, rules they follow, things they avoid
+- episode: notable one-time events worth remembering
- if (!approved) {
- approved = approveSlackPendingRequest(config, value, 'member');
- resultLabel = value;
- }
+CATEGORIES (pick 1-3 domain buckets that best fit this memory):
+- personal: the user's private life, non-work
+- health: medical, physical, mental wellbeing
+- family: family members, family relationships
+- work: job, professional, career
+- finance: money, spending, investments
+- technical: programming, tools, engineering
+- education: learning, study, courses
+- social: friends, social life, community
+- travel: trips, places, geography
+- general: anything that doesn't fit the above
- if (!approved) {
- await channel.send(`No pending Slack request found for \`${resultLabel}\`.`, channelId);
- return true;
- }
+RULES:
+- Each semantic fact must appear EXACTLY ONCE. Never store the same information under multiple types.
+- If a fact is about someone else's role/relationship to the user, use "relationship" (not "identity").
+- "identity" is ONLY for the user themselves.
+- For relationships, always name the person: "Salman is user's co-developer" not "User works with a co-developer".
+- Only extract specific, durable, user-specific information.
+- Do NOT extract trivial observations, greetings, or assistant behavior.
+- "categories" must be an array of 1-3 lowercase strings from the list above. If none fit, suggest a new single-word lowercase category.
+- Output pure JSON array, no markdown fences.`,
+ messages: [
+ { role: 'user', content: `User: ${userMessage}\nAssistant: ${agentResponse}` },
+ ],
+ maxOutputTokens: 400,
+ });
- saveConfig(config);
- await channel.send(`Approved Slack user ${formatSlackUser(approved)}.`, channelId);
- return true;
- }
+ this.tokenBudget.recordUsage({
+ provider: provider.name,
+ model: provider.getModel(),
+ inputTokens: result.usage?.inputTokens ?? 0,
+ outputTokens: result.usage?.outputTokens ?? 0,
+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),
+ channelType: 'internal',
+ agentId: this.config.cloud.agentId || undefined,
+ });
+ this.syncTokenInfoToCli();
- if (action === 'reject') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/slack reject <user-id>`', channelId);
- return true;
- }
+ const text = result.text.trim();
+ if (!text) return;
- const rejected = rejectSlackPendingRequestConfig(config, value);
- if (!rejected) {
- await channel.send(`No pending Slack request found for \`${value}\`.`, channelId);
- return true;
- }
+ let candidates: Array<{
+ type: string;
+ categories?: string[];
+ summary: string;
+ detail?: string;
+ evidenceKind?: string;
+ confidence: number;
+ importance: number;
+ durability: number;
+ }>;
- saveConfig(config);
- await channel.send(`Rejected Slack request for ${formatSlackUser(rejected)}.`, channelId);
- return true;
+ try {
+ const jsonStr = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
+ const parsed = JSON.parse(jsonStr);
+ // Handle both single object and array of objects
+ candidates = Array.isArray(parsed) ? parsed : [parsed];
+ } catch {
+ const facts = text
+ .split('\n')
+ .map(l => l.replace(/^-\s*/, '').trim())
+ // Skip JSON-like lines (key-value pairs, braces, brackets)
+ .filter(f => f.length > 10 && f.length < 200 && !/^["{\[\]}]|":\s*"/.test(f));
+ candidates = facts.slice(0, 3).map(f => ({
+ type: 'preference',
+ categories: ['general'],
+ summary: f,
+ confidence: 0.75,
+ importance: 0.7,
+ durability: 0.7,
+ evidenceKind: 'inferred',
+ }));
}
- if (action === 'remove') {
- const value = parts[1];
- if (!value) {
- await channel.send('Usage: `/slack remove <user-id>`', channelId);
- return true;
- }
+ const validTypes = ['identity', 'preference', 'goal', 'project', 'habit', 'decision', 'constraint', 'relationship', 'episode'];
+ const typed = candidates
+ .filter(c => c.summary && c.summary.length >= 12 && c.summary.length <= 220)
+ .filter(c => validTypes.includes(c.type))
+ .map(c => {
+ // Normalise categories: must be array of strings, 1-3, lowercase, trimmed.
+ let cats: string[] = ['general'];
+ if (Array.isArray(c.categories) && c.categories.length > 0) {
+ const cleaned = c.categories
+ .map((cat: unknown) => String(cat).trim().toLowerCase())
+ .filter((cat: string) => cat.length > 0)
+ .slice(0, 3);
+ if (cleaned.length > 0) cats = cleaned;
+ }
+ return {
+ type: c.type as any,
+ categories: cats,
+ summary: c.summary,
+ detail: c.detail,
+ evidenceKind: (c.evidenceKind === 'direct' ? 'direct' : 'inferred') as 'direct' | 'inferred',
+ confidence: Math.min(1, Math.max(0, c.confidence ?? 0.7)),
+ importance: Math.min(1, Math.max(0, c.importance ?? 0.7)),
+ durability: Math.min(1, Math.max(0, c.durability ?? 0.7)),
+ };
+ });
- const removed = removeSlackUser(config, value);
- if (!removed) {
- await channel.send(`No approved Slack user found for \`${value}\`.`, channelId);
- return true;
+ if (typed.length > 0) {
+ const remembered = this.userMemory.remember(typed, 'conversation');
+ if (remembered.length > 0) {
+ logger.info({ count: remembered.length, types: remembered.map(r => r.type) }, 'Second brain memories stored');
}
-
- saveConfig(config);
- await channel.send(`Removed Slack access for ${formatSlackUser(removed)}.`, channelId);
- return true;
- }
-
- if (action === 'reset' || action === 'unpair') {
- clearSlackAccess(config);
- saveConfig(config);
- await channel.send('Slack access reset. New users can send /mercury start in a DM to begin pairing again.', channelId);
- return true;
}
-
- await channel.send(
- `Unknown Slack command "${action}". Try \`/slack\`, \`/slack pending\`, or \`/slack users\`.`,
- channelId,
- );
- return true;
- }
-
- if ((cmd === '/' || cmd === '/menu') && channelType === 'cli' && channel instanceof CLIChannel) {
- await this.openCliCommandMenu(channel, channelId);
- return true;
+ } catch (err) {
+ logger.warn({ err }, 'Memory extraction error');
}
+ }
- if (cmd === '/tools') {
- const tools = ctx.toolNames();
- const grouped = [
- `**${tools.length} tools loaded:**`,
- '',
- ...tools.sort().map(t => `• \`${t}\``),
- ];
- await channel.send(grouped.join('\n'), channelId);
- return true;
+ /**
+ * Mark all queued/running work as user-cancelled (terminal state).
+ * Used by deliberate-stop paths (TUI Ctrl+C, /exit, SIGTERM) so the
+ * next start does not auto-resume killed tasks. Crash recovery is
+ * unaffected — this is only invoked on intentional exits.
+ */
+ cancelActiveWork(reason = 'Cancelled by the user.'): number {
+ try {
+ return this.workLedger.cancelActive(reason);
+ } catch (error) {
+ logger.warn({ error }, 'Failed to cancel active work');
+ return 0;
}
+ }
- if (cmd === '/skills' || cmd.startsWith('/skills ')) {
- await this.handleSkillsSlashCommand(trimmed, channel, channelId, ctx);
- return true;
+ async shutdown(): Promise<void> {
+ // Deliberate shutdown: never resume this work on restart.
+ try { this.workLedger.cancelActive('Mercury was shut down.'); } catch { /* best effort */ }
+ if (this.supervisor) {
+ await this.supervisor.haltAll();
}
+ this.backgroundTasks.destroy();
+ this.providers.destroy();
+ await this.sleep();
+ logger.info('Mercury has shut down');
+ }
- if (cmd.startsWith('/code')) {
- const rawArgs = trimmed.slice('/code'.length).trim().toLowerCase();
- const cliChannel = channelType === 'cli' && channel instanceof CLIChannel ? channel : null;
-
- if (!rawArgs) {
- if (cliChannel) {
- const cwd = this.capabilities.getCwd();
- const entered = cliChannel.enterMercuryCode(cwd, cliChannel.getTuiState().version || 'dev');
- if (entered.ok) {
- // Keep the agent-side ProgrammingMode in sync with the TUI:
- // AUTO is the default Mercury Code flow (plan and build in one
- // pass). setProgrammingStatus pushes it to the TUI — the stale
- // 'plan' here was overriding the TUI's AUTO in the status bar.
- this.programmingMode.setAuto();
- this.programmingMode.setProjectContext(cwd);
- cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());
- // Plain message, not a heartbeat: entering /code starts no task,
- // so the TUI must not flip into a perpetual "Analyzing" spinner.
- // channel.send() also clears any stale heartbeat + isThinking.
- await channel.send('Mercury Code active (AUTO). Describe the change — I will plan and build in one flow, confirming with you only before large or consequential changes.', channelId);
- return true;
- }
- await channel.send(entered.message, channelId);
- return true;
- }
- await channel.send(this.programmingMode.getStatusText(), channelId);
- return true;
- }
-
- if (rawArgs === 'exit' || rawArgs === 'quit') {
- if (cliChannel && cliChannel.getTuiState().mercuryCode) {
- // Arm the inline confirmation; the TUI resolves it (Esc cancels,
- // Enter/`y` confirms, Ctrl+D force-quits without asking).
- cliChannel.setMercuryCodeExitConfirm(true);
- return true;
- }
- 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;
- }
-
- 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 === 'auto') {
- this.programmingMode.setAuto();
- if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());
- await channel.send('Programming mode: **Auto**\nI plan and build in one flow — reading first, implementing immediately, and asking for confirmation only before large or consequential changes. Use `/code off` to exit.', channelId);
- return true;
- }
+ /**
+ * Notify all active channels with a message. Used before forced exits
+ * (SIGTERM, crash, watchdog kill) so the user is never left wondering
+ * what happened to their task.
+ */
+ async notifyAllChannels(message: string): Promise<void> {
+ const active = this.channels.getActiveChannels();
+ const sends = active.map((type) => {
+ const ch = this.channels.get(type);
+ if (!ch) return Promise.resolve();
+ return ch.send(message).catch((e) => {
+ logger.warn({ e, channel: type }, 'Failed to notify channel before exit');
+ });
+ });
+ await Promise.allSettled(sends);
+ }
- 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` or `/code auto` to switch to execution.', channelId);
- return true;
- }
+ /**
+ * AI self-check: ask the model itself whether repeated tool usage is productive or a loop.
+ * Used in allow-all mode instead of prompting the user.
+ * Returns true if the AI thinks it should continue, false if it should stop.
+ */
+ private async aiSelfCheck(context: {
+ toolName: string;
+ callCount: number;
+ recentCalls: string[];
+ taskDescription: string;
+ }): Promise<boolean> {
+ try {
+ const provider = this.providers.getDefault();
+ if (!provider) return true; // no provider = let it continue
- 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;
- }
+ const selfCheckResult = await generateText({
+ model: provider.getModelInstance(),
+ system: `You are Mercury Autopilot, a monitoring system inside an AI coding agent. Your job is to determine whether repeated tool usage is productive iteration or a stuck loop.
- 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;
- }
+Productive patterns (CONTINUE):
+- Fetching multiple different URLs (e.g., scraping articles, reading docs)
+- Reading multiple different files to understand a codebase
+- Editing different sections of code across files
+- Running different commands (build, test, lint, deploy)
+- Creating multiple files for a project
- if (rawArgs.startsWith('agent ') || rawArgs.startsWith('delegate ')) {
- if (!this.supervisor) {
- await channel.send('Sub-agents are not enabled in this environment.', channelId);
- return true;
- }
- const taskDescription = rawArgs.replace(/^(agent|delegate)\s+/, '').trim();
- if (!taskDescription) {
- await channel.send('Usage: `/code agent <task>`', channelId);
- return true;
- }
- const cwd = this.capabilities.getCwd();
- const agentId = await this.supervisor.spawn({
- task: taskDescription,
- sourceChannelId: channelId,
- sourceChannelType: channelType as any,
- workingDirectory: cwd,
- });
- const bgId = this.backgroundTasks.spawnAgent(taskDescription, cwd, agentId);
- this.syncBgTasksToTui();
- await channel.send(`Started coding sub-agent ${agentId} in background task ${bgId}. Use /bg ${bgId} for progress.`, channelId);
- return true;
- }
+Stuck patterns (STOP):
+- Same exact call repeated with identical parameters
+- Retrying the same failing operation with minor variations
+- Reading the same file over and over
+- Running the same failing command repeatedly
- if (rawArgs === 'off') {
- this.programmingMode.setOff();
- if (cliChannel) {
- if (cliChannel.getTuiState().mercuryCode) cliChannel.exitMercuryCode();
- cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());
- }
- await channel.send('Programming mode: **Off**\nBack to normal conversation mode.', channelId);
- return true;
- }
+Respond with ONLY "CONTINUE" or "STOP" followed by a one-line reason.`,
+ messages: [{
+ role: 'user',
+ content: `Tool "${context.toolName}" called ${context.callCount} times consecutively.
- if (rawArgs === 'toggle') {
- const newState = this.programmingMode.toggle();
- const labels: Record<string, string> = { off: 'Off', auto: 'Auto', plan: 'Plan', execute: 'Execute' };
- if (cliChannel) cliChannel.setProgrammingStatus(this.programmingMode.getState(), this.programmingMode.getProjectContext());
- await channel.send(`Programming mode: **${labels[newState]}**`, channelId);
- return true;
- }
+User's task: ${context.taskDescription}
- if (rawArgs === 'init') {
- // Ask the agent itself to write/maintain AGENTS.md for this repo.
- await channel.send('Scanning the repository and writing AGENTS.md...', channelId);
- await this.processInternalPrompt(
- 'You are in Mercury Code (/code). Create or refresh the repo-level AGENTS.md in the current working directory. ' +
- 'Read the repo structure: package manifests, build config, CI, test setup, directory layout. ' +
- 'AGENTS.md must contain ONLY durable, verified facts you confirmed by reading files: build/test/lint commands, ' +
- 'project layout, code conventions you actually observed, entry points. Keep it under 40 lines. ' +
- 'If AGENTS.md already exists, merge-preserving accurate human edits and fixing stale commands.',
- channelId,
- channelType,
- );
- return true;
- }
+Recent calls (newest last):
+${context.recentCalls.join('\n')}
- if (rawArgs === 'diff') {
- const cwd = this.capabilities.getCwd();
- try {
- const { execFileSync } = await import('node:child_process');
- const diff = execFileSync('git', ['--no-pager', 'diff', '--no-color', 'HEAD'], { cwd, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024 });
- const trimmedDiff = diff.length > 20000 ? diff.slice(-20000) : diff;
- if (!trimmedDiff.trim()) {
- await channel.send('Working tree is clean — no unstaged/staged changes vs HEAD.', channelId);
- } else {
- await channel.send('```\n' + trimmedDiff + '\n```', channelId);
- }
- } catch (err: any) {
- await channel.send(`git diff failed: ${err?.message || String(err)}`, channelId);
- }
- return true;
- }
+Is this productive iteration or a stuck loop?`,
+ }],
+ maxOutputTokens: 80,
+ });
- await channel.send('Unknown /code command. Available: /code, /code plan, /code execute, /code build, /code init, /code diff, /code expand, /code workspace, /code agent <task>, /code off, /code toggle, /code exit', channelId);
- return true;
+ const answer = (selfCheckResult.text || '').trim().toUpperCase();
+ const shouldContinue = answer.startsWith('CONTINUE');
+ logger.info({
+ toolName: context.toolName,
+ count: context.callCount,
+ decision: shouldContinue ? 'continue' : 'stop',
+ reason: selfCheckResult.text?.trim().slice(0, 120),
+ }, 'Mercury Autopilot verdict');
+ return shouldContinue;
+ } catch (err) {
+ logger.warn({ err }, 'Mercury Autopilot self-check failed — defaulting to continue');
+ return true; // on failure, be permissive
}
+ }
- if (cmd.startsWith('/research')) {
- const rawArgs = trimmed.slice('/research'.length).trim();
+ setSpotifyClient(client: SpotifyClient): void {
+ this.spotifyClient = client;
+ }
- if (!rawArgs || rawArgs.toLowerCase() === 'status') {
- await channel.send(this.researchMode.getStatusText(), channelId);
- return true;
- }
+ async presentChoice(question: string, choices: string[], channelId: string, channelType: string): Promise<string> {
+ const channel = this.channels.get(channelType as any);
- if (rawArgs.toLowerCase() === 'on') {
- this.researchMode.setOn();
- await channel.send(
- 'Research mode: **On**\nI will perform deep, multi-source web research and produce a full markdown research article. Long tasks are expected. Use `/research off` to exit.',
- channelId,
- );
- return true;
- }
+ if (channelType === 'cli' && channel instanceof CLIChannel) {
+ const options = choices.map((label, i) => ({
+ value: String(i),
+ label,
+ }));
- if (rawArgs.toLowerCase() === 'off') {
- this.researchMode.setOff();
- await channel.send('Research mode: **Off**\nBack to normal conversation mode.', channelId);
- return true;
- }
+ const selected = await channel.presentChoicePrompt(question, options);
+ const index = parseInt(selected, 10);
+ return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
+ }
- if (rawArgs.toLowerCase() === 'toggle') {
- const newState = this.researchMode.toggle();
- await channel.send(`Research mode: **${newState === 'on' ? 'On' : 'Off'}**`, channelId);
- return true;
- }
+ if (channelType === 'web' && channel instanceof WebChannel) {
+ const options = choices.map((label, i) => ({
+ value: String(i),
+ label,
+ }));
- // Treat remaining args as a topic + enable research mode
- this.researchMode.setOn(rawArgs);
- if (channel instanceof WebChannel) {
- channel.sendHeartbeat(`Research mode: On. Topic: ${rawArgs}. I will gather live sources and produce a full research article.`, channelId);
- } else {
- await channel.send(
- `Research mode: **On**\nTopic: ${rawArgs}\nI will gather live sources and produce a full research article. Use \`/research off\` to exit.`,
- channelId,
- );
- }
- // Enqueue the topic as a real user message so the agent immediately
- // begins researching it, rather than only setting mode + topic and
- // waiting for the user to repeat themselves.
- const researchTopicMsg: ChannelMessage = {
- id: `research-${Date.now().toString(36)}`,
- channelId,
- channelType: channelType as ChannelType,
- senderId: 'user',
- senderName: 'You',
- content: rawArgs,
- timestamp: Date.now(),
- };
- this.enqueueMessage(researchTopicMsg);
- return true;
+ const selected = await channel.presentChoicePrompt(question, options, channelId);
+ const index = parseInt(selected, 10);
+ return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
}
- 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;
- }
+ if (channelType === 'telegram' && channel instanceof TelegramChannel) {
+ const options = choices.map((label, i) => ({
+ value: String(i),
+ label,
+ }));
- const base = cmd.startsWith('/workspace') ? '/workspace' : '/ws';
- const rawArgs = trimmed.slice(base.length).trim();
- const rawLower = rawArgs.toLowerCase();
+ const selected = await channel.presentChoicePrompt(question, options, channelId);
+ const index = parseInt(selected, 10);
+ return isNaN(index) ? choices[0] : (choices[index] ?? choices[0]);
+ }
- 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;
- }
+ await channel?.send(`${question}\n${choices.map((c, i) => ` ${i + 1}. ${c}`).join('\n')}`, channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
+ return choices[0];
+ }
- 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;
- }
+ private async handleBudgetOverrideCLI(channel: import('../channels/base.js').Channel, msg: ChannelMessage): Promise<void> {
+ const status = this.tokenBudget.getStatusText();
+ await channel.send(
+ `Token budget exceeded! ${status}\n\nChoose an option:\n 1 — Override (allow this one request)\n 2 — Reset usage to zero\n 3 — Set a new daily budget (current: ${this.tokenBudget.getBudget().toLocaleString()})\n 4 — Cancel\n\nOr use /budget override, /budget reset, /budget set <number> anytime.`,
+ msg.channelId,
+ );
+ }
- if (rawLower === 'refresh') {
- cliChannel.refreshWorkspace();
- await channel.send('Workspace refreshed.', channelId);
- return true;
- }
+ async handleBudgetCommand(subcommand: string, channelType: string, channelId: string): Promise<void> {
+ const channel = this.channels.get(channelType as any);
+ if (!channel) return;
- if (rawLower.startsWith('stage ')) {
- const fileArg = rawArgs.slice(6).trim();
- const result = cliChannel.stageWorkspaceFile(fileArg || 'all');
- await channel.send(result.message, channelId);
- return true;
- }
+ const parts = subcommand.trim().split(/\s+/);
+ const action = parts[0]?.toLowerCase();
- if (rawLower.startsWith('commit ')) {
- const message = rawArgs.slice(7).trim();
- const result = cliChannel.commitWorkspace(message);
- await channel.send(result.message, channelId);
- return true;
+ if (action === 'override' || action === '1') {
+ this.tokenBudget.forceAllowNext();
+ await channel.send('Budget override applied — your next request will proceed.', channelId);
+ } else if (action === 'reset' || action === '2') {
+ this.tokenBudget.resetUsage();
+ this.syncTokenInfoToCli();
+ await channel.send(`Usage reset to zero. ${this.tokenBudget.getStatusText()}`, channelId);
+ } else if (action === 'set' || action === '3') {
+ const newBudget = parseInt(parts[1], 10);
+ if (isNaN(newBudget) || newBudget <= 0) {
+ await channel.send('Please specify the new budget. Usage: `/budget set 100000` or type e.g. `3 100000`', channelId);
+ return;
}
+ this.tokenBudget.setBudget(newBudget);
+ this.syncTokenInfoToCli();
+ await channel.send(`Daily budget updated to ${newBudget.toLocaleString()} tokens. ${this.tokenBudget.getStatusText()}`, channelId);
+ } else if (action === 'cancel' || action === '4') {
+ await channel.send(`Cancelled. ${this.tokenBudget.getStatusText()}`, channelId);
+ } else if (!action || action === 'status') {
+ await channel.send(this.tokenBudget.getStatusText(), channelId);
+ } else {
+ await channel.send(`Unknown budget command "${action}". Available: /budget, /budget override, /budget reset, /budget set <number>, /budget status`, channelId);
+ }
+ }
- if (rawLower.startsWith('undo ')) {
- const fileArg = rawArgs.slice(5).trim();
- const result = cliChannel.undoWorkspaceFile(fileArg);
- await channel.send(result.message, channelId);
- return true;
- }
+ /**
+ * Handle the /saver slash command — Token Saver Mode controls.
+ * Subcommands: (empty)|status|on|off|toggle|threshold <n>|auto on|off|routing on|off|stats
+ */
+ async handleSaverCommand(subcommand: string, channelType: string, channelId: string): Promise<void> {
+ return handleSaverCommandImpl(this, subcommand, channelType, channelId);
+ }
- 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;
- }
+ /** Push the current saver state to the CLI status bar if present. */
+ syncSaverToCli(): void {
+ const ch = this.channels.get('cli');
+ if (ch && (ch as any).setSaverMode) {
+ (ch as any).setSaverMode(
+ this.saverMode.getState(),
+ this.tokenBudget.getSavedToday(),
+ this.tokenBudget.getSavedLifetime(),
+ );
+ }
+ }
- await channel.send('Unknown workspace command. Use `/ws help`.', channelId);
- return true;
+ private syncTokenInfoToCli(): void {
+ const ch = this.channels.get('cli');
+ if (ch && (ch as any).setTokenInfo) {
+ (ch as any).setTokenInfo(
+ this.tokenBudget.getDailyUsed(),
+ this.tokenBudget.getBudget(),
+ Math.round(this.tokenBudget.getUsagePercentage()),
+ );
}
+ }
- if (cmd.startsWith('/spotify')) {
- if (!this.spotifyClient) {
- await channel.send('Spotify is not connected. Set SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in your config, then run /spotify auth.', channelId);
- return true;
- }
- const rawArgs = trimmed.slice('/spotify'.length).trim().toLowerCase();
+ async handleSkillsSlashCommand(
+ trimmed: string,
+ channel: any,
+ channelId: string,
+ ctx: { skillNames: () => string[] },
+ ): Promise<void> {
+ const parts = trimmed.split(/\s+/).slice(1);
+ const sub = (parts[0] || 'list').toLowerCase();
+ const args = parts.slice(1);
+ const arg = args.join(' ').trim();
- if (!rawArgs || rawArgs === 'status') {
- const auth = this.spotifyClient.isAuthenticated() ? 'Connected' : 'Not connected';
- const device = this.spotifyClient.getDeviceId() || 'none';
+ const { RegistryClient, isValidSkillId, searchFeed } = await import('../skills/registry.js');
+ const { SkillStore } = await import('../skills/store.js');
+ const registry = new RegistryClient();
+ const store = new SkillStore({ registry });
- let accountName = this.spotifyClient.getAccountName();
- let accountId = this.spotifyClient.getAccountId();
- let product = this.spotifyClient.getProduct();
- let accountError = '';
+ try {
+ switch (sub) {
+ case 'help':
+ case '-h':
+ case '--help': {
+ await channel.send(
+ [
+ '**Mercury Skills — in-chat commands**',
+ '',
+ '`/skills` — list installed skills',
+ '`/skills search <query>` — search the registry',
+ '`/skills view <id>` — show details + registry URL',
+ '`/skills install <id>` — install from the registry',
+ '`/skills install <url>` — install raw SKILL.md from a URL',
+ '`/skills remove <id>` — uninstall',
+ '',
+ 'Browse the full catalog at https://skills.mercuryagent.sh',
+ ].join('\n'),
+ channelId,
+ );
+ return;
+ }
- if (!accountName) {
- try {
- await this.spotifyClient.saveAccountInfo();
- accountName = this.spotifyClient.getAccountName();
- accountId = this.spotifyClient.getAccountId();
- product = this.spotifyClient.getProduct();
- } catch (err: any) {
- accountError = err.message;
- logger.warn({ err: err.message }, 'Failed to fetch Spotify account info');
+ case 'list': {
+ const names = ctx.skillNames();
+ if (names.length === 0) {
+ await channel.send(
+ 'No skills installed. Try `/skills search <query>` to browse https://skills.mercuryagent.sh.',
+ channelId,
+ );
+ return;
}
+ const lines = [
+ `**${names.length} skill${names.length > 1 ? 's' : ''} installed:**`,
+ '',
+ ...names.map((n) => `• ${n}`),
+ '',
+ '_Run `/skills search <query>` to find more on the registry._',
+ ];
+ await channel.send(lines.join('\n'), channelId);
+ return;
}
- let premium = this.spotifyClient.getPremiumStatus();
- if (premium === null) {
- premium = await this.spotifyClient.checkPremium();
+ case 'search':
+ case 'find': {
+ if (!arg) {
+ await channel.send('Usage: `/skills search <query>`', channelId);
+ return;
+ }
+ await channel.send(`🔍 Searching the registry for "${arg}"…`, channelId);
+ const feed = await registry.getFeed();
+ const scored = searchFeed(feed, arg, 5);
+ if (scored.length === 0) {
+ await channel.send(`No matches for "${arg}".`, channelId);
+ return;
+ }
+ const lines = scored.map(({ skill }) =>
+ [
+ `• \`${skill.id}\` (v${skill.version})`,
+ ` ${skill.description}`,
+ ` ${registry.webUrl(skill.id)}`,
+ ].join('\n'),
+ );
+ await channel.send(
+ [
+ `**Top ${scored.length} matches for "${arg}":**`,
+ '',
+ lines.join('\n\n'),
+ '',
+ 'Inspect one with `/skills view <id>`, install with `/skills install <id>`.',
+ ].join('\n'),
+ channelId,
+ );
+ return;
}
- let status = `Spotify: **${auth}**`;
- if (accountName) status += `\nAccount: **${accountName}**`;
- if (accountId) status += `\nUser ID: ${accountId}`;
- if (product) status += `\nPlan: ${product}`;
- if (premium === true) {
- status += ' — all features available';
- } else if (premium === false) {
- status += ' — playback control requires Premium';
+ case 'view':
+ case 'show':
+ case 'info': {
+ if (!arg) {
+ await channel.send('Usage: `/skills view <category/slug>`', channelId);
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
+ return;
+ }
+ const detail = await registry.getSkill(arg);
+ const author = detail.author ? `\n**Author:** ${detail.author}` : '';
+ const tags = detail.tags?.length ? `\n**Tags:** ${detail.tags.join(', ')}` : '';
+ await channel.send(
+ [
+ `**${detail.title}** (\`${detail.id}\`)`,
+ `**Version:** ${detail.version}`,
+ `**Category:** ${detail.category}${author}${tags}`,
+ '',
+ detail.description,
+ '',
+ `🔗 ${registry.webUrl(detail.id)}`,
+ '',
+ `Install with \`/skills install ${detail.id}\``,
+ ].join('\n'),
+ channelId,
+ );
+ return;
}
- if (accountError) status += `\n⚠ Could not verify account: ${accountError}`;
- status += `\nDevice: ${device !== 'none' ? device : 'none selected'}`;
- await channel.send(status, channelId);
- return true;
- }
- if (rawArgs === 'auth') {
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- try {
- const choice = await channel.withMenu(async (select) => {
- return select('Spotify Authorization', [
- { value: 'browser', label: 'Open browser (recommended)' },
- { value: 'manual', label: 'Paste authorization code manually' },
- { value: 'cancel', label: 'Cancel' },
- ]);
- });
- if (!choice || choice === 'cancel') {
- await channel.send('Spotify auth cancelled.', channelId);
- return true;
- }
- if (choice === 'manual') {
- const authUrl = this.spotifyClient.getAuthUrl();
- await channel.send('1. Open this URL in your browser:\n' + authUrl + '\n\n2. After authorizing, you will be redirected to localhost — it may show an error page, that is OK.\n3. Copy the `code` parameter from the URL in your browser address bar.\n4. Paste it below:', channelId);
- const code = await channel.prompt('Authorization code: ');
- if (!code || !code.trim()) {
- await channel.send('No code provided. Auth cancelled.', channelId);
- return true;
- }
- await this.spotifyClient.authenticateWithCode(code.trim());
- await channel.send('Spotify connected successfully! Try: play some music', channelId);
- } else {
- await channel.send('Opening browser for Spotify authorization...', channelId);
- await this.spotifyClient.authenticate();
- await channel.send('Spotify connected successfully! Try: play some music', channelId);
- }
- } catch (err: any) {
- await channel.send(`Spotify auth failed: ${err.message}`, channelId);
+ case 'install':
+ case 'add': {
+ if (!arg) {
+ await channel.send('Usage: `/skills install <category/slug>` or `/skills install <url>`', channelId);
+ return;
}
- } else {
- const authUrl = this.spotifyClient.getAuthUrl();
+ // URL install → delegate to the existing capability path
+ if (/^https?:\/\//i.test(arg)) {
+ const { SkillLoader } = await import('../skills/loader.js');
+ const loader = new SkillLoader();
+ await channel.send(`📦 Installing from \`${arg}\`…`, channelId);
+ const installed = await loader.installFromUrl(arg);
+ await channel.send(
+ `✅ Installed \`${installed.name}\` from URL.\n${installed.skillDir}`,
+ channelId,
+ );
+ return;
+ }
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>` or a `https://` URL.', channelId);
+ return;
+ }
+ await channel.send(`📦 Installing \`${arg}\` from the registry…`, channelId);
+ const result = await store.install(arg);
+ const verb =
+ result.status === 'already-installed'
+ ? 'Already installed'
+ : result.status === 'updated'
+ ? 'Updated'
+ : result.status === 'reinstalled'
+ ? 'Reinstalled'
+ : 'Installed';
await channel.send(
- '**Connect Spotify**\n\n1. Open this URL on any device with a browser:\n' + authUrl + '\n\n2. After authorizing, you will be redirected to localhost — that page may show an error, that is OK.\n3. Copy the `code` from the URL, then type:\n`/spotify code <paste-code-here>`',
- channelId
+ `✅ ${verb} \`${result.id}\` (v${result.version})\n🔗 ${registry.webUrl(result.id)}`,
+ channelId,
);
+ return;
}
- return true;
- }
-
- if (rawArgs.startsWith('code ')) {
- const code = rawArgs.slice('code '.length).trim();
- if (!code) {
- await channel.send('Usage: /spotify code <authorization-code>', channelId);
- return true;
- }
- try {
- await this.spotifyClient.authenticateWithCode(code);
- await channel.send('Spotify connected successfully! Try: play some music', channelId);
- } catch (err: any) {
- await channel.send(`Spotify auth failed: ${err.message}`, channelId);
- }
- return true;
- }
-
- if (rawArgs === 'devices') {
- try {
- const data = await this.spotifyClient.getDevices();
- if (!data?.devices?.length) { await channel.send('No active devices. Open Spotify on a device first.', channelId); return true; }
- const lines = ['**Spotify Devices:**\n'];
- for (const d of data.devices) {
- lines.push(`${d.is_active ? '▶' : '○'} **${d.name}** (${d.type}) — \`${d.id}\`${d.is_active ? ' [active]' : ''}`);
- }
- await channel.send(lines.join('\n'), channelId);
- } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
- return true;
- }
- if (rawArgs.startsWith('device ')) {
- const id = rawArgs.slice('device '.length).trim();
- this.spotifyClient.setDevice(id);
- await channel.send(`Active device set to: ${id}`, channelId);
- return true;
- }
-
- if (rawArgs === 'player' && channelType === 'cli' && channel instanceof CLIChannel) {
- await channel.withMenu(async (select) => {
- while (true) {
- try {
- const np = await this.spotifyClient!.getCurrentlyPlaying();
- if (np) {
- await channel.send(formatNowPlaying(np), channelId);
- }
- } catch {}
- const action = await select('Spotify Player', PLAYER_CONTROLS);
- if (action === 'exit' || !action) return;
- if (action === 'search') {
- const query = await channel.prompt('Search: ');
- if (!query) continue;
- try {
- const results = await this.spotifyClient!.search(query, 'track', 5);
- const tracks = results?.tracks?.items || [];
- if (tracks.length === 0) { await channel.send('No results found.', channelId); continue; }
- const trackOptions = tracks.map((t: any, i: number) => ({
- value: t.uri,
- label: `${t.artists?.map((a: any) => a.name).join(', ')} — ${t.name}`,
- }));
- const picked = await select('Play which track?', [...trackOptions, { value: 'back', label: 'Back' }]);
- if (picked && picked !== 'back') {
- await this.spotifyClient!.play([picked]);
- }
- } catch (err: any) { await channel.send(`Search failed: ${err.message}`, channelId); }
- continue;
- }
- if (action === 'volume') {
- const vol = await channel.prompt('Volume (0-100): ');
- const n = parseInt(vol, 10);
- if (!isNaN(n) && n >= 0 && n <= 100) {
- await this.spotifyClient!.setVolume(n);
- await channel.send(`Volume: ${n}%`, channelId);
- }
- continue;
- }
- if (action === 'queue') {
- const query = await channel.prompt('Search track to queue: ');
- if (!query) continue;
- try {
- const results = await this.spotifyClient!.search(query, 'track', 5);
- const tracks = results?.tracks?.items || [];
- if (tracks.length === 0) { await channel.send('No results.', channelId); continue; }
- const trackOptions = tracks.map((t: any) => ({
- value: t.uri,
- label: `${t.artists?.map((a: any) => a.name).join(', ')} — ${t.name}`,
- }));
- const picked = await select('Queue which track?', [...trackOptions, { value: 'back', label: 'Back' }]);
- if (picked && picked !== 'back') {
- await this.spotifyClient!.addToQueue(picked);
- await channel.send('Added to queue.', channelId);
- }
- } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
- continue;
- }
- try {
- const result = await handlePlayerAction(action, this.spotifyClient!);
- await channel.send(result, channelId);
- } catch (err: any) {
- await channel.send(`Failed: ${err.message}`, channelId);
- }
+ case 'remove':
+ case 'rm':
+ case 'delete':
+ case 'uninstall': {
+ if (!arg) {
+ await channel.send('Usage: `/skills remove <category/slug>`', channelId);
+ return;
}
- });
- return true;
- }
-
- if (rawArgs === 'now' || rawArgs === 'playing' || rawArgs === 'np') {
- try {
- const text = await this.spotifyClient.getNowPlayingText();
- await channel.send(text, channelId);
- } catch (err: any) { await channel.send(`Failed: ${err.message}`, channelId); }
- return true;
- }
-
- if (rawArgs === 'logout') {
- this.spotifyClient.logout();
- await channel.send('Spotify disconnected. Run `/spotify auth` to reconnect.', channelId);
- return true;
- }
-
- await channel.send('Unknown /spotify command. Available: /spotify, /spotify auth, /spotify code <code>, /spotify logout, /spotify player, /spotify devices, /spotify device <id>, /spotify now', channelId);
- return true;
- }
-
- if (cmd === '/stream on') {
- this.telegramStreaming = true;
- await channel.send('Telegram streaming enabled. Responses will appear progressively.', channelId);
- return true;
- }
-
- if (cmd === '/stream off') {
- this.telegramStreaming = false;
- await channel.send('Telegram streaming disabled. Responses will arrive as a single message.', channelId);
- return true;
- }
-
- if (cmd === '/stream') {
- this.telegramStreaming = !this.telegramStreaming;
- await channel.send(
- this.telegramStreaming
- ? 'Telegram streaming enabled. Responses will appear progressively.'
- : 'Telegram streaming disabled. Responses will arrive as a single message.',
- channelId,
- );
- return true;
- }
- if (cmd === '/stream off') {
- this.telegramStreaming = false;
- await channel.send('Telegram streaming disabled. Responses will arrive as a single message.', channelId);
- return true;
- }
-
- if (cmd.startsWith('/agents')) {
- if (!this.supervisor) {
- await channel.send('Sub-agents are not available.', channelId);
- return true;
- }
- const rawArgs = trimmed.slice('/agents'.length).trim();
-
- if (!rawArgs) {
- const agents = this.supervisor.getActiveAgents();
- const resourceInfo = this.supervisor.getResourceUsage();
- if (agents.length === 0) {
- await channel.send(`No active sub-agents.\nMax concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`, channelId);
- return true;
- }
- const statusIcons: Record<string, string> = { pending: '🔵', running: '🟢', paused: '🟡', completed: '✅', failed: '❌', halted: '⛔' };
- const lines = [`**Sub-Agents** (${agents.length})`, ''];
- for (const agent of agents) {
- const icon = statusIcons[agent.status] || '❓';
- const taskPreview = agent.task.length > 40 ? agent.task.slice(0, 40) + '...' : agent.task;
- lines.push(`${icon} **${agent.id}** ${taskPreview}`);
- if (agent.progress) lines.push(` ${agent.progress}`);
- }
- lines.push('');
- lines.push(`Max concurrent: ${resourceInfo.maxConcurrentAgents} (auto) | CPU: ${resourceInfo.cpuCores} cores`);
- lines.push(`Active: ${resourceInfo.activeAgents} | Queued: ${resourceInfo.queuedAgents}`);
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
-
- const parts = rawArgs.split(/\s+/);
- const action = parts[0]?.toLowerCase();
-
- if (action === 'stop') {
- const target = parts[1]?.toLowerCase();
- if (!target) {
- await channel.send('Usage: /agents stop <id> or /agents stop all', channelId);
- return true;
- }
- if (target === 'all') {
- await this.supervisor.haltAll();
- await channel.send('All sub-agents halted. They will finish their current tool step before stopping.', channelId);
- } else {
- const halted = await this.supervisor.halt(target);
- if (!halted) {
- await channel.send(`No active agent found with ID "${target}".`, channelId);
- } else {
- await channel.send(`Agent ${target} halt signal sent. It will finish its current step then stop.`, channelId);
+ if (!isValidSkillId(arg)) {
+ await channel.send('Invalid skill id. Expected `<category>/<slug>`.', channelId);
+ return;
}
+ const removed = store.remove(arg);
+ await channel.send(
+ removed ? `🗑 Removed \`${arg}\`.` : `Skill \`${arg}\` is not installed.`,
+ channelId,
+ );
+ return;
}
- return true;
- }
-
- if (action === 'pause') {
- const target = parts[1]?.toLowerCase();
- if (!target) {
- await channel.send('Usage: /agents pause <id>', channelId);
- return true;
- }
- const paused = await this.supervisor.pause(target);
- await channel.send(paused ? `Agent ${target} paused. Use /agents resume ${target} to continue.` : `No running agent found with ID "${target}".`, channelId);
- return true;
- }
-
- if (action === 'resume') {
- const target = parts[1]?.toLowerCase();
- if (!target) {
- await channel.send('Usage: /agents resume <id>', channelId);
- return true;
- }
- const resumed = await this.supervisor.resume(target);
- await channel.send(resumed ? `Agent ${target} resumed.` : `No paused agent found with ID "${target}".`, channelId);
- return true;
- }
-
- if (action === 'config') {
- const info = this.supervisor.getResourceUsage();
- const lines = [
- '**Sub-Agent Configuration**',
- `CPU cores: ${info.cpuCores}`,
- `System RAM: ${info.systemMemoryMB}MB`,
- `Available RAM: ${info.availableMemoryMB}MB`,
- `Max concurrent: ${info.maxConcurrentAgents}`,
- `Active agents: ${info.activeAgents}`,
- `Queued agents: ${info.queuedAgents}`,
- `Token budget remaining: ${info.tokenBudgetRemaining.toLocaleString()}`,
- ];
- await channel.send(lines.join('\n'), channelId);
- return true;
- }
-
- if (action === 'set' && parts[1]?.toLowerCase() === 'max') {
- const n = parseInt(parts[2], 10);
- if (isNaN(n) || n < 1) {
- await channel.send('Usage: /agents set max <number>', channelId);
- return true;
- }
- this.supervisor.setMaxConcurrent(n);
- await channel.send(`Max concurrent sub-agents set to ${n}.`, channelId);
- return true;
- }
-
- await channel.send(`Unknown /agents command "${action}". Available: /agents, /agents stop <id|all>, /agents pause <id>, /agents resume <id>, /agents config, /agents set max <n>`, channelId);
- return true;
- }
-
- if (cmd === '/halt') {
- if (!this.supervisor) {
- await channel.send('Sub-agents are not available.', channelId);
- return true;
- }
- await this.supervisor.haltAll();
- await channel.send('All sub-agents halted and queue cleared.', channelId);
- return true;
- }
-
- if (cmd === '/stop') {
- if (!this.supervisor) {
- await channel.send('Sub-agents are not available.', channelId);
- return true;
- }
- await this.supervisor.haltAll();
- this.supervisor.clearTaskBoard();
- this.lifecycle.transition('idle');
- await channel.send('All sub-agents stopped, queue cleared, locks released, task board cleared. Short-term memory preserved.', channelId);
- return true;
- }
- if (cmd === '/reset') {
- if (channelType === 'cli' && channel instanceof CLIChannel) {
- const confirmed = await channel.askToContinue(
- '⚠ /reset will halt ALL agents, clear queues, release locks, clear task board, and wipe conversation context. Continue? (y/n)',
- channelId,
- ).catch(() => false);
- if (!confirmed) {
- await channel.send('Reset cancelled.', channelId);
- return true;
- }
- }
- if (this.supervisor) {
- await this.supervisor.haltAll();
- this.supervisor.clearTaskBoard();
+ default:
+ await channel.send(
+ `Unknown subcommand \`${sub}\`. Try \`/skills help\`.`,
+ channelId,
+ );
}
- this.shortTerm.clearAll();
- this.lifecycle.transition('idle');
- await channel.send('Mercury reset. All agents stopped, all state cleared. Long-term memory preserved. Ready for a fresh start.', channelId);
- return true;
+ } catch (err: any) {
+ const msg = err?.message || 'Skill registry request failed';
+ await channel.send(`⚠️ ${msg}`, channelId);
}
+ }
- return false;
+ async handleChatCommand(content: string, channelType: string, channelId: string): Promise<boolean> {
+ return handleChatCommandImpl(this, content, channelType, channelId);
}
/** Render the trace for a turn in this chat's session (latest when no id). */