Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(core): TaskSurface — one feedback contract for every channel; /trace
Salman Qureshi9cc209032916
diff --git a/src/core/agent.ts b/src/core/agent.tsindex 35ac674b..c59a5f46 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -91,6 +91,7 @@ import { verbPoolFor } from '../ui/status-word.js';import { StallWatchdog } from './stall-watchdog.js';import { setProgressPulse } from './progress-pulse.js';import { selectActiveTools } from './tool-exposure.js';+import { createTaskSurface } from './task-surface.js';import { buildFileChangePreview } from '../utils/file-preview.js';import { whatsNewText } from '../utils/whats-new.js';@@ -2819,6 +2820,8 @@ export class Agent {private async handleMessage(msg: ChannelMessage): Promise<void> {this.lifecycle.transition('thinking');const startTime = Date.now();+ // Short id printed on every terminal message and resolvable with /trace.+ const traceId = (msg.id || '').replace(/[^a-z0-9]/gi, '').slice(-8) || Date.now().toString(36);let loopAbortController = new AbortController();this.currentMessage = msg;this.currentAbort = loopAbortController;@@ -3416,27 +3419,12 @@ export class Agent {const canStream = msg.channelType === 'cli' || msg.channelType === 'web' || (msg.channelType === 'telegram' && this.telegramStreaming) || msg.channelType === 'signal' || (msg.channelType === 'discord' && this.config.channels.discord.streaming) || (msg.channelType === 'slack' && this.config.channels.slack.streaming);- const tgChannel = this.channels.get('telegram');- if (msg.channelType === 'telegram' && tgChannel) {- (tgChannel as TelegramChannel).resetStepCounter(msg.channelId);- (tgChannel as TelegramChannel).beginTask(msg.channelId);- }-- const sigChannel = this.channels.get('signal');- if (msg.channelType === 'signal' && sigChannel) {- (sigChannel as SignalChannel).resetStepCounter(msg.channelId);- (sigChannel as SignalChannel).beginTask(msg.channelId);- }-- const dcChannel = this.channels.get('discord');- if (msg.channelType === 'discord' && dcChannel) {- (dcChannel as DiscordChannel).beginTask(msg.channelId);- }-- const slChannel = this.channels.get('slack');- if (msg.channelType === 'slack' && slChannel) {- (slChannel as SlackChannel).beginTask(msg.channelId);- }+ // One feedback contract for every channel (see core/task-surface.ts):+ // begin → steps → done-with-evidence | pause | fail. The per-channel+ // if/else chains that used to live here drifted apart; now channels+ // render and the agent decides.+ const surface = createTaskSurface(channel, msg.channelType, msg.channelId);+ surface.begin();// Saver-mode-aware request limits. When saver is off these resolve to// the original constants (byte-identical to pre-saver behavior).@@ -4472,22 +4460,9 @@ export class Agent {}if (this.currentWorkKey) this.workLedger.markFailed(this.currentWorkKey, errMsg, errMsg);if (channel && msg.channelType !== 'internal') {- // End task before sending error so it goes through as a normal message- if (channel instanceof TelegramChannel) {- (channel as TelegramChannel).endTask(msg.channelId);- (channel as TelegramChannel).resetStepCounter(msg.channelId);- } else if (channel instanceof SignalChannel) {- (channel as SignalChannel).endTask(msg.channelId);- (channel as SignalChannel).resetStepCounter(msg.channelId);- } else if (channel instanceof DiscordChannel) {- (channel as DiscordChannel).endTask(msg.channelId);- (channel as DiscordChannel).resetStepCounter(msg.channelId);- } else if (channel instanceof SlackChannel) {- (channel as SlackChannel).endTask(msg.channelId);- (channel as SlackChannel).resetStepCounter(msg.channelId);- }- const delivered = channel instanceof WebChannel ? channel.sendError(errMsg, msg.channelId) : true;- if (!(channel instanceof WebChannel)) await channel.send(errMsg, msg.channelId);+ // Failure is a persistent message with the reason (TaskSurface.fail+ // ends the task first so it is never a status-card notice).+ const delivered = await surface.fail(`${errMsg}\n\n_/trace ${traceId}_`);const awaitsCloudAck = msg.channelType === 'web'&& typeof msg.metadata?.externalConversationId === 'string'&& typeof msg.metadata?.requestId === 'string';@@ -4892,27 +4867,8 @@ export class Agent {this.workLedger.markPaused(this.currentWorkKey, reason);}if (channel && msg.channelType !== 'internal') {- // End the task FIRST so the banner is delivered as a normal,- // persistent message. While a task is active the messaging- // channels route short sends into the status card (truncated to- // ~80 chars) and then delete the card on finalize — which made a- // pause look like the bot simply went silent. Flush any deferred- // streamed text too, so the user sees what was produced.- let deferred: string | undefined;- if (- channel instanceof TelegramChannel- || channel instanceof SignalChannel- || channel instanceof DiscordChannel- || channel instanceof SlackChannel- ) {- channel.endTask(msg.channelId);- channel.resetStepCounter(msg.channelId);- deferred = channel.popDeferredResponse(msg.channelId);- }- if (deferred && deferred.trim()) {- await channel.send(deferred, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));- }- await channel.send(banner, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));+ // 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');@@ -5048,6 +5004,14 @@ export class Agent {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) {@@ -5079,146 +5043,36 @@ export class Agent {if (channel && msg.channelType !== 'internal') {const elapsed = Date.now() - startTime;const stepCount = this.completedStepCount;-- // Send completion banner only for substantial tasks (3+ steps AND >30s)- // Simple responses (greetings, quick answers) don't need a banner- const isSubstantialTask = stepCount >= 3 && elapsed >= 30_000;- if (isSubstantialTask && channel instanceof TelegramChannel) {- // For substantial Telegram tasks: sendCompletion handles endTask + deferred flush + cleanup.- // Always queue the final answer explicitly; streaming normally already- // defers it, but non-streamed/fallback responses must not be dropped.- if (finalText && finalText.trim()) {- (channel as TelegramChannel).deferResponse(msg.channelId, finalText);- }- 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(),- };- await (channel as TelegramChannel).sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);- } else if (channel instanceof TelegramChannel) {- // For non-substantial Telegram tasks: end task, flush deferred, clean up- (channel as TelegramChannel).endTask(msg.channelId);- // Flush deferred response- const deferred = (channel as TelegramChannel).popDeferredResponse(msg.channelId);- const responseText = deferred || finalText;- if (responseText && responseText.trim()) {- await channel.send(responseText, msg.channelId, elapsed);- }- if (stepCount > 0) {- await (channel as TelegramChannel).cleanupEphemeralMessages(msg.channelId);- (channel as TelegramChannel).resetStepCounter(msg.channelId);- }- this.markProgress();- } else if (channel instanceof SignalChannel) {- // For Signal tasks: end task, flush deferred, send completion banner for substantial tasks- const sigCh = channel as SignalChannel;- if (isSubstantialTask) {- await sigCh.stream((async function* () { yield finalText; })(), msg.channelId);- 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(),- };- await sigCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);- } else {- sigCh.endTask(msg.channelId);- const deferred = sigCh.popDeferredResponse(msg.channelId);- const responseText = deferred || finalText;- if (responseText && responseText.trim()) {- await channel.send(responseText, msg.channelId, elapsed);- }- sigCh.resetStepCounter(msg.channelId);- this.markProgress();- }- } else if (channel instanceof DiscordChannel) {- const dcCh = channel as DiscordChannel;- if (isSubstantialTask) {- await dcCh.stream((async function* () { yield finalText; })(), msg.channelId);- 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(),- };- await dcCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);- } else {- dcCh.endTask(msg.channelId);- const deferred = dcCh.popDeferredResponse(msg.channelId);- const responseText = deferred || finalText;- if (responseText && responseText.trim()) {- await channel.send(responseText, msg.channelId, elapsed);- }- dcCh.resetStepCounter(msg.channelId);- this.markProgress();- }- } else if (channel instanceof SlackChannel) {- const slCh = channel as SlackChannel;- if (isSubstantialTask) {- await slCh.stream((async function* () { yield finalText; })(), msg.channelId);- 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(),- };- await slCh.sendCompletion(elapsed, stepCount, msg.channelId, completionMeta);- } else {- slCh.endTask(msg.channelId);- const deferred = slCh.popDeferredResponse(msg.channelId);- const responseText = deferred || finalText;- if (responseText && responseText.trim()) {- await channel.send(responseText, msg.channelId, elapsed);- }- slCh.resetStepCounter(msg.channelId);- this.markProgress();- }- } else {- // CLI or other channels — original flow- logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending durable response');- if (requiresFinalSend(msg.channelType, cliResponseStreamed)) {- await channel.send(finalText, msg.channelId, elapsed);- }- this.markProgress();- const isMercuryCodeExecution = channel instanceof CLIChannel- && channel.getTuiState().mode === 'mercury-code'- && (channel.getTuiState().programmingMode === 'execute' || channel.getTuiState().programmingMode === 'auto');- if ((isSubstantialTask || isMercuryCodeExecution) && channel instanceof CLIChannel) {- 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(),- };- (channel as CLIChannel).sendCompletion(elapsed, stepCount, completionMeta, undefined, lastVerificationNote || undefined);- }- }+ 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';@@ -6223,6 +6077,13 @@ Is this productive iteration or a stuck loop?`,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);@@ -7754,6 +7615,35 @@ Is this productive iteration or a stuck loop?`,return false;}+ /** Render the trace for a turn in this chat's session (latest when no id). */+ renderTrace(channelType: ChannelType, channelId: string, idArg = ''): string {+ const bindingId = channelType === 'cli' ? 'current' : channelId;+ const session = this.sessions.getByBinding(channelType, bindingId);+ if (!session) return 'No session is bound to this chat yet.';+ const turns = session.messages.filter((m) => m.role === 'assistant' && m.kind === 'message');+ const wanted = idArg.toLowerCase();+ const target = wanted+ ? [...turns].reverse().find((m) => String((m.metadata as Record<string, unknown> | undefined)?.traceId ?? '').toLowerCase().startsWith(wanted))+ : turns.at(-1);+ if (!target) return wanted ? `No turn found for trace "${idArg}".` : 'No turns in this session yet.';+ const meta = (target.metadata ?? {}) as Record<string, unknown>;+ const baseId = (target.externalMessageId ?? '').replace(/:assistant$/, '');+ const toolEntry = baseId+ ? session.messages.find((m) => m.kind === TOOL_TRACE_KIND && m.externalMessageId === `${baseId}:tools`)+ : undefined;+ const num = (v: unknown) => (typeof v === 'number' ? v : undefined);+ const elapsed = num(meta.elapsedMs);+ return [+ `Trace ${String(meta.traceId ?? target.id.slice(0, 8))} · ${new Date(target.timestamp).toISOString()}`,+ `Provider: ${String(meta.provider ?? 'unknown')} / ${String(meta.model ?? 'unknown')}`,+ `Tokens: ${num(meta.inputTokens) ?? '?'} in (${num(meta.cachedInputTokens) ?? 0} cached) · ${num(meta.outputTokens) ?? '?'} out`,+ `Steps: ${num(meta.steps) ?? '?'} · Elapsed: ${elapsed != null ? `${(elapsed / 1000).toFixed(1)}s` : '?'}`,+ `Verification: ${typeof meta.verification === 'string' ? meta.verification : 'none'}`,+ '',+ toolEntry ? toolEntry.content : 'No tool calls in this turn.',+ ].join('\n');+ }+private async handleSessionCommand(content: string, channelType: ChannelType, channelId: string): Promise<void> {const channel = this.channels.get(channelType);if (!channel) return;diff --git a/src/core/completion-contract.test.ts b/src/core/completion-contract.test.tsindex 5f95d18e..3ee87540 100644--- a/src/core/completion-contract.test.ts+++ b/src/core/completion-contract.test.ts@@ -86,7 +86,8 @@ describe('completion contract — source guarantees', () => {// The pause verdict must short-circuit BEFORE the completion delivery —// the markPaused return path precedes the first sendCompletion call.const pauseIdx = agent.indexOf("turnEnd() === 'steps-exhausted'");- const deliverIdx = agent.indexOf('sendCompletion(elapsed, stepCount');+ // Delivery now goes through the TaskSurface contract (core/task-surface.ts).+ const deliverIdx = agent.indexOf('surface.done({');expect(pauseIdx).toBeGreaterThan(-1);expect(deliverIdx).toBeGreaterThan(pauseIdx);});@@ -106,7 +107,8 @@ describe('completion contract — source guarantees', () => {expect(agent).toContain('WORK_NOT_STARTED_BANNER');expect(agent).toContain('Narration guard exhausted (both cycles)');const guardExhaustedIdx = agent.indexOf('Narration guard exhausted (both cycles)');- const deliverIdx = agent.indexOf('sendCompletion(elapsed, stepCount');+ // Delivery now goes through the TaskSurface contract (core/task-surface.ts).+ const deliverIdx = agent.indexOf('surface.done({');expect(guardExhaustedIdx).toBeGreaterThan(-1);expect(deliverIdx).toBeGreaterThan(guardExhaustedIdx);});diff --git a/src/core/task-surface.test.ts b/src/core/task-surface.test.tsnew file mode 100644index 00000000..877de4b1--- /dev/null+++ b/src/core/task-surface.test.ts@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from 'vitest';+import { createTaskSurface, evidenceFooter, isSubstantialTask } from './task-surface.js';++const meta = { provider: 'p', model: 'm', inputTokens: 1, outputTokens: 2, totalTokens: 3, budgetUsed: 0, budgetTotal: 100, budgetPercentage: 0 };++function messagingChannel(opts: { deferResponse?: boolean } = {}) {+ const calls: string[] = [];+ const ch: any = {+ type: 'telegram',+ send: vi.fn(async (text: string) => { calls.push(`send:${text}`); }),+ stream: vi.fn(async (it: AsyncIterable<string>) => { let out = ''; for await (const c of it) out += c; calls.push(`stream:${out}`); return out; }),+ beginTask: vi.fn(() => calls.push('beginTask')),+ endTask: vi.fn(() => calls.push('endTask')),+ resetStepCounter: vi.fn(() => calls.push('resetStepCounter')),+ popDeferredResponse: vi.fn(() => undefined),+ sendCompletion: vi.fn(async () => { calls.push('sendCompletion'); }),+ cleanupEphemeralMessages: vi.fn(async () => { calls.push('cleanup'); }),+ };+ if (opts.deferResponse) ch.deferResponse = vi.fn((_id: string, text: string) => calls.push(`defer:${text}`));+ return { ch, calls };+}++describe('TaskSurface (ROADMAP P1.1 feedback contract)', () => {+ it('is a no-op for internal turns and missing channels', async () => {+ const none = createTaskSurface(undefined, 'cli', 'x');+ expect(none.kind).toBe('none');+ await none.done({ finalText: 'x', elapsedMs: 0, stepCount: 0, meta, traceId: 't', alreadyStreamed: false });+ expect(await none.fail('boom')).toBe(false);+ expect(createTaskSurface({ send: vi.fn() } as any, 'internal', 'x').kind).toBe('none');+ });++ it('messaging: begin resets and starts the task; pause ends the task BEFORE sending (persistent message)', async () => {+ const { ch, calls } = messagingChannel();+ ch.popDeferredResponse = vi.fn(() => 'streamed so far');+ const s = createTaskSurface(ch, 'telegram', 'chat1');+ s.begin();+ await s.pause('paused banner');+ expect(calls).toEqual(['resetStepCounter', 'beginTask', 'endTask', 'resetStepCounter', 'send:streamed so far', 'send:paused banner']);+ });++ it('messaging: fail ends the task first and delivers the reason', async () => {+ const { ch, calls } = messagingChannel();+ const s = createTaskSurface(ch, 'discord', 'c');+ expect(await s.fail('All providers failed')).toBe(true);+ expect(calls.slice(0, 2)).toEqual(['endTask', 'resetStepCounter']);+ expect(calls.at(-1)).toBe('send:All providers failed');+ });++ it('messaging: short turns send the text (deferred wins) and clean up; evidence rides in the text', async () => {+ const { ch, calls } = messagingChannel();+ const s = createTaskSurface(ch, 'slack', 'c');+ await s.done({ finalText: 'answer', elapsedMs: 1000, stepCount: 1, meta, verificationNote: 'npm test ✓', traceId: 'abc123', alreadyStreamed: false });+ expect(calls).toEqual(['endTask', 'send:answer\n\n_Verification: npm test ✓ · /trace abc123_', 'cleanup', 'resetStepCounter']);+ });++ it('messaging: substantial turns defer (Telegram) or stream (others) then send the completion banner', async () => {+ const tg = messagingChannel({ deferResponse: true });+ await createTaskSurface(tg.ch, 'telegram', 'c').done({ finalText: 'big', elapsedMs: 60_000, stepCount: 5, meta, traceId: 't1', alreadyStreamed: false });+ expect(tg.calls).toEqual(['defer:big', 'sendCompletion']);++ const sg = messagingChannel();+ await createTaskSurface(sg.ch, 'signal', 'c').done({ finalText: 'big', elapsedMs: 60_000, stepCount: 5, meta, traceId: 't1', alreadyStreamed: false });+ expect(sg.calls).toEqual(['stream:big', 'sendCompletion']);+ });++ it('cli: sends unless already streamed; banner on substantial or forced turns carries verification + trace', async () => {+ const cli: any = { type: 'cli', send: vi.fn(async () => {}), sendCompletion: vi.fn() };+ const s = createTaskSurface(cli, 'cli', 'current');+ await s.done({ finalText: 'streamed', elapsedMs: 100, stepCount: 0, meta, traceId: 't2', alreadyStreamed: true });+ expect(cli.send).not.toHaveBeenCalled();+ expect(cli.sendCompletion).not.toHaveBeenCalled();+ await s.done({ finalText: 'x', elapsedMs: 100, stepCount: 0, meta, verificationNote: 'tsc ✓', traceId: 't2', alreadyStreamed: false, forceBanner: true });+ expect(cli.send).toHaveBeenCalledWith('x', 'current', 100);+ expect(cli.sendCompletion).toHaveBeenCalledWith(100, 0, meta, undefined, 'tsc ✓ · /trace t2');+ });++ it('web: failures go through sendError and report delivery', async () => {+ const web: any = { type: 'web', send: vi.fn(async () => {}), sendError: vi.fn(() => false) };+ expect(await createTaskSurface(web, 'web', 'conv').fail('nope')).toBe(false);+ expect(web.sendError).toHaveBeenCalledWith('nope', 'conv');+ });++ it('helpers', () => {+ expect(isSubstantialTask(3, 30_000)).toBe(true);+ expect(isSubstantialTask(2, 30_000)).toBe(false);+ expect(evidenceFooter(undefined, 'id')).toBe('_/trace id_');+ });+});diff --git a/src/core/task-surface.ts b/src/core/task-surface.tsnew file mode 100644index 00000000..7be458a8--- /dev/null+++ b/src/core/task-surface.ts@@ -0,0 +1,205 @@+/**+ * TaskSurface — the feedback contract, implemented once.+ *+ * Every channel used to get its own copy of "begin task / deliver / pause /+ * fail" inside Agent.handleMessage, and the copies drifted: verification+ * evidence reached the CLI only, pause banners were swallowed by Telegram's+ * status card, and Discord/Slack diverged from Signal. The agent now talks+ * to one surface; channels render, they do not decide.+ *+ * States: begin → (steps, via the channel's own feedback) → done | pause | fail.+ * done carries evidence (verification note, trace id); pause and fail are+ * always persistent messages, never status-card notices.+ */+import type { Channel } from '../channels/base.js';+import type { ChannelType } from '../types/index.js';+import { logger } from '../utils/logger.js';++export interface CompletionMetaLike {+ provider: string;+ model: string;+ inputTokens: number;+ outputTokens: number;+ totalTokens: number;+ budgetUsed: number;+ budgetTotal: number;+ budgetPercentage: number;+}++export interface DoneInput {+ finalText: string;+ elapsedMs: number;+ stepCount: number;+ meta: CompletionMetaLike;+ /** "npm test ✓" style note; shown on every surface, not only the CLI. */+ verificationNote?: string;+ /** Short id resolvable with /trace. */+ traceId: string;+ /** The CLI already streamed the text; do not send it again. */+ alreadyStreamed: boolean;+ /** Show the completion banner even for a short task (Mercury Code execution). */+ forceBanner?: boolean;+}++export interface TaskSurface {+ readonly kind: 'cli' | 'web' | 'messaging' | 'plain' | 'none';+ begin(): void;+ done(input: DoneInput): Promise<void>;+ /** Persistent pause/failure banner; flushes deferred streamed text first. */+ pause(banner: string): Promise<void>;+ /** Returns whether the message was delivered (web may report false). */+ fail(message: string): Promise<boolean>;+}++/** A task is "substantial" when it earns a completion banner. */+export const isSubstantialTask = (stepCount: number, elapsedMs: number): boolean => stepCount >= 3 && elapsedMs >= 30_000;++/** Evidence footer appended to the final text on surfaces without a banner slot. */+export function evidenceFooter(verificationNote: string | undefined, traceId: string): string {+ const parts = [verificationNote ? `Verification: ${verificationNote}` : null, `/trace ${traceId}`].filter(Boolean);+ return `_${parts.join(' · ')}_`;+}++interface MessagingTaskChannel extends Channel {+ beginTask(targetId?: string): void;+ endTask(targetId?: string): void;+ resetStepCounter(targetId?: string): void;+ popDeferredResponse(targetId?: string): string | undefined;+ deferResponse?(targetId: string | undefined, content: string): void;+ cleanupEphemeralMessages?(targetId?: string): Promise<void>;+ sendCompletion(elapsedMs: number, stepCount: number, targetId?: string, meta?: CompletionMetaLike): Promise<void>;+}++interface CliTaskChannel extends Channel {+ sendCompletion(elapsedMs: number, stepCount: number, meta?: CompletionMetaLike, outcome?: 'complete' | 'steps-paused', verificationNote?: string): void;+}++interface WebTaskChannel extends Channel {+ sendError(message: string, targetId?: string): boolean;+}++const hasFn = (obj: unknown, name: string): boolean => typeof (obj as Record<string, unknown> | null)?.[name] === 'function';++function isMessagingTaskChannel(channel: Channel): channel is MessagingTaskChannel {+ return ['beginTask', 'endTask', 'resetStepCounter', 'popDeferredResponse', 'sendCompletion'].every((n) => hasFn(channel, n));+}++const warnSend = (e: unknown) => logger.warn({ e }, 'channel send failed');++export function createTaskSurface(channel: Channel | undefined, channelType: ChannelType, channelId: string): TaskSurface {+ if (!channel || channelType === 'internal') return NONE;++ if (channelType === 'cli') {+ const cli = channel as CliTaskChannel;+ return {+ kind: 'cli',+ begin() {},+ async done({ finalText, elapsedMs, stepCount, meta, verificationNote, traceId, alreadyStreamed, forceBanner }) {+ if (!alreadyStreamed) await cli.send(finalText, channelId, elapsedMs);+ if (isSubstantialTask(stepCount, elapsedMs) || forceBanner) {+ const note = verificationNote ? `${verificationNote} · /trace ${traceId}` : `/trace ${traceId}`;+ cli.sendCompletion(elapsedMs, stepCount, meta, undefined, note);+ }+ },+ async pause(banner) {+ await cli.send(banner, channelId).catch(warnSend);+ },+ async fail(message) {+ await cli.send(message, channelId);+ return true;+ },+ };+ }++ if (channelType === 'web') {+ const web = channel as WebTaskChannel;+ return {+ kind: 'web',+ begin() {},+ async done({ finalText, elapsedMs }) {+ await web.send(finalText, channelId, elapsedMs);+ },+ async pause(banner) {+ await web.send(banner, channelId).catch(warnSend);+ },+ async fail(message) {+ return hasFn(web, 'sendError') ? web.sendError(message, channelId) : (await web.send(message, channelId), true);+ },+ };+ }++ if (isMessagingTaskChannel(channel)) {+ const ch = channel;+ const finish = (): string | undefined => {+ ch.endTask(channelId);+ ch.resetStepCounter(channelId);+ return ch.popDeferredResponse(channelId);+ };+ return {+ kind: 'messaging',+ begin() {+ ch.resetStepCounter(channelId);+ ch.beginTask(channelId);+ },+ async done({ finalText, elapsedMs, stepCount, meta, verificationNote, traceId }) {+ // Evidence used to reach the CLI only; messaging users got "done"+ // with nothing to back it. Carry it in the final text instead.+ const text = verificationNote ? `${finalText}\n\n${evidenceFooter(verificationNote, traceId)}` : finalText;+ if (isSubstantialTask(stepCount, elapsedMs)) {+ // sendCompletion owns endTask + deferred flush + cleanup on these channels.+ if (ch.deferResponse) {+ if (text.trim()) ch.deferResponse(channelId, text);+ } else {+ await ch.stream((async function* () { yield text; })(), channelId);+ }+ await ch.sendCompletion(elapsedMs, stepCount, channelId, meta);+ return;+ }+ ch.endTask(channelId);+ const deferred = ch.popDeferredResponse(channelId);+ const responseText = deferred || text;+ if (responseText && responseText.trim()) await ch.send(responseText, channelId, elapsedMs);+ if (stepCount > 0 && ch.cleanupEphemeralMessages) await ch.cleanupEphemeralMessages(channelId);+ ch.resetStepCounter(channelId);+ },+ async pause(banner) {+ // End the task FIRST: while a task is active these channels route+ // short sends into the status card (truncated) and delete the card+ // on finalize, which made a pause look like silence.+ const deferred = finish();+ if (deferred && deferred.trim()) await ch.send(deferred, channelId).catch(warnSend);+ await ch.send(banner, channelId).catch(warnSend);+ },+ async fail(message) {+ finish();+ await ch.send(message, channelId);+ return true;+ },+ };+ }++ return {+ kind: 'plain',+ begin() {},+ async done({ finalText, elapsedMs }) {+ await channel.send(finalText, channelId, elapsedMs);+ },+ async pause(banner) {+ await channel.send(banner, channelId).catch(warnSend);+ },+ async fail(message) {+ await channel.send(message, channelId);+ return true;+ },+ };+}++const NONE: TaskSurface = {+ kind: 'none',+ begin() {},+ async done() {},+ async pause() {},+ async fail() {+ return false;+ },+};