| title | Plugin Architecture & Context |
|---|---|
| description | Core interfaces, definePlugin, PluginBuilder, and the complete PluginContext contract. |
| product | sdk |
| section | sdk-plugins |
| order | 1 |
| icon | Puzzle |
| slug | plugin-interface |
The Weavetab SDK provides two paradigms for creating plugins:
definePlugin: A declarative functional API for static and dynamic registration.PluginBuilder: A fluent, chainable builder for complex middleware pipelines.
Both paradigms compile to the same runtime contract and receive a typed PluginContext at load time.
The SDK uses Zod for input schema validation. Tools defined with defineTool automatically generate JSON Schema Draft-07 representations and infer runtime TypeScript argument types.
import { defineTool, z } from "@weavetab/sdk";
export const tableExtractor = defineTool({
name: "extract_table",
description: "Extracts tabular data matching a CSS selector into structured JSON rows",
requiresSession: true, // Requires an active browser tab session
schema: {
selector: z.string().describe("CSS selector targeting the <table> or data grid"),
maxRows: z.number().int().min(1).max(500).default(50).describe("Maximum rows to parse"),
cleanWhitespace: z.boolean().default(true).describe("Strip extra whitespace and newlines"),
},
handler: async (args, session) => {
// args is strictly typed: { selector: string; maxRows: number; cleanWhitespace: boolean }
if (!session) {
throw new Error("Active browser tab is required.");
}
const evalRes = await session.Runtime.evaluate({
expression: `((sel, limit, clean) => {
const table = document.querySelector(sel);
if (!table) return [];
const trs = Array.from(table.querySelectorAll('tbody tr, tr')).slice(0, limit);
return trs.map(tr => {
const cells = Array.from(tr.querySelectorAll('td, th'));
return cells.map(c => clean ? c.innerText.trim().replace(/\\s+/g, ' ') : c.innerText);
});
})(${JSON.stringify(args.selector)}, ${args.maxRows}, ${args.cleanWhitespace})`,
returnByValue: true,
});
const rows = evalRes.result?.value || [];
return {
content: [
{
type: "text",
text: JSON.stringify({ selector: args.selector, rowCount: rows.length, rows }, null, 2),
},
],
};
},
});Tools that only execute API calls, compute transformations, or query local databases should specify requiresSession: false. The host skips launching or connecting to Chrome:
export const dnsLookup = defineTool({
name: "dns_lookup",
description: "Performs DNS record queries without launching a browser",
requiresSession: false,
schema: {
domain: z.string().describe("Domain name to query"),
recordType: z.enum(["A", "AAAA", "CNAME", "MX", "TXT"]).default("A"),
},
handler: async (args) => {
// session is undefined, Chrome is never started
const records = await resolveDns(args.domain, args.recordType);
return {
content: [{ type: "text", text: JSON.stringify(records) }],
};
},
});import { definePlugin, type PluginContext } from "@weavetab/sdk";
import { tableExtractor } from "./tools/extractor.js";
import { tableCommand } from "./commands/table.js";
export default definePlugin({
name: "weavetab-plugin-grid",
version: "1.0.0",
description: "Grid extraction and data transformation tools",
instructions: "Grid extraction and data transformation tools.",
defaultConfig: {
defaultLimit: 50,
},
// Statically registered tools & commands
tools: [tableExtractor],
commands: [tableCommand],
// Lifecycle hooks
async onLoad(ctx: PluginContext) {
ctx.logger.info(`Loaded grid plugin with limit=${ctx.config.defaultLimit}`);
},
async onUnload(ctx: PluginContext) {
ctx.logger.info("Unloaded grid plugin");
},
});For plugins requiring conditional tool mounting or middleware interceptors (permissions are declared exclusively in weavetab.json):
import { PluginBuilder, z } from "@weavetab/sdk";
export default new PluginBuilder("weavetab-plugin-security")
.version("1.0.0")
.description("Security auditor and URL sanitizer")
.instructions("Security auditor and URL sanitizer.")
.defaultConfig({ strictAudit: true })
.addTool({
name: "security_scan",
description: "Audits page headers, cookies, and scripts for security compliance",
schema: {
deep: z.boolean().default(false),
},
handler: async (args, callCtx) => {
return { content: [{ type: "text", text: "Security scan passed." }] };
},
})
.onBeforeAction(async (tool, args, session) => {
// Block navigations to unencrypted HTTP addresses
if (tool === "browser_navigate" && typeof args.url === "string" && args.url.startsWith("http://")) {
return { __blocked: true, reason: "Plain HTTP navigation blocked by security policy." };
}
})
.onPageNavigate(async (url) => {
// React to page navigations (requires permissions.hooks.onPageNavigate)
})
.onLoad(async (ctx) => {
ctx.logger.info("Security interceptor armed.");
})
.build();The PluginContext passed to onLoad(ctx) gives plugins access to Weavetab's subsystem APIs:
| Subsystem | Type | Responsibility |
|---|---|---|
ctx.name |
string |
Unique npm package identifier declared in weavetab.json. |
ctx.version |
string |
Plugin semver version. |
ctx.pluginDir |
string |
Absolute path to ~/.weavetab/plugins/<name>/. |
ctx.config |
Record<string, unknown> |
Merged configuration from defaults and ~/.weavetab/plugins/<name>/config.json. |
ctx.cli |
PluginCliContext |
Register CLI subcommands invoked via weavetab plugin use <pkg> <cmd>. |
ctx.mcp |
PluginMcpContext |
Register MCP tools, / prompt templates, @ resources, and tool overrides. |
ctx.storage |
PluginStorage |
Isolated persistent key-value store, TTL cache, and JSON file system. |
ctx.tab |
TabProxy (optional) |
Lightweight CDP tab wrapper (isAvailable, url, title, evaluate, waitForSelector, extract). |
ctx.desktop |
DesktopProxy (optional) |
Electron desktop app discovery client (isAvailable, listApps, getApp, getTargets(portOrName)). |
ctx.extension |
PluginExtensionBridge |
In-browser visual extensions: floating thoughts, HUD state, panels, CSS/JS injection. |
ctx.memory |
PluginMemoryContext (optional) |
Cross-session persistent site profiles and workflow pattern memory. |
ctx.hooks |
PluginHooks |
Runtime execution interceptors (onBeforeAction, onAfterAction, onDOMMutation, onPageNavigate). |
ctx.logger |
PluginLogger |
Scoped logger writing to ~/.weavetab/logs/ with level gating (info, warn, error, debug). |
Tool handlers with 2 parameters (args, toolCtx) receive a ToolExecutionContext containing tab, desktop, storage, extension, config, logger, signal, and session.
interface TabProxy {
isAvailable(): boolean;
url(): Promise<string>;
title(): Promise<string>;
evaluate<T = any>(fn: string | ((...args: any[]) => T), ...args: any[]): Promise<T>;
waitForSelector(selector: string, opts?: { timeoutMs?: number; visible?: boolean }): Promise<boolean>;
extract(selector: string, mode?: "text" | "html" | "value"): Promise<string | null>;
}
interface DesktopProxy {
isAvailable(): boolean;
listApps(): Promise<DiscoveredApp[]>;
getApp(name: string): Promise<DiscoveredApp | null>;
getTargets(portOrName: number | string): Promise<any[]>;
}interface PluginCliContext {
// Registers a terminal command callable via `weavetab plugin use <pkg> <cmd>`
registerCommand(cmd: DefinedCommand): void;
// Unregisters a command dynamically
unregisterCommand?(name: string): void;
}interface PluginMcpContext {
registerTool(tool: DefinedTool | McpToolRegistration): void;
registerPrompt(prompt: DefinedPrompt): void;
registerResource(resource: DefinedResource): void;
overrideTool?(name: string, overrideHandler: ToolOverrideHandler | Omit<ToolOverrideDefinition, "name">): void;
removeTool?(name: string): void;
unregisterTool?(name: string): void;
unregisterPrompt?(name: string): void;
unregisterResource?(uriOrName: string): void;
}interface PluginStorage {
get<T = any>(key: string, defaultValue?: T): Promise<T | null>;
set<T = any>(key: string, value: T): Promise<void>;
delete(key: string): Promise<boolean>;
list(subpath?: string): Promise<string[]>;
clear(): Promise<void>;
getJSON<T = any>(filename: string): Promise<T | null>;
setJSON<T = any>(filename: string, data: T): Promise<void>;
getPath(subpath?: string): string;
setWithExpiry<T = any>(key: string, value: T, ttlMs: number): Promise<void>;
getWithExpiry<T = any>(key: string): Promise<T | null>;
remember<T = any>(key: string, ttlMs: number, resolver: () => Promise<T>): Promise<T>;
pruneExpired(): Promise<number>;
}interface PluginExtensionBridge {
send(session: any, message: object): Promise<boolean>;
showThought(session: any, text: string, options?: { durationMs?: number }): Promise<void>;
clearThought(session: any): Promise<void>;
setHudState(session: any, state: { action?: string; badge?: string; badgeColor?: string; groupState?: string }): Promise<void>;
injectStyles(session: any, css: string): Promise<void>;
injectCss(session: any, css: string): Promise<void>;
injectScript<T = any>(session: any, js: string): Promise<T>;
mountPanel(session: any, content: { title?: string; text?: string; html?: string; position?: "bottom-right" | "bottom-left" | "top-right" | "top-left" } | string): Promise<void>;
clearPanel(session: any): Promise<void>;
hideOverlay(session: any): Promise<void>;
restoreOverlay(session: any): Promise<void>;
}Throw PluginError to deliver structured error responses back to agents and terminal callers:
import { PluginError } from "@weavetab/sdk";
throw new PluginError(
"INVALID_TARGET",
"Target selector '#payment-form' was not found in the DOM after 3000ms.",
{ selector: "#payment-form", timeoutMs: 3000 }
);Standard error codes:
INVALID_ARGUMENTS: Argument failed schema validation.EXECUTION_FAILED: Execution threw an unhandled exception.SESSION_REQUIRED: Tool requires an active tab but none is attached.UNAUTHORIZED_CAPABILITY: Plugin attempted an action not declared in itsweavetab.jsonpermissions.RATE_LIMITED: Plugin exceeded its invocation budget.