Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(plugins): Windows-portable plugin tests; clear new lint violations

Salman Qureshib714b095beb3
diff --git a/src/core/agent.ts b/src/core/agent.ts
index dd263354..12be08c0 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -100,7 +100,7 @@ import { modelSeesImages, withAttachments } from './attachments.js';
import { AlertGate } from './alert-gate.js';
import { setPluginImagesAllowed } from '../plugins/tool-bridge.js';
import { handleCallCommand } from '../plugins/call-schedule.js';
-import { handlePluginsCommand, tryPluginCommand, pluginCommandHelp, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
+import { handlePluginsCommand, tryPluginCommand, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
import { handleChatCommand as handleChatCommandImpl } from './commands/chat-command.js';
import { handleBgCommand as handleBgCommandImpl } from './commands/bg-command.js';
import { handleSaverCommand as handleSaverCommandImpl } from './commands/saver-command.js';
@@ -760,7 +760,7 @@ export class Agent {
const channel = this.channels.getChannelForMessage(msg);
if (channel) {
answerPluginDialog(trimmed, msg, channel).catch((err) => {
- logger.error({ err: (err as any)?.message ?? err }, 'plugin dialog failed');
+ logger.error({ err: err instanceof Error ? err.message : err }, 'plugin dialog failed');
});
return;
}
@@ -781,7 +781,7 @@ export class Agent {
const channel = this.channels.getChannelForMessage(msg);
if (channel) {
handlePluginsCommand(trimmed, msg, channel).catch((err) => {
- logger.error({ err: (err as any)?.message ?? err, content: trimmed.slice(0, 50) }, '/plugins command failed');
+ logger.error({ err: err instanceof Error ? err.message : err, content: trimmed.slice(0, 50) }, '/plugins command failed');
});
}
return;
diff --git a/src/plugins/dialog.ts b/src/plugins/dialog.ts
index 28a35bd5..49d90a5d 100644
--- a/src/plugins/dialog.ts
+++ b/src/plugins/dialog.ts
@@ -209,7 +209,7 @@ export class PluginDialog {
if (!follow.length) return { kind: 'next', message };
return {
kind: 'push',
- steps: follow.map((f, n) => this.liveSettingStep(f.key, { index: n + 1, total: follow.length })),
+ steps: follow.map((f) => this.liveSettingStep(f.key)),
message: `${message}\nNext, ${follow.length === 1 ? 'one more thing it needs' : `${follow.length} things it needs`}:`,
};
}
@@ -386,7 +386,7 @@ export class PluginDialog {
const i = (await this.svc.info(this.pluginId))!;
if (option.value === 'walk') {
const keys = (i.settings ?? []).filter((x) => x.group === gid).map((x) => x.key);
- return { kind: 'push', steps: [...keys.map((k, n) => this.liveSettingStep(k, { index: n + 1, total: keys.length })), this.groupMenuStep(gid)] };
+ return { kind: 'push', steps: [...keys.map((k) => this.liveSettingStep(k)), this.groupMenuStep(gid)] };
}
const fresh = i.settings?.find((x) => x.key === option.value.slice('set:'.length));
return fresh ? { kind: 'push', steps: [this.settingStep(fresh), this.groupMenuStep(gid)] } : { kind: 'retry', message: 'That setting is gone.' };
@@ -395,7 +395,7 @@ export class PluginDialog {
}
/** A setting step that looks the setting up when it's reached (values may have changed since). */
- private liveSettingStep(key: string, ctx: { index: number; total: number }): Step {
+ private liveSettingStep(key: string): Step {
let inner: Step | null = null;
const load = async () => {
const s = (await this.svc.info(this.pluginId))?.settings?.find((x) => x.key === key);
diff --git a/src/plugins/installer.test.ts b/src/plugins/installer.test.ts
index 83176137..8c2b9d56 100644
--- a/src/plugins/installer.test.ts
+++ b/src/plugins/installer.test.ts
@@ -1,6 +1,6 @@
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, resolve } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { installPackage, parseSource, rollbackPackage, sha256File, uninstallPackage, loadManifest } from './installer.js';
import { pluginDataDir, pluginDir, pluginVersionDir, readState, stagingRoot, withLock } from './store.js';
@@ -25,7 +25,7 @@ describe('parseSource', () => {
it('recognises ids, paths, https URLs and github repos', () => {
expect(parseSource('weather')).toEqual({ kind: 'id', id: 'weather' });
expect(parseSource('./plugins/weather')).toMatchObject({ type: 'path' });
- expect(parseSource('/tmp/x.tgz')).toMatchObject({ type: 'path', path: '/tmp/x.tgz' });
+ expect(parseSource('/tmp/x.tgz')).toMatchObject({ type: 'path', path: resolve('/tmp/x.tgz') });
expect(parseSource('https://example.com/p.tgz')).toEqual({ type: 'url', url: 'https://example.com/p.tgz' });
expect(parseSource('github:acme/[email protected]')).toEqual({ type: 'github', repo: 'acme/mercury-weather', tag: 'v1.2.0' });
});
diff --git a/src/plugins/manager.test.ts b/src/plugins/manager.test.ts
index 09110014..5cb05203 100644
--- a/src/plugins/manager.test.ts
+++ b/src/plugins/manager.test.ts
@@ -184,7 +184,7 @@ describe('in-process plugins', () => {
it('an uncaught error from plugin code is attributed and the plugin disabled', async () => {
await mgr.install(inProcessPlugin(src, { id: 'crasher' }));
const err = new Error('raw timer blew up');
- err.stack = `Error: raw timer blew up\n at Timeout._onTimeout (${pluginDir('crasher')}/versions/1.0.0/index.mjs:3:11)`;
+ err.stack = `Error: raw timer blew up\n at Timeout._onTimeout (${join(pluginDir('crasher'), 'versions', '1.0.0', 'index.mjs')}:3:11)`;
expect(mgr.attributeFault(err)).toBe(true);
await waitFor(() => readState().plugins.crasher?.enabled === false);
expect(mgr.attributeFault(new Error('not from a plugin'))).toBe(false);
diff --git a/src/plugins/qr-svg.ts b/src/plugins/qr-svg.ts
index c7ec467d..13aa9b59 100644
--- a/src/plugins/qr-svg.ts
+++ b/src/plugins/qr-svg.ts
@@ -3,9 +3,9 @@
* encoder bundled in qrcode-terminal, which Mercury already ships, so the
* dashboard needs no QR library of its own.
*/
-// @ts-ignore: CommonJS module without types
+// @ts-expect-error: CommonJS module without types
import QRCode from 'qrcode-terminal/vendor/QRCode/index.js';
-// @ts-ignore: CommonJS module without types
+// @ts-expect-error: CommonJS module without types
import QRErrorCorrectLevel from 'qrcode-terminal/vendor/QRCode/QRErrorCorrectLevel.js';
interface QRCodeInstance {
diff --git a/src/plugins/runtime/in-process.ts b/src/plugins/runtime/in-process.ts
index d5e1a412..956074a8 100644
--- a/src/plugins/runtime/in-process.ts
+++ b/src/plugins/runtime/in-process.ts
@@ -150,10 +150,9 @@ export class InProcessRuntime implements PluginRuntime {
...(Object.keys(m.permissions.providers ?? {}) as PluginProviderId[]).flatMap((p) => Object.values(providerSecretNames(p))),
]);
const signal = this.ac.signal;
- const self = this;
const register = (def: PluginToolDefinition): Disposable => {
- if (!self.running) throw new Error('Plugin is not running.');
+ if (!this.running) throw new Error('Plugin is not running.');
const decl = declaredTools.get(def?.name);
if (!decl) throw new Error(`Tool "${def?.name}" is not declared in mercury-plugin.json (contributes.tools).`);
if (typeof def.execute !== 'function') throw new Error(`Tool "${def.name}" has no execute function.`);
@@ -170,20 +169,20 @@ export class InProcessRuntime implements PluginRuntime {
readOnly: decl.readOnly,
timeoutMs: decl.timeoutMs,
invoke: async (args, toolSignal) => {
- if (!self.running) throw new Error('the plugin is not running');
+ if (!this.running) throw new Error('the plugin is not running');
const combined = AbortSignal.any([toolSignal, signal]);
return def.execute(args, { signal: combined });
},
});
- self.registered.add(`tool:${decl.name}`);
- return self.track(() => {
+ this.registered.add(`tool:${decl.name}`);
+ return this.track(() => {
unpublish();
- self.registered.delete(`tool:${decl.name}`);
+ this.registered.delete(`tool:${decl.name}`);
});
};
const registerCommand = (def: PluginCommandDefinition): Disposable => {
- if (!self.running) throw new Error('Plugin is not running.');
+ if (!this.running) throw new Error('Plugin is not running.');
const decl = declaredCommands.get(def?.name);
if (!decl) throw new Error(`Command "${def?.name}" is not declared in mercury-plugin.json (contributes.commands).`);
if (typeof def.run !== 'function') throw new Error(`Command "${def.name}" has no run function.`);
@@ -193,19 +192,19 @@ export class InProcessRuntime implements PluginRuntime {
name: decl.name,
description: decl.description,
run: async (args, io) => {
- if (!self.running) throw new Error('the plugin is not running');
+ if (!this.running) throw new Error('the plugin is not running');
await def.run(args, { reply: io.reply, signal: AbortSignal.any([io.signal, signal]) });
},
});
- self.registered.add(`command:${decl.name}`);
- return self.track(() => {
+ this.registered.add(`command:${decl.name}`);
+ return this.track(() => {
unpublish();
- self.registered.delete(`command:${decl.name}`);
+ this.registered.delete(`command:${decl.name}`);
});
};
const pluginFetch = async (url: string, init: RequestInit = {}): Promise<Response> => {
- if (!self.running) throw new Error('Plugin is not running.');
+ if (!this.running) throw new Error('Plugin is not running.');
let target = url;
const reqSignal = init.signal ? AbortSignal.any([init.signal, signal]) : signal;
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
@@ -238,28 +237,28 @@ export class InProcessRuntime implements PluginRuntime {
error: (msg: string, data?: Record<string, unknown>) => scoped.error(msg, data),
}),
settings: Object.freeze({
- get: <T,>(key: string) => self.deps.settings[key] as T | undefined,
- all: () => ({ ...self.deps.settings }),
+ get: <T,>(key: string) => this.deps.settings[key] as T | undefined,
+ all: () => ({ ...this.deps.settings }),
}),
secrets: Object.freeze({
- get: (name: string) => (declaredSecrets.has(name) ? self.deps.secrets[name] : undefined),
+ get: (name: string) => (declaredSecrets.has(name) ? this.deps.secrets[name] : undefined),
}),
tools: Object.freeze({ register }),
commands: Object.freeze({ register: registerCommand }),
timers: Object.freeze({
setTimeout: (fn: () => void | Promise<void>, ms: number): Disposable => {
- const h = setTimeout(() => self.guard(fn, 'timer'), Math.max(0, ms));
- return self.track(() => clearTimeout(h));
+ const h = setTimeout(() => this.guard(fn, 'timer'), Math.max(0, ms));
+ return this.track(() => clearTimeout(h));
},
setInterval: (fn: () => void | Promise<void>, ms: number): Disposable => {
- const h = setInterval(() => self.guard(fn, 'interval'), Math.max(1000, ms));
- return self.track(() => clearInterval(h));
+ const h = setInterval(() => this.guard(fn, 'interval'), Math.max(1000, ms));
+ return this.track(() => clearInterval(h));
},
}),
fetch: pluginFetch,
signal,
onDispose: (fn: () => void | Promise<void>) => {
- self.track(fn);
+ this.track(fn);
},
}) as PluginContext;
}
diff --git a/src/plugins/scaffold.test.ts b/src/plugins/scaffold.test.ts
index f4d9cb9d..7c062857 100644
--- a/src/plugins/scaffold.test.ts
+++ b/src/plugins/scaffold.test.ts
@@ -17,7 +17,8 @@ afterEach(async () => { await mgr.shutdown(); resetToolBridge(); env.restore();
describe('author tooling', () => {
it('the embedded SDK types match src/plugins/sdk.ts (run: node scripts/gen-plugin-sdk.mjs)', () => {
- expect(PLUGIN_SDK_DTS).toBe(readFileSync(join(process.cwd(), 'src/plugins/sdk.ts'), 'utf8'));
+ // Git may check sdk.ts out with CRLF endings on Windows; the embedded copy is always LF.
+ expect(PLUGIN_SDK_DTS).toBe(readFileSync(join(process.cwd(), 'src/plugins/sdk.ts'), 'utf8').replace(/\r\n/g, '\n'));
});
for (const kind of ['in-process', 'out-of-process'] as const) {
diff --git a/src/plugins/tool-bridge.test.ts b/src/plugins/tool-bridge.test.ts
index eed99599..e4a47a09 100644
--- a/src/plugins/tool-bridge.test.ts
+++ b/src/plugins/tool-bridge.test.ts
@@ -19,6 +19,8 @@ function liveTool(result: unknown) {
async function run(result: unknown, callId = 'call-1') {
publishTool(liveTool(result));
+ // The bridge returns an AI SDK tool; the test drives its two callbacks directly.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
const t = getPluginTools({} as PermissionManager)['shots__look'] as any;
const output = await t.execute({}, { toolCallId: callId, messages: [] });
const model = await t.toModelOutput({ toolCallId: callId, input: {}, output });