中文
文档
基于 OpenCode 构建
插件
服务端

服务端插件

开发 OpenCode 插件的服务端部分:工具、钩子、集成、命令与代理。

插件的服务端部分运行在 OpenCode 服务器进程中,用于修改 OpenCode 的默认行为并扩展工具、钩子、集成、命令与代理等功能。关于插件包的目录结构、加载与发布方式,请参阅构建插件概览。

.opencode/plugins/example/index.ts
import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "example",
  async setup(ctx) {
    await ctx.storage.set("loaded", true)
  },
})

生命周期

插件加载时会执行 setup。它可以返回一个清理函数,在插件卸载时自动调用:

import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "example",
  setup(ctx) {
    console.log(`loaded in OpenCode ${ctx.app.version}`)
    return () => console.log("unloaded")
  },
})

上下文(Context)

插件上下文实质上是一个 OpenCode 服务器客户端。它的读取和操作方法与客户端拥有完全一致的输入和返回值,同时额外提供了插件专属的 transforms、运行时 hooks、重载、注册以及插件选项等能力:

setup(ctx) {
  console.log(ctx.app.version)
}

ctx.location 描述当前插件实例所加载的位置,包含 directory、可选的 workspaceID 以及 project 元数据(id、directory 与 canonical)。Promise 插件与 Effect 插件均可访问该字段。注意它代表的是插件实例自身的位置,而非其能够访问的每个会话或收到的每条事件的位置:

setup(ctx) {
  console.log(ctx.location.directory)
  console.log(ctx.location.project.canonical)
}

配置选项(Options)

在 opencode.json(c) 中通过对象形式传入插件选项:

opencode.jsonc
{
  "plugins": [
    {
      "package": "./plugins/company",
      "options": {
        "strict": true,
      },
    },
  ],
}

在 setup 中通过 ctx.options 读取这些配置值:

plugins/company/index.ts
import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "company",
  setup(ctx) {
    const strict = ctx.options.strict === true
  },
})

转换器(Transforms)

Transform 是对 OpenCode 领域状态的同步编辑操作,同一领域内每个 transform 都基于先前注册的结果继续构建。诸如 ctx.model.list() 等注册表读取接口会立即反映截至当前的所有注册(包括插件 setup 期间);启动批处理仅合并更新通知,绝不会延迟读取结果。资源状态接口仍汇报运行中资源的真实状态:已注册某个定义并不意味着其连接或其他异步初始化工作已经完成。

数据源通过 ctx.provider.transform 贡献提供商和不可变模型定义:

plugins/models/index.ts
import { Model, Plugin, Provider } from "@opencode/plugin"
 
export default Plugin.define({
  id: "company.models",
  async setup(ctx) {
    const providerID = Provider.ID.make("acme")
    const models = [{ ...Model.Info.default(providerID, Model.ID.make("reasoner")), name: "Acme Reasoner" }]
    await ctx.provider.transform((editor) => {
      editor.add({
        info: {
          ...Provider.Info.empty(providerID),
          name: "Acme",
          activation: "enabled",
          package: "@opencode/ai/providers/openai-compatible",
          settings: { baseURL: "http://127.0.0.1:8000/v1" },
        },
        models,
      })
    })
 
    const available = await ctx.model.list()
  },
})

任何注册、移除或 reload() 都会将注册表标记为已变更;下一次读取时,系统会基于全新初始值按注册顺序重放所有活跃 transform。请确保 transform 轻量且可重复执行。已经读取过的值绝不会被后续重建原地修改。

在提供商 transform 与可用性解析完成后,OpenCode 会物化所有活跃提供商的模型列表,并按顺序重放所有模型 transform。模型策略因此可以审查完整候选集合,包括刚刚刷新过的数据源:

plugins/model-budget/index.ts
import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "company.model-budget",
  async setup(ctx) {
    await ctx.model.transform((editor) => {
      editor
        .list()
        .filter((model) => model.cost.some((tier) => tier.output > 20))
        .forEach((model) => {
          editor.remove(model.providerID, model.id)
        })
    })
  },
})

回调闭包捕获的外部输入不会自动监听变更。请先在同步回调外加载外部数据,数据变化后再调用 reload()。下例中 loadFromSource() 返回 { info: Provider.Info, models: readonly Model.Info[] } 条目:

plugins/models/index.ts
import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "company.models",
  async setup(ctx) {
    const source = { providers: await loadFromSource() }
 
    await ctx.provider.transform((editor) => {
      source.providers.forEach((provider) => editor.add(provider))
    })
 
    const refresh = async () => {
      source.providers = await loadFromSource()
      await ctx.provider.reload()
    }
 
    const timer = setInterval(() => void refresh().catch(console.error), 60_000)
    return () => clearInterval(timer)
  },
})

提供商变更会使整个活跃模型结果失效并重新计算,因此输出单价策略依然会过滤刷新后的模型。如果仅模型 transform 捕获的输入发生变化,调用 ctx.model.reload() 即可。

API

Agent(代理)

读取全部代理或按 ID 获取单个代理:

const agents = await ctx.agent.list()
const build = await ctx.agent.get({ agentID: "build" })

注册 transform 以检查、更新、移除代理或设置默认代理:

await ctx.agent.transform((editor) => {
  const agents = editor.list()
  const build = editor.get("build")
 
  editor.default("build")
  editor.update("build", (agent) => {
    agent.description = "Builds features and fixes bugs"
  })
  editor.remove("legacy")
})

当 transform 依赖的外部状态变化后,重载代理:

await ctx.agent.reload()

类型参考

Schema:Agent.Info (opens in a new tab)

interface AgentContext {
  list(input?: AgentListInput, requestOptions?: RequestOptions): Promise<AgentListOutput>
  get(input: AgentGetInput, requestOptions?: RequestOptions): Promise<AgentGetOutput>
  transform(callback: (editor: AgentEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface AgentEditor {
  list(): readonly AgentInfo[]
  get(id: string): AgentInfo | undefined
  default(id: string | undefined): void
  update(id: string, update: (agent: AgentInfo) => void): void
  remove(id: string): void
}
 
interface Registration {
  dispose(): Promise<void>
}

Providers(提供商)

读取可用提供商或按 ID 查看单个提供商的元数据:

const providers = await ctx.provider.list()
const provider = await ctx.provider.get({ providerID: "anthropic" })

提供商 transform 用于编辑提供商配置与源定义。编辑器读取结果包含未激活提供商并暴露不可变定义;models.update 编辑的是源模型的独立副本:

await ctx.provider.transform((editor) => {
  editor.update("anthropic", (provider) => {
    provider.headers = { ...provider.headers, "x-company": "engineering" }
  })
  editor.models.update("anthropic", "claude-sonnet-5-5", (model) => {
    model.name = "Team Sonnet"
  })
  editor.models.remove("anthropic", "legacy-model")
  editor.remove("legacy-provider")
})

使用 models.set 替换提供商的源模型清单,并在捕获的定义变化后调用 reload:

const source = { models: await loadModels() }
await ctx.provider.transform((editor) => {
  editor.models.set("acme", source.models)
})
 
source.models = await loadModels()
await ctx.provider.reload()

对于按账号维度发现的模型清单,请将加载清单所用的连接作为 sourceConnection 传入。当用户切换到其他连接时,OpenCode 会先排除该提供商,直到你的插件发布刷新后的清单:

const connection = await ctx.integration.connection.active("acme")
if (!connection) return
const inventory = await loadInventory(connection)
await ctx.provider.transform((editor) => {
  editor.add({ info: inventory.provider, models: inventory.models, sourceConnection: connection })
})

类型参考

Schemas:Provider.Info (opens in a new tab)、Model.Info (opens in a new tab)

interface ProviderDomain extends ProviderApi {
  transform(callback: (editor: ProviderEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface ProviderRecord {
  readonly provider: Provider.Info
  readonly models: ReadonlyMap<string, Model.Info>
  readonly sourceConnection?: ConnectionInfo
}
 
interface ProviderEditor {
  list(): readonly ProviderRecord[]
  get(providerID: string): ProviderRecord | undefined
  add(input: { info: Provider.Info; models: readonly Model.Info[]; sourceConnection?: ConnectionInfo }): void
  update(providerID: string, update: (provider: DeepMutable<Provider.Info>) => void): void
  remove(providerID: string): void
  readonly models: {
    set(providerID: string, models: readonly Model.Info[]): void
    update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
    remove(providerID: string, modelID: string): void
  }
}

Models(模型)

读取可用模型与默认选中项:

const models = await ctx.model.list()
const selected = await ctx.model.default()

模型 transform 编辑的是所有活跃提供商的完整候选模型集合。已禁用的候选模型在全部 transform 完成前依然可编辑;update 只能在可用提供商下新增模型:

await ctx.model.transform((editor) => {
  editor.list("anthropic").forEach((model) => {
    editor.update(model.providerID, model.id, (draft) => {
      draft.enabled = draft.capabilities.tools
    })
  })
  editor.default.set("anthropic", "claude-sonnet-5-5")
  editor.remove("anthropic", "legacy-model")
})

回调编辑的是原始模型覆写项。OpenCode 在提交结果时会一次性合并提供商默认值,未变更的读取直接复用该结果。editor.provider 暴露的是不可变源定义(包括未激活模板),而非模型 transform 的输出:

await ctx.model.transform((editor) => {
  const source = editor.provider.get("anthropic")?.models.get("claude-sonnet-5-5")
  if (!source) return
  editor.update("anthropic", source.id, (model) => {
    model.limit.context = Math.min(model.limit.context, source.limit.context)
  })
})
 
await ctx.model.reload()

类型参考

Schema:Model.Info (opens in a new tab)

interface ModelDomain extends ModelApi {
  transform(callback: (editor: ModelEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface ModelEditor {
  list(providerID?: string): readonly DeepMutable<Model.Info>[]
  get(providerID: string, modelID: string): DeepMutable<Model.Info> | undefined
  update(providerID: string, modelID: string, update: (model: DeepMutable<Model.Info>) => void): void
  remove(providerID: string, modelID: string): void
  readonly default: {
    get(): { providerID: string; modelID: string } | undefined
    set(providerID: string, modelID: string): void
  }
  readonly provider: {
    list(): readonly ProviderRecord[]
    get(providerID: string): ProviderRecord | undefined
  }
}

Commands(命令)

读取当前位置下可用的命令:

const commands = await ctx.command.list()

通过 transform 注册自定义命令。执行器会收到会话、提示词附件以及请求的投递模式:

await ctx.command.transform((editor) => {
  editor.add({
    name: "security-review",
    description: "Review changes for security issues",
    execute: async ({ sessionID, prompt, delivery }) => {
      await ctx.session.prompt({
        ...prompt,
        sessionID,
        text: `Review these changes for security issues.\n\n${prompt.text}`,
        delivery,
      })
    },
  })
})

当 transform 依赖的外部状态变化后,重载命令:

await ctx.command.reload()

类型参考

Schemas:Command.Info (opens in a new tab)、Session.Inbox.Delivery (opens in a new tab)

interface CommandContext {
  list(input?: CommandListInput, requestOptions?: RequestOptions): Promise<CommandListOutput>
  transform(callback: (editor: CommandEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface CommandEditor {
  add(definition: CommandDefinition): void
}
 
interface CommandDefinition {
  name: string
  description?: string
  execute(input: CommandInvocation): Promise<void>
}
 
interface CommandInvocation {
  sessionID: string
  prompt: PromptInput
  delivery: "steer" | "queue"
}

Integrations(集成)

读取集成列表并查看当前活跃凭据:

const integrations = await ctx.integration.list()
const github = await ctx.integration.get({ integrationID: "github" })
const connection = await ctx.integration.connection.active("github")
const credential = connection ? await ctx.integration.connection.resolve(connection) : undefined

使用 API 密钥连接集成:

await ctx.integration.connect.key({
  integrationID: "github",
  key: process.env.GITHUB_TOKEN!,
})

发起、查询、完成或取消 OAuth 连接流程:

const attempt = await ctx.integration.oauth.connect({ integrationID: "github", methodID: "oauth" })
const status = await ctx.integration.oauth.status({ integrationID: "github", attemptID: attempt.data.attemptID })
await ctx.integration.oauth.complete({ integrationID: "github", attemptID: attempt.data.attemptID, code })
await ctx.integration.oauth.cancel({ integrationID: "github", attemptID: attempt.data.attemptID })

基于命令的连接方式遵循相同的启动、查询状态与取消流程:

const attempt = await ctx.integration.command.connect({ integrationID: "acme", methodID: "cli" })
const status = await ctx.integration.command.status({ integrationID: "acme", attemptID: attempt.data.attemptID })
await ctx.integration.command.cancel({ integrationID: "acme", attemptID: attempt.data.attemptID })

注册 transform 以查看集成并管理其认证方式:

await ctx.integration.transform((editor) => {
  const integrations = editor.list()
  const acme = editor.get("acme")
 
  editor.update("acme", (integration) => {
    integration.name = "Acme"
  })
  editor.method.update({
    integrationID: "acme",
    method: { id: "cli", type: "command", label: "Sign in with Acme CLI", command: ["acme", "login"] },
  })
 
  const methods = editor.method.list("acme")
  const legacy = methods.find((method) => method.type === "command" && method.id === "legacy")
  if (legacy) editor.method.remove("acme", legacy)
  editor.remove("legacy")
})

当 transform 依赖的外部状态变化后,重载集成:

await ctx.integration.reload()

类型参考

Schemas:Integration.Info (opens in a new tab)、Integration.Method (opens in a new tab)、Connection.Info (opens in a new tab)、Form.Answer (opens in a new tab)

interface IntegrationContext {
  list(input?: IntegrationListInput, requestOptions?: RequestOptions): Promise<IntegrationListOutput>
  get(input: IntegrationGetInput, requestOptions?: RequestOptions): Promise<IntegrationGetOutput>
  connect: {
    key(input: IntegrationConnectKeyInput, requestOptions?: RequestOptions): Promise<void>
  }
  oauth: {
    connect(
      input: IntegrationOauthConnectInput,
      requestOptions?: RequestOptions,
    ): Promise<IntegrationOauthConnectOutput>
    status(input: IntegrationOauthStatusInput, requestOptions?: RequestOptions): Promise<IntegrationOauthStatusOutput>
    complete(input: IntegrationOauthCompleteInput, requestOptions?: RequestOptions): Promise<void>
    cancel(input: IntegrationOauthCancelInput, requestOptions?: RequestOptions): Promise<void>
  }
  command: {
    connect(
      input: IntegrationCommandConnectInput,
      requestOptions?: RequestOptions,
    ): Promise<IntegrationCommandConnectOutput>
    status(
      input: IntegrationCommandStatusInput,
      requestOptions?: RequestOptions,
    ): Promise<IntegrationCommandStatusOutput>
    cancel(input: IntegrationCommandCancelInput, requestOptions?: RequestOptions): Promise<void>
  }
  transform(callback: (editor: IntegrationEditor) => void): Promise<Registration>
  reload(): Promise<void>
  connection: {
    active(integrationID: string): Promise<ConnectionInfo | undefined>
    resolve(connection: ConnectionInfo): Promise<CredentialValue | undefined>
  }
}
 
interface IntegrationEditor {
  list(): readonly IntegrationRef[]
  get(id: string): IntegrationRef | undefined
  update(id: string, update: (integration: IntegrationRef) => void): void
  remove(id: string): void
  method: {
    list(integrationID: string): readonly IntegrationMethod[]
    update(input: IntegrationMethodRegistration): void
    remove(integrationID: string, method: IntegrationMethod): void
  }
}

Credentials(凭据)

将已保存的凭据设为对应集成的当前活跃凭据:

await ctx.credential.activate({ credentialID })

类型参考

interface CredentialContext {
  activate(input: CredentialActivateInput, requestOptions?: RequestOptions): Promise<void>
}

MCP

列出 MCP 服务器及其当前连接状态:

const servers = await ctx.mcp.list()

插件仅通过 transform 管理 MCP 服务器。使用 editor.set 新增或替换服务器,使用 editor.update 修改配置,使用 editor.remove 移除服务器,使用 editor.list 与 editor.get 查看配置:

await ctx.mcp.transform((editor) => {
  const servers = editor.list()
  const docs = editor.get("docs")
  editor.set("docs", { type: "remote", url: "https://mcp.example.com" })
  editor.update("docs", (server) => {
    server.disabled = false
  })
  editor.remove("legacy")
})

在 transform 中设置 disabled: true 可停用并断开对应服务器,设置 disabled: false 可启用并允许 OpenCode 连接。OpenCode 会根据转换后的配置自动协调服务器生命周期。

当 transform 使用的外部状态变化后,调用 reload() 以重新应用 transform 并协调服务器状态:

await ctx.mcp.reload()

类型参考

Schemas:Mcp.Server (opens in a new tab)、Mcp.LocalConfigEncoded (opens in a new tab)、Mcp.RemoteConfigEncoded (opens in a new tab)

interface MCPContext {
  list(input?: McpListInput, requestOptions?: RequestOptions): Promise<McpListOutput>
  transform(callback: (editor: MCPEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface MCPEditor {
  list(): readonly (readonly [string, McpServerConfig])[]
  get(name: string): McpServerConfig | undefined
  set(name: string, config: McpServerConfig): void
  update(name: string, update: (config: McpServerConfig) => void): void
  remove(name: string): void
}

Plugins(插件)

列出当前位置下已激活的插件:

const plugins = await ctx.plugin.list()

类型参考

Schemas:Plugin.Info (opens in a new tab)、Plugin.Source (opens in a new tab)

interface PluginContext {
  list(input?: PluginListInput, requestOptions?: RequestOptions): Promise<PluginListOutput>
}

References(引用)

读取当前位置下可用的引用:

const references = await ctx.reference.list()

注册 transform 以查看、新增或移除本地与 Git 引用。get(name) 返回当前配置的源,若名称不存在则返回 undefined:

await ctx.reference.transform((editor) => {
  const references = editor.list()
  editor.add("handbook", { type: "local", path: "/workspace/docs/handbook" })
  editor.add("standards", { type: "git", repository: "https://github.com/acme/standards", branch: "main" })
  const handbook = editor.get("handbook")
  editor.remove("legacy")
})

当 transform 依赖的外部状态变化后,重载引用:

await ctx.reference.reload()

类型参考

Schemas:Reference.Info (opens in a new tab)、Reference.LocalSource (opens in a new tab)、Reference.GitSource (opens in a new tab)

interface ReferenceContext {
  list(input?: ReferenceListInput, requestOptions?: RequestOptions): Promise<ReferenceListOutput>
  transform(callback: (editor: ReferenceEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface ReferenceEditor {
  list(): readonly (readonly [string, ReferenceLocalSource | ReferenceGitSource])[]
  get(name: string): ReferenceLocalSource | ReferenceGitSource | undefined
  add(name: string, source: ReferenceLocalSource | ReferenceGitSource): void
  remove(name: string): void
}

Generate(实验性)

使用指定模型直接生成文本,无需创建会话、调用工具或写入会话历史。该组 API 未来可能变更。ctx.generate.text 仍可使用但已弃用,请改用 ctx.experimental.generate.text:

const review = await ctx.experimental.generate.text({
  model: { providerID: "anthropic", id: "claude-sonnet-5-5" },
  prompt: "Review this proposed action.",
})
 
const { images } = await ctx.experimental.generate.image({
  model: { providerID: "openai", id: "gpt-image-1-mini" },
  prompt: "A watercolor fox in the snow",
  aspect: "16:9",
})
 
const { answers } = await ctx.experimental.generate.decisions({
  model: { providerID: "opencode", id: "jev-1.13" },
  input: [{ type: "text", text: "I was charged twice, please refund one." }],
  questions: [{ type: "predicate", name: "refund", instructions: "Is this a refund request?" }],
})

Permissions(权限)

在执行敏感操作前请求权限。assert 会评估会话的权限规则(含已保存的审批记录),当规则判定为 ask 时提示用户确认,并在允许后 resolve:

execute: async (input, context) => {
  await ctx.permission.assert({
    sessionID: context.sessionID,
    agent: context.agent,
    source: { type: "tool", messageID: context.messageID, id: context.id },
    action: "deploy",
    resources: [input.environment],
    save: [input.environment],
  })
  return { content: await deploy(input.environment) }
}
  • action 与 resources 会与权限规则进行匹配。命中任意 deny 将阻止操作;否则命中任意 ask 会向用户发起确认。
  • save 指定用户选择“始终允许”时保存的模式列表。
  • agent 指定应用哪位代理的规则,默认使用当前会话的代理;source 将权限提示关联到某次工具调用。
  • metadata 向权限提示界面和 evaluate 钩子传递附加详情。

命中 deny 规则或用户附带反馈拒绝时,会抛出携带原因的 Tool.Error,模型可以看到拒绝原因并继续执行;普通拒绝则会终止当前步骤。请让这些错误直接向外传播,切勿捕获后当作普通工具输出返回。

查看或处理待审批的权限请求:

const pending = await ctx.permission.list({ sessionID })
const request = await ctx.permission.get({ sessionID, requestID })
await ctx.permission.reply({ sessionID, requestID, decision: "once" })

替换会话级权限规则。会话级规则在代理规则之后评估,且最后一条匹配规则生效。子会话会继承创建时正在生效的规则:

await ctx.session.update({
  sessionID,
  permissions: [{ action: "edit", resource: "/path/to/original/checkout/**", effect: "deny" }],
})

Sessions(会话)

创建或读取会话:

const created = await ctx.session.create({ title: "Review" })
const session = await ctx.session.get({ sessionID })
const messages = await ctx.session.context({ sessionID })

分页列出会话。将返回的 cursor.next 作为 cursor 传回即可获取下一页;游标会自动记住你的筛选条件,无需重复传递:

const page = await ctx.session.list({ directory: ctx.location.directory, limit: 20 })
const next = page.cursor.next ? await ctx.session.list({ cursor: page.cursor.next, limit: 20 }) : undefined

切换后续请求所使用的代理或模型:

await ctx.session.switchAgent({ sessionID, agent: "build" })
await ctx.session.switchModel({ sessionID, model: { providerID: "anthropic", id: "claude-sonnet-5-5" } })

发送用户提示词、临时生成请求、命令或合成消息:

const prompt = await ctx.session.prompt({ sessionID, text: "Review the current changes" })
const generated = await ctx.session.generate({ sessionID, prompt: "Summarize this project" })
await ctx.session.command({ sessionID, name: "review", text: "--staged" })
const synthetic = await ctx.session.synthetic({ sessionID, text: "Deployment completed" })

generate 会同时返回 text 以及本次调用的 tokens 和 cost,其结构与助手消息汇报的格式一致。

重命名、中断或等待会话完成:

await ctx.session.update({ sessionID, title: "Review" })
await ctx.session.interrupt({ sessionID, resume: false })
await ctx.session.wait({ sessionID })

使用 remove 删除临时会话。删除会停止当前活跃执行并递归删除所有子会话:

await ctx.session.remove({ sessionID })

使用 compact 请求上下文压缩。它返回已准入的收件箱条目而非压缩完成的摘要;默认在下一个步骤边界运行。如需按队列顺序执行,请传入 delivery: "queue":

const compaction = await ctx.session.compact({ sessionID })

使用 instructions.entry 附加、列出或移除带键名的会话指令条目。条目在会话指令中渲染为 <context key="..."> 块,更新或移除会在下一个步骤边界通知模型,而不会排队触发新的消息轮次:

await ctx.session.instructions.entry.put({ sessionID, key: "deploy-target", value: "production" })
const entries = await ctx.session.instructions.entry.list({ sessionID })
await ctx.session.instructions.entry.remove({ sessionID, key: "deploy-target" })

类型参考

Schemas:Session.Info (opens in a new tab)、Model.Ref (opens in a new tab)、Session.Inbox.User (opens in a new tab)、Session.Inbox.Synthetic (opens in a new tab)、InstructionEntry.Info (opens in a new tab)

interface SessionContext {
  create(input?: SessionCreateInput, requestOptions?: RequestOptions): Promise<SessionInfo>
  get(input: SessionGetInput, requestOptions?: RequestOptions): Promise<SessionInfo>
  remove(input: SessionRemoveInput, requestOptions?: RequestOptions): Promise<void>
  context(input: SessionContextInput, requestOptions?: RequestOptions): Promise<readonly SessionMessageInfo[]>
  instructions: {
    entry: {
      list(
        input: ExperimentalSessionInstructionsEntryListInput,
        requestOptions?: RequestOptions,
      ): Promise<readonly InstructionEntryInfo[]>
      put(input: ExperimentalSessionInstructionsEntryPutInput, requestOptions?: RequestOptions): Promise<void>
      remove(input: ExperimentalSessionInstructionsEntryRemoveInput, requestOptions?: RequestOptions): Promise<void>
    }
  }
  switchAgent(input: SessionSwitchAgentInput, requestOptions?: RequestOptions): Promise<void>
  switchModel(input: SessionSwitchModelInput, requestOptions?: RequestOptions): Promise<void>
  update(input: SessionUpdateInput, requestOptions?: RequestOptions): Promise<void>
  move(input: SessionMoveInput, requestOptions?: RequestOptions): Promise<void>
  prompt(input: SessionPromptInput, requestOptions?: RequestOptions): Promise<SessionInboxUser>
  generate(input: SessionGenerateInput, requestOptions?: RequestOptions): Promise<{ text: string }>
  command(input: SessionCommandInput, requestOptions?: RequestOptions): Promise<void>
  compact(input: SessionCompactInput, requestOptions?: RequestOptions): Promise<SessionInboxCompaction>
  synthetic(input: SessionSyntheticInput, requestOptions?: RequestOptions): Promise<SessionInboxSynthetic>
  interrupt(input: SessionInterruptInput, requestOptions?: RequestOptions): Promise<{ interrupted: boolean }>
  wait(input: ExperimentalSessionWaitInput, requestOptions?: RequestOptions): Promise<void>
}

Skills(技能)

读取当前位置下可用的技能:

const skills = await ctx.skill.list()

注册 transform 以查看、新增、更新或移除技能。get(id) 返回当前编辑器中的条目,若技能不存在则返回 undefined:

import { Skill } from "@opencode/plugin"
 
await ctx.skill.transform((editor) => {
  const skills = editor.list()
  editor.add({
    id: Skill.ID.make("review"),
    name: Skill.Name.make("Review"),
    description: "Review the current changes",
    path: Skill.Info.fields.path.make("/workspace/.opencode/skills/review/SKILL.md"),
    content: "Review the current changes for correctness and missing tests.",
  })
  const review = editor.get("review")
  editor.update("review", (skill) => {
    skill.autoinvoke = true
  })
  editor.remove("legacy")
})

当 transform 依赖的外部状态变化后,重载技能:

await ctx.skill.reload()

类型参考

Schema:Skill.Info (opens in a new tab)

interface SkillContext {
  list(input?: SkillListInput, requestOptions?: RequestOptions): Promise<SkillListOutput>
  transform(callback: (editor: SkillEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface SkillEditor {
  list(): readonly SkillInfo[]
  get(id: string): SkillInfo | undefined
  add(skill: SkillInfo): void
  update(id: string, update: (skill: SkillInfo) => void): void
  remove(id: string): void
}

Storage(存储)

存取或删除按插件隔离的持久化 JSON 数据:

await ctx.storage.set("settings", { strict: true })
const settings = await ctx.storage.get("settings")
await ctx.storage.remove("settings")

按前缀扫描键,并支持可选游标分页:

const page = await ctx.storage.scan({ prefix: "cache/", limit: 100 })
const next = page.next

类型参考

interface StorageContext {
  get(key: string): Promise<Json | undefined>
  set(key: string, value: Json): Promise<void>
  remove(key: string): Promise<void>
  scan(options: StorageScanOptions): Promise<StorageScanResult>
}
 
interface StorageScanOptions {
  prefix: string
  after?: string
  limit?: number
}
 
interface StorageScanResult {
  entries: readonly { key: string; value: Json }[]
  next?: string
}

Tools(工具)

在 transform 回调外部读取经过所有 transform 处理后的当前已注册工具。每个工具都带有包含其有效名称的 id:

const tools = await ctx.tool.list()
const read = tools.find((tool) => tool.id === "read")

使用同步 transform 注册、更新和移除工具(Promise 插件同样要求回调同步)。请先加载外部数据再注册或重载。对于相同的有效工具名,后注册的有效定义会覆盖先前的定义:

const registration = await ctx.tool.transform((editor) => {
  editor.namespace({
    name: "acme",
    description: "Customer account tools",
  })
  editor.add({
    name: "greeting",
    description: "Create a greeting",
    input: {
      type: "object",
      properties: { name: { type: "string" } },
      required: ["name"],
      additionalProperties: false,
    },
    options: { namespace: "acme", codemode: true },
    execute: async (input, context) => {
      await context.progress({ status: "greeting" })
      return { content: `Hello ${(input as { name: string }).name}!` }
    },
  })
})

Promise 工具执行器会收到 context.signal。请将其透传给 fetch 等可取消操作,以便在会话被停止时同步中止底层任务:

execute: async ({ url }, context) => {
  const response = await fetch(url, { signal: context.signal })
  return { content: await response.text() }
}

自由格式工具输入(Freeform tool input)

如果直接暴露给模型的工具仅有一个必填字符串字段,你可以让模型无需包裹 JSON 直接输出该字符串。将 freeform 设为 { type: "text" }、{ type: "regex", pattern } 或 { type: "lark", grammar }:

editor.add({
  name: "ticket",
  description: "Look up a ticket by ID",
  options: { codemode: false },
  input: Schema.Struct({ id: Schema.String }),
  freeform: { type: "regex", pattern: "OPS-[0-9]+" },
  execute: async ({ id }) => ({ content: await lookup(id) }),
})

如果所选模型的 API 在 models.dev 中声明支持 regex,模型便可以直接输出 OPS-42。否则 Core 会仅省略 freeform:模型仍然拥有 ticket 工具并以 {"id":"OPS-42"} 调用它。缺少或空的格式列表表示不支持自由格式。无论模型走哪条路径,执行器收到的始终是 { id }。

在 Code Mode(codemode: true)中,自由格式工具可直接接收字符串参数(如 await tools.ticket("OPS-42")),同时也兼容对象形式 await tools.ticket({ id: "OPS-42" })。

当回调捕获的源数据变化后调用 reload()。重载会在不改变顺序的情况下重放活跃 transform,而不会重新执行插件 setup:

await ctx.tool.reload()

使用 list() 与 get() 检查编辑器中当前的工具。每个工具都有包含其有效名称的 id,若 ID 不存在则 get() 返回 undefined。调用 update 与 remove 时必须传入包含命名空间的完整有效工具名(如上例中的 acme_greeting)。命名空间中的点号以及工具名中的不支持字符都会转换为 _。不存在的名称会被忽略;创建新工具必须使用 add 并提供完整定义。更新操作会保留工具名和命名空间。替换 Schema 或选项时请直接赋新值,不要原地修改嵌套对象。无效更新会被记录日志并保持原定义不变:

await ctx.tool.transform((editor) => {
  editor.update("acme_greeting", (tool) => {
    tool.description = "Greet the user by name"
  })
  editor.remove("acme_obsolete")
})

更新与移除操作会与新增操作按顺序一同重放,包括在 MCP 目录刷新之后。释放对应的注册句柄即可撤回这些修改并基于剩余 transform 重建。

释放(dispose)某个注册句柄会移除该 transform 并从其余 transform 重建,从而重新暴露此前被它覆盖的旧定义。释放操作是幂等的,插件卸载时也会自动释放其全部注册:

await registration.dispose()

每次模型请求都会捕获一份稳定且可执行的工具快照。后续的 transform、重载和释放只会影响未来的快照,不会改变已被现有请求捕获的定义、Code Mode 命名空间描述或执行器。如果执行器闭包引用了可变的插件状态,它仍会读到最新值;若希望某个值固定绑定到该工具定义,请在 transform 内部捕获它。

类型参考

Schemas:Tool.Content (opens in a new tab)、Tool.TextContent (opens in a new tab)、Tool.FileContent (opens in a new tab)

interface ToolContext {
  list(): Promise<readonly (ToolInfo & { readonly id: string })[]>
  transform(callback: (editor: ToolEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface ToolEditor {
  list(): readonly (ToolInfo & { readonly id: string })[]
  get(id: string): (ToolInfo & { readonly id: string }) | undefined
  namespace(namespace: { name: string; description: string }): void
  add(tool: ToolInfo): void
  update(id: string, update: (tool: Types.Mutable<ToolInfo>) => void): void
  remove(id: string): void
}

VCS(版本控制)

读取仓库信息、工作副本状态或文件差异(diff):

const info = await ctx.vcs.get()
const branches = await ctx.vcs.branch.list({ search: "feature", limit: 10 })
const changes = await ctx.vcs.status()
const diff = await ctx.vcs.diff({ mode: "working", context: 3 })

通过 transform 注册位置级 VCS 提供商。与检测到的仓库类型匹配的提供商会被自动选中;使用 editor.default.set 可显式切换为其他提供商:

await ctx.vcs.transform((editor) => {
  editor.add({
    id: "custom",
    name: "Custom VCS",
    info: async () => ({ branch: { current: "feature", default: "main" } }),
    branches: async (input, { signal }) => readBranches(input, signal),
    status: async (scope, { signal }) => readStatus(scope.worktree, signal),
    diff: async (input, { signal }) => readDiff(input, signal),
  })
  editor.default.set("custom")
})

提供商回调会收到当前位置、工作副本根目录、规范项目根目录以及可选的仓库存储位置;diff 回调还会收到所选模式、请求的上下文行数以及输出字节预算。仓库发现仍使用 OpenCode 内置的 Git 与 Mercurial 检测器。

提供商可选择实现 init(scope, { signal }) 在 scope.worktree 中创建仓库。初始化按提供商 ID 选择(默认为 Git),而非按检测到的仓库类型。即使当前位置尚未包含仓库,也可以注册带 init 的提供商;OpenCode 会在调用前检查目录存在且无仓库,并在初始化后重新发现项目。全新的仓库格式除该回调外仍需要相应的发现支持。

类型参考

Schemas:Vcs.Info (opens in a new tab)、Vcs.FileStatus (opens in a new tab)、FileDiff.Info (opens in a new tab)

interface VcsContext {
  get(input?: VcsGetInput, requestOptions?: RequestOptions): Promise<VcsGetOutput>
  branch: {
    list(input?: VcsBranchListInput, requestOptions?: RequestOptions): Promise<VcsBranchListOutput>
  }
  status(input?: VcsStatusInput, requestOptions?: RequestOptions): Promise<VcsStatusOutput>
  diff(input: VcsDiffInput, requestOptions?: RequestOptions): Promise<VcsDiffOutput>
  transform(callback: (editor: VcsEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface VcsEditor {
  add(definition: VcsDefinition): void
  default: {
    get(): string | undefined
    set(providerID: string): void
  }
}
 
interface VcsDefinition {
  init?(scope: VcsScope, context: { signal: AbortSignal }): Promise<void>
  // Existing info, branches, status, and diff callbacks are required.
}

Worktrees

使用常规插件生命周期注册本地 worktree 策略。本例中的实现模块负责选项校验以及后端的 create、remove 与 list 操作:

plugins/worktrees/index.ts
import { Plugin } from "@opencode/plugin"
import { makeStrategy } from "./strategy"
 
export default Plugin.define({
  id: "company.worktrees",
  async setup(ctx) {
    const strategy = makeStrategy(ctx.options)
    await ctx.worktree.transform((editor) => {
      editor.add(strategy)
    })
  },
})

通过 plugins 加载该插件,并单独配置通用目标目录:

opencode.jsonc
{
  "worktree": { "directory": "../worktrees" },
  "plugins": [{ "package": "./plugins/worktrees", "options": {} }],
}
  • 添加策略后会自动选中它。最后生效的注册胜出,无需额外的策略选择配置。
  • 释放该注册句柄或卸载插件会恢复上一个实现,最终回退到内置的 Git 策略。
  • reload() 在捕获的输入变化后重放 transform,不会重新运行插件 setup。
  • 创建失败不会回退到 Git 重试。已有 worktree 会保留其记录的归属策略,即使默认策略随后发生变化。
  • 策略仅管理本地目录;远程工作区置备不属于该接口职责。

操作方法

插件上下文暴露与客户端相同的项目级 worktree 操作,每个操作都必须传入 projectID。list 仅读取已保存的清单(包括同一项目的已知检出目录),不会加载配置、启动插件或扫描文件系统变更:

const projectID = ctx.location.project.id
const created = await ctx.worktree.create({ projectID, name: "task" })
const inventory = await ctx.worktree.list({ projectID })
await ctx.worktree.refresh({ projectID })
await ctx.worktree.remove({ projectID, directory: created.directory, force: false })

create 会从项目已保存的 canonical 目录加载配置和插件,并使用其选中的策略。它接受可选的父目录 directory、来源目录 from、起始分支 branch 以及名称 name。来源默认为规范检出目录,且显式指定的 from 必须属于同一项目;指定来源不会改变配置根目录。传入的起始 ref 必须受所选策略支持——例如 Rift 的原生快照操作不支持选择 ref。

create 与 refresh 会等待规范检出目录的插件完成激活。如果是在该检出目录自身的插件 setup 期间调用,则会看到截至当前的注册而不会死等自身激活。

remove 会加载规范配置并激活其插件,随后使用该 worktree 创建时记录的策略,而不是当前默认策略。若记录的策略不可用则会报错。worktree 的目标路径可以位于其他位置:

await ctx.worktree.remove({
  directory: "/worktrees/task",
  projectID,
  force: false,
})

若归属策略缺失,移除将直接失败而不会回退到 Git。策略可以从 @opencode/plugin 导入 Worktree 并抛出 new Worktree.OperationError({ message: "Uncommitted changes", forceRequired: true }),从而在不依赖 Core 或 Git 内部错误的前提下请求强制删除确认。

refresh 会加载规范配置并调用所有可用策略在已知检出根目录下发现 worktree。它会合并结果、保留已记录的归属关系,并清理已不存在的目录。单个发现源失败会被记录日志,其余发现源继续执行。即使没有任何可用策略上报,已存在的目录仍会保留在记录中。监听 worktree.updated 事件并重新调用 list 即可读取更新后的清单:

await ctx.worktree.refresh({ projectID })

类型参考

策略实现会收到经过命名与冲突处理后的建议目标路径,并从 create 返回实际创建的目录路径;若后端有自己的目录布局要求,返回值可以与建议路径不同。OpenCode 会解析返回路径,并将其用于清单记录、启动命令及 API 返回结果。返回的目录必须真实存在。

若策略选择其他目标路径,需自行处理该处的命名冲突;OpenCode 仍会在调用策略前先创建建议的父目录。list 必须只上报该策略自身拥有的目录以及仓库根目录:

interface WorktreeDefinition {
  readonly id: string
  create(
    input: { sourceDirectory: string; directory: string; branch?: string },
    context: { signal: AbortSignal },
  ): Promise<{ directory: string }>
  remove(input: { directory: string; force: boolean }, context: { signal: AbortSignal }): Promise<void>
  list(
    sourceDirectory: string,
    context: { signal: AbortSignal },
  ): Promise<readonly { directory: string; type: "root" | "worktree" }[]>
}
 
interface WorktreeEditor {
  add(definition: WorktreeDefinition): void
}
 
interface WorktreeDomain extends WorktreeApi {
  transform(callback: (editor: WorktreeEditor) => void): Promise<Registration>
  reload(): Promise<void>
}

Promise 回调必须配合 signal 响应取消;Effect 回调则返回 Effect 并改用 Effect 中断机制。注册与插件运行时生命周期绑定;项目级操作使用规范检出目录的注册表,Core 配置适配器负责将目录设置注入该注册表。

Websearch(网页搜索)

列出网页搜索提供商,或通过所选提供商执行查询:

const providers = await ctx.websearch.providers()
const results = await ctx.websearch.query({ query: "OpenCode plugins", providerID: "internal" })

通过 transform 注册搜索提供商并设为默认:

await ctx.websearch.transform((editor) => {
  editor.add({
    id: "internal",
    name: "Internal search",
    execute: async ({ query }, { signal }) => {
      const response = await fetch(`https://search.example.com?q=${encodeURIComponent(query)}`, { signal })
      const result = (await response.json()) as { url: string; title: string; content: string }
      return [{ url: result.url, title: result.title, content: result.content, time: {} }]
    },
  })
  editor.default.set("internal")
})

选择 false 可禁用网页搜索;外部状态变化后调用 reload() 重载提供商:

await ctx.websearch.transform((editor) => editor.default.set(false))
await ctx.websearch.reload()

类型参考

Schemas:WebSearch.Provider (opens in a new tab)、WebSearch.Result (opens in a new tab)

interface WebSearchContext {
  providers(input?: WebsearchProvidersInput, requestOptions?: RequestOptions): Promise<WebsearchProvidersOutput>
  query(input: WebsearchQueryInput, requestOptions?: RequestOptions): Promise<WebsearchQueryOutput>
  transform(callback: (editor: WebSearchEditor) => void): Promise<Registration>
  reload(): Promise<void>
}
 
interface WebSearchEditor {
  add(provider: WebSearchDefinition): void
  default: {
    get(): string | false | undefined
    set(providerID: string | false): void
  }
}

Events(事件)

订阅当前所连服务器的公开事件流,并在插件清理时中止订阅。传入 types(例如 ctx.event.subscribe({ types: ["config.updated"] }))即可只接收指定事件类型,事件类型会自动收窄。插件运行在服务器内部,因此与 SDK 客户端不同,永远不会收到 server.connected。未知的事件类型名会被忽略并在服务器日志中输出警告:

const controller = new AbortController()
void (async () => {
  for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
    console.log(event.type)
  }
})()
return () => controller.abort()

类型参考

Schema:V2EventEncoded (opens in a new tab)

type EventType = Exclude<OpenCodeEvent["type"], "server.connected">
 
interface EventContext {
  subscribe<Type extends EventType = EventType>(options?: {
    types?: Type[]
    signal?: AbortSignal
  }): AsyncIterable<Extract<OpenCodeEvent, { type: Type }>>
}

钩子(Hooks)

钩子用于拦截实时运行中的操作。在对应领域注册钩子,不再需要时释放返回的注册句柄即可:

const registration = await ctx.session.hook("context", () => {})
await registration.dispose()

多个插件可以注册同一个钩子。OpenCode 按插件顺序依次运行,因此后续钩子可以看到先前钩子所做的修改。

Sessions(会话钩子)

会话钩子拦截提示词准入、模型调用、原生 HTTP 交互以及重试策略。

分叉(Forks)

fork 钩子在 OpenCode 复制完历史记录之后、fork 调用返回之前运行,其中 sessionID 标识新建的会话:

await ctx.session.hook("fork", ({ sessionID }) => console.log(sessionID))

提示词准入(Prompt admission)

在附件与技能解析及持久化收件箱准入之前拦截传入的用户提示词:

await ctx.session.hook("prompt", (event) => {
  event.prompt.text = event.prompt.text.replaceAll("company-secret", "[redacted]")
  event.prompt.files ??= []
  event.prompt.files.push({ uri: "file:///project/policy.md" })
  event.metadata = { ...event.metadata, source: "company-policy" }
  event.delivery = "queue"
})

该钩子接收一份独立拥有的可变草稿:

  • prompt 包含 text、files、agents 中的代理提及以及选中的 skills。
  • metadata 包含应用自定义的准入元数据。
  • delivery 默认为 "steer",可修改为 "queue"。
  • 会话 ID 与消息 ID 为只读,钩子不能重定向准入目标。

钩子新增的文件和技能会走常规解析与校验流程。重写文本时,请同步更新或移除不再匹配的附件 mention 偏移量。代理提及不会切换会话的当前活跃代理。

prompt 钩子在以下条件下触发:

  • 在会话所在位置的插件准备就绪后,按注册顺序运行。
  • 通过 session.prompt 提交的命令会触发该钩子。
  • 合成消息、Shell 消息、压缩控制指令和移动控制指令不会触发。
  • 仅在准入阶段运行一次,不会在每次模型调用前重复运行。
  • 不支持按提供商限定作用域,因为模型解析发生在准入之后。

修改结果会成为规范持久化的用户输入。如果准备阶段失败或被中断,OpenCode 不会准入该提示词。

请确保 prompt 钩子具备重试安全性,它并非精确一次(exactly-once)的副作用边界:

  • 重试已处于待处理或已投递状态的 ID 会直接返回原始准入结果,不会重跑钩子。
  • 并发提交可能导致钩子被运行多次,但只有最先成功准入的一次生效。
  • prompt 钩子仅用于转换输入,不暴露类型化的拒绝 API。

模型请求(Model requests)

在模型请求发出前修改组装好的系统指令、消息列表、工具集或请求选项。会话发出的每种请求都有各自对应的钩子,便于插件区别处理代理主循环与辅助请求:

  • context:用于代理主循环,包括工具调用驱动的续写轮次。
  • compaction:用于检查点摘要。messages 为待摘要的对话记录;OpenCode 会在钩子运行后追加摘要提示词。设置 result 可自行记录压缩结果并跳过模型调用,其字段与已完成的压缩消息一致。
  • generate:用于临时的 ctx.session.generate 调用。
  • title:用于标题生成。没有 agent 或 tools,设置 result 可直接提供标题并跳过模型调用。
await ctx.session.hook("context", (event) => {
  event.system.push({ type: "text", text: "Keep the review focused on correctness." })
  delete event.tools.write
  event.options.temperature = 0.2
  event.options.maxTokens = 8_000
})
 
await ctx.session.hook("compaction", async (event) => {
  event.result = { summary: await summarize(event.messages) }
})

修改仅影响本次发出的模型调用,不会改写持久化历史或配置。如需对所有请求生效,必须分别为每种请求类型注册钩子。

context、compaction 和 generate 钩子中的消息携带其已存储消息的只读 metadata(例如 prompt 钩子写入的内容),不会发送给模型。

承载 OpenCode 指令的 system 分片还会通过 metadata.experimental.instructions 以 { key, text } 列表形式标明各指令来源(如 core/date 或 core/environment),便于钩子区分来源。该列表为副本,编辑分片的 text 不会同步更新它。此能力属于实验特性,后续可能变更。

请求选项覆写遵循以下规则:

  • options 在每次模型调用开始时为空,不包含已解析的模型默认设置。
  • 具备静态类型的键为生成参数;其余任意键会作为提供商选项透传给所选协议。
  • 钩子按注册顺序执行,并可见先前钩子写入的覆写项。
  • 请求级覆写优先级高于模型默认值,模型默认值高于路由默认值。
  • 提供商选项对象会递归合并;数组与标量值会直接替换先前值。
  • 删除覆写项或将其设为 undefined 会回退到已配置的默认值,而不会删除默认配置。
  • 原始 HTTP 请求体叠加层在协议降级(lowering)之后应用,可覆写最终生成的字段。

提供商选项(Provider options)

提供商选项应使用所选协议的语义化选项名,而非原始 HTTP 请求体字段,并建议限定到对应提供商。例如 OpenAI Responses 使用 reasoningEffort:

await ctx.session.hook(
  "context",
  (event) => {
    event.options.reasoningEffort = "high"
  },
  { providerID: "openai" },
)

可用的生成选项取决于所选协议和模型:

  • maxTokens 是语义化的输出 Token 上限。
  • Gemini 支持 topK;OpenAI Responses 不暴露该参数。

模型解析(Model resolve)

实验性能力。每当会话为某次请求解析模型时、在构建请求内容之前运行。model 初始值为当前选中模型;修改它即可让本次请求改用同一提供商下的另一个模型(包括在模型选择器中隐藏的模型)。会话本身仍保持原选中模型,仅本次请求及其助手消息使用新模型。kind 指明正在解析哪类请求,方便路由器跳过标题生成或在压缩后重新路由。指向其他提供商的模型会因不可用而失败:

await ctx.session.hook(
  "experimental.model.resolve",
  (event) => {
    if (event.model.id === "auto" && event.kind !== "title")
      event.model = { providerID: event.model.providerID, id: pick(event.sessionID) }
  },
  { providerID: "acme" },
)

模型请求设置(Model request)

修改模型请求参数,并可选择将钩子限定到单个提供商。事件携带与下方 HTTP 钩子相同的 kind 字段:

await ctx.session.hook(
  "model.request",
  (event) => {
    event.headers["x-plugin"] = "review"
  },
  { providerID: "anthropic" },
)

原生 HTTP(Native HTTP)

修改发往提供商的原生 HTTP 请求或响应。请求体与响应体都是一次性流,读取前请先 clone 或替换。

两个钩子都会对会话发出的每次请求触发。event.kind 指明触发来源:"primary" 表示代理主循环,"compaction" 表示检查点摘要,"title" 表示标题生成,"generate" 表示临时的 ctx.session.generate 调用。请使用 event.kind 而非代理 ID 来区分辅助请求:

await ctx.session.hook("http.request", (event) => {
  event.request.headers.set("x-session-id", event.sessionID)
  if (event.kind === "title") event.request.headers.set("x-priority", "background")
})
 
await ctx.session.hook("http.response", (event) => {
  event.response = new Response(event.response.body, {
    status: event.response.status,
    headers: { ...Object.fromEntries(event.response.headers), "x-plugin": "review" },
  })
})

原生 WebSocket(实验性)

通过 WebSocket 流式通信的提供商会为每个会话建立一条连接并在多次请求间复用,因此 http.request 与 http.response 不会看到该流量。experimental.ws.handshake 钩子在每次模型调用选择连接前运行一次,携带与 HTTP 钩子相同的 sessionID、agent、model 和 kind,外加连接 url 与 headers。修改 url 或 headers 会改变请求所用的套接字,从而在轮换 Bearer 令牌后自动重连。

HTTP 钩子仍会对所有 HTTP 请求触发,包括 WebSocket 路由回退到的 HTTP 请求:

await ctx.session.hook(
  "experimental.ws.handshake",
  async (event) => {
    event.headers.authorization = `Bearer ${await mintToken(event.url)}`
    delete event.headers["api-key"]
  },
  { providerID: "azure" },
)

experimental.ws.send 和 experimental.ws.receive 直接暴露 WebSocket 帧本身,对应于编辑 HTTP 请求体或响应体。send 在提供商驱动构造出站帧之后、写出之前触发;receive 在驱动处理每条入站帧之前触发。两者均以字符串形式携带 frame,并在钩子返回时直接发送或递交最终的 frame 值。

OpenCode 不会校验改写后的帧。底层驱动依据提供商回复维护协议状态,因此就像改写 HTTP 请求体一样,若改写改变了协议语义,需由插件自行负责:

await ctx.session.hook(
  "experimental.ws.send",
  (event) => {
    const body = JSON.parse(event.frame)
    if (body.type === "response.create") body.metadata = { ...body.metadata, session: event.sessionID }
    event.frame = JSON.stringify(body)
  },
  { providerID: "openai" },
)
 
await ctx.session.hook("experimental.ws.receive", (event) => {
  if (event.frame.includes('"type":"error"')) console.error(event.frame)
})

上述 WebSocket 钩子均为实验性接口,其名称与结构未来可能变更。

重试策略(Retry policy)

覆写提供商调用失败时的重试决策或替换等待延迟(毫秒)。该钩子在 OpenCode 完成错误分类并给出默认策略之后、调度重试之前执行,不暴露 OpenCode 内部发起下次尝试的具体实现:

await ctx.session.hook("retry", (event) => {
  if (event.error.status === 429) {
    event.decision = { retry: true, delay: 10_000 }
    return
  }
  if (event.error.type === "provider.invalid-request" && event.attempt === 2) {
    event.decision = { retry: true, delay: 0 }
    return
  }
  if (event.attempt >= 3) event.decision = { retry: false }
})

重试钩子可以修改 OpenCode 的初始 decision,将原本终止的错误改为可重试,或否决原本计划的重试。

重试决策遵循以下规则:

  • 多个钩子按注册顺序执行,后续钩子可见当前决策。
  • 内置的最大尝试次数始终是硬上限。
  • attempt 表示当前正在评估的物理尝试序号:首次请求为 1,第一次重试为 2。
  • 无效延迟(如 NaN、无穷大或负数)会回退到系统计算出的延迟。
  • 上下文溢出恢复机制与此独立,因为它通过压缩对话而非重试同一请求来恢复。

会话钩子类型参考

import type { SessionPrompt } from "@opencode/plugin/promise/session"
 
interface SessionHooks {
  prompt: SessionPrompt
  context: SessionContextHook
  compaction: SessionContextHook & { result?: SessionCompactionResult }
  generate: SessionContextHook
  title: SessionRequestHook & { result?: string }
  "experimental.model.resolve": SessionModelResolveHook
  "model.request": SessionModelRequestHook
  "http.request": SessionHttpRequestHook
  "http.response": SessionHttpResponseHook
  "experimental.ws.handshake": SessionWebSocketHandshakeHook
  "experimental.ws.send": SessionWebSocketSendHook
  "experimental.ws.receive": SessionWebSocketReceiveHook
  retry: SessionRetryHook
}
 
interface SessionModelResolveHook {
  readonly sessionID: string
  readonly agent: string
  readonly kind: "primary" | "compaction" | "title" | "generate"
  model: { providerID: string; id: string; variant?: string }
}
 
interface SessionWebSocketHandshakeHook {
  readonly sessionID: string
  readonly agent: string
  readonly model: { providerID: string; id: string; variant?: string }
  readonly kind: "primary" | "compaction" | "title" | "generate"
  url: string
  headers: Record<string, string>
}
 
interface SessionWebSocketSendHook {
  readonly sessionID: string
  readonly agent: string
  readonly model: { providerID: string; id: string; variant?: string }
  readonly kind: "primary" | "compaction" | "title" | "generate"
  frame: string
}
 
interface SessionWebSocketReceiveHook {
  readonly sessionID: string
  readonly agent: string
  readonly model: { providerID: string; id: string; variant?: string }
  readonly kind: "primary" | "compaction" | "title" | "generate"
  frame: string
}
 
type RetryDecision = { retry: false } | { retry: true; delay: number }
 
interface SessionRetryHook {
  readonly sessionID: string
  readonly agent: string
  readonly model: { providerID: string; id: string; variant?: string }
  readonly error: { type: string; message: string; status?: number }
  readonly attempt: number
  decision: RetryDecision
}
 
interface SessionRequestHook {
  readonly sessionID: string
  readonly model: { providerID: string; id: string; variant?: string }
  system: SystemPart[]
  messages: Message[]
  options: {
    maxTokens?: number
    temperature?: number
    topP?: number
    topK?: number
    frequencyPenalty?: number
    presencePenalty?: number
    seed?: number
    stop?: string[]
  } & Record<string, unknown>
}
 
interface SessionContextHook extends SessionRequestHook {
  readonly agent: string
  tools: Record<string, { description: string; input: JsonSchema }>
}
 
interface SessionCompactionResult {
  summary: string
  native?: Record<string, unknown>
  metadata?: Record<string, unknown>
  tokens?: TokenUsage
}
 
interface SessionHookContext {
  hook<Name extends keyof SessionHooks>(
    name: Name,
    callback: (event: SessionHooks[Name]) => Promise<void> | void,
    options?: Name extends "prompt" ? never : { providerID?: string },
  ): Promise<Registration>
}

Permissions(权限钩子)

在已配置的权限规则评估完毕之后、执行操作或发出用户权限提示之前,审查并调整权限决策:

await ctx.permission.hook("evaluate", async (event) => {
  if (event.action === "read") return
 
  const messages = await ctx.session.context({ sessionID: event.sessionID })
  const review = await ctx.generate.text({
    model: { providerID: "anthropic", id: "claude-sonnet-5-5" },
    prompt: buildSafetyPrompt({ messages, action: event.action, resources: event.resources }),
  })
  const decision = parseDecision(review.text)
 
  event.effect = decision.effect
  event.message = decision.reason
})

权限钩子遵循以下规则:

  • 仅对 allow 和 ask 决策触发。
  • 配置中显式命中的 deny 为最终结果,不会调用该钩子。
  • 钩子可将 effect 修改为 allow、ask 或 deny。
  • message 会展示在升级后的权限确认弹窗中,或在拒绝时作为拒绝理由。

类型参考

interface PermissionEvaluation {
  readonly sessionID: string
  readonly agent?: string
  readonly action: string
  readonly resources: readonly string[]
  readonly metadata?: Record<string, unknown>
  readonly source?: { type: "tool"; messageID: string; id: string }
  effect: "allow" | "ask" | "deny"
  message?: string
}

Shell

在执行前修改 Shell 命令、工作目录、超时时间、可执行程序或环境变量:

await ctx.shell.hook("create.before", (event) => {
  event.timeout = Math.min(event.timeout, 60_000)
  event.env.COMPANY_ENV = "development"
})

类型参考

interface ShellHookContext {
  hook(name: "create.before", callback: (event: ShellCreateBefore) => Promise<void> | void): Promise<Registration>
}
 
interface ShellCreateBefore {
  command: string
  cwd: string
  timeout: number
  shell: string
  env: Record<string, string | undefined>
}

Tools(工具钩子)

在工具执行前检查或替换输入参数:

await ctx.tool.hook("execute.before", (event) => {
  if (event.tool === "read") console.log(event.input)
})

在工具执行后检查成功结果或错误信息:

await ctx.tool.hook("execute.after", (event) => {
  if (event.status === "completed") event.result = { ...event.result, metadata: { observed: true } }
  if (event.status === "error") console.error(event.error.message)
})

类型参考

interface ToolHooks {
  "execute.before": ToolExecuteBefore
  "execute.after": ToolExecuteCompleted | ToolExecuteFailed
}
 
interface ToolHookContext {
  hook<Name extends keyof ToolHooks>(
    name: Name,
    callback: (event: ToolHooks[Name]) => Promise<void> | void,
  ): Promise<Registration>
}

兼容 V1

插件可以通过同一个包入口同时兼容 V1 和 V2:默认导出一个同时包含 V1 server() 函数与 V2 setup() 函数的对象:

src/index.ts
import { Plugin } from "@opencode/plugin"
 
export default {
  ...Plugin.define({
    id: "example",
    async setup(ctx) {
      await ctx.tool.hook("execute.before", () => {
        console.log("A tool is about to run")
      })
    },
  }),
  async server() {
    return {
      "tool.execute.before": async () => {
        console.log("A tool is about to run")
      },
    }
  },
}
  • V1 会调用 server() 并使用其返回的钩子。
  • V2 会读取默认导出的 id 与 setup()(Effect 插件为 effect()),忽略 server()。
  • 两套实现各自遵循对应版本的 API,共享导出入口不会自动把 V1 钩子转换为 V2 钩子。
  • 请将 Plugin.define(...) 展开到导出对象中,以便与 server() 分开对 V2 定义进行类型检查。

OpenCode 1.18.29 支持 V1 对象导出形式。更早的 V1 版本可能仍要求函数导出,请务必使用你计划支持的最低 V1 版本和 V2 版本分别测试实际安装后的包。