Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -482,9 +482,11 @@ const nativeGoal = (status: "active" | "paused" | "complete") => ({
});

it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
it.effect("switches the session's model and variant before a turn that changed them", () =>
it.effect("switches the session's agent, model and variant before a turn that changed them", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
out("session.switchAgent", { sessionID: SESSION, agent: "researcher" }),
reply("session.switchAgent", null),
out("session.switchModel", {
sessionID: SESSION,
model: { providerID: "openrouter", id: "deepseek/deepseek-v4-flash", variant: "high" },
Expand All @@ -504,7 +506,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
turnInput(thread, {
instanceId,
model: "openrouter/deepseek/deepseek-v4-flash",
options: [{ id: "variant", value: "high" }],
options: [
{ id: "variant", value: "high" },
{ id: "agent", value: "researcher" },
],
}),
);
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,8 @@ describe("OpenCode 2 through the orchestrator", () => {
],
commands: [
thread.create,
thread.message("plan"),
// A stored agent must not outrank Plan while Plan mode is on.
thread.message("plan", { ...bigPickle, options: [{ id: "agent", value: "researcher" }] }),
{
type: "thread.interaction-mode.set",
commandId: thread.command("default"),
Expand Down
31 changes: 31 additions & 0 deletions apps/web/src/providerModels.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,35 @@ describe("getProviderModelCapabilities", () => {
customCapabilities,
);
});

it.each([undefined, "plan"])(
"keeps an unset agent unset when the Plan agent is hidden (current: %s)",
(currentValue) => {
const models = [
model({
slug: "opencode/test",
capabilities: {
optionDescriptors: [
{
id: "agent",
label: "Agent",
type: "select",
options: [
{ id: "researcher", label: "Researcher" },
{ id: "plan", label: "Plan" },
],
...(currentValue === undefined ? {} : { currentValue }),
},
],
},
}),
];

const descriptor = getProviderModelCapabilities(models, "opencode/test", PROVIDER, false)
.optionDescriptors?.[0];
expect(
descriptor?.type === "select" ? descriptor.currentValue : "unexpected",
).toBeUndefined();
},
);
});
7 changes: 5 additions & 2 deletions apps/web/src/providerModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,14 @@ function withoutPlanAgentOption(caps: ModelCapabilities): ModelCapabilities {
if (options.length === 0) {
return [];
}
// A filtered-out value must not fall back to another option: that would store an agent the
// user never picked and let it override the Plan toggle.
const currentValue =
descriptor.currentValue && options.some((option) => option.id === descriptor.currentValue)
? descriptor.currentValue
: (options.find((option) => option.isDefault)?.id ?? options[0]?.id);
return [{ ...descriptor, options, ...(currentValue ? { currentValue } : {}) }];
: options.find((option) => option.isDefault)?.id;
const { currentValue: _previousValue, ...rest } = descriptor;
return [{ ...rest, options, ...(currentValue ? { currentValue } : {}) }];
}),
};
}
Expand Down
6 changes: 6 additions & 0 deletions docs/user/providers-opencode.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ OpenCode 2 converts the shared OpenCode database to its own format the first tim
runs. Don't run OpenCode 1.x and 2.x side by side on the same machine. Threads you
started on 1.x continue on 2.x.

Use a model option's **Agent** selector to choose a visible primary OpenCode agent,
such as Coder, Researcher, or Reviewer. Subagent-only and hidden agents do not appear.
Discovery reads the environment server's working directory, so agents defined in
another project's `opencode.json` may not appear. With no agent selected, T3 Code
uses `build`, and the Plan toggle still chooses `plan` while it is on.

## Compaction

OpenCode compacts long conversations itself, and T3 Code has no setting for it. On
Expand Down
69 changes: 49 additions & 20 deletions packages/provider-opencode/src/server/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
checkOpenCodeProviderStatus,
followOpenCode2Scans,
loadOpenCode2Workspace,
makeOpenCode2AgentLoader,
makeOpenCode2CatalogWatch,
makeOpenCode2ModelLoader,
makePendingOpenCodeProvider,
Expand Down Expand Up @@ -439,6 +440,22 @@ export const OpenCodeDriver: ProviderDriver<
),
processEnv,
);
const loadOpenCode2Agents = yield* makeOpenCode2AgentLoader(
openCode2Server.withConnection(({ client }) =>
client.agent.list({ location: { directory: host.paths.cwd } }).pipe(
Effect.map((response) => response.data),
Effect.timeout(resolveProviderProbeTimeoutMs("opencode", 10_000, processEnv)),
Effect.mapError(
(cause) =>
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "agent.list",
detail: "The OpenCode server could not list its agents.",
cause,
}),
),
),
),
);
const listOpenCode2Workspace = (cwd: string) =>
openCode2Server.withConnection(({ client, events, url }) =>
Effect.gen(function* () {
Expand Down Expand Up @@ -549,6 +566,7 @@ export const OpenCodeDriver: ProviderDriver<
loadOpenCode2Models,
processEnv,
host.compatibility,
loadOpenCode2Agents.read,
).pipe(
Effect.annotateLogs({ providerInstanceId: instanceId }),
Effect.annotateSpans({ providerInstanceId: instanceId }),
Expand Down Expand Up @@ -763,29 +781,40 @@ export const OpenCodeDriver: ProviderDriver<
[
snapshot.getSnapshot,
// A project's opencode.jsonc can define its own providers.
openCode2Server
.withConnection(({ client, events, url }) => {
const read = loadOpenCode2DirectoryCatalog(client, cwd);
return readSettledOpenCode2Catalog(read, processEnv).pipe(
Effect.tap((settled) =>
catalogWatch.follow(url, events, read, {
cwd,
...Option.match(settled, {
onNone: () => ({}),
onSome: (catalog) => ({ settled: catalog }),
}),
}),
),
);
})
.pipe(
Effect.orElseSucceed(() => Option.none<ReadonlyArray<OpenCode2Model>>()),
Effect.map(
Option.map((catalog) =>
openCode2ProviderModels(effectiveConfig, catalog),
Effect.all(
{
catalog: openCode2Server
.withConnection(({ client, events, url }) => {
const read = loadOpenCode2DirectoryCatalog(client, cwd);
return readSettledOpenCode2Catalog(read, processEnv).pipe(
Effect.tap((settled) =>
catalogWatch.follow(url, events, read, {
cwd,
...Option.match(settled, {
onNone: () => ({}),
onSome: (catalog) => ({ settled: catalog }),
}),
}),
),
);
})
.pipe(
Effect.orElseSucceed(() =>
Option.none<ReadonlyArray<OpenCode2Model>>(),
),
),
// A project's models must carry the same agent options as the machine
// catalog, or the snapshot reports them as a workspace override.
agents: loadOpenCode2Agents.latest,
},
{ concurrency: 2 },
).pipe(
Effect.map(({ catalog, agents }) =>
Option.map(catalog, (project) =>
openCode2ProviderModels(effectiveConfig, project, agents),
),
),
),
listOpenCode2Workspace(cwd).pipe(
// Leaves room for the reads around the scan wait, which uses the same override.
Effect.timeout(
Expand Down
22 changes: 22 additions & 0 deletions packages/provider-opencode/src/server/probeResponses.fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ export function replayOpenCodeServer(
return HttpClient.make((request) => {
const path = new URL(request.url).pathname;
requestedPaths.push(path);
// OpenCode 2 answers per location; a static body would hand one project's agents to another.
if (path === "/api/agent") {
const directory = new URL(request.url).searchParams.get("location[directory]") ?? "/work";
return Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json({
location: { directory },
data: [
{
id: "build",
name: "build",
mode: "primary",
hidden: false,
request: { settings: {}, headers: {}, body: {} },
permissions: [],
},
],
}),
),
);
}
const recorded: RecordedResponse =
request.headers.authorization === expected
? (answers[path] ?? responses.unauthorized)
Expand Down
132 changes: 132 additions & 0 deletions packages/provider-opencode/src/server/status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,14 @@ import { OpenCodeSettings } from "../settings.ts";
import type { ProviderCompatibilityLookup } from "@t3tools/provider-core/server/compatibility";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
import { Agent } from "@opencode/schema/agent";
import {
checkOpenCodeProviderStatus,
loadOpenCode2Workspace,
makeOpenCode2AgentLoader,
makeOpenCode2CatalogWatch,
makeOpenCode2ModelLoader,
type OpenCode2AgentLoader,
type OpenCode2Model,
type OpenCode2Workspace,
} from "./status.ts";
Expand Down Expand Up @@ -513,6 +516,7 @@ const checkProvider = Effect.fn("checkProvider")(function* (
OpenCodeRuntime.OpenCodeRuntimeError
> = Effect.succeed([]),
compatibility?: ProviderCompatibilityLookup,
loadAgents?: OpenCode2AgentLoader,
) {
return yield* Effect.scoped(
Effect.gen(function* () {
Expand All @@ -533,6 +537,7 @@ const checkProvider = Effect.fn("checkProvider")(function* (
openCode2Models,
environment,
compatibility,
loadAgents?.read ?? Effect.succeed({ agents: [] }),
).pipe(Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner));
}),
);
Expand Down Expand Up @@ -1177,6 +1182,133 @@ it.layer(layerTest)("checkOpenCodeProviderStatus with configured server URL", (i
}),
);

it.effect("lists global OpenCode 2 agents and keeps them when a refresh fails", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "opencode v2.0.18\n";
let failed = false;
let agents = [
Agent.Info.default(Agent.ID.make("build")),
{
...Agent.Info.default(Agent.ID.make("researcher")),
name: Agent.Name.make("Researcher"),
mode: "all" as const,
},
];
const loadAgents = yield* makeOpenCode2AgentLoader(
Effect.suspend(() =>
failed
? Effect.fail(
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "agent.list",
detail: "agents unavailable",
}),
)
: Effect.succeed(agents),
),
);
const read = checkProvider(
makeOpenCodeSettings(),
process.cwd(),
undefined,
undefined,
Effect.succeed([
{ providerID: "opencode", id: "big-pickle", name: "Big Pickle", variants: [] },
]),
undefined,
loadAgents,
);
// A workspace scan can beat the first machine status check.
NodeAssert.deepEqual(yield* loadAgents.latest, agents);
const ready = yield* read;
type AgentDescriptor = {
readonly type?: string;
readonly options?: ReadonlyArray<unknown>;
readonly currentValue?: string;
};
const agentDescriptor = (snapshot: typeof ready): AgentDescriptor | undefined => {
const descriptors = snapshot.models[0]?.capabilities?.optionDescriptors ?? [];
const descriptor = descriptors.find((option) => option.id === "agent") as
| AgentDescriptor
| undefined;
return descriptor?.type === "select" ? descriptor : undefined;
};

NodeAssert.equal(ready.status, "ready");
NodeAssert.deepEqual(agentDescriptor(ready)?.options, [
{ id: "build", label: "build", isDefault: true },
{ id: "researcher", label: "Researcher" },
]);
NodeAssert.equal(agentDescriptor(ready)?.currentValue, "build");

failed = true;
const stale = yield* read;
// A failed agent refresh keeps the last known choices and leaves the probe alone.
NodeAssert.equal(stale.status, "ready");
NodeAssert.deepEqual(agentDescriptor(stale), agentDescriptor(ready));

failed = false;
agents = [];
const empty = yield* read;
NodeAssert.equal(empty.status, "ready");
NodeAssert.equal(agentDescriptor(empty), undefined);
}),
);

it.effect("offers discovered agents on a custom model without capabilities", () =>
Effect.gen(function* () {
runtimeMock.state.versionStdout = "opencode v2.0.18\n";
const loadAgents = yield* makeOpenCode2AgentLoader(
Effect.succeed([Agent.Info.default(Agent.ID.make("researcher"))]),
);
const snapshot = yield* checkProvider(
makeOpenCodeSettings({ customModels: ["opencode/custom-pick"] }),
process.cwd(),
undefined,
undefined,
Effect.succeed([
{ providerID: "opencode", id: "big-pickle", name: "Big Pickle", variants: [] },
]),
undefined,
loadAgents,
);

const custom = snapshot.models.find((model) => model.slug === "opencode/custom-pick");
const descriptor = custom?.capabilities?.optionDescriptors?.find(
(option) => option.id === "agent",
);
NodeAssert.deepEqual(
descriptor?.type === "select" ? descriptor.options.map((option) => option.id) : [],
["researcher"],
);
}),
);

it.effect("a workspace waits for the first in-flight OpenCode 2 agent read", () =>
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
const release = yield* Deferred.make<void>();
const agents = [Agent.Info.default(Agent.ID.make("researcher"))];
let reads = 0;
const loader = yield* makeOpenCode2AgentLoader(
Effect.gen(function* () {
reads++;
yield* Deferred.succeed(started, undefined);
yield* Deferred.await(release);
return agents;
}),
);
const probe = yield* Effect.forkChild(loader.read);
yield* Deferred.await(started);
const workspace = yield* Effect.forkChild(loader.latest);
yield* Deferred.succeed(release, undefined);
yield* Fiber.join(probe);
NodeAssert.deepEqual(yield* Fiber.join(workspace), agents);
NodeAssert.equal(reads, 1);
NodeAssert.deepEqual(yield* loader.latest, agents);
NodeAssert.equal(reads, 1);
}),
);

it.effect("reports a rejected OpenCode 2 password as an auth error, not a version", () =>
Effect.gen(function* () {
const snapshot = yield* checkProvider(
Expand Down
Loading
Loading