npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

ai-sdk-provider-opencode-sdk

v0.0.2

Published

AI SDK v5 provider for OpenCode via @opencode-ai/sdk

Downloads

179

Readme

AI SDK Provider for OpenCode

Initial Release: Version 0.0.1 - Compatible with AI SDK v5 and @opencode-ai/sdk.

A community provider for the Vercel AI SDK that enables using AI models through OpenCode and the @opencode-ai/sdk. OpenCode is a terminal-based AI coding assistant that supports multiple providers (Anthropic, OpenAI, Google, and more).

This provider enables you to use OpenCode's AI capabilities through the familiar Vercel AI SDK interface, supporting generateText(), streamText(), generateObject(), and streamObject().

Installation

npm install ai-sdk-provider-opencode-sdk

Prerequisites

  • Node.js >= 18
  • OpenCode CLI installed (npm install -g opencode)
  • Valid API keys configured in OpenCode for your preferred providers

Quick Start

import { generateText } from 'ai';
import { opencode } from 'ai-sdk-provider-opencode-sdk';

const result = await generateText({
  model: opencode('anthropic/claude-opus-4-5-20251101'),
  prompt: 'What is the capital of France?',
});

console.log(result.text);

Usage

Creating a Provider

import { createOpencode } from 'ai-sdk-provider-opencode-sdk';

// Default provider (auto-starts server)
const opencode = createOpencode();

// With custom settings
const opencode = createOpencode({
  hostname: '127.0.0.1',
  port: 4096,
  autoStartServer: true,
  serverTimeout: 10000,
  defaultSettings: {
    agent: 'build',
    sessionTitle: 'My Session',
  },
});

Model Selection

Models are specified in providerID/modelID format:

// Anthropic models (Claude 4.5 series)
opencode('anthropic/claude-sonnet-4-5-20250929')
opencode('anthropic/claude-haiku-4-5-20251001')
opencode('anthropic/claude-opus-4-5-20251101')

// OpenAI models (GPT-5.1 series)
opencode('openai/gpt-5.1')
opencode('openai/gpt-5.1-codex')
opencode('openai/gpt-5.1-codex-mini')
opencode('openai/gpt-5.1-codex-max')

// Google Gemini models
opencode('google/gemini-3-pro-preview')
opencode('google/gemini-2.5-flash')
opencode('google/gemini-2.5-pro')
opencode('google/gemini-2.0-flash')

Streaming

import { streamText } from 'ai';

const result = streamText({
  model: opencode('anthropic/claude-opus-4-5-20251101'),
  prompt: 'Write a haiku about coding.',
});

for await (const chunk of result.textStream) {
  process.stdout.write(chunk);
}

Conversation History

import { generateText, type CoreMessage } from 'ai';

const messages: CoreMessage[] = [
  { role: 'user', content: 'My name is Alice.' },
  { role: 'assistant', content: 'Hello Alice! How can I help you today?' },
  { role: 'user', content: 'What is my name?' },
];

const result = await generateText({
  model: opencode('anthropic/claude-opus-4-5-20251101'),
  messages,
});

Agent Selection

OpenCode supports different agents for different tasks:

const model = opencode('anthropic/claude-opus-4-5-20251101', {
  agent: 'build',  // or 'plan', 'general', 'explore'
});

Session Management

Sessions maintain conversation context:

const model = opencode('anthropic/claude-opus-4-5-20251101', {
  sessionTitle: 'Code Review Session',
});

// First call creates a session
const result1 = await generateText({ model, prompt: 'Review this code...' });

// Subsequent calls reuse the same session
const result2 = await generateText({ model, prompt: 'What did you find?' });

// Get session ID from metadata
const sessionId = result1.providerMetadata?.opencode?.sessionId;

// Resume a specific session
const resumeModel = opencode('anthropic/claude-opus-4-5-20251101', {
  sessionId: sessionId,
});

Tool Observation

OpenCode executes tools server-side. You can observe tool execution but cannot provide custom implementations:

import { streamText } from 'ai';

const result = streamText({
  model: opencode('anthropic/claude-opus-4-5-20251101'),
  prompt: 'List files in the current directory.',
});

for await (const part of result.fullStream) {
  if (part.type === 'tool-call') {
    console.log(`Tool: ${part.toolName}`);
    console.log(`Input: ${part.args}`);
  }
  if (part.type === 'tool-result') {
    console.log(`Result: ${part.result}`);
  }
}

Feature Support

| Feature | Support | Notes | |---------|---------|-------| | Text generation | ✅ Full | generateText(), streamText() | | Streaming | ✅ Full | Real-time SSE streaming | | Multi-turn conversations | ✅ Full | Session-based context | | Tool observation | ✅ Full | See tool execution | | Reasoning/thinking | ✅ Full | ReasoningPart support | | Model selection | ✅ Full | Per-request model | | Agent selection | ✅ Full | build, plan, general, explore | | Abort/cancellation | ✅ Full | AbortSignal support | | Image input (base64) | ⚠️ Partial | Data URLs only | | Image input (URL) | ❌ None | Not supported | | JSON mode | ⚠️ Partial | Prompt-based | | Custom tools | ❌ None | Server-side only | | temperature/topP/topK | ❌ None | Provider defaults | | maxTokens | ❌ None | Agent config |

Provider Settings

interface OpencodeProviderSettings {
  hostname?: string;        // Default: '127.0.0.1'
  port?: number;            // Default: 4096
  baseUrl?: string;         // Override full URL
  autoStartServer?: boolean; // Default: true
  serverTimeout?: number;   // Default: 10000
  defaultSettings?: OpencodeSettings;
}

Model Settings

interface OpencodeSettings {
  sessionId?: string;       // Resume session
  createNewSession?: boolean; // Force new session
  sessionTitle?: string;    // Title for new sessions
  agent?: string;           // Agent name
  systemPrompt?: string;    // Override system prompt
  tools?: Record<string, boolean>; // Enable/disable tools
  cwd?: string;             // Working directory
  logger?: Logger | false;  // Logging
  verbose?: boolean;        // Debug logging
}

Error Handling

The provider converts OpenCode errors to AI SDK error types:

import { isAuthenticationError, isTimeoutError } from 'ai-sdk-provider-opencode-sdk';

try {
  const result = await generateText({ model, prompt: '...' });
} catch (error) {
  if (isAuthenticationError(error)) {
    console.error('Check your API keys in OpenCode');
  } else if (isTimeoutError(error)) {
    console.error('Request timed out');
  }
}

Cleanup

Always dispose of the provider when done to stop the managed server:

const opencode = createOpencode();

// ... use the provider ...

// Clean up
await opencode.dispose?.();

License

MIT