Official

opencode-v2

OpenCode 2 agent provider: runs opencode serve (2.x) and talks to its /api over HTTP and server-sent events.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/opencode-v2@0.1.4

Permissions in 0.1.4

  • Provide agents agents.provideMediumAdds agents to the app.Provide the OpenCode 2 agent, and serve plugin tools to it through the host's loopback MCP server
  • Run named programs processMediumStarts the listed programs.Run the OpenCode 2 server (`opencode serve`, or the binary you choose in Settings), read its version and update it (`opencode upgrade`), and ask npm for the newest versionPrograms: opencode${settings.binaryPath}npm
  • Network access netMediumConnects to the listed hosts.Talk to the OpenCode server it starts on this computer, at the port it picks for each launch, to the OpenCode background service on this computer, and to the external server you choose in SettingsHosts: localhost:*${settings.serverUrl}
  • Environment variables envMediumReads the listed environment variables.Read the user name and password of the OpenCode server, and where OpenCode keeps its background service recordVariables: OPENCODE_SERVER_USERNAMEOPENCODE_SERVER_PASSWORDDIVERGENCE_OPENCODE_SERVER_PASSWORDXDG_STATE_HOMEHOME
  • Read files fs.readMediumReads files in the listed places.Read the record of the OpenCode background service (its address and password) so chats use the service you already run instead of starting another serverPlaces: ~/.local/state/opencode/service.json

Files

audit.test.ts22.2 KB
import { test } from "node:test";
import assert from "node:assert/strict";
import type { AgentEvent, AgentInitializeParams, TaskInfo } from "divergence/protocol";
import * as api from "./api.ts";
import * as map from "./map.ts";
import * as usage from "./usage.ts";
import { harness, session } from "./testing.test.ts";

const of = <K extends AgentEvent["event"]>(events: AgentEvent[], kind: K) =>
  events.filter((event): event is Extract<AgentEvent, { event: K }> => event.event === kind);
const time = { created: 100 };
const assistant = (content: unknown[], id = "msg_parent") => ({
  type: "assistant", id, time, agent: "build", model: { id: "model", providerID: "provider" }, content,
});
const tool = (name: string, metadata: Record<string, unknown>, content: unknown[] = []) => ({
  type: "tool", id: "call", name, time: { created: 100, ran: 100 }, state: { status: "completed", input: {}, metadata, content },
});

test("forms retain external actions and apply typed defaults before conditional filtering", () => {
  const form = api.form.parse({
    id: "frm", sessionID: "ses", title: "Setup", fields: [
      { key: "login", type: "external", url: "https://example.com/login" },
      { key: "enabled", type: "boolean", default: false },
      { key: "count", type: "integer", default: 0 },
      { key: "price", type: "number", default: 1.5, when: [{ key: "count", op: "eq", value: 0 }] },
      { key: "empty", type: "string", default: "" },
      { key: "none", type: "multiselect", default: [], options: [] },
      { key: "tags", type: "multiselect", default: ["a"], options: [{ value: "a", label: "A" }] },
      { key: "secret", type: "string", default: "hidden default", hidden: true },
      { key: "active", type: "string", default: "yes", when: [{ key: "tags", op: "eq", value: "a" }, { key: "enabled", op: "eq", value: false }] },
      { key: "inactive", type: "string", default: "no", when: [{ key: "enabled", op: "neq", value: false }] },
      { key: "cascaded", type: "string", when: [{ key: "inactive", op: "neq", value: "x" }] },
      { key: "missing", type: "string", required: true },
    ],
  });
  const question = map.formQuestion(form);
  assert.equal(question.url, "https://example.com/login");
  assert.equal(question.fields[0].kind, "boolean");
  assert.equal(question.fields[0].required, true);
  assert.equal(question.fields.some((field) => field.id === "secret"), false);
  assert.deepEqual(Object.fromEntries(question.fields.filter((field) => field.default !== undefined).map((field) => [field.id, field.default])), {
    enabled: false, count: 0, price: 1.5, empty: "", none: [], tags: ["a"], active: "yes", inactive: "no",
  });
  assert.deepEqual(question.fields.find((field) => field.id === "active")?.when, [
    { field: "tags", op: "eq", value: "a" }, { field: "enabled", op: "eq", value: false },
  ]);
  assert.deepEqual(question.fields.find((field) => field.id === "cascaded")?.when, [{ field: "inactive", op: "ne", value: "x" }]);
  assert.deepEqual(question.fields.find((field) => field.id === "price")?.when, [{ field: "count", op: "eq", value: 0 }]);
  assert.equal(Object.hasOwn(question.fields[0], "default"), false);
  assert.equal(Object.hasOwn(question.fields[0], "when"), false);
  assert.equal(question.fields.some((field) => field.secret !== undefined), false);
  assert.deepEqual(map.formAnswer(form, { login: "true", enabled: "", count: null, tags: [], inactive: "stale", cascaded: "stale" }), {
    login: true, enabled: false, count: 0, price: 1.5, empty: "", none: [], tags: ["a"], secret: "hidden default", active: "yes",
  });
  assert.equal(map.formAnswer(form, { enabled: true, count: "2", tags: ["b"] }).enabled, true);
  assert.equal(map.formAnswer(form, { enabled: true, count: "2", tags: ["b"] }).count, 2);
});

