Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
chore(lint): no new any, control-regex or escape violations; tests stay deterministic
Salman Qureshid59a4350705e
diff --git a/.lint-baseline.json b/.lint-baseline.jsonindex 99f40143..67c77089 100644--- a/.lint-baseline.json+++ b/.lint-baseline.json@@ -1,22 +1,22 @@{"$comment": "ESLint ratchet baseline. Per-rule counts (errors + warnings) may only go down. Refresh with `npm run lint:ratchet -- --update` after a clean-up.","provisional": false,- "generatedAt": "2026-10-15T16:08:14.521Z",+ "generatedAt": "2026-10-29T16:10:10.539Z","target": "src","rules": {"(unknown)": 1,- "@typescript-eslint/no-explicit-any": 1133,+ "@typescript-eslint/no-explicit-any": 1130,"@typescript-eslint/no-require-imports": 6,"@typescript-eslint/no-this-alias": 5,"@typescript-eslint/no-unused-expressions": 100,- "@typescript-eslint/no-unused-vars": 278,+ "@typescript-eslint/no-unused-vars": 276,"no-console": 135,"no-control-regex": 27,"no-func-assign": 5,"no-prototype-builtins": 8,"no-undef": 7,"no-unexpected-multiline": 1,- "no-useless-escape": 5,+ "no-useless-escape": 4,"prefer-const": 4,"react-hooks/exhaustive-deps": 2,"require-yield": 9diff --git a/src/channels/credential-check.ts b/src/channels/credential-check.tsindex 3f40a167..3807d8c4 100644--- a/src/channels/credential-check.ts+++ b/src/channels/credential-check.ts@@ -19,10 +19,13 @@ export interface ChannelCheck {field?: string;}-async function getJson(f: Fetch, url: string, init: RequestInit = {}): Promise<{ status: number; body: any }> {+/** A vendor's JSON answer: read field by field, nothing assumed. */+type VendorJson = Record<string, unknown> | null;++async function getJson(f: Fetch, url: string, init: RequestInit = {}): Promise<{ status: number; body: VendorJson }> {const res = await f(url, { ...init, signal: AbortSignal.timeout(10_000) });- let body: any = null;- try { body = await res.json(); } catch { /* not JSON */ }+ let body: VendorJson = null;+ try { body = (await res.json()) as VendorJson; } catch { /* not JSON */ }return { status: res.status, body };}diff --git a/src/cli/headless-setup.ts b/src/cli/headless-setup.tsindex e9671b4e..5ba7d2fb 100644--- a/src/cli/headless-setup.ts+++ b/src/cli/headless-setup.ts@@ -58,5 +58,6 @@ export function applyHeadlessSetup(config: MercuryConfig, opts: HeadlessSetupOpt}function cleanName(raw: string | undefined): string {+ // eslint-disable-next-line no-control-regex -- strips control characters on purposereturn (raw ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 64);}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 8178c7d7..6e2f2e39 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -2024,25 +2024,30 @@ export class Agent {* user sees which step is being implemented. Never throws.*//** Tell the owner about this turn's artifacts: a card in the apps, a line in the terminal (it can't show them). */- private announceArtifacts(channel: any, items: Artifact[], targetId?: string): void {+ private announceArtifacts(channel: unknown, items: Artifact[], targetId?: string): void {try {if (channel instanceof CLIChannel) {const list = items.slice(0, 6).map((a) => `${a.name} (${artifactKindLabel(a.kind)}, ${formatBytes(a.size)})`).join(', ');const more = items.length > 6 ? ` and ${items.length - 6} more` : '';const where = items.length === 1 ? `\n ${items[0].originalPath}` : '';channel.sendSystemNotice(`◆ ${items.length === 1 ? 'Artifact' : `${items.length} artifacts`}: ${list}${more}${where}\n Open them in Mercury Desktop → Artifacts.`);- } else if (typeof channel?.sendArtifacts === 'function') {- channel.sendArtifacts(items.map(artifactRef), targetId);+ } else {+ const app = channel as { sendArtifacts?: (refs: ReturnType<typeof artifactRef>[], targetId?: string) => void } | null;+ if (typeof app?.sendArtifacts === 'function') app.sendArtifacts(items.map(artifactRef), targetId);}} catch { /* telling about artifacts must never break a turn */ }}- private maybeRecordPlanProgress(channel: any, toolName: string, input: unknown, targetId?: string): void {+ private maybeRecordPlanProgress(channel: unknown, toolName: string, input: unknown, targetId?: string): void {try {if (toolName !== 'update_plan') return;- if (channel instanceof CLIChannel) channel.setPlanProgress((input as any)?.steps);- // The apps (Chat, Code): a card above the composer, kept with the conversation.- else if (typeof channel?.sendPlan === 'function') channel.sendPlan((input as any)?.steps, targetId);+ const steps = (input as { steps?: Parameters<CLIChannel['setPlanProgress']>[0] } | null)?.steps;+ if (channel instanceof CLIChannel) channel.setPlanProgress(steps);+ else {+ // The apps (Chat, Code): a card above the composer, kept with the conversation.+ const app = channel as { sendPlan?: (s: typeof steps, targetId?: string) => void } | null;+ if (typeof app?.sendPlan === 'function') app.sendPlan(steps, targetId);+ }} catch { /* checklist must never break the tool loop */ }}diff --git a/src/memory/user-memory.ts b/src/memory/user-memory.tsindex 53cf7a98..a65c6722 100644--- a/src/memory/user-memory.ts+++ b/src/memory/user-memory.ts@@ -852,7 +852,7 @@ function extractHumanNames(segment: string, allowSentenceStart = false): string[let match: RegExpExecArray | null;while ((match = nameRegex.exec(segment)) !== null) {const before = segment.slice(0, match.index);- const atStart = /(^|[.!?:;\n•\-–—(\[]\s*)$/.test(before);+ const atStart = /(^|[.!?:;\n•\-–—([]\s*)$/.test(before);const first = match[1].split(' ')[0];if (atStart) firstWords.add(first);else midSentence.add(first);@@ -862,7 +862,7 @@ function extractHumanNames(segment: string, allowSentenceStart = false): string[const name = match[1].trim();if (!isLikelyHumanName(name)) continue;const before = segment.slice(0, match.index);- const atStart = /(^|[.!?:;\n•\-–—(\[]\s*)$/.test(before);+ const atStart = /(^|[.!?:;\n•\-–—([]\s*)$/.test(before);const single = !name.includes(' ');if (!allowSentenceStart && atStart && single && !midSentence.has(name)) continue;found.add(name);diff --git a/src/providers/chatgpt-web.test.ts b/src/providers/chatgpt-web.test.tsindex 9326b7a2..76ab09a0 100644--- a/src/providers/chatgpt-web.test.ts+++ b/src/providers/chatgpt-web.test.ts@@ -3,6 +3,9 @@ import { sseToJsonResponse } from './chatgpt-web.js';const sse = (...events: object[]) => new Response(events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join('') + 'data: [DONE]\n\n');+interface OutputItem { name: string; arguments: string; encrypted_content: string; content: Array<{ text: string }> }+interface ResponseBody { output: OutputItem[] }+describe('ChatGPT web: rebuilding a whole answer from the stream', () => {it('keeps a tool call\'s arguments, which only arrive after the call is announced', async () => {const call = { type: 'function_call', id: 'fc_1', call_id: 'call_1', name: 'web_search' };@@ -13,7 +16,7 @@ describe('ChatGPT web: rebuilding a whole answer from the stream', () => {{ type: 'response.output_item.done', output_index: 0, item: { ...call, arguments: '{"query":"Srinagar news","kind":"news"}', status: 'completed' } },{ type: 'response.completed', response: { id: 'r1', output: [] } },));- const body = (await res.json()) as { output: any[] };+ const body = (await res.json()) as ResponseBody;expect(body.output).toHaveLength(1);expect(body.output[0].name).toBe('web_search');expect(JSON.parse(body.output[0].arguments)).toEqual({ query: 'Srinagar news', kind: 'news' });@@ -25,7 +28,7 @@ describe('ChatGPT web: rebuilding a whole answer from the stream', () => {{ type: 'response.function_call_arguments.done', output_index: 0, arguments: '{"name":"web-search"}' },{ type: 'response.completed', response: { id: 'r2', output: [] } },));- expect(((await res.json()) as { output: any[] }).output[0].arguments).toBe('{"name":"web-search"}');+ expect(((await res.json()) as ResponseBody).output[0].arguments).toBe('{"name":"web-search"}');});it('keeps the reply text and the reasoning item\'s encrypted content', async () => {@@ -37,7 +40,7 @@ describe('ChatGPT web: rebuilding a whole answer from the stream', () => {{ type: 'response.output_item.done', output_index: 1, item: { type: 'message', id: 'm1', role: 'assistant', content: [] } },{ type: 'response.completed', response: { id: 'r3', output: [] } },));- const body = (await res.json()) as { output: any[] };+ const body = (await res.json()) as ResponseBody;expect(body.output[0].encrypted_content).toBe('enc');expect(body.output[1].content[0].text).toBe('Here is the news.');});diff --git a/src/sessions/repository.test.ts b/src/sessions/repository.test.tsindex 22124b3b..162b0685 100644--- a/src/sessions/repository.test.ts+++ b/src/sessions/repository.test.ts@@ -181,7 +181,7 @@ describe('SessionRepository.updateTitle without touching', () => {const older = repo.create({ title: 'Older' });repo.appendMessage(older.id, { role: 'user', content: 'a', timestamp: 1_000 });const newer = repo.create({ title: 'Newer' });- repo.appendMessage(newer.id, { role: 'user', content: 'b' });+ repo.appendMessage(newer.id, { role: 'user', content: 'b', timestamp: Date.now() + 60_000 });const before = repo.get(older.id).updatedAt;repo.updateTitle(older.id, 'Fixed Title', 'generated', { touch: false });expect(repo.get(older.id)).toMatchObject({ title: 'Fixed Title', titleSource: 'generated', updatedAt: before });diff --git a/src/skills/builder.test.ts b/src/skills/builder.test.tsindex ad2bfadd..b96d367c 100644--- a/src/skills/builder.test.ts+++ b/src/skills/builder.test.ts@@ -12,7 +12,7 @@ const good = {const provider = (...replies: string[]) => {const generateText = vi.fn();for (const r of replies) generateText.mockResolvedValueOnce({ text: r });- return { generateText, getModel: () => 'test-model' } as never;+ return { p: { generateText, getModel: () => 'test-model' } as never, generateText };};describe('skill builder', () => {@@ -28,17 +28,17 @@ describe('skill builder', () => {});it('fixes a draft that breaks the rules with one automatic retry', async () => {- const p = provider(JSON.stringify({ ...good, instructions: 'Do the report.' }), JSON.stringify(good));+ const { p, generateText } = provider(JSON.stringify({ ...good, instructions: 'Do the report.' }), JSON.stringify(good));const r = await buildSkillDraft(p, 'a weekly sales report from my sheet', ['read_file']);expect(r.problem).toBeNull();expect(r.draft.instructions).toContain('1. Ask the owner');- expect((p as any).generateText).toHaveBeenCalledTimes(2);- expect((p as any).generateText.mock.calls[1][0]).toMatch(/Fix this: instructions are too short/);+ expect(generateText).toHaveBeenCalledTimes(2);+ expect(generateText.mock.calls[1][0]).toMatch(/Fix this: instructions are too short/);});it('asks for changes in the owner\'s words', async () => {- const p = provider(JSON.stringify(good));+ const { p, generateText } = provider(JSON.stringify(good));await buildSkillDraft(p, 'sales report', ['read_file'], { draft: parseDraft(JSON.stringify(good), ['read_file']), feedback: 'also email it to finance' });- expect((p as any).generateText.mock.calls[0][0]).toContain('Change it like this: also email it to finance');+ expect(generateText.mock.calls[0][0]).toContain('Change it like this: also email it to finance');});});diff --git a/src/web/api-contract.test.ts b/src/web/api-contract.test.tsindex c77e1ac3..b57555e9 100644--- a/src/web/api-contract.test.ts+++ b/src/web/api-contract.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { Hono } from 'hono';+import { Hono, type Context } from 'hono';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -170,8 +170,8 @@ describe('api contract', () => {});});-function makeContext(path: string, token: string, remoteAddress: string): any {- return {+function makeContext(path: string, token: string, remoteAddress: string): Context {+ const fake = {req: {url: `http://127.0.0.1:6174${path}`,raw: new Request(`http://127.0.0.1:6174${path}`),@@ -181,4 +181,5 @@ function makeContext(path: string, token: string, remoteAddress: string): any {env: { incoming: { socket: { remoteAddress } } },json: (body: unknown, status = 200) => ({ body, status }),};+ return fake as unknown as Context;}diff --git a/src/web/api/artifacts-route.test.ts b/src/web/api/artifacts-route.test.tsindex 7740b9d5..4af93c30 100644--- a/src/web/api/artifacts-route.test.ts+++ b/src/web/api/artifacts-route.test.ts@@ -19,7 +19,7 @@ describe('artifacts API', () => {const f = join(home, 'clip.mp4');writeFileSync(f, Buffer.from('0123456789abcdef'));const a = artifactStore().add({ threadId: 't1', path: f, kind: 'video' });- const list = (await (await artifacts.request('http://127.0.0.1/api/artifacts?kind=video')).json()) as any;+ const list = (await (await artifacts.request('http://127.0.0.1/api/artifacts?kind=video')).json()) as { items: unknown[]; counts: Record<string, number> };expect(list.items[0]).toMatchObject({ id: a.id, name: 'clip.mp4', kind: 'video', threadExists: false });expect(JSON.stringify(list)).not.toContain('storedPath');expect(list.counts).toMatchObject({ all: 1, video: 1 });diff --git a/src/web/api/auth.ts b/src/web/api/auth.tsindex 06e4b994..4ce2ff65 100644--- a/src/web/api/auth.ts+++ b/src/web/api/auth.ts@@ -116,7 +116,7 @@ const tokenLimiter = createLoginLimiter();function peerAddress(c: { env?: unknown }): string {try {- return String((c.env as any)?.incoming?.socket?.remoteAddress || 'unknown');+ return String((c.env as { incoming?: { socket?: { remoteAddress?: string } } } | undefined)?.incoming?.socket?.remoteAddress || 'unknown');} catch {return 'unknown';}@@ -148,8 +148,8 @@ auth.post('/api/auth/token', async (c) => {let created;try {created = createDevice(body.deviceName, body.platform);- } catch (err: any) {- return c.json({ error: err?.message || 'Could not create device' }, 409);+ } catch (err) {+ return c.json({ error: err instanceof Error ? err.message : 'Could not create device' }, 409);}return c.json({ token: created.token, device: created.device, ...apiContract() });});diff --git a/src/web/api/channels-route.test.ts b/src/web/api/channels-route.test.tsindex e4f689c7..5bb0a2cd 100644--- a/src/web/api/channels-route.test.ts+++ b/src/web/api/channels-route.test.ts@@ -26,10 +26,19 @@ import { loadConfig } from '../../utils/config.js';const call = (method: string, path: string, body?: unknown) => channels.request(`http://127.0.0.1${path}`, { method, headers: { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');+interface ChannelRow {+ type: string;+ settings: Record<string, unknown>;+ access: { admins: unknown[]; members: unknown[]; pending: unknown[] };+}+interface ChannelsListBody { channels: ChannelRow[] }+interface ChannelSaveBody { identity?: string; channel: ChannelRow }+type DiscordUser = ReturnType<typeof loadConfig>['channels']['discord']['admins'][number];+describe('channels settings', () => {it('lists every channel with keys hidden and people in one shape', async () => {- const body = (await (await call('GET', '/api/channels')).json()) as any;- expect(body.channels.map((c: any) => c.type)).toEqual(['telegram', 'discord', 'slack', 'signal']);+ const body = (await (await call('GET', '/api/channels')).json()) as ChannelsListBody;+ expect(body.channels.map((c) => c.type)).toEqual(['telegram', 'discord', 'slack', 'signal']);const tg = body.channels[0];expect(tg.settings.botToken).toBe('1234••••ed00');expect(JSON.stringify(body)).not.toContain('savedsaved');@@ -40,7 +49,7 @@ describe('channels settings', () => {it('approves a request, and refuses to leave the channel without an admin', async () => {const ok = await call('POST', '/api/channels/telegram/access', { action: 'approve', id: '2' });expect(ok.status).toBe(200);- expect(((await ok.json()) as any).channel.access.members).toEqual([expect.objectContaining({ id: '2' })]);+ expect(((await ok.json()) as ChannelSaveBody).channel.access.members).toEqual([expect.objectContaining({ id: '2' })]);expect((await call('POST', '/api/channels/telegram/access', { action: 'remove', id: '1' })).status).toBe(409);expect((await call('POST', '/api/channels/telegram/access', { action: 'demote', id: '1' })).status).toBe(409);expect((await call('POST', '/api/channels/telegram/access', { action: 'promote', id: '2' })).status).toBe(200);@@ -53,7 +62,7 @@ describe('channels settings', () => {setChannelTestHooks({ fetch: vi.fn().mockResolvedValue({ status: 401, json: async () => ({ ok: false }) }) as never });const bad = await call('PUT', '/api/channels/discord', { enabled: true, botToken: 'MTIz' + 'NDU2Nzg5MDEyMzQ1Njc4.GabcDe.abcdefghijklmnopqrstuvwxyz0123' });expect(bad.status).toBe(400);- expect(((await bad.json()) as any).field).toBe('botToken');+ expect(await bad.json()).toMatchObject({ field: 'botToken' });expect(loadConfig().channels.discord.enabled).toBe(false);});@@ -63,7 +72,7 @@ describe('channels settings', () => {.mockResolvedValueOnce({ status: 200, json: async () => ({ ok: true }) });setChannelTestHooks({ fetch: f as never });const res = await call('PUT', '/api/channels/slack', { enabled: true, botToken: 'xoxb' + '-1234567890-abcdefghijklmnopqrst', appToken: 'xapp' + '-1-A123-4567890-abcdefghijklmnop', channelId: 'C123' });- const body = (await res.json()) as any;+ const body = (await res.json()) as ChannelSaveBody;expect(res.status).toBe(200);expect(body.identity).toBe('@mercury in Cosmic');expect(body.channel.settings).toMatchObject({ hasBotToken: true, hasAppToken: true, channelId: 'C123' });@@ -80,8 +89,8 @@ describe('channels settings', () => {it('Discord and Slack keep the role field in step when promoting', () => {const cfg = loadConfig();- cfg.channels.discord.admins = [{ userId: 'a', role: 'admin', approvedAt: 'x' } as any];- cfg.channels.discord.members = [{ userId: 'b', role: 'member', approvedAt: 'x' } as any];+ cfg.channels.discord.admins = [{ userId: 'a', role: 'admin', approvedAt: 'x' } as DiscordUser];+ cfg.channels.discord.members = [{ userId: 'b', role: 'member', approvedAt: 'x' } as DiscordUser];expect(applyAccess('discord', cfg, 'promote', 'b')).toEqual({ ok: true });expect(cfg.channels.discord.admins.find((u) => u.userId === 'b')?.role).toBe('admin');});diff --git a/src/web/api/channels.ts b/src/web/api/channels.tsindex 2f848947..4c77adf2 100644--- a/src/web/api/channels.ts+++ b/src/web/api/channels.ts@@ -79,20 +79,30 @@ const masked = (v: unknown) => typeof v === 'string' && v.includes('•');// ── People, in one shape for every channel ──────────────────────────────────+/** A person as each channel stores them (Telegram, Discord, Slack, Signal use different fields). */+interface ChannelUser {+ userId?: string | number; chatId?: string | number; phoneNumber?: string;+ name?: string; firstName?: string; username?: string; userName?: string; displayName?: string;+ approvedAt?: string; pairedAt?: string; pairingCode?: string; requestedAt?: string; role?: string;+}+type ChannelPeople = { admins: ChannelUser[]; members: ChannelUser[]; pending: ChannelUser[] };+interface Person { id: string; name: string; detail?: string; role: 'admin' | 'member'; since?: string }interface Pending { id: string; name: string; detail?: string; code?: string; requestedAt?: string }function people(type: ExternalChannel, c: MercuryConfig['channels']) {- const ch = c[type] as unknown as { admins: any[]; members: any[]; pending: any[] };- const person = (u: any, role: 'admin' | 'member'): Person => {- if (type === 'telegram') return { id: String(u.userId), name: u.firstName || (u.username ? `@${u.username}` : String(u.userId)), detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };- if (type === 'signal') return { id: u.phoneNumber, name: u.name || u.phoneNumber, detail: u.name ? u.phoneNumber : undefined, role, since: u.pairedAt };- if (type === 'slack') return { id: u.userId, name: u.displayName || u.userName || u.userId, detail: u.userName ? `@${u.userName}` : undefined, role, since: u.approvedAt };- return { id: u.userId, name: u.displayName || u.username || u.userId, detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };+ const ch = c[type] as unknown as ChannelPeople;+ const person = (u: ChannelUser, role: 'admin' | 'member'): Person => {+ const uid = String(u.userId ?? '');+ if (type === 'telegram') return { id: uid, name: u.firstName || (u.username ? `@${u.username}` : uid), detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };+ const phone = u.phoneNumber ?? '';+ if (type === 'signal') return { id: phone, name: u.name || phone, detail: u.name ? phone : undefined, role, since: u.pairedAt };+ if (type === 'slack') return { id: uid, name: u.displayName || u.userName || uid, detail: u.userName ? `@${u.userName}` : undefined, role, since: u.approvedAt };+ return { id: uid, name: u.displayName || u.username || uid, detail: u.username ? `@${u.username}` : undefined, role, since: u.approvedAt };};- const pending = (u: any): Pending => {- const id = type === 'signal' ? u.phoneNumber : String(u.userId);- const name = type === 'telegram' ? (u.firstName || (u.username ? `@${u.username}` : id)) : type === 'signal' ? (u.name || u.phoneNumber) : (u.displayName || u.username || u.userName || id);+ const pending = (u: ChannelUser): Pending => {+ const id = type === 'signal' ? (u.phoneNumber ?? '') : String(u.userId ?? '');+ const name = type === 'telegram' ? (u.firstName || (u.username ? `@${u.username}` : id)) : type === 'signal' ? (u.name || id) : (u.displayName || u.username || u.userName || id);return { id, name, detail: u.username ? `@${u.username}` : u.userName ? `@${u.userName}` : undefined, code: u.pairingCode, requestedAt: u.requestedAt };};return {@@ -227,9 +237,9 @@ type AccessResult = { ok: true; welcome?: { target: string; text: string } } | {/** One place for every channel's access rules: approve, reject, remove, promote, demote, reset. */export function applyAccess(type: ExternalChannel, config: MercuryConfig, action: string, id: string, role?: 'admin' | 'member'): AccessResult {- const ch = config.channels[type] as unknown as { admins: any[]; members: any[]; pending: any[] };- const keyOf = (u: any) => String(type === 'signal' ? u.phoneNumber : u.userId);- const find = (list: any[]) => list.find((u) => keyOf(u) === id);+ const ch = config.channels[type] as unknown as ChannelPeople;+ const keyOf = (u: ChannelUser) => String(type === 'signal' ? u.phoneNumber : u.userId);+ const find = (list: ChannelUser[]) => list.find((u) => keyOf(u) === id);if (action !== 'reset' && !id) return { ok: false, error: 'Who? (id is required)' };switch (action) {diff --git a/src/web/api/chat-save-route.test.ts b/src/web/api/chat-save-route.test.tsindex 93eff166..9f4bc7de 100644--- a/src/web/api/chat-save-route.test.ts+++ b/src/web/api/chat-save-route.test.ts@@ -21,7 +21,8 @@ function threads() {const older = repo.create({ title: 'Older' });repo.appendMessage(older.id, { role: 'user', content: 'hi', timestamp: 1_000 });const newer = repo.create({ title: 'Newer' });- repo.appendMessage(newer.id, { role: 'user', content: 'hello' });+ // Clearly later than the first, so the order can't depend on the clock's resolution.+ repo.appendMessage(newer.id, { role: 'user', content: 'hello', timestamp: Date.now() + 60_000 });return { repo, older: older.id, newer: newer.id };}diff --git a/src/web/api/cloud-route.test.ts b/src/web/api/cloud-route.test.tsindex bcb16467..dba03e8c 100644--- a/src/web/api/cloud-route.test.ts+++ b/src/web/api/cloud-route.test.ts@@ -44,10 +44,20 @@ const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');afterEach(() => vi.useRealTimers());+interface CloudStatusBody {+ paired: boolean;+ chat: { ok: boolean; models?: string[]; error?: string };+ session: string;+ selfRecovers: boolean;+ modelOk: boolean;+ action: string;+}+interface SigninBody { status: string; error?: string; upgradeUrl?: string }+describe('Mercury Cloud status', () => {it('chat key works but the session is gone and the model is a reranker: asks to sign in', async () => {setCloudTestHooks({ fetch: models(['mercury-mini', 'claude-sonnet-4.6', 'nemotron-3.5-rerank-8b:free', 'text-embedding-3-small']) });- const body = await (await get('/api/cloud/status?fresh=1')).json() as any;+ const body = await (await get('/api/cloud/status?fresh=1')).json() as CloudStatusBody;expect(body.paired).toBe(true);expect(body.chat.ok).toBe(true);expect(body.chat.models).toEqual(['mercury-mini', 'claude-sonnet-4.6']);@@ -60,7 +70,7 @@ describe('Mercury Cloud status', () => {it('a rejected chat key reads as signed out, not as a crash', async () => {setCloudTestHooks({ fetch: vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({}) } as unknown as Response) });- const body = await (await get('/api/cloud/status?fresh=1')).json() as any;+ const body = await (await get('/api/cloud/status?fresh=1')).json() as CloudStatusBody;expect(body.chat).toMatchObject({ ok: false });expect(body.chat.error).toMatch(/no longer accepts/);expect(body.action).toBe('sign-in');@@ -68,7 +78,7 @@ describe('Mercury Cloud status', () => {it('an unreachable Cloud says so', async () => {setCloudTestHooks({ fetch: vi.fn().mockRejectedValue(new Error('The operation was aborted due to timeout')) });- const body = await (await get('/api/cloud/status?fresh=1')).json() as any;+ const body = await (await get('/api/cloud/status?fresh=1')).json() as CloudStatusBody;expect(body.chat.error).toMatch(/10 seconds/);});});@@ -83,12 +93,12 @@ describe('Mercury Cloud sign-in from the app', () => {poll: vi.fn().mockReturnValue(new Promise((r) => { approve = r; })) as never,restart,});- const started = await (await post('/api/cloud/signin')).json() as any;+ const started: unknown = await (await post('/api/cloud/signin')).json();expect(started).toMatchObject({ code: 'ABCD-1234', status: 'pending' });- expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('pending');+ expect(await (await get('/api/cloud/signin')).json()).toMatchObject({ status: 'pending' });approve({ jwt: 'new.jwt.token', refreshToken: 'rt-new', agentId: 'agent-1', tier: 'extended', apiKey: 'agent-key-1', accessKey: 'sk-mc-new' });- await vi.waitFor(async () => expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('done'));+ await vi.waitFor(async () => expect(await (await get('/api/cloud/signin')).json()).toMatchObject({ status: 'done' }));vi.advanceTimersByTime(400);expect(restart).toHaveBeenCalledOnce();@@ -108,8 +118,8 @@ describe('Mercury Cloud sign-in from the app', () => {});await cloud.request('http://127.0.0.1/api/cloud/signin', { method: 'DELETE' });await post('/api/cloud/signin');- await vi.waitFor(async () => expect((await (await get('/api/cloud/signin')).json() as any).status).toBe('failed'));- const body = await (await get('/api/cloud/signin')).json() as any;+ await vi.waitFor(async () => expect(await (await get('/api/cloud/signin')).json()).toMatchObject({ status: 'failed' }));+ const body = await (await get('/api/cloud/signin')).json() as SigninBody;expect(body.error).toMatch(/limit/);expect(body.upgradeUrl).toBe('https://cloud.test/upgrade');});@@ -121,7 +131,7 @@ describe('turning Mercury Cloud off, and signing out', () => {it("won't turn Cloud off when it's the only model", async () => {const res = await cloud.request('http://127.0.0.1/api/cloud/enabled', body({ enabled: false }));expect(res.status).toBe(409);- expect(((await res.json()) as any).needsOther).toBe(true);+ expect(await res.json()).toMatchObject({ needsOther: true });});it('turns off (handing the default to another provider) and back on, staying signed in', async () => {@@ -132,7 +142,7 @@ describe('turning Mercury Cloud off, and signing out', () => {writeFileSync(join(home, 'mercury.yaml'), YAML.stringify(doc));const off = await cloud.request('http://127.0.0.1/api/cloud/enabled', body({ enabled: false }));expect(off.status).toBe(200);- expect(((await off.json()) as any).default).toBe('deepseek');+ expect(await off.json()).toMatchObject({ default: 'deepseek' });expect(yaml()).toMatch(/mercuryCloud:[\s\S]*?enabled: false/);expect(yaml()).toContain('sk-mc-new');const on = await cloud.request('http://127.0.0.1/api/cloud/enabled', body({ enabled: true }));@@ -144,7 +154,7 @@ describe('turning Mercury Cloud off, and signing out', () => {const restart = vi.fn().mockReturnValue(true);setCloudTestHooks({ restart });const res = await cloud.request('http://127.0.0.1/api/cloud/signout', { method: 'POST' });- expect(((await res.json()) as any)).toMatchObject({ ok: true, restarting: true, fallback: 'deepseek', setupNext: false });+ expect(await res.json()).toMatchObject({ ok: true, restarting: true, fallback: 'deepseek', setupNext: false });vi.advanceTimersByTime(400);expect(restart).toHaveBeenCalledOnce();const saved = yaml();diff --git a/src/web/api/providers-route.test.ts b/src/web/api/providers-route.test.tsindex 29486347..1af37875 100644--- a/src/web/api/providers-route.test.ts+++ b/src/web/api/providers-route.test.ts@@ -41,6 +41,15 @@ function call(method: string, path: string, body?: unknown) {}const yaml = () => readFileSync(join(home, 'mercury.yaml'), 'utf-8');+interface ProviderRow { id: string; apiKey?: string; signInOnly?: boolean }+interface ProviderSettingsBody {+ default: { provider: string; model: string };+ providers: ProviderRow[];+ roles: Record<string, string | null>;+ setupRequired: boolean;+}+interface CheckBody { ok: boolean; error?: string; field?: string; models: string[] }+afterEach(() => {catalog.fn.mockReset();setProvidersReload(null);@@ -50,19 +59,19 @@ afterEach(() => {describe('providers settings', () => {it('lists every provider with masked keys, the default and roles', async () => {const res = await call('GET', '/api/providers/settings');- const body = await res.json() as any;+ const body = await res.json() as ProviderSettingsBody;expect(body.default).toEqual({ provider: 'deepseek', model: 'deepseek-chat' });const ds = body.providers.find((p: { id: string }) => p.id === 'deepseek');expect(ds).toMatchObject({ label: 'DeepSeek', kind: 'cloud', configured: true, isDefault: true, hasKey: true });- expect(ds.apiKey).toBe('sk-s••••0000');+ expect(ds?.apiKey).toBe('sk-s••••0000');expect(JSON.stringify(body)).not.toContain('saveddeepseekkey');- expect(body.providers.find((p: { id: string }) => p.id === 'chatgptWeb').signInOnly).toBe(true);+ expect(body.providers.find((p: { id: string }) => p.id === 'chatgptWeb')?.signInOnly).toBe(true);expect(body.setupRequired).toBe(false);});it('checks an unsaved key: shape first, with no network call', async () => {const res = await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-wrong-shape-1234567890' });- const body = await res.json() as any;+ const body = await res.json() as CheckBody;expect(body).toMatchObject({ ok: false, field: 'apiKey' });expect(body.error).toMatch(/sk-ant-/);expect(catalog.fn).not.toHaveBeenCalled();@@ -70,7 +79,7 @@ describe('providers settings', () => {it('never accepts the masked form of a key', async () => {const res = await call('POST', '/api/providers/deepseek/check', { apiKey: 'sk-s••••0000' });- expect((await res.json() as any).error).toMatch(/hidden form/);+ expect(await res.json()).toMatchObject({ error: expect.stringMatching(/hidden form/) });const save = await call('POST', '/api/providers/deepseek', { apiKey: 'sk-s••••0000' });expect(save.status).toBe(400);expect(yaml()).toContain('sk-saveddeepseekkey0000000000');@@ -80,7 +89,7 @@ describe('providers settings', () => {const many = Array.from({ length: 120 }, (_, i) => `claude-model-${i}`);catalog.fn.mockResolvedValue({ recommendedModel: 'claude-sonnet-x', models: many });const res = await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx' });- const body = await res.json() as any;+ const body = await res.json() as CheckBody;expect(body.ok).toBe(true);expect(body.models[0]).toBe('claude-sonnet-x');expect(body.models.length).toBe(121);@@ -91,7 +100,7 @@ describe('providers settings', () => {it('points a vendor rejection at the key field', async () => {catalog.fn.mockRejectedValue(new Error('Anthropic rejected the API key (401). Please re-enter it.'));- const body = await (await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx' })).json() as any;+ const body = await (await call('POST', '/api/providers/anthropic/check', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx' })).json();expect(body).toMatchObject({ ok: false, field: 'apiKey' });});@@ -99,20 +108,20 @@ describe('providers settings', () => {const reload = vi.fn().mockResolvedValue({ ok: true, providers: ['deepseek', 'anthropic'], default: 'deepseek', model: 'deepseek-chat' });setProvidersReload(reload);const res = await call('POST', '/api/providers/anthropic', { apiKey: 'sk-ant-abcdefghijklmnopqrstuvwx', model: 'claude-sonnet-x', enabled: true });- const body = await res.json() as any;+ const body: unknown = await res.json();expect(res.status).toBe(200);expect(body).toMatchObject({ success: true, applied: true, restartRequired: false });- expect(body.provider).toMatchObject({ configured: true, model: 'claude-sonnet-x' });+ expect(body).toMatchObject({ provider: { configured: true, model: 'claude-sonnet-x' } });expect(reload).toHaveBeenCalledOnce();expect(yaml()).toContain('sk-ant-abcdefghijklmnopqrstuvwx');});it('rejects a bad model and a bad URL with the field to fix', async () => {const m = await call('POST', '/api/providers/anthropic', { model: 'has spaces in it' });- expect(await m.json() as any).toMatchObject({ field: 'model' });+ expect(await m.json()).toMatchObject({ field: 'model' });const u = await call('POST', '/api/providers/openaiCompat', { baseUrl: 'ftp://nope', model: 'x', enabled: true });expect(u.status).toBe(400);- expect(await u.json() as any).toMatchObject({ field: 'baseUrl' });+ expect(await u.json()).toMatchObject({ field: 'baseUrl' });});it('sets the default model and job roles, only to connected providers', async () => {@@ -120,7 +129,7 @@ describe('providers settings', () => {expect(bad.status).toBe(400);const ok = await call('PUT', '/api/providers/roles', { default: { provider: 'anthropic', model: 'claude-opus-x' }, learning: 'deepseek', crew: null });expect(ok.status).toBe(200);- const s = await (await call('GET', '/api/providers/settings')).json() as any;+ const s = await (await call('GET', '/api/providers/settings')).json() as ProviderSettingsBody;expect(s.default).toEqual({ provider: 'anthropic', model: 'claude-opus-x' });expect(s.roles.learning).toBe('deepseek');});@@ -128,7 +137,7 @@ describe('providers settings', () => {it('forgetting the default key hands the default to another working provider', async () => {const res = await call('DELETE', '/api/providers/anthropic/key');expect(res.status).toBe(200);- const s = await (await call('GET', '/api/providers/settings')).json() as any;+ const s = await (await call('GET', '/api/providers/settings')).json() as ProviderSettingsBody;expect(s.default.provider).toBe('deepseek');expect(s.providers.find((p: { id: string }) => p.id === 'anthropic')).toMatchObject({ hasKey: false, enabled: false, configured: false });});@@ -142,8 +151,8 @@ describe('providers settings', () => {vi.useFakeTimers();const restart = vi.fn();setFirstProviderHandler(restart);- expect((await (await call('GET', '/api/providers/settings')).json() as any).setupRequired).toBe(true);- const body = await (await call('POST', '/api/providers/grok', { apiKey: 'xai-abcdefghijklmnopqrstuvwxyz123456', model: 'grok-4', enabled: true })).json() as any;+ expect(await (await call('GET', '/api/providers/settings')).json()).toMatchObject({ setupRequired: true });+ const body = await (await call('POST', '/api/providers/grok', { apiKey: 'xai-abcdefghijklmnopqrstuvwxyz123456', model: 'grok-4', enabled: true })).json();expect(body).toMatchObject({ success: true, restarting: true });vi.advanceTimersByTime(400);expect(restart).toHaveBeenCalledOnce();diff --git a/src/web/api/skill-builder-route.test.ts b/src/web/api/skill-builder-route.test.tsindex 76837db9..58c873b1 100644--- a/src/web/api/skill-builder-route.test.ts+++ b/src/web/api/skill-builder-route.test.ts@@ -22,7 +22,7 @@ describe('skill builder routes', () => {const generateText = vi.fn().mockResolvedValue({ text: JSON.stringify({ ...draft, allowedTools: ['list_dir', 'made_up'] }) });setSkillBuilder({ provider: () => ({ generateText, getModel: () => 'm' }) as never, tools: () => ['list_dir', 'move_file'] });const res = await post('/api/skills/draft', { request: 'tidy my downloads folder by type' });- const body = (await res.json()) as any;+ const body = (await res.json()) as { draft: { allowedTools: string[] }; problem: string | null };expect(res.status).toBe(200);expect(body.draft.allowedTools).toEqual(['list_dir']);expect(body.problem).toBeNull();@@ -37,7 +37,7 @@ describe('skill builder routes', () => {it('saves a reviewed draft as a self-made skill that shows up in the list', async () => {const res = await post('/api/skills/self-made', { draft });expect(res.status).toBe(200);- expect(((await res.json()) as any).name).toBe('tidy-downloads');+ expect(await res.json()).toMatchObject({ name: 'tidy-downloads' });const list = (await (await system.request('http://127.0.0.1/api/skills')).json()) as { skills: Array<{ name: string; selfMade: boolean }> };expect(list.skills.find((s) => s.name === 'tidy-downloads')?.selfMade).toBe(true);});diff --git a/src/web/api/speak-route.test.ts b/src/web/api/speak-route.test.tsindex 6a6005d4..617dfb4e 100644--- a/src/web/api/speak-route.test.ts+++ b/src/web/api/speak-route.test.ts@@ -74,6 +74,6 @@ describe('read aloud', () => {setSpeakFetch(vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({ error: { message: 'bad key' } }) }) as never);const res = await post('Hello');expect(res.status).toBe(502);- expect((await res.json() as any).error).toMatch(/rejected the key/);+ expect(await res.json()).toMatchObject({ error: expect.stringMatching(/rejected the key/) });});});diff --git a/src/web/api/transcribe-route.test.ts b/src/web/api/transcribe-route.test.tsindex c34354b7..a43062fd 100644--- a/src/web/api/transcribe-route.test.ts+++ b/src/web/api/transcribe-route.test.ts@@ -36,7 +36,7 @@ describe('dictation', () => {process.env.DEEPGRAM_API_KEY = 'dg-key';const f = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ results: { channels: [{ alternatives: [{ transcript: 'hello from deepgram' }] }] } }) });setTranscribeFetch(f as never);- const body = await (await post()).json() as any;+ const body: unknown = await (await post()).json();expect(body).toEqual({ text: 'hello from deepgram', engine: 'Deepgram' });expect(f.mock.calls[0][0]).toContain('api.deepgram.com/v1/listen');expect(f.mock.calls[0][1].headers['Content-Type']).toBe('audio/webm');@@ -47,7 +47,7 @@ describe('dictation', () => {process.env.DEEPGRAM_API_KEY = 'dg-key';const f = vi.fn().mockResolvedValue({ ok: true, status: 200, json: async () => ({ text: ' Remind me to call Heer. ' }) });setTranscribeFetch(f as never);- const body = await (await post(audio, 'audio/mp4', '?language=en')).json() as any;+ const body: unknown = await (await post(audio, 'audio/mp4', '?language=en')).json();expect(body).toEqual({ text: 'Remind me to call Heer.', engine: 'OpenAI' });const form = f.mock.calls[0][1].body as FormData;expect(form.get('model')).toBe('gpt-4o-mini-transcribe');@@ -58,8 +58,8 @@ describe('dictation', () => {it('a rejected key and an empty recording read plainly', async () => {withOpenAI();setTranscribeFetch(vi.fn().mockResolvedValue({ ok: false, status: 401, json: async () => ({ error: { message: 'bad key' } }) }) as never);- expect((await (await post()).json() as any).error).toMatch(/rejected the key/);- expect((await (await post(new Uint8Array(10))).json() as any).error).toMatch(/Didn't catch anything/);+ expect(await (await post()).json()).toMatchObject({ error: expect.stringMatching(/rejected the key/) });+ expect(await (await post(new Uint8Array(10))).json()).toMatchObject({ error: expect.stringMatching(/Didn't catch anything/) });});it('refuses non-audio bodies', async () => {diff --git a/src/web/devices.ts b/src/web/devices.tsindex 8056daed..f7c6bd12 100644--- a/src/web/devices.ts+++ b/src/web/devices.ts@@ -112,6 +112,7 @@ const MAX_NAME_LENGTH = 64;const MAX_DEVICES = 200;export function normalizeDeviceName(name: unknown): string {+ // eslint-disable-next-line no-control-regex -- strips control characters on purposeconst trimmed = String(name ?? '').replace(/[\u0000-\u001f\u007f]/g, '').trim();return (trimmed || 'Unnamed device').slice(0, MAX_NAME_LENGTH);}