Plugin API Reference

Complete reference for the CortexPrism plugin system APIs, covering the lifecycle hooks, capability interface, permission model, and runtime APIs.

Plugin Lifecycle Hooks

Plugins can hook into lifecycle events to perform initialization and cleanup:

export default definePlugin({
  name: "lifecycle-demo",
  version: "1.0.0",

  onInstall(ctx: LifecycleContext): void | Promise<void> {
    // Called when the plugin is first installed
    // Use for one-time setup: create directories, initialize state
  },

  onActivate(ctx: LifecycleContext): void | Promise<void> {
    // Called when the plugin is activated (enabled)
    // Use for per-session setup: connect to services, allocate resources
  },

  onDeactivate(ctx: LifecycleContext): void | Promise<void> {
    // Called when the plugin is deactivated (disabled)
    // Use for cleanup: close connections, release resources
  },

  onUninstall(ctx: LifecycleContext): void | Promise<void> {
    // Called right before the plugin is removed
    // Use for final cleanup: remove data, revoke permissions
  },

  onConfigChange(ctx: LifecycleContext, prev: Record<string, unknown>): void | Promise<void> {
    // Called when plugin configuration changes at runtime
    // Use to hot-reload settings without restart
  },
});

LifecycleContext

PropertyTypeDescription
pluginDirstringPlugin installation directory path
dataDirstringPlugin-scoped data directory for persistent storage
configRecord<string, unknown>Current plugin configuration
logLoggerStructured logger
dbKVStoreSimple key-value store backed by plugins.db

Capability Definition

ESM Capabilities

type CapabilityFunction<TInput = unknown, TOutput = unknown> = (
  input: TInput,
  context: CapabilityContext
) => TOutput | Promise<TOutput>;

CapabilityContext

PropertyTypeDescription
sandboxSandboxAPIRestricted file/network access
logLoggerStructured logger
memoryMemoryAPIRead-only memory access
configRecord<string, unknown>Plugin config scoped to this call
abortSignalAbortSignalSignals timeout/cancellation
requestIdstringUnique ID for this capability invocation

SandboxAPI

interface SandboxAPI {
  readFile(path: string): Promise<string>;
  writeFile(path: string, content: string): Promise<void>;
  readDir(path: string): Promise<string[]>;
  fetch(url: string, options?: RequestInit): Promise<Response>;
  exec(command: string, args?: string[]): Promise<ExecResult>;
  tempDir(): Promise<string>;
}

Each SandboxAPI method is gated by the Parallax policy engine. Access is denied unless the plugin manifest declares the required permission.

MemoryAPI

interface MemoryAPI {
  search(query: string, options?: { limit?: number; tier?: MemoryTier }): Promise<MemoryEntry[]>;
  get(id: string): Promise<MemoryEntry | null>;
}

type MemoryTier = "ephemeral" | "working" | "episodic" | "semantic" | "reflection";

interface MemoryEntry {
  id: string;
  content: string;
  score: number;
  tier: MemoryTier;
  timestamp: number;
}

Plugin Manifest Schema

Full schema for manifest.json:

Required Fields

FieldTypeDescription
namestringUnique plugin identifier (kebab-case). Primary key in the plugin database.
versionstringSemantic version (e.g. 1.0.0).
descriptionstringShort description shown in marketplace and plugin list.
kind`"esm""mcp"
entryPointstringPath to module, URL, or WASM binary (relative to manifest).
runtime`"deno""wasm"`
capabilitiesstring[]Declared extension points and permissions.

Optional Fields

FieldTypeDescription
authorstringAuthor name or organization.
homepagestring (url)Plugin homepage URL.
licensestringSPDX license identifier (e.g. MIT).
repositorystring (url)Source repository URL.
hashstringSHA-256 hash of entry point for integrity verification.
signaturestringOptional GPG/JWT signature for trust verification.
iconstringPath to icon file.
dependenciesRecord<string, string>Other plugins required, keyed by name with semver constraints.
peerDependenciesRecord<string, string>Host CortexPrism version constraint.
toolsToolDeclaration[]Tool definitions (names, params). ESM plugins provide the implementation.
cliCommandsCliCommandDeclaration[]CLI subcommand specifications.
uiUiContributionUI panels, widgets, and settings forms.
configConfigContributionConfig schema extensions and defaults.
eventsstring[]Event types the plugin subscribes to.
permissionsobjectGranular sandbox permissions.
mcpobjectMCP-specific transport and timeout settings.
wasmobjectWASM-specific memory and allocator settings.

Capabilities

Capabilities serve dual purpose: they declare what extension points the plugin uses AND what permissions it needs.

Extension Point Capabilities:

ValueDescription
toolsPlugin provides Tool[]
cli:commandsPlugin provides CLI subcommands
ui:panelPlugin provides a Web UI panel/tab
ui:widgetPlugin provides a dashboard widget
config:schemaPlugin extends config schema
config:providerPlugin provides an LLM provider
memory:storePlugin provides a custom memory backend
memory:embedderPlugin provides an embedding provider
events:listenerPlugin subscribes to event bus
middleware:prePlugin provides pre-execution middleware
middleware:postPlugin provides post-execution middleware

Permission Capabilities:

ValueDescription
fs:readRead filesystem access
fs:writeWrite filesystem access
fs:listDirectory listing
fs:editFile editing
fs:deleteFile deletion
fs:searchFile searching
shell:runShell command execution
network:fetchOutbound HTTP requests
net:outboundGeneral outbound network access
net:inboundInbound network (listening)
db:readDatabase read access
db:writeDatabase write access

ToolDeclaration

{
  "tools": [
    {
      "name": "my_tool",
      "description": "What this tool does",
      "params": [
        { "name": "input", "type": "string", "description": "Input value", "required": true }
      ]
    }
  ]
}

CliCommandDeclaration

{
  "cliCommands": [
    {
      "name": "my-cmd",
      "description": "My custom command",
      "args": [
        { "name": "target", "type": "string", "description": "Target to operate on", "required": true }
      ],
      "options": [
        { "name": "verbose", "type": "boolean", "description": "Verbose output", "flag": "-v" }
      ]
    }
  ]
}

UiContribution

{
  "ui": {
    "panels": [
      { "id": "my-panel", "title": "My Panel", "icon": "star", "htmlPath": "./ui/panel.html" }
    ],
    "widgets": [
      { "id": "my-widget", "title": "My Widget", "type": "html", "config": {} }
    ],
    "settings": [
      {
        "section": "General",
        "fields": [
          { "key": "apiKey", "label": "API Key", "type": "secret", "defaultValue": "" },
          { "key": "maxRetries", "label": "Max Retries", "type": "number", "defaultValue": 3 },
          { "key": "enabled", "label": "Enabled", "type": "boolean", "defaultValue": true },
          {
            "key": "mode", "label": "Mode", "type": "select",
            "defaultValue": "auto",
            "options": [
              { "label": "Automatic", "value": "auto" },
              { "label": "Manual", "value": "manual" }
            ]
          }
        ]
      }
    ]
  }
}

UiSettingField Types:

TypeDescription
textSingle-line text input
numberNumeric input
booleanCheckbox toggle
selectDropdown with options array
secretPassword field (masked input)

ConfigContribution

{
  "config": {
    "providers": [
      { "kind": "my-provider", "label": "My Provider", "defaultModel": "my-model-v1" }
    ],
    "settings": {
      "defaultEndpoint": "https://api.example.com"
    }
  }
}

Trust Levels

LevelSandboxPermissions
untrustedWorker sandboxLimited to declared permissions
signedWorker sandboxBroader permissions based on signature
trustedIn-processFull declared permissions

Trust level is set at install time and can be changed via cortex plugins permissions <name>.

Full Manifest Example

{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "An example plugin with tools, UI panel, and settings",
  "kind": "esm",
  "entryPoint": "./mod.ts",
  "runtime": "deno",
  "capabilities": ["tools", "ui:panel", "network:fetch"],
  "author": "Your Name",
  "license": "MIT",
  "repository": "https://github.com/you/my-plugin",
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather for a city",
      "params": [
        { "name": "city", "type": "string", "description": "City name", "required": true }
      ]
    }
  ],
  "cliCommands": [
    {
      "name": "my-command",
      "description": "My custom CLI command",
      "options": [
        { "name": "verbose", "type": "boolean", "flag": "-v" }
      ]
    }
  ],
  "ui": {
    "panels": [
      { "id": "weather", "title": "Weather", "icon": "cloud", "htmlPath": "./ui/panel.html" }
    ],
    "settings": [
      {
        "section": "API",
        "fields": [
          { "key": "apiKey", "label": "API Key", "type": "secret", "defaultValue": "" }
        ]
      }
    ]
  }
}

Runtime API (Available to ESM Plugins)

Global Objects

ObjectDescription
CortexPrismVersion info and build metadata
fetchGlobal fetch (limited by policy)
consoleScoped console (prefixed with plugin name)

Importable SDK

import {
  definePlugin,        // Type-safe plugin definition
  z,                   // Zod validation
  HttpError,           // 400-level errors
  PermissionError,     // Policy denial errors
  PluginError,         // Generic plugin errors
  TimeoutError,        // Capability timeout errors
} from "@cortexprism/plugin-sdk";

Error Types

Error ClassHTTP StatusWhen to Use
PluginError500Unexpected internal errors
HttpError400-599Client errors, service unavailable
PermissionError403Policy denial
TimeoutError408Operation exceeded time limit

Registry DB Schema (plugins.db)

The plugin registry is stored in plugins.db with this schema:

CREATE TABLE plugins (
  id          TEXT PRIMARY KEY,
  name        TEXT NOT NULL UNIQUE,
  version     TEXT NOT NULL,
  type        TEXT NOT NULL CHECK(type IN ('esm','mcp','wasm')),
  entry_point TEXT NOT NULL,
  manifest    TEXT NOT NULL,       -- Full manifest as JSON
  enabled     INTEGER DEFAULT 1,
  installed_at TEXT NOT NULL,
  updated_at  TEXT NOT NULL,
  download_count INTEGER DEFAULT 0
);

CREATE TABLE plugin_permissions (
  id          TEXT PRIMARY KEY,
  plugin_id   TEXT NOT NULL REFERENCES plugins(id),
  permission  TEXT NOT NULL,
  granted     INTEGER DEFAULT 0
);

CREATE TABLE plugin_config (
  plugin_id TEXT PRIMARY KEY REFERENCES plugins(id),
  config    TEXT NOT NULL DEFAULT '{}'
);

CLI Commands

cortex plugin install <source>     # Install from marketplace, path, npm, jsr, or URL
cortex plugin uninstall <name>     # Remove a plugin
cortex plugin list                  # List installed plugins with status
cortex plugin enable <name>        # Activate a plugin
cortex plugin disable <name>       # Deactivate without removing
cortex plugin config <name>        # View or set plugin configuration
cortex plugin info <name>          # Show plugin details and capabilities
cortex plugin call <name> <cap>    # Invoke a capability directly (for testing)