> ## Documentation Index
> Fetch the complete documentation index at: https://docs.enconvo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Extension API Reference

> Look up the @enconvo/api building blocks a plugin uses: entry points, requests and responses, native helpers, storage, streams and providers.

This reference is for plugin developers who already have a project from [Developing Extensions](https://docs.enconvo.ai/extensions/developing.md) and need the exact SDK call for a job: reading the request, answering in chat, streaming, calling other commands, using the clipboard, storing data, or building a provider.

Each command runs in its own Worker thread inside Enconvo's Node.js runtime. The runtime talks to the Mac app over a local Unix domain socket, with JSON-RPC-style messages; the SDK wraps all of it.

> [!NOTE]
>
> All imports in this reference come from `@enconvo/api` unless otherwise noted.

## Entry points

A plugin file exports one default function. What it takes and returns depends on what the file is.

### Standard command

```typescript theme={null}
// src/my_command.ts
import { Commander, EnconvoResponse } from "@enconvo/api";

export default async function main(req: Request): Promise<EnconvoResponse> {
  const options = await req.json();
  const result = processInput(options.input_text);
  return EnconvoResponse.text(result);
}
```

### Provider command

```typescript theme={null}
// src/my_provider.ts
export default function main(options: any) {
  return new MyProvider(options);
}
```

See [Providers](#providers) and [AI Model and Voice Plugins](https://docs.enconvo.ai/extensions/provider-plugins.md).

### API route

```typescript theme={null}
// src/api/my_endpoint.ts
export default async function main(request: Request) {
  const params = await request.json();
  return Response.json({ result: "ok" });
}
```

## API routes

Files placed in `src/api/` are automatically discovered and registered as API routes during build. No `package.json` entry is needed.

### Single file route

```
src/api/status.ts  →  extensionName/status
```

```typescript theme={null}
// src/api/status.ts
export default async function main(request: Request) {
  return Response.json({ status: "ok", uptime: process.uptime() });
}
```

### Directory route

```
src/api/users/          →  extensionName/users (auto-generated router)
src/api/users/list.ts   →  extensionName/users/list
src/api/users/create.ts →  extensionName/users/create
```

```typescript theme={null}
// src/api/users/list.ts
interface ListParams {
  /** Maximum number of users to return @default 20 */
  limit?: number;
  /** Page offset @required */
  offset: number;
}

export default async function main(request: Request) {
  const params = await request.json() as ListParams;
  // The interface is parsed for automatic schema generation
  return Response.json({ users: [], total: 0 });
}
```

### JSDoc annotations

| Annotation | Effect |
| - | - |
| `@private` (or `@hidden`) on export | Hides the route from generated API docs and schemas |
| `@private` on interface field | Hides that field |
| `@required` on interface field | Marks parameter as required. A field without `?` is required too |
| `@default <value>` on interface field | Sets default value in schema |

### Generated files

The build system generates:

* `skills/schemas.json` -- JSON schema for all API endpoints
* `skills/<plugin name>/SKILL.md` -- when the file exists, the build updates its front matter and its table of API routes, for AI agent discovery

## Requests and responses

### Request object

A command receives a standard `Request`. The body contains `RequestOptions` -- a merged object of command configuration, user preferences, and runtime parameters.

```typescript theme={null}
export default async function main(req: Request) {
  const options: RequestOptions = await req.json();

  // Common fields
  options.input_text;          // User input text
  options.selection_text;      // Selected text
  options.context;             // Additional context, as text
  options.context_items;       // Context items attached to the request
  options.context_files;       // Attached files
  options.history_messages;    // Previous conversation history (for chat/agent)
  options.tools;               // Tools the request names, as { tool_name }
  options.commandType;         // "agent" | "chat" | "tool" | "provider" | etc.
  options.commandName;         // Current command name
  options.extensionName;       // Current extension name
  options.runType;             // "agent" | "flow" | "command" | "api"

  // All preference values are accessible by their name
  options.my_custom_preference; // Value of preference named "my_custom_preference"
}
```

### EnconvoResponse

The return type for command handlers. Multiple factory methods create different response types.

#### EnconvoResponse.text

Returns a simple text response displayed as a chat message.

```typescript theme={null}
return EnconvoResponse.text("Here is your result");
```

#### EnconvoResponse.messages

Returns one or more structured chat messages with rich content.

```typescript theme={null}
import { BaseChatMessage, ChatMessageContent } from "@enconvo/api";

return EnconvoResponse.messages([
  BaseChatMessage.assistant([
    ChatMessageContent.text("Here is the analysis:"),
    ChatMessageContent.imageUrl({ url: "https://example.com/chart.png" })
  ])
]);
```

#### EnconvoResponse.json

Returns a JSON object as a text response (serialized).

```typescript theme={null}
return EnconvoResponse.json({ status: "ok", count: 42 });
```

#### EnconvoResponse.none

Returns nothing -- useful for commands that produce side effects only.

```typescript theme={null}
await Clipboard.copy("copied text");
return EnconvoResponse.none();
```

#### EnconvoResponse.error

Returns an error message displayed to the user.

```typescript theme={null}
return EnconvoResponse.error("API key is missing", 401);
```

#### Returning a string

You can also return a plain string, which is automatically wrapped as a text response.

```typescript theme={null}
export default async function main(req: Request) {
  return "Simple text response";
}
```

### Action

Response actions displayed as buttons below chat messages. Pass them as the second argument of `EnconvoResponse.messages`.

```typescript theme={null}
import { Action } from "@enconvo/api";

return EnconvoResponse.messages(
  [BaseChatMessage.assistant([ChatMessageContent.text("Done!")])],
  [
    Action.OpenLink({ url: "https://example.com", title: "Open Website" }),
    Action.OpenConfig({ page: "key_management", title: "Configure Keys" })
  ]
);
```

Enconvo adds a **Retry** button (`Action.Retry`) to every response that has actions, so don't add one yourself.

### Streaming with res

The `res` namespace provides methods for streaming partial results back to the UI during command execution.

#### res.write

Stream content incrementally to the chat UI.

```typescript theme={null}
import { res, EnconvoResponse, AssistantMessage, ChatMessageContent } from "@enconvo/api";

// Stream text content
await res.write({
  content: "Partial result...",
  action: EnconvoResponse.WriteAction.AppendToLastMessageLastTextContent
});

// Stream a structured message
await res.write({
  content: new AssistantMessage([ChatMessageContent.text("Updated content")]),
  action: EnconvoResponse.WriteAction.OverwriteLastMessage
});
```

#### res.writeLoading

Display a loading indicator in the chat UI.

```typescript theme={null}
await res.writeLoading("Analyzing document...");
```

#### Write actions

Control how streamed content updates the UI:

| Action | Behavior |
| - | - |
| `AppendToLastMessageLastTextContent` | Append text to the last message's text content |
| `OverwriteLastMessage` | Replace the entire last message |
| `OverwriteLastMessageAllContent` | Replace all content in the last message |
| `AppendToLastMessageContent` | Append a new content block to the last message |
| `AppendMessage` | Add a new message to the conversation |

`EnconvoResponse.WriteAction` has more members for thinking text, tool messages and workflows; your editor lists them all.

## Talk to Enconvo and other plugins

### Commander

The `Commander` namespace handles all communication between extension Worker threads and the Enconvo host process.

#### Commander.addClickListener

Registers the main entry point handler for a command. The build/runtime adapter uses this registration mechanism. For ordinary plugin command files, use the default-exported handler shown in [Entry points](#entry-points), rather than registering the same handler twice.

```typescript theme={null}
import { Commander, EnconvoResponse } from "@enconvo/api";

Commander.addClickListener(async (req: Request) => {
  const options = await req.json();
  // Process the request
  return EnconvoResponse.text("Hello from my extension!");
});
```

The `req` parameter is a standard `Request` object. Use `req.json()` to access the merged command configuration and user-provided parameters.

#### Commander.send

Send a request to the native macOS app. Returns a Promise for the matching response. Use `sendAsync` only when the operation does not need a result.

```typescript theme={null}
// Send a custom method with payloads
await Commander.send("responseStream", {
  type: "messages",
  messages: [message]
});
```

#### Commander.sendRequest

Request/response communication with the native app. Returns a Promise resolved when the host sends back a matching response.

```typescript theme={null}
const result = await Commander.sendRequest({
  method: "getSelectedText",
  payloads: {}
});
```

`extensionName` and `commandName` default to the current command's. To read the selection, `Clipboard.selectedText()` does this for you.

#### Commander.sendAsync

Non-blocking fire-and-forget message. Does not wait for acknowledgment.

```typescript theme={null}
Commander.sendAsync("responseStream", { type: "text", content: "partial result" });
```

### NativeAPI

The `NativeAPI` namespace provides typed methods for calling native macOS operations and invoking other extension commands.

#### NativeAPI.callCommand

Invoke any other extension command programmatically, by its key `extensionName|commandName`.

```typescript theme={null}
import { NativeAPI } from "@enconvo/api";

// Run the hello command of the hello_enconvo plugin
const result = await NativeAPI.callCommand("hello_enconvo|hello", {
  input_text: "Ada"
});
```

#### NativeAPI.request / NativeAPI.api

Call extension API routes (files in `src/api/`). `request` is another name for `api`.

```typescript theme={null}
// Call an API endpoint
const response = await NativeAPI.request("knowledge_base/search", {
  knowledge_base_id_list: [],   // empty: all your knowledge bases except Memory
  query: ["machine learning"],
  limit: 10
});
```

#### NativeAPI.localApi

Call the local HTTP server API endpoint directly. It returns the HTTP response, so read its body with `.json()`.

```typescript theme={null}
const response = await NativeAPI.localApi("enconvo/extension/available_list", {});
const extensions = await response.json();
```

### NativeEventUtils

Send and listen for events across extensions and the native app.

```typescript theme={null}
import { NativeEventUtils } from "@enconvo/api";

// Send a custom event
await NativeEventUtils.sendEvent("my_custom_event", {
  key: "value"
});
```

`NativeEventUtils.registerEvent(name, callback)` listens for one. Events sent through this system can be hooked by the user via `~/.enconvo/hooks.json` (see [Hooks](https://docs.enconvo.ai/configuration/hooks.md)).

## Mac and app helpers

### Clipboard

Read and write clipboard content, paste into the active application, or insert text below the cursor.

```typescript theme={null}
import { Clipboard } from "@enconvo/api";

// Copy text to clipboard
await Clipboard.copy("text to copy");

// Paste text into the frontmost application
await Clipboard.paste("text to paste");

// Insert text below the current cursor position
await Clipboard.insertBelow("text below cursor");

// Read current clipboard content
const content = await Clipboard.getLatestClipboard();

// Read the text selected in the frontmost application
const selected = await Clipboard.selectedText();
```

### Toast & HUD

Display notifications and heads-up messages.

```typescript theme={null}
import { showToast, showHUD } from "@enconvo/api";

// Show a toast notification
await showToast({ title: "Success", message: "File saved" });

// Show a brief HUD message overlay
await showHUD("Operation complete");
```

### SmartBar & window

Control the SmartBar and window display modes.

```typescript theme={null}
import { SmartBar } from "@enconvo/api";

// Close the SmartBar
await SmartBar.close();
```

### environment

The `environment` object exposes runtime context about the current command execution.

```typescript theme={null}
import { environment } from "@enconvo/api";

environment.extensionName;       // Current extension name
environment.commandName;         // Current command name
environment.commandTitle;        // Display title of the command
environment.assetsPath;          // Path to extension's assets/ directory
environment.supportPath;         // Per-extension support directory
environment.rootSupportPath;     // Root support directory
environment.cachePath;           // Cache directory
environment.isDevelopment;       // true if running in dev mode
environment.appearance;          // "light" | "dark"
environment.textSize;            // "medium" | "large"
environment.sessionId;           // Current session ID
environment.enconvoVersion;      // Enconvo app version
environment.runType;             // "agent" | "command" | "api" | "flow"
environment.flowId;              // Workflow ID (if running in a workflow)
```

### KV (key-value storage)

Persistent key-value storage for extension data. Values persist across command invocations.

```typescript theme={null}
import { KV } from "@enconvo/api";

// String operations
await KV.set("last_query", "machine learning");
const query = await KV.get("last_query", "default_value");

// Number operations
await KV.setNumber("run_count", 42);
const count = await KV.getNumber("run_count", 0);

// Boolean operations
await KV.setBool("feature_enabled", true);
const enabled = await KV.getBool("feature_enabled");
```

`KV.getBool` takes no default, so set a value before you read it.

## Stream

The `Stream` class provides utilities for working with streaming responses, particularly SSE (Server-Sent Events) from LLM APIs.

### Stream.fromSSEResponse

Parse an SSE response into an async iterable of typed objects.

```typescript theme={null}
import { Stream } from "@enconvo/api";

const response = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  body: JSON.stringify({ stream: true, /* ... */ })
});

const controller = new AbortController();
const stream = Stream.fromSSEResponse<ChatCompletionChunk>(response, controller);

for await (const chunk of stream) {
  // Process each SSE chunk
  console.log(chunk.choices[0].delta.content);
}
```

### Stream.fromReadableStream

Parse a newline-delimited JSON `ReadableStream` into typed objects.

```typescript theme={null}
const stream = Stream.fromReadableStream<MyItem>(readableStream, controller);

for await (const item of stream) {
  // Process each JSON item
}
```

### Stream.tee

Split a stream into two independent streams that can be read at different speeds.

```typescript theme={null}
const [stream1, stream2] = stream.tee();
```

### Stream.toReadableStream

Convert back to a `ReadableStream` of newline-delimited JSON.

```typescript theme={null}
const readable = stream.toReadableStream();
```

## Providers

[AI Model and Voice Plugins](https://docs.enconvo.ai/extensions/provider-plugins.md) builds a complete provider plugin step by step. The classes it uses:

### LLMProvider base class

The abstract base class for implementing LLM provider extensions. `_stream` yields Enconvo's content-block events, not your API's raw chunks.

```typescript theme={null}
import { LLMProvider, Stream, BaseChatMessage, BaseChatMessageChunk, ChatMessageContent } from "@enconvo/api";

class MyLLMProvider extends LLMProvider {
  constructor(options: LLMProvider.LLMOptions) {
    super(options);
  }

  // Required: non-streaming completion
  protected async _call(params: LLMProvider.ResolvedParams): Promise<BaseChatMessage> {
    const response = await myApiCall(params.messages, {
      model: this.options.modelName?.value,
      temperature: this.options.temperature?.value
    });
    return BaseChatMessage.assistant([
      ChatMessageContent.text(response.content)
    ]);
  }

  // Required: streaming completion, as content-block events
  protected async _stream(params: LLMProvider.ResolvedParams): Promise<Stream<BaseChatMessageChunk>> {
    const controller = new AbortController();
    async function* events(): AsyncGenerator<BaseChatMessageChunk> {
      yield { type: "content_block_start", content_block: { type: "text", text: "" } };
      for await (const text of myStreamingApiCall(params.messages, controller.signal)) {
        yield { type: "content_block_delta", delta: { type: "text_delta", text } };
      }
      yield { type: "content_block_stop" };
    }
    return new Stream(events, controller);
  }
}

// Entry point
export default function main(options: LLMProvider.LLMOptions) {
  return new MyLLMProvider(options);
}
```

#### LLMProvider.LLMOptions

Key options available on `this.options`:

| Field | Type | Description |
| - | - | - |
| `modelName` | `{ title, value, ... }` | The model picked in the model picker; `value` is the model id |
| `temperature` | `{ title, value: number }` | Sampling temperature |
| Your preferences | any | Every preference of the plugin and the command, by name, such as `api_key` |

The conversation (`messages`), the tools for function calling (`tools`, as `AITool[]`), `maxTokens` and the abort `signal` arrive with each call in `params`.

### TTSProvider base class

The abstract base class for implementing TTS provider extensions.

```typescript theme={null}
import fs from "node:fs";
import { TTSProvider } from "@enconvo/api";

class MyTTSProvider extends TTSProvider {
  constructor(options: TTSProvider.TTSOptions) {
    super({ options });
  }

  // Required: convert text to audio file
  protected async _toFile(params: TTSProvider._ToFileTTSParams): Promise<TTSProvider.TTSItem> {
    const audioBuffer = await myTTSApi(params.text, {
      voice: this.options.voice?.value,
      speed: this.options.speed?.value
    });

    // Enconvo passes the path to write, already ending in the right extension
    fs.writeFileSync(params.audioFilePath, audioBuffer);

    return { path: params.audioFilePath, text: params.text };
  }
}

export default function main(options: TTSProvider.TTSOptions) {
  return new MyTTSProvider(options);
}
```

### ServiceProvider.load

Load and instantiate any provider extension dynamically.

```typescript theme={null}
import { ServiceProvider } from "@enconvo/api";

// Load an LLM provider
const llm = ServiceProvider.load<LLMProvider>(options);

// Load a TTS provider
const tts = ServiceProvider.load<TTSProvider>(options);
```

The `options` object must include `extensionName` and `commandName` identifying the provider to load (or a `commandKey` such as `llm|open_ai`). Provider instances are cached by their options for reuse, and loaded again when the provider's code changes.

## Extension and command management

Utilities for working with extension metadata and configuration.

```typescript theme={null}
import { CommandManageUtils, ExtensionManageUtils, PreferenceManageUtils } from "@enconvo/api";

// Load a command's full configuration
const config = await CommandManageUtils.loadCommandConfig({
  commandKey: "hello_enconvo|hello",
  useAsRunParams: true
});

// Get raw command info (synchronous)
const rawCmd = CommandManageUtils.getRawCommandInfo("llm|open_ai");
```

## Build commands

```bash theme={null}
# Build for production
npx enconvo plugin build

# Dev mode with hot reload
npx enconvo plugin build --dev

# Generate API schema
npx enconvo plugin generate-schema

# Check against the store rules
npx enconvo plugin validate

# Publish to store
npx enconvo plugin publish
```

## Next steps

> [card] [Developing Extensions](https://docs.enconvo.ai/extensions/developing.md)
>
> Step-by-step guide to creating extensions

> [card] [AI Model and Voice Plugins](https://docs.enconvo.ai/extensions/provider-plugins.md)
>
> Add your own model or voice to Enconvo's pickers

> [card] [Skills](https://docs.enconvo.ai/configuration/skills.md)
>
> Package AI instructions as reusable skills

> [card] [Hooks](https://docs.enconvo.ai/configuration/hooks.md)
>
> React to extension events with hooks


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.