test("form replies send defaults and acknowledgements through the native reply endpoint", async () => {
  const { agent, run, server, emitted } = harness();
  agent.remember("ses", { workspace: "/w", options: {} }, { model: null, agent: null, mode: null, instructions: null });
  await run(agent.dispatch({ type: "form.created", data: { form: api.form.parse({ id: "frm", sessionID: "ses", title: "Setup", fields: [
    { key: "login", type: "external", url: "https://example.com" }, { key: "name", type: "string", default: "Default" },
    { key: "conditional", type: "string", default: "Inactive", when: [{ key: "name", op: "neq", value: "Default" }] },
  ] }) } }));
  assert.equal(of(emitted, "question")[0].fields[1].default, "Default");
  assert.deepEqual(of(emitted, "question")[0].fields[2].when, [{ field: "name", op: "ne", value: "Default" }]);
  await run(agent.respondToQuestion("frm", { values: { login: true, name: "" }, cancelled: false }));
  assert.deepEqual(server.find("POST", "/api/session/ses/form/frm/reply")?.body, { answer: { login: true, name: "Default" } });
});

test("imported subagents use execution state and synthetic reports instead of launch completion", async (t) => {
  const cases = [
    { name: "A background launch is still running", head: {}, active: {}, report: undefined, status: "running", summary: undefined },
    { name: "A follow-up does not inherit an earlier execution outcome or report", head: { outcome: "succeeded", time: { created: 1, updated: 3, busy: 100, idle: 200 } }, active: {}, report: "completed", launch: 300, status: "running", summary: undefined },
    { name: "An active execution overrides an old completion", head: { outcome: "succeeded" }, active: { ses_child: {} }, report: "completed", status: "running", summary: undefined },
    { name: "A busy timestamp overrides a previous idle timestamp", head: { outcome: "succeeded", time: { created: 1, updated: 3, busy: 300, idle: 200 } }, active: {}, report: "completed", status: "running", summary: undefined },
    { name: "A synthetic report supplies the final summary", head: {}, active: {}, report: "completed", status: "completed", summary: "Final answer" },
    { name: "A failed execution is preserved", head: { outcome: "failed" }, active: {}, report: "error", status: "failed", summary: "Final answer" },
    { name: "An interrupted execution is preserved", head: { outcome: "interrupted" }, active: {}, report: "cancelled", status: "cancelled", summary: "Final answer" },
    { name: "An idle child can finish before its report arrives", head: { outcome: "succeeded", time: { created: 1, updated: 3, busy: 100, idle: 200 } }, active: {}, report: undefined, status: "completed", summary: undefined },
  ];
  for (const entry of cases) await t.test(entry.name, async () => {
    const launch = tool("subagent", { sessionID: "ses_child", status: "running" }, [{ type: "text", text: "Launch instructions" }]);
    if (entry.launch !== undefined) launch.time = { created: entry.launch, ran: entry.launch };
    const messages: unknown[] = [assistant([launch])];
    if (entry.report) messages.push({ type: "synthetic", id: "msg_report", time: { created: 200 },
      text: '<subagent sessionID="ses_child">\nFinal answer\n</subagent>', metadata: { source: "subagent", childID: "ses_child", state: entry.report } });
    const { agent, run } = harness({ routes: (call) => {
      if (call.path === "/api/session/ses_parent/message") return { body: { data: messages } };
      if (call.path === "/api/session/ses_child/message") return { body: { data: [assistant([{ type: "text", text: "Child text" }], "msg_child")] } };
      if (call.path === "/api/session/ses_child") return { body: { data: session("ses_child", entry.head) } };
      if (call.path === "/api/session/active") return { body: { data: entry.active } };
      return undefined;
    } });
    const { items } = await run(agent.readSession("ses_parent"));
    const task = items.find((item) => item.role === "task");
    assert.ok(task?.role === "task");
    assert.equal(task.task.status, entry.status);
    assert.equal(task.task.summary, entry.summary);
    assert.equal(task.items?.[0].id, "msg_child/text/0");
    assert.equal(items.some((item) => item.id === "msg_report"), false);
  });
});

test("a child history read failure is reported instead of returning an empty transcript", async () => {
  const { agent, run } = harness({ routes: (call) => {
    if (call.path === "/api/session/ses_parent/message") return { body: { data: [assistant([tool("subagent", { sessionID: "ses_child", status: "running" })])] } };
    if (call.path === "/api/session/ses_child/message") return { status: 503, body: { message: "Child history unavailable" } };
    return undefined;
  } });
  await assert.rejects(run(agent.readSession("ses_parent")), /Child history unavailable/);
});

test("child execution updates are reread when the parent timestamp stays unchanged", async () => {
  let active = true;
  const { agent, run } = harness({ routes: (call) => {
    if (call.path === "/api/session/ses_parent/message") return { body: { data: [assistant([tool("subagent", { sessionID: "ses_child", status: "running" })])] } };
    if (call.path === "/api/session/ses_child/message") return { body: { data: [] } };
    if (call.path === "/api/session/ses_child") return { body: { data: session("ses_child", { outcome: active ? undefined : "succeeded" }) } };
    if (call.path === "/api/session/active") return { body: { data: active ? { ses_child: {} } : {} } };
    return undefined;
  } });
  const first = await run(agent.readSession("ses_parent"));
  assert.equal(first.version, undefined);
  active = false;
  const second = await run(agent.readSession("ses_parent", first.version));
  const task = second.items.find((item) => item.role === "task");
  assert.ok(task?.role === "task");
  assert.equal(task.task.status, "completed");
});

test("native image results survive both live events and stored tool rows", async () => {
  const content = [{ type: "text", text: "Screenshot" }, { type: "file", uri: "data:image/png;base64,AAAA", mime: "image/png" }];
  const expected = [{ type: "text", text: "Screenshot" }, { type: "image", mimeType: "image/png", data: "AAAA" }];
  const { agent, run, emitted } = harness();
  agent.remember("ses", { workspace: "/w", options: {} }, { model: null, agent: null, mode: null, instructions: null });
  const data = { sessionID: "ses", assistantMessageID: "msg_parent", id: "call" };
  await run(agent.dispatch({ type: "session.tool.input.started", data: { ...data, name: "screenshot" } }));
  await run(agent.dispatch({ type: "session.tool.success", data: { ...data, content } }));
  assert.deepEqual(of(emitted, "tool_call_updated").at(-1)?.content, expected);
  const items = map.transcript([api.message.parse(assistant([tool("screenshot", {}, content)]))]);
  assert.deepEqual(items[0].role === "tool" && items[0].call.content, expected);
  assert.deepEqual(map.toolContent("screenshot", {}, content.slice(1)), expected.slice(1));
  await run(agent.dispatch({ type: "session.tool.failed", data: { ...data, error: { message: "Capture failed" }, content: content.slice(1) } }));
  const failed = [{ type: "text", text: "Capture failed" }, ...expected.slice(1)];
  assert.deepEqual(of(emitted, "tool_call_updated").at(-1)?.content, failed);
  const row = api.assistantContent.parse({ type: "tool", id: "failed", name: "screenshot", state: { status: "error", input: {}, content: content.slice(1), error: { message: "Capture failed" } } });
  assert.ok(row.type === "tool");
  assert.deepEqual(map.toolCall("msg", row).content, failed);
  assert.deepEqual(map.toolContent("read", {}, [{ type: "file", uri: "file:///w/a%20b.png", mime: "image/png" }]), [{ type: "image", mimeType: "image/png", path: "/w/a b.png" }]);
  assert.deepEqual(map.toolContent("read", {}, [{ type: "file", uri: "data:audio/wav;base64,AAAA", mime: "audio/wav" }]), []);
});

test("session listing follows every cursor without resending the initial filters", async () => {
  const { agent, run, server } = harness({ routes: (call) => {
    if (call.path !== "/api/session") return undefined;
    const cursor = call.query.cursor;
    return { body: { data: cursor === "second" ? [] : [session(cursor === "last" ? "ses_old" : "ses_new", { time: { created: 1, updated: cursor ? 1 : 2 } })],
      cursor: { next: cursor === "last" ? null : cursor ? "last" : "second" } } };
  } });
  const result = await run(agent.listSessions("/w"));
  assert.deepEqual(result.sessions.map((session) => session.id), ["ses_new", "ses_old"]);
  assert.deepEqual(server.calls.map((call) => call.query), [
    { directory: "/w", limit: "200", parentID: "null" }, { cursor: "second", limit: "200" }, { cursor: "last", limit: "200" },
  ]);
});

test("terminal cancellation uses the owning location and preserves other tasks and the parent run", async () => {
  let fail = true;
  const { agent, run, emitted, server } = harness({ routes: (call) => call.method === "DELETE" && fail ? { status: 503, body: { message: "Cannot stop shell" } } : undefined });
  agent.remember("ses", { workspace: "/workspace", options: {} }, { model: null, agent: null, mode: null, instructions: null });
  agent.children.set("child", { root: "ses", parent: "ses", task: { id: "child", title: "Child", status: "running" } });
  const task: TaskInfo = { id: "sh_one", title: "Command", status: "running", kind: "terminal", output: "tail" };
  agent.terminals.set("sh_one", { session: "child", task, cursor: 4 });
  agent.terminals.set("sh_two", { session: "ses", task: { ...task, id: "sh_two" }, cursor: 0 });
  agent.runs.set("ses", "run");
  await assert.rejects(run(agent.cancelTask("wrong", "sh_one")), /no OpenCode subagent/);
  await assert.rejects(run(agent.cancelTask("ses", "sh_one")), /Cannot stop shell/);
  assert.equal(task.status, "running");
  assert.equal(agent.terminals.has("sh_one"), true);
  fail = false;
  await run(agent.cancelTask("ses", "sh_one"));
  assert.deepEqual(server.find("DELETE", "/api/shell/sh_one")?.query, { "location[directory]": "/workspace" });
  assert.equal(agent.terminals.has("sh_one"), false);
  assert.equal(agent.terminals.get("sh_two")?.task.status, "running");
  assert.equal(agent.runs.get("ses"), "run");
  assert.equal(of(emitted, "task").at(-1)?.status, "cancelled");
  assert.equal(of(emitted, "task").at(-1)?.output, "tail");
  await run(agent.dispatch({ type: "shell.exited", data: { id: "sh_one", status: "exited", exit: 0 } }));
  assert.equal(of(emitted, "task").at(-1)?.status, "cancelled");
});

const limits = (id: string) => ({
  workspace: { id, name: id, usageURL: `https://example.com/${id}` },
  go: { rolling: { percent: 25, limited: false, resetsAt: 1000 }, weekly: { percent: 100, limited: true, resetsAt: 2000 }, monthly: { percent: 0, limited: false, resetsAt: 3000 } },
  budgets: [{ id: "budget", limit: 10, spent: 15, scope: "each", per: "set", coverage: "all", models: [], vendors: [], picked: false, shared: false, resetsAt: 4000 }],
});

test("usage limits combine locations, deduplicate Console workspaces and retain their identity", async () => {
  const { agent, run, server } = harness({ routes: (call) => call.path === "/api/experimental/usage/limits"
    ? { body: { data: limits(call.query["location[directory]"] === "/other" ? "other" : "same") } } : undefined });
  for (const workspace of ["/one", "/two", "/other"]) agent.remember(workspace, { workspace, options: {} }, { model: null, agent: null, mode: null, instructions: null });
  assert.equal(typeof agent.definition().usage_limits, "function");
  assert.equal((await run(agent.initialize())).capabilities?.usageLimits, true);
  const { limits: result } = await run(agent.usageLimits());
  assert.equal(result?.windows.length, 8);
  assert.equal(result?.windows[1].blocked, true);
  assert.equal(result?.windows[3].usedPercent, 150);
  assert.equal(result?.windows[3].budget?.limit, 10);
  assert.equal(result?.windows[3].resetsAt, new Date(4000).toISOString());
  assert.equal(result?.windows[4].workspace.id, "other");
  assert.equal(server.calls.filter((call) => call.path === "/api/experimental/usage/limits").length, 3);
});

test("per-model budgets use the model spend and zero budgets remain finite", () => {
  const source = limits("workspace");
  const budget = source.budgets[0];
  const windows = usage.windows(usage.info.parse({ ...source, go: undefined, budgets: [
    { ...budget, per: "model", models: [{ providerID: "p", modelID: "a", name: "A", spent: 2 }, { providerID: "p", modelID: "b", name: "B" }] },
    { ...budget, id: "zero", limit: 0, spent: 0 },
  ] }));
  assert.deepEqual(windows.map((window) => window.usedPercent), [20, 0, 100]);
  assert.deepEqual(windows.map((window) => window.model), ["A", "B", undefined]);
  assert.equal(windows[2].blocked, true);
});

test("unsigned usage returns null, while transport failures remain errors", async () => {
  let status = 200;
  const { agent, run, server } = harness({ routes: () => ({ status, body: status === 200 ? { data: null } : { message: "Usage service unavailable" } }) });
  assert.deepEqual(await run(agent.usageLimits()), { limits: null });
  assert.deepEqual(server.calls[0].query, {});
  for (status of [404, 503]) await assert.rejects(run(agent.usageLimits()), /Usage service unavailable/);
});

test("todo plans use the host's negotiated statuses live and in history", async (t) => {
  const todos = [{ content: "First", status: "pending" }, { content: "Second", status: "in_progress" }, { content: "Third", status: "completed" }, { content: "Dropped", status: "cancelled" }];
  const hosts: { name: string; params: AgentInitializeParams }[] = [
    { name: "An older host sends no feature list", params: {} },
    { name: "A host can send an empty feature list", params: { hostFeatures: [] } },
    { name: "MCP Apps alone do not enable cancelled plans", params: { hostFeatures: ["mcpApps"] } },
    { name: "A host can support cancelled plans alone", params: { hostFeatures: ["planCancelled"] } },
    { name: "A host can support both extensions", params: { hostFeatures: ["mcpApps", "planCancelled"] } },
  ];
  for (const { name, params } of hosts) await t.test(name, async () => {
    const expected = todos.map((todo) => ({ ...todo, status: todo.status === "cancelled" && !params.hostFeatures?.includes("planCancelled") ? "completed" : todo.status }));
    const { agent, run, emitted } = harness({ routes: (call) => call.path.endsWith("/message") ? { body: { data: [
      assistant([tool("todowrite", { todos: [{ content: "Old", status: "pending" }] })], "msg_old"),
      assistant([tool("todowrite", { todos })]),
    ] } } : undefined });
    const info = await run(agent.definition().initialize!({ ...params, agentId: "opencode-v2" }, { agentId: "opencode-v2", emit: agent.emit }));
    assert.deepEqual(agent.hostFeatures, params.hostFeatures ?? []);
    assert.equal(info.capabilities?.mcpApps, undefined);
    assert.equal(agent.definition().mcp_read_resource, undefined);
    assert.equal(agent.definition().mcp_call_tool, undefined);
    agent.remember("ses", { workspace: "/w", options: {} }, { model: null, agent: null, mode: null, instructions: null });
    const data = { sessionID: "ses", assistantMessageID: "msg", id: "todo" };
    await run(agent.dispatch({ type: "session.tool.input.started", data: { ...data, name: "todowrite" } }));
    await run(agent.dispatch({ type: "session.tool.success", data: { ...data, content: [], metadata: { todos } } }));
    assert.equal(of(emitted, "plan").length, 1);
    assert.deepEqual(of(emitted, "plan").at(-1)?.entries, expected);
    const { items } = await run(agent.readSession("ses"));
    assert.equal(of(emitted, "plan").length, 2);
    assert.deepEqual(of(emitted, "plan").at(-1)?.entries, expected);
    assert.equal(items.some((item) => item.role === "plan"), false);
    assert.deepEqual(map.todoPlan("todowrite", { todos: [] }, params.hostFeatures), []);
    assert.equal(map.todoPlan("other", { todos }, params.hostFeatures), null);
    assert.equal(map.todoPlan("todowrite", {}, params.hostFeatures), null);
  });
});

test("a changed host feature list invalidates cached plans and an older host resets negotiation", async () => {
  const todos = [{ content: "Dropped", status: "cancelled" }];
  const { agent, run, emitted } = harness({ routes: (call) => call.path.endsWith("/message")
    ? { body: { data: [assistant([tool("todowrite", { todos })])] } } : undefined });
  const legacy = await run(agent.readSession("ses"));
  assert.equal(of(emitted, "plan").at(-1)?.entries?.[0]?.status, "completed");
  await run(agent.initialize({ hostFeatures: ["planCancelled"] }));
  const supported = await run(agent.readSession("ses", legacy.version));
  assert.notEqual(supported.version, legacy.version);
  assert.equal(of(emitted, "plan").at(-1)?.entries?.[0]?.status, "cancelled");
  const plans = of(emitted, "plan").length;
  await run(agent.readSession("ses", supported.version));
  assert.equal(of(emitted, "plan").length, plans);
  await run(agent.initialize({}));
  const reset = await run(agent.readSession("ses", supported.version));
  assert.equal(reset.version, legacy.version);
  assert.equal(of(emitted, "plan").at(-1)?.entries?.[0]?.status, "completed");
});

test("automatic and manual compaction start once and failures clear the running state", async () => {
  let fail = false;
  let expectedStarts = 2;
  const { agent, run, emitted } = harness({ routes: (call) => {
    if (call.path.endsWith("/compact")) {
      assert.equal(of(emitted, "compacting").length, expectedStarts);
      return fail ? { status: 500, body: { message: "Cannot compact" } } : undefined;
    }
    return undefined;
  } });
  agent.remember("ses", { workspace: "/w", options: {} }, { model: null, agent: null, mode: null, instructions: null });
  const started = api.parseEvent({ type: "session.compaction.started", data: { sessionID: "ses", reason: "auto" } });
  assert.ok(started);
  await run(agent.dispatch(started));
  await run(agent.dispatch({ type: "session.compaction.ended", data: { sessionID: "ses", text: "Summary" } }));
  assert.equal(of(emitted, "compacted")[0].summary, "Summary");
  await run(agent.compact("ses"));
  await run(agent.dispatch(started));
  assert.equal(of(emitted, "compacting").length, 2);
  await run(agent.dispatch({ type: "session.compaction.failed", data: { sessionID: "ses", error: { message: "Failed to summarize" } } }));
  assert.equal(agent.compactions.size, 0);
  assert.equal(of(emitted, "compacted").length, 2);
  assert.match(of(emitted, "notice").at(-1)?.message ?? "", /Failed to summarize/);
  fail = true;
  expectedStarts = 3;
  await assert.rejects(run(agent.compact("ses")), /Cannot compact/);
  assert.equal(agent.compactions.size, 0);
  assert.equal(of(emitted, "compacted").length, 3);
});

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.1.5latestNov 21, 2026>=5 <672.4 KB5 permissionsListed
0.1.4Nov 16, 2026>=5 <672 KB5 permissionsListed
0.1.3Nov 11, 2026>=5 <662.4 KB5 permissionsListed
0.1.2Nov 9, 2026>=5 <659.2 KB5 permissionsListed
0.1.1Oct 27, 2026>=2 <458.4 KB5 permissionsListed

Reviews and comments

0 threads · 0 reviews

No comments yet.