@bunny-agent/sdk

中文文档
0.10.3-beta1发布于 2026/11/07Apache-2.0TypeScriptES Module近 30 天下载 7219

BunnyAgent SDK - AI Provider and React hooks for building AI agents

原始使用文档
文档目录20 节
  1. Why @bunny-agent/sdk?
  2. Features
  3. Quick Start
  4. 1. Install
  5. 2. Backend — Create an API Route (Next.js)
  6. 3. Frontend — Chat UI
  7. 4. Run
  8. Local vs Cloud Sandbox
  9. Local Mode (Desktop apps & debugging)
  10. Cloud Mode — Sandock (Recommended)
  11. Other Cloud Sandboxes
  12. Agent Templates
  13. Request-Scoped MCP Servers
  14. React Hooks
  15. API Reference
  16. Provider
  17. Exports
  18. Environment Variables
  19. Documentation
  20. License

@bunny-agent/sdk

Plug Coding Agent superpowers into your product — in one afternoon.

Turn Claude Code, Anthropic Agent SDK, Codex CLI, OpenCode, and other Coding Agents into an AI SDK-compatible model you can stream from any backend and render in any React UI.

npm License AI SDK


Why @bunny-agent/sdk?

Coding Agents (Claude Code, Codex CLI, Gemini CLI, OpenCode …) already have:

  • ✅ Sophisticated memory & context management
  • ✅ Battle-tested tool use (bash, file I/O, web search)
  • ✅ MCP server ecosystem
  • ✅ Refined prompts from millions of interactions

@bunny-agent/sdk lets you harness all of that inside your own product — as a standard AI SDK model, with zero prompt engineering.

Your App  →  @bunny-agent/sdk  →  Coding Agent (Claude / Codex / …)
                                      ↕
                              Sandbox (Local or Cloud)

Features

FeatureDescription
🔌 AI SDK ProvidercreateBunnyAgent() returns a model you pass to streamText / generateText
⚛️ React HooksuseBunnyAgentChat, useArtifacts, useWriteTool, useAskUserQuestion
🖥️ Local ModeBuilt-in LocalMachine (no isolation) and SrtSandbox (OS-level isolation) — run on your machine for Desktop apps & debugging
☁️ Cloud SandboxesPlug in Sandock, E2B, or Daytona for isolated cloud execution
🎨 Agent TemplatesMarkdown-based templates turn a generic agent into a domain expert
🔄 Multi-turn SessionsResume conversations with full filesystem continuity

Quick Start

1. Install

npm install @bunny-agent/sdk ai

2. Backend — Create an API Route (Next.js)

// app/api/ai/route.ts
import { createBunnyAgent, LocalMachine } from "@bunny-agent/sdk";
import {
  convertToModelMessages,
  createUIMessageStream,
  createUIMessageStreamResponse,
  streamText,
} from "ai";

export async function POST(request: Request) {
  const { messages } = await request.json();

  const sandbox = new LocalMachine({
    workdir: process.cwd(),
    templatesPath: process.cwd(),
    runnerCommand: ["npx", "-y", "@bunny-agent/runner-cli@latest", "run"],
    env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! },
  });

  const bunnyAgent = createBunnyAgent({
    sandbox,
    cwd: sandbox.getWorkdir(),
  });

  const stream = createUIMessageStream({
    execute: async ({ writer }) => {
      const result = streamText({
        model: bunnyAgent("sonnet"),
        messages: await convertToModelMessages(messages),
        abortSignal: request.signal,
      });
      writer.merge(result.toUIMessageStream());
    },
  });

  return createUIMessageStreamResponse({ stream });
}

3. Frontend — Chat UI

"use client";
import { useBunnyAgentChat } from "@bunny-agent/sdk/react";

export default function Chat() {
  const { messages, isLoading, sendMessage } = useBunnyAgentChat({
    apiEndpoint: "/api/ai",
  });

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          {m.parts.map((p, i) => p.type === "text" && <span key={i}>{p.text}</span>)}
        </div>
      ))}
      <form onSubmit={(e) => { e.preventDefault(); sendMessage(e.currentTarget.input.value); }}>
        <input name="input" placeholder="Ask anything…" />
        <button disabled={isLoading}>Send</button>
      </form>
    </div>
  );
}

4. Run

export ANTHROPIC_API_KEY=sk-ant-xxx
npm run dev

That's it — you now have a full Coding Agent streaming into your app.


Local vs Cloud Sandbox

Local Mode (Desktop apps & debugging)

LocalMachine is built-in — no extra packages needed. The agent runs directly on your machine's filesystem, with your user's permissions and no isolation (it was previously named LocalSandbox; that alias still works but is deprecated). When you want actual OS-level isolation on the local machine, use SrtSandbox instead — same API, but every command is wrapped with Anthropic's sandbox runtime (bubblewrap on Linux, Seatbelt on macOS): writes are restricted to the workdir, network access is blocked unless you allowlist domains.

import { createBunnyAgent, SrtSandbox } from "@bunny-agent/sdk";

const sandbox = new SrtSandbox({
  workdir: "/path/to/project",
  isolation: {
    allowedDomains: ["api.anthropic.com", "*.npmjs.org"],
    denyRead: ["~/.ssh", "~/.aws"],
    allowWrite: ["~/.npm"], // runners that write to the home dir need this
  },
});

Linux needs bubblewrap + socat installed (and on Ubuntu 24.04+, an AppArmor profile that grants userns to bwrap). macOS works out of the box.

import { createBunnyAgent, LocalMachine } from "@bunny-agent/sdk";

const sandbox = new LocalMachine({
  workdir: "/path/to/project",
  templatesPath: "./my-agent-template",
  env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! },
});

const bunnyAgent = createBunnyAgent({ sandbox, cwd: sandbox.getWorkdir() });

Best for: Electron/Tauri desktop apps, local development, debugging.

Sandock provides Docker-based cloud sandboxes with persistent volumes.

Why Sandock? Coding Agents rely on filesystem append and other POSIX semantics. Sandock is the only cloud sandbox with 100% POSIX-compatible filesystems, ensuring agents run without FS failures. Volumes are persistent and shareable across sandboxes.

npm install @bunny-agent/sandbox-sandock
import { createBunnyAgent } from "@bunny-agent/sdk";
import { SandockSandbox } from "@bunny-agent/sandbox-sandock";

const sandbox = new SandockSandbox({
  apiKey: process.env.SANDOCK_API_KEY,   // Get yours at https://sandock.ai
  image: "ghcr.io/vikadata/bunny-agent:latest",     // Pre-built image (fast startup)
  skipBootstrap: true,
  workdir: "/workspace",
  env: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY! },
  // Optional: persistent volumes
  volumes: [
    { volumeName: "my-workspace", volumeMountPath: "/workspace" },
  ],
});

const bunnyAgent = createBunnyAgent({ sandbox, cwd: sandbox.getWorkdir() });
Sandock OptionDescription
apiKeyYour Sandock API key (sandock.ai)
imageDocker image — use ghcr.io/vikadata/bunny-agent:latest for pre-built, or sandockai/sandock-code:latest
skipBootstraptrue when using pre-built image (skips npm install inside sandbox)
volumesNamed volumes for persistent workspace & session storage
keeptrue (default) keeps sandbox alive ~30 min after execution
memoryLimitMbMemory limit in MB

Other Cloud Sandboxes

npm install @bunny-agent/sandbox-e2b      # E2B cloud sandbox
npm install @bunny-agent/sandbox-daytona   # Daytona workspace
import { E2BSandbox } from "@bunny-agent/sandbox-e2b";
const sandbox = new E2BSandbox({ apiKey: process.env.E2B_API_KEY });

import { DaytonaSandbox } from "@bunny-agent/sandbox-daytona";
const sandbox = new DaytonaSandbox({ apiKey: process.env.DAYTONA_API_KEY });

Agent Templates

Templates customize what the agent knows and how it behaves — pure Markdown, no code.

my-agent/
├── CLAUDE.md              # System instructions
├── skills/
│   └── sql-expert/
│       └── SKILL.md       # Modular capability
└── .claude/
    └── mcp.json           # MCP server integrations
const sandbox = new LocalMachine({
  workdir: process.cwd(),
  templatesPath: "./templates/analyst",  // Point to your template
});

Built-in templates: default, coder, analyst, researcher, seo-agent.


Request-Scoped MCP Servers

The Pi runner accepts MCP configuration per model request. The configuration travels through daemon JSON or a one-shot runner CLI payload and is never written to the workspace:

const bunnyAgent = createBunnyAgent({
  sandbox,
  runnerType: "pi",
  allowedTools: ["read", "bash", "mcp"],
  mcpConfig: {
    mcpServers: {
      analytics: {
        url: "https://mcp.example.com/rpc",
        headers: {
          "X-API-Key": process.env.ANALYTICS_MCP_KEY!,
        },
        auth: false,
        lifecycle: "lazy",
        directTools: false,
      },
    },
    settings: {
      hostConfigDiscovery: "off",
      outputGuard: true,
    },
  },
});

Trusted SDK callers may also configure stdio servers with command, args, env, and cwd; those commands execute inside the selected sandbox. An explicit allowedTools list must include mcp.

Configuration is request-scoped. A new configuration applies to the next message, including a resumed conversation, while an active turn keeps the configuration it started with. OAuth and active-turn hot replacement are not provided by this API.

Public web routes should not accept this trusted shape directly. Convert a strict HTTPS-only input into McpConfig, reject localhost/private targets and unsafe headers, and enforce network egress policy at the sandbox boundary.


React Hooks

All hooks are available from @bunny-agent/sdk/react:

import {
  useBunnyAgentChat,     // Full chat with streaming
  useArtifacts,         // Display agent-generated files (reports, charts)
  useWriteTool,         // Handle file write tool calls
  useAskUserQuestion,   // Handle interactive questions from the agent
} from "@bunny-agent/sdk/react";

API Reference

Provider

createBunnyAgent — sandbox transport (cloud / local filesystem)

import { createBunnyAgent, LocalMachine } from "@bunny-agent/sdk";

const bunnyAgent = createBunnyAgent({
  sandbox: SandboxAdapter,       // LocalMachine, SrtSandbox, SandockSandbox, E2BSandbox, etc.
  cwd?: string,                  // Working directory inside sandbox
  env?: Record<string, string>,  // Environment variables
  template?: string,             // Template name
  resume?: string,               // Session ID for multi-turn
  verbose?: boolean,             // Debug logging
});

const model = bunnyAgent("claude-sonnet-4-20250514");

Daemon HTTP transport (same provider)

With any sandbox adapter (E2B, Sandock, LocalMachine, etc.): pass sandbox + daemonUrl. The URL is resolved inside the sandbox (the vikadata/bunny-agent image starts bunny-agent-daemon on port 3080). The SDK streams via streamCodingRunFromSandbox (curl -N in the sandbox, including LocalMachine), not fetch from your server. It does not call /healthz unless you select Pi search contract "auto", as described below. Use isBunnyAgentDaemonHealthy from @bunny-agent/sdk for an explicit readiness probe before setting daemonUrl (e.g. to fall back to the CLI runner).

import { createBunnyAgent, DEFAULT_BUNNY_AGENT_DAEMON_URL } from "@bunny-agent/sdk";

const bunnyAgent = createBunnyAgent({
  sandbox: mySandboxAdapter,
  daemonUrl: DEFAULT_BUNNY_AGENT_DAEMON_URL, // http://127.0.0.1:3080 inside the container
  runnerType: "claude",
  cwd: "/workspace",
});

Omit daemonUrl to use the CLI runner in the same sandbox. createBunnyAgent always requires a sandbox adapter.

Structured web search and answer citations

For Pi daemon execution, select searchContractVersion: "auto" on the provider or an individual model. The SDK discovers the attached runtime's capabilities before starting the turn:

const bunnyAgent = createBunnyAgent({
  sandbox: mySandboxAdapter,
  daemonUrl: DEFAULT_BUNNY_AGENT_DAEMON_URL,
  runnerType: "pi",
  searchContractVersion: "auto",
});
  • A capable daemon uses v1 structured search and answer annotations, with a required stream acknowledgement. A healthy older daemon uses legacy search.
  • Discovery sends a read-only /healthz GET through the same sandbox transport. The turn executes once; it is never replayed to negotiate support. Failed or malformed discovery rejects before execution instead of silently downgrading.
  • Healthy results are cached for 30 seconds per attached handle, sandbox ID, and daemon URL. An in-place runtime restart can take that long to be discovered.
  • Omitting the option preserves legacy behavior without discovery. Explicit 1 preserves strict acknowledgement requirements without discovery. CLI execution and other runners remain legacy when "auto" is selected.

See the search citation contract for the capability schema, AI SDK requirements, and citation metadata fields.

Exports

Entry PointExports
@bunny-agent/sdkcreateBunnyAgent, BunnyAgentLanguageModel, submitAnswer, DEFAULT_BUNNY_AGENT_DAEMON_URL; re-exports LocalMachine (from @bunny-agent/sandbox-local) and SrtSandbox (from @bunny-agent/sandbox-srt)
@bunny-agent/sdk/reactuseBunnyAgentChat, useArtifacts, useWriteTool, useAskUserQuestion, DEFAULT_BUNNY_AGENT_DAEMON_URL (re-exported from @bunny-agent/manager)

Environment Variables

VariableRequiredDescription
ANTHROPIC_API_KEYYesAnthropic API key
SANDOCK_API_KEYFor Sandocksandock.ai API key
E2B_API_KEYFor E2BE2B API key
DAYTONA_API_KEYFor DaytonaDaytona API key

Documentation

📖 Full docs: bunny-agent.dev/docs


License

Apache-2.0

版本与发布记录

@bunny-agent/sdk 共发布 115 个版本,首次发布于 2026/04/14;过去 12 个月发布了 115 个版本。

版本发布日期距今
0.10.3-beta1latest2026/11/071 天前
0.10.22026/10/2811 天前
0.10.1-beta.22026/10/2811 天前
0.10.1-beta.12026/10/2712 天前
0.10.0-release.62026/10/2613 天前
0.10.0-beta.52026/10/2316 天前

关于 @bunny-agent/sdk 的常见问题

@bunny-agent/sdk 是什么?

BunnyAgent SDK - AI Provider and React hooks for building AI agents

如何安装 @bunny-agent/sdk?

在项目目录运行 npm install @bunny-agent/sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:ai(^6.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@bunny-agent/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@bunny-agent/sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@bunny-agent/sdk 可以商用吗?

@bunny-agent/sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@bunny-agent/sdk 的下载量有多少?

根据 npm 官方下载统计,@bunny-agent/sdk 在 2026/10/09 – 2026/11/07 这 30 天内被下载 7,219 次,日均约 241 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@bunny-agent/sdk 还在维护吗?

最新版本 0.10.3-beta1 发布于 2026/11/07(1 天前);至今共发布 115 个版本,其中过去 12 个月发布了 115 个;首次发布于 2026/04/14。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。