Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(providers): add OpenCode Go support (#137)

Leoc03626085a48
diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx
index 13cc7fc17..e119a18e5 100644
--- a/apps/mobile/src/components/ProviderIcon.tsx
+++ b/apps/mobile/src/components/ProviderIcon.tsx
@@ -61,7 +61,7 @@ export function ProviderIcon(props: ProviderIconProps) {
);
}
- if (props.provider === "opencode") {
+ if (props.provider === "opencode" || props.provider === "opencodeGo") {
return (
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index ec842b780..402f8fb37 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -18,6 +18,7 @@ const PLAN_LABELS = {
cursor: "Cursor",
xai: "Grok",
"kimi-for-coding": "Kimi For Coding",
+ "opencode-go": "OpenCode Go",
} as const;
export function UsageRouteScreen() {
diff --git a/apps/server/package.json b/apps/server/package.json
index da7ce1723..d48424d3f 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -23,6 +23,8 @@
},
"dependencies": {
"@ai-sdk/anthropic": "3.0.113",
+ "@ai-sdk/openai": "3.0.101",
+ "@ai-sdk/openai-compatible": "2.0.72",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@chat-adapter/state-memory": "4.39.0",
"@chat-adapter/whatsapp": "4.39.0",
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index ac3ce3586..586a7f208 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -388,6 +388,27 @@ describe("AkeruMastraHarness", () => {
);
});
+ it("keeps OpenCode Go model names on the direct subscription transport", () => {
+ const authStorage = new AuthStorage("/tmp/akeru-unused-auth.json");
+ assert.equal(
+ mastraModelId(ProviderDriverKind.make("opencodeGo"), "gpt-5.6-luna"),
+ "opencode-go/gpt-5.6-luna",
+ );
+ assert.deepInclude(
+ resolveAkeruMastraModel(
+ "opencode-go/gpt-5.6-luna",
+ authStorage,
+ undefined,
+ async () => "go-key",
+ ),
+ { provider: "opencode-go.responses", modelId: "gpt-5.6-luna" },
+ );
+ assert.throws(
+ () => resolveAkeruMastraModel("opencode-go/gpt-5.6-luna", authStorage),
+ "subscription access is unavailable",
+ );
+ });
+
it("builds a compact, human prompt with the bot name and current date", () => {
const instructions = createAkeruAgentInstructions({
name: " Research\nBot ",
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index f4b4ebc4c..11dec844f 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -47,6 +47,7 @@ import {
createAkeruBotInstructions,
} from "./AkeruAgentInstructions.ts";
import { akeruKimiProvider, type AkeruKimiAccess } from "./AkeruKimiProvider.ts";
+import { akeruOpenCodeGoProvider } from "./AkeruOpenCodeGoProvider.ts";
import { createAkeruMastraTools } from "./AkeruMastraTools.ts";
import type { AkeruToolRuntime } from "./AkeruToolRuntime.ts";
import { isCodexComputerUseTool } from "./CodexComputerUse.ts";
@@ -186,6 +187,7 @@ export function withAkeruModelRunOptions(
export interface AkeruMastraHarnessOptions {
readonly authStorage: AuthStorage;
readonly getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>;
+ readonly getOpenCodeGoApiKey?: () => Promise<string | undefined>;
readonly memoryDbPath: string;
readonly startMemoryCall?: (input: {
readonly threadId: string;
@@ -244,6 +246,7 @@ type AkeruMastraToolOptions = Pick<
AkeruMastraHarnessOptions,
| "authStorage"
| "getKimiAccess"
+ | "getOpenCodeGoApiKey"
| "getThreadTools"
| "syncThreadToolApproval"
| "toolRuntime"
@@ -362,7 +365,10 @@ export class AkeruPassiveObservationalMemoryProcessor implements Processor<"obse
}
export async function createAkeruMastraMemory(
- options: Pick<AkeruMastraHarnessOptions, "authStorage" | "getKimiAccess" | "memoryDbPath">,
+ options: Pick<
+ AkeruMastraHarnessOptions,
+ "authStorage" | "getKimiAccess" | "getOpenCodeGoApiKey" | "memoryDbPath"
+ >,
) {
const storage = new LibSQLStore({
id: "akeru-observational-memory",
@@ -375,6 +381,7 @@ export async function createAkeruMastraMemory(
controllerModelId(requestContext),
options.authStorage,
options.getKimiAccess,
+ options.getOpenCodeGoApiKey,
);
const memory = new Memory({
storage,
@@ -426,6 +433,7 @@ export async function createAkeruMastraMemory(
const MASTRA_MODEL_PREFIX = {
codex: "openai",
kimi: "kimi-for-coding",
+ opencodeGo: "opencode-go",
} as const;
export function mastraModelId(provider: ProviderDriverKind, model: string): string {
@@ -440,6 +448,7 @@ export function resolveAkeruMastraModel(
modelId: string,
authStorage: AuthStorage,
getKimiAccess?: () => Promise<AkeruKimiAccess | undefined>,
+ getOpenCodeGoApiKey?: () => Promise<string | undefined>,
modelOptions?: AkeruMastraState["modelOptions"],
) {
const trimmed = modelId.trim();
@@ -454,6 +463,10 @@ export function resolveAkeruMastraModel(
if (!getKimiAccess) throw new Error("Kimi For Coding subscription access is unavailable.");
return akeruKimiProvider(trimmed.slice("kimi-for-coding/".length), getKimiAccess);
}
+ if (trimmed.startsWith("opencode-go/")) {
+ if (!getOpenCodeGoApiKey) throw new Error("OpenCode Go subscription access is unavailable.");
+ return akeruOpenCodeGoProvider(trimmed.slice("opencode-go/".length), getOpenCodeGoApiKey);
+ }
throw new Error(`Mastra has no subscription transport for model '${modelId}'.`);
}
@@ -812,6 +825,7 @@ export async function createAkeruMastraHarness(
controllerModelId(requestContext),
options.authStorage,
options.getKimiAccess,
+ options.getOpenCodeGoApiKey,
controllerModelOptions(requestContext),
),
tools: ({ requestContext }) => resolveAkeruTools(requestContext, options),
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
new file mode 100644
index 000000000..0c2ddd7e3
--- /dev/null
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import {
+ akeruOpenCodeGoProvider,
+ buildAkeruOpenCodeGoFetch,
+ openCodeGoProtocol,
+} from "./AkeruOpenCodeGoProvider.ts";
+
+describe("AkeruOpenCodeGoProvider", () => {
+ it("selects the protocol required by each model family", () => {
+ expect(openCodeGoProtocol("gpt-5.6-luna")).toBe("responses");
+ expect(openCodeGoProtocol("qwen3.8-max")).toBe("anthropic");
+ expect(openCodeGoProtocol("deepseek-v4-pro")).toBe("chat-completions");
+ });
+
+ it("builds a model while keeping the OpenCode Go model id", () => {
+ expect(akeruOpenCodeGoProvider("gpt-5.6-luna", async () => "go-key")).toMatchObject({
+ modelId: "gpt-5.6-luna",
+ });
+ });
+
+ it("uses the saved API key and removes stale auth headers", async () => {
+ const request = vi.fn(async (_input: string | Request | URL, init?: RequestInit) => {
+ const headers = new Headers(init?.headers);
+ expect(headers.get("authorization")).toBe("Bearer go-key");
+ expect(headers.get("x-api-key")).toBeNull();
+ expect(headers.get("user-agent")).toBe("akeru-bot/0.0.37");
+ expect(headers.get("x-opencode-client")).toBe("akeru-bot");
+ return new Response("{}", { status: 200 });
+ });
+
+ await buildAkeruOpenCodeGoFetch(
+ "chat-completions",
+ async () => "go-key",
+ request,
+ )("https://opencode.ai/zen/go/v1/chat/completions", {
+ method: "POST",
+ headers: { Authorization: "stale", "x-api-key": "stale" },
+ });
+
+ expect(request).toHaveBeenCalledOnce();
+ });
+
+ it("fails closed when no API key is connected", async () => {
+ const request = vi.fn();
+ await expect(
+ buildAkeruOpenCodeGoFetch(
+ "chat-completions",
+ async () => undefined,
+ request,
+ )("https://opencode.ai/zen/go/v1/chat/completions"),
+ ).rejects.toThrow("not connected");
+ expect(request).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/provider/AkeruOpenCodeGoProvider.ts b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
new file mode 100644
index 000000000..bcf90c6f2
--- /dev/null
+++ b/apps/server/src/provider/AkeruOpenCodeGoProvider.ts
@@ -0,0 +1,83 @@
+import { createAnthropic } from "@ai-sdk/anthropic";
+import { createOpenAI } from "@ai-sdk/openai";
+import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
+import type { MastraModelConfig } from "@mastra/core/llm";
+
+const OPEN_CODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
+const OPEN_CODE_GO_USER_AGENT = "akeru-bot/0.0.37";
+
+const RESPONSES_MODELS = new Set([
+ "gpt-5.6-luna",
+ "grok-4.5",
+ "grok-4.6",
+ "muse-spark-1.2-contributor",
+]);
+
+export type OpenCodeGoProtocol = "anthropic" | "chat-completions" | "responses";
+type AkeruOpenCodeGoFetch = (
+ input: string | URL | Request,
+ init?: RequestInit,
+) => Promise<Response>;
+
+export function openCodeGoProtocol(modelId: string): OpenCodeGoProtocol {
+ if (RESPONSES_MODELS.has(modelId)) return "responses";
+ if (modelId.startsWith("minimax-") || modelId.startsWith("qwen")) return "anthropic";
+ return "chat-completions";
+}
+
+export function buildAkeruOpenCodeGoFetch(
+ protocol: OpenCodeGoProtocol,
+ getApiKey: () => Promise<string | undefined>,
+ request: AkeruOpenCodeGoFetch = globalThis.fetch,
+): AkeruOpenCodeGoFetch {
+ return async (input, init) => {
+ const apiKey = await getApiKey();
+ if (!apiKey) throw new Error("OpenCode Go is not connected. Add an API key in Settings.");
+
+ const headers = new Headers(input instanceof Request ? input.headers : undefined);
+ if (init?.headers) {
+ new Headers(init.headers).forEach((value, key) => headers.set(key, value));
+ }
+ headers.delete("authorization");
+ headers.delete("x-api-key");
+ headers.set("User-Agent", OPEN_CODE_GO_USER_AGENT);
+ headers.set("x-opencode-client", "akeru-bot");
+ if (protocol === "anthropic") {
+ headers.set("x-api-key", apiKey);
+ } else {
+ headers.set("Authorization", `Bearer ${apiKey}`);
+ }
+ return request(input, { ...init, headers });
+ };
+}
+
+export function akeruOpenCodeGoProvider(
+ modelId: string,
+ getApiKey: () => Promise<string | undefined>,
+): MastraModelConfig {
+ const protocol = openCodeGoProtocol(modelId);
+ const fetch = buildAkeruOpenCodeGoFetch(protocol, getApiKey) as NonNullable<
+ NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]
+ >;
+ if (protocol === "responses") {
+ return createOpenAI({
+ name: "opencode-go",
+ apiKey: "api-key-placeholder",
+ baseURL: OPEN_CODE_GO_BASE_URL,
+ fetch: fetch as NonNullable<NonNullable<Parameters<typeof createOpenAI>[0]>["fetch"]>,
+ }).responses(modelId);
+ }
+ if (protocol === "anthropic") {
+ return createAnthropic({
+ apiKey: "api-key-placeholder",
+ baseURL: OPEN_CODE_GO_BASE_URL,
+ fetch: fetch as NonNullable<NonNullable<Parameters<typeof createAnthropic>[0]>["fetch"]>,
+ })(modelId);
+ }
+ return createOpenAICompatible({
+ name: "opencode-go",
+ apiKey: "api-key-placeholder",
+ baseURL: OPEN_CODE_GO_BASE_URL,
+ fetch: fetch as NonNullable<NonNullable<Parameters<typeof createOpenAICompatible>[0]>["fetch"]>,
+ })(modelId);
+}
diff --git a/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts b/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts
new file mode 100644
index 000000000..6c916e6d7
--- /dev/null
+++ b/apps/server/src/provider/Drivers/OpenCodeGoDriver.test.ts
@@ -0,0 +1,89 @@
+// @effect-diagnostics nodeBuiltinImport:off preferSchemaOverJson:off
+import * as NodeFS from "node:fs";
+import * as NodePath from "node:path";
+
+import { NodeServices } from "@effect/platform-node";
+import { describe, expect, it } from "@effect/vitest";
+import { ProviderInstanceId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+
+import { ServerConfig } from "../../config.ts";
+import { BUILT_IN_DRIVERS } from "../builtInDrivers.ts";
+import { OpenCodeGoDriver } from "./OpenCodeGoDriver.ts";
+
+describe("OpenCodeGoDriver", () => {
+ it.effect("registers a Mastra-native provider with OpenCode Go models", () => {
+ expect(BUILT_IN_DRIVERS.map((driver) => String(driver.driverKind))).toContain("opencodeGo");
+ const program = Effect.scoped(
+ Effect.gen(function* () {
+ const instance = yield* OpenCodeGoDriver.create({
+ instanceId: ProviderInstanceId.make("opencodeGo"),
+ displayName: undefined,
+ environment: [],
+ enabled: true,
+ config: OpenCodeGoDriver.defaultConfig(),
+ });
+ const snapshot = yield* instance.snapshot.getSnapshot;
+ return { instance, snapshot };
+ }),
+ );
+ return program.pipe(
+ Effect.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "akeru-opencode-go-driver-test-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ Effect.tap(({ instance, snapshot }) =>
+ Effect.sync(() => {
+ expect(instance.adapter).toBeUndefined();
+ expect(snapshot).toMatchObject({
+ instanceId: "opencodeGo",
+ driver: "opencodeGo",
+ displayName: "OpenCode Go",
+ auth: { status: "unauthenticated", type: "apiKey" },
+ models: expect.arrayContaining([
+ expect.objectContaining({ slug: "gpt-5.6-luna", isDefault: true }),
+ expect.objectContaining({ slug: "grok-4.5" }),
+ expect.objectContaining({ slug: "qwen3.8-max" }),
+ ]),
+ });
+ }),
+ ),
+ );
+ });
+
+ it.effect("refreshes after an API key is connected", () => {
+ const program = Effect.scoped(
+ Effect.gen(function* () {
+ const config = yield* ServerConfig;
+ const instance = yield* OpenCodeGoDriver.create({
+ instanceId: ProviderInstanceId.make("opencodeGo"),
+ displayName: undefined,
+ environment: [],
+ enabled: true,
+ config: OpenCodeGoDriver.defaultConfig(),
+ });
+ NodeFS.mkdirSync(config.secretsDir, { recursive: true });
+ NodeFS.writeFileSync(
+ NodePath.join(config.secretsDir, "subscription-auth.json"),
+ JSON.stringify({ "opencode-go": { type: "api-key", access: "offline-test-key" } }),
+ );
+ return yield* instance.snapshot.refresh;
+ }),
+ );
+ return program.pipe(
+ Effect.provide(
+ ServerConfig.layerTest(process.cwd(), { prefix: "akeru-opencode-go-refresh-test-" }).pipe(
+ Layer.provide(NodeServices.layer),
+ ),
+ ),
+ Effect.tap((snapshot) =>
+ Effect.sync(() => {
+ expect(snapshot.status).toBe("ready");
+ expect(snapshot.auth.status).toBe("authenticated");
+ }),
+ ),
+ );
+ });
+});
diff --git a/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts b/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
new file mode 100644
index 000000000..76c49e7e2
--- /dev/null
+++ b/apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
@@ -0,0 +1,138 @@
+import {
+ OpenCodeGoSettings,
+ ProviderDriverKind,
+ type ServerProvider,
+ type ServerProviderModel,
+} from "@t3tools/contracts";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as PubSub from "effect/PubSub";
+import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
+
+import { ServerConfig } from "../../config.ts";
+import { SubscriptionAuthService } from "../../subscription-auth/service.ts";
+import type { ProviderDriver } from "../ProviderDriver.ts";
+import { defaultProviderContinuationIdentity } from "../ProviderDriver.ts";
+import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
+
+const DRIVER_KIND = ProviderDriverKind.make("opencodeGo");
+const decodeSettings = Schema.decodeSync(OpenCodeGoSettings);
+
+export const OPEN_CODE_GO_MODELS = [
+ "gpt-5.6-luna",
+ "grok-4.5",
+ "grok-4.6",
+ "glm-5.3-flash",
+ "glm-5.3",
+ "glm-5.2",
+ "glm-5.1",
+ "glm-5",
+ "kimi-k3",
+ "kimi-k2.7-code",
+ "kimi-k2.6",
+ "kimi-k2.5",
+ "longcat-2.0",
+ "deepseek-v4-pro",
+ "deepseek-v4-flash",
+ "deepseek-v4-flash-vision-exp",
+ "mimo-v2.5",
+ "mimo-v2.5-pro",
+ "mimo-v2-pro",
+ "mimo-v2-omni",
+ "minimax-m3",
+ "minimax-m2.7",
+ "minimax-m2.5",
+ "muse-spark-1.2-contributor",
+ "qwen3.8-max",
+ "qwen3.8-flash",
+ "qwen3.7-max",
+ "qwen3.7-plus",
+ "qwen3.6-plus",
+ "qwen3.5-plus",
+ "hy4-preview",
+ "hy3",
+ "hy3-preview",
+] as const;
+
+function models(customModels: readonly string[]): ServerProviderModel[] {
+ const modelIds = [...OPEN_CODE_GO_MODELS, ...customModels.map((model) => model.trim())];
+ return [...new Set(modelIds)]
+ .filter((model) => model.length > 0)
+ .map((model, index) => ({
+ slug: model,
+ name: model,
+ isCustom: !OPEN_CODE_GO_MODELS.includes(model as (typeof OPEN_CODE_GO_MODELS)[number]),
+ ...(index === 0 ? { isDefault: true } : {}),
+ capabilities: null,
+ }));
+}
+
+export type OpenCodeGoDriverEnv = ServerConfig;
+
+export const OpenCodeGoDriver: ProviderDriver<OpenCodeGoSettings, OpenCodeGoDriverEnv> = {
+ driverKind: DRIVER_KIND,
+ metadata: { displayName: "OpenCode Go", supportsMultipleInstances: false },
+ configSchema: OpenCodeGoSettings,
+ defaultConfig: () => decodeSettings({}),
+ create: ({ instanceId, displayName, accentColor, enabled, config }) =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig;
+ const auth = SubscriptionAuthService.forSecretsDir(serverConfig.secretsDir);
+ const changes = yield* Effect.acquireRelease(
+ PubSub.unbounded<ServerProvider>(),
+ PubSub.shutdown,
+ );
+ const effectiveEnabled = enabled && config.enabled;
+ const continuationIdentity = defaultProviderContinuationIdentity({
+ driverKind: DRIVER_KIND,
+ instanceId,
+ });
+ const readSnapshot = Effect.sync(() => {
+ auth.reload();
+ const connected = auth.isConnected("opencode-go");
+ return {
+ instanceId,
+ driver: DRIVER_KIND,
+ displayName: displayName ?? "OpenCode Go",
+ ...(accentColor ? { accentColor } : {}),
+ continuation: { groupKey: continuationIdentity.continuationKey },
+ enabled: effectiveEnabled,
+ installed: true,
+ version: null,
+ status: !effectiveEnabled ? "disabled" : connected ? "ready" : "warning",
+ auth: { status: connected ? "authenticated" : "unauthenticated", type: "apiKey" },
+ checkedAt: DateTime.formatIso(DateTime.nowUnsafe()),
+ ...(!connected && effectiveEnabled
+ ? { message: "Connect OpenCode Go in Settings." }
+ : {}),
+ availability: "available",
+ models: models(config.customModels),
+ slashCommands: [],
+ skills: [],
+ } satisfies ServerProvider;
+ });
+ const refresh = readSnapshot.pipe(
+ Effect.tap((snapshot) => PubSub.publish(changes, snapshot)),
+ );
+ return {
+ instanceId,
+ driverKind: DRIVER_KIND,
+ continuationIdentity,
+ displayName,
+ accentColor,
+ enabled: effectiveEnabled,
+ adapter: undefined,
+ textGeneration: undefined,
+ snapshot: {
+ maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
+ provider: DRIVER_KIND,
+ packageName: null,
+ }),
+ getSnapshot: readSnapshot,
+ refresh,
+ streamChanges: Stream.fromPubSub(changes),
+ },
+ };
+ }),
+};
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index 07fb6cdea..8ccdd21ae 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -46,6 +46,7 @@ import {
type MemoryCandidateRepositoryShape,
} from "../../memory/Services/MemoryCandidateRepository.ts";
import { AgentController } from "../Services/AgentController.ts";
+import { ProviderValidationError } from "../Errors.ts";
import { LegacyProviderBridge } from "../Services/LegacyProviderBridge.ts";
import type { ProviderServiceShape } from "../Services/ProviderService.ts";
import {
@@ -67,9 +68,11 @@ import {
const codexThreadId = ThreadId.make("thread-mastra-codex");
const claudeThreadId = ThreadId.make("thread-legacy-claude");
const kimiThreadId = ThreadId.make("thread-mastra-kimi");
+const openCodeGoThreadId = ThreadId.make("thread-mastra-opencode-go");
const codexInstanceId = ProviderInstanceId.make("codex");
const claudeInstanceId = ProviderInstanceId.make("claudeAgent");
const kimiInstanceId = ProviderInstanceId.make("kimi-custom");
+const openCodeGoInstanceId = ProviderInstanceId.make("opencodeGo");
const codexSelection = {
instanceId: codexInstanceId,
@@ -125,6 +128,12 @@ function makeProviderSession(
}
function makeBridge() {
+ let instanceEnabled = true;
+ let disableBeforeNextDispatchAdmission = false;
+ let nextDispatchAdmissionWait: Promise<void> | undefined;
+ let releaseNextDispatchAdmission: (() => void) | undefined;
+ let nextDispatchAdmissionReached = Promise.resolve();
+ let markNextDispatchAdmissionReached: (() => void) | undefined;
const startSession = vi.fn<ProviderServiceShape["startSession"]>((threadId, input) =>
Effect.succeed(
makeProviderSession(threadId, String(input.provider) === "codex" ? "codex" : "claudeAgent"),
@@ -153,19 +162,43 @@ function makeBridge() {
rollbackConversation,
listSessions: () => Effect.succeed([]),
getCapabilities,
- getInstanceInfo: (instanceId) => {
- const driverKind = ProviderDriverKind.make(
- instanceId === kimiInstanceId ? "kimi" : String(instanceId),
- );
- return Effect.succeed({
- instanceId,
- driverKind,
- displayName: undefined,
- enabled: true,
- continuationIdentity: {
+ getInstanceInfo: (instanceId) =>
+ Effect.sync(() => {
+ const driverKind = ProviderDriverKind.make(
+ instanceId === kimiInstanceId ? "kimi" : String(instanceId),
+ );
+ return {
+ instanceId,
driverKind,
- continuationKey: `${driverKind}:instance:${instanceId}`,
- },
+ displayName: undefined,
+ enabled: instanceEnabled,
+ continuationIdentity: {
+ driverKind,
+ continuationKey: `${driverKind}:instance:${instanceId}`,
+ },
+ };
+ }),
+ dispatchIfEnabled: (instanceId, operation, dispatch) => {
+ const dispatchNow = () => {
+ if (disableBeforeNextDispatchAdmission) {
+ disableBeforeNextDispatchAdmission = false;
+ instanceEnabled = false;
+ }
+ return instanceEnabled
+ ? Effect.sync(dispatch)
+ : Effect.fail(
+ new ProviderValidationError({
+ operation,
+ issue: `Provider instance '${instanceId}' is disabled in Akeru Bot settings.`,
+ }),
+ );
+ };
+ return Effect.suspend(() => {
+ const wait = nextDispatchAdmissionWait;
+ nextDispatchAdmissionWait = undefined;
+ markNextDispatchAdmissionReached?.();
+ markNextDispatchAdmissionReached = undefined;
+ return wait ? Effect.promise(() => wait).pipe(Effect.flatMap(dispatchNow)) : dispatchNow();
});
},
uploadFeedback: (input) => Effect.succeed({ feedbackId: `feedback-${String(input.threadId)}` }),
@@ -181,6 +214,25 @@ function makeBridge() {
stopSession,
rollbackConversation,
getCapabilities,
+ setInstanceEnabled: (enabled: boolean) => {
+ instanceEnabled = enabled;
+ },
+ disableBeforeNextDispatchAdmission: () => {
+ disableBeforeNextDispatchAdmission = true;
+ },
+ blockNextDispatchAdmission: () => {
+ nextDispatchAdmissionWait = new Promise<void>((resolve) => {
+ releaseNextDispatchAdmission = resolve;
+ });
+ nextDispatchAdmissionReached = new Promise<void>((resolve) => {
+ markNextDispatchAdmissionReached = resolve;
+ });
+ },
+ waitForNextDispatchAdmission: () => nextDispatchAdmissionReached,
+ releaseNextDispatchAdmission: () => {
+ releaseNextDispatchAdmission?.();
+ releaseNextDispatchAdmission = undefined;
+ },
};
}
@@ -1010,6 +1062,175 @@ describe("AgentControllerLive", () => {
);
});
+ it.effect("rejects a queued Mastra turn when its provider is disabled", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* controller.resolveEngine({
+ threadId: openCodeGoThreadId,
+ engine: { provider: String(openCodeGoInstanceId), model: "gpt-5.6-luna" },
+ fallback: codexSelection,
+ mode: "default",
+ botConversation: true,
+ });
+ yield* controller.startSession(openCodeGoThreadId, {
+ threadId: openCodeGoThreadId,
+ provider: ProviderDriverKind.make("opencodeGo"),
+ providerInstanceId: openCodeGoInstanceId,
+ modelSelection: { instanceId: openCodeGoInstanceId, model: "gpt-5.6-luna" },
+ runtimeMode: "approval-required",
+ });
+ yield* controller.sendTurn({ threadId: openCodeGoThreadId, input: "First message" });
+ const queued = yield* controller.sendTurn({
+ threadId: openCodeGoThreadId,
+ input: "Queued follow-up",
+ });
+ const failedTurn = yield* controller.streamEvents.pipe(
+ Stream.filter(
+ (event) =>
+ event.type === "turn.completed" &&
+ event.turnId === queued.turnId &&
+ event.payload.state === "failed",
+ ),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Effect.yieldNow;
+
+ bridge.setInstanceEnabled(false);
+ mastra.finishSend();
+ const failure = yield* Fiber.join(failedTurn);
+
+ assert.equal(failure._tag, "Some");
+ expect(mastra.sendMessage).toHaveBeenCalledTimes(1);
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("serializes queued turns while dispatch admission is pending", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ modelSelection: codexSelection,
+ runtimeMode: "full-access",
+ });
+
+ bridge.blockNextDispatchAdmission();
+ const firstFiber = yield* controller
+ .sendTurn({ threadId: codexThreadId, input: "First message" })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Effect.promise(bridge.waitForNextDispatchAdmission);
+
+ const second = yield* controller.sendTurn({
+ threadId: codexThreadId,
+ input: "Queued while admission is pending",
+ });
+ expect(mastra.sendMessage).not.toHaveBeenCalled();
+
+ const secondStarted = yield* controller.streamEvents.pipe(
+ Stream.filter((event) => event.type === "turn.started" && event.turnId === second.turnId),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Effect.yieldNow;
+ bridge.releaseNextDispatchAdmission();
+ yield* Fiber.join(firstFiber);
+ expect(mastra.sendMessage).toHaveBeenCalledTimes(1);
+
+ mastra.finishSend();
+ const started = yield* Fiber.join(secondStarted);
+ assert.equal(started._tag, "Some");
+ expect(mastra.sendMessage).toHaveBeenCalledTimes(2);
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("does not revive a turn interrupted during dispatch admission", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ modelSelection: codexSelection,
+ runtimeMode: "full-access",
+ });
+ const events: ProviderRuntimeEvent[] = [];
+ const eventsFiber = yield* controller.streamEvents.pipe(
+ Stream.runForEach((event) => Effect.sync(() => events.push(event))),
+ Effect.forkChild({ startImmediately: true }),
+ );
+
+ bridge.blockNextDispatchAdmission();
+ const sendFiber = yield* controller
+ .sendTurn({ threadId: codexThreadId, input: "Do not revive this turn" })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Effect.promise(bridge.waitForNextDispatchAdmission);
+ yield* controller.interruptTurn({ threadId: codexThreadId });
+ bridge.setInstanceEnabled(false);
+ bridge.releaseNextDispatchAdmission();
+
+ const exit = yield* Fiber.await(sendFiber);
+ assert.equal(Exit.isFailure(exit), true);
+ yield* Effect.yieldNow;
+ expect(mastra.sendMessage).not.toHaveBeenCalled();
+ expect(events.some((event) => event.type === "turn.started")).toBe(false);
+ yield* Fiber.interrupt(eventsFiber);
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("releases dispatch admission when the caller is interrupted", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ modelSelection: codexSelection,
+ runtimeMode: "full-access",
+ });
+
+ bridge.blockNextDispatchAdmission();
+ const blocked = yield* controller
+ .sendTurn({ threadId: codexThreadId, input: "Canceled before admission" })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Effect.promise(bridge.waitForNextDispatchAdmission);
+ yield* Fiber.interrupt(blocked);
+
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Next message" });
+ expect(mastra.sendMessage).toHaveBeenCalledTimes(1);
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
it.effect("ignores a stale Mastra send failure after the next turn starts", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
@@ -2807,6 +3028,174 @@ describe("AgentControllerLive", () => {
);
});
+ it.effect("rejects an OpenCode Go turn after the provider is disabled", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* controller.resolveEngine({
+ threadId: openCodeGoThreadId,
+ engine: { provider: String(openCodeGoInstanceId), model: "gpt-5.6-luna" },
+ fallback: codexSelection,
+ mode: "default",
+ botConversation: true,
+ });
+ yield* controller.startSession(openCodeGoThreadId, {
+ threadId: openCodeGoThreadId,
+ provider: ProviderDriverKind.make("opencodeGo"),
+ providerInstanceId: openCodeGoInstanceId,
+ cwd: process.cwd(),
+ modelSelection: { instanceId: openCodeGoInstanceId, model: "gpt-5.6-luna" },
+ runtimeMode: "approval-required",
+ });
+
+ bridge.setInstanceEnabled(false);
+ const error = yield* controller
+ .sendTurn({ threadId: openCodeGoThreadId, input: "Do not run this turn." })
+ .pipe(Effect.flip);
+
+ assert.equal(error._tag, "ProviderValidationError");
+ if (error._tag === "ProviderValidationError") {
+ assert.include(error.issue, "disabled in Akeru Bot settings");
+ }
+ expect(mastra.sendMessage).not.toHaveBeenCalled();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("rejects an OpenCode Go turn disabled during dispatch admission", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* controller.resolveEngine({
+ threadId: openCodeGoThreadId,
+ engine: { provider: String(openCodeGoInstanceId), model: "gpt-5.6-luna" },
+ fallback: codexSelection,
+ mode: "default",
+ botConversation: true,
+ });
+ yield* controller.startSession(openCodeGoThreadId, {
+ threadId: openCodeGoThreadId,
+ provider: ProviderDriverKind.make("opencodeGo"),
+ providerInstanceId: openCodeGoInstanceId,
+ cwd: process.cwd(),
+ modelSelection: { instanceId: openCodeGoInstanceId, model: "gpt-5.6-luna" },
+ runtimeMode: "approval-required",
+ });
+
+ bridge.disableBeforeNextDispatchAdmission();
+ const error = yield* controller
+ .sendTurn({ threadId: openCodeGoThreadId, input: "Do not dispatch this turn." })
+ .pipe(Effect.flip);
+
+ assert.equal(error._tag, "ProviderValidationError");
+ expect(mastra.sendMessage).not.toHaveBeenCalled();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("rejects an OpenCode Go approval after the provider is disabled", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* controller.resolveEngine({
+ threadId: openCodeGoThreadId,
+ engine: { provider: String(openCodeGoInstanceId), model: "gpt-5.6-luna" },
+ fallback: codexSelection,
+ mode: "default",
+ botConversation: true,
+ });
+ yield* controller.startSession(openCodeGoThreadId, {
+ threadId: openCodeGoThreadId,
+ provider: ProviderDriverKind.make("opencodeGo"),
+ providerInstanceId: openCodeGoInstanceId,
+ cwd: process.cwd(),
+ modelSelection: { instanceId: openCodeGoInstanceId, model: "gpt-5.6-luna" },
+ runtimeMode: "approval-required",
+ });
+ yield* controller.sendTurn({ threadId: openCodeGoThreadId, input: "Run a tool." });
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "disabled-approval",
+ toolName: "Shell",
+ args: { command: "pwd" },
+ } as AgentControllerEvent);
+
+ bridge.disableBeforeNextDispatchAdmission();
+ const error = yield* controller
+ .respondToRequest({
+ threadId: openCodeGoThreadId,
+ requestId: ApprovalRequestId.make("disabled-approval"),
+ decision: "accept",
+ })
+ .pipe(Effect.flip);
+
+ assert.equal(error._tag, "ProviderValidationError");
+ expect(mastra.session.respondToToolApproval).not.toHaveBeenCalled();
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("rejects OpenCode Go user input after the provider is disabled", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ yield* controller.resolveEngine({
+ threadId: openCodeGoThreadId,
+ engine: { provider: String(openCodeGoInstanceId), model: "gpt-5.6-luna" },
+ fallback: codexSelection,
+ mode: "default",
+ botConversation: true,
+ });
+ yield* controller.startSession(openCodeGoThreadId, {
+ threadId: openCodeGoThreadId,
+ provider: ProviderDriverKind.make("opencodeGo"),
+ providerInstanceId: openCodeGoInstanceId,
+ cwd: process.cwd(),
+ modelSelection: { instanceId: openCodeGoInstanceId, model: "gpt-5.6-luna" },
+ runtimeMode: "approval-required",
+ });
+ yield* controller.sendTurn({ threadId: openCodeGoThreadId, input: "Ask for input." });
+ mastra.emit({
+ type: "tool_suspended",
+ toolCallId: "disabled-user-input",
+ toolName: "ask_user",
+ args: {},
+ suspendPayload: {},
+ } as AgentControllerEvent);
+
+ bridge.disableBeforeNextDispatchAdmission();
+ const error = yield* controller
+ .respondToUserInput({
+ threadId: openCodeGoThreadId,
+ requestId: ApprovalRequestId.make("disabled-user-input"),
+ answers: { "disabled-user-input": "Continue" },
+ })
+ .pipe(Effect.flip);
+
+ assert.equal(error._tag, "ProviderValidationError");
+ expect(mastra.session.respondToToolSuspension).not.toHaveBeenCalled();
+ mastra.finishSend();
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
it.effect("applies saved Codex options to initial and active Mastra sessions", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index 7e5cf76d4..d64c4310d 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -122,7 +122,11 @@ import {
botWorkspaceIdentity,
botWorkspaceResourceKey,
} from "../botWorkspacePool.ts";
-import { AgentControllerRuntimeError, AgentControllerUnsupportedEngineError } from "../Errors.ts";
+import {
+ AgentControllerRuntimeError,
+ AgentControllerUnsupportedEngineError,
+ ProviderValidationError,
+} from "../Errors.ts";
import {
AgentController,
type AgentControllerSendTurnInput,
@@ -197,6 +201,7 @@ interface ActiveSession {
model: string;
status: ProviderSession["status"];
activeTurn: ActiveTurn | null;
+ admittingTurn: PendingTurn | null;
readonly pendingTurns: PendingTurn[];
readonly toolNames: Map<string, string>;
readonly approvalRequests: Map<string, { readonly name: string; readonly input: unknown }>;
@@ -388,7 +393,17 @@ function approvalDetail(toolName: string, action: string | null, oneUse: boolean
}
function usesMastraCode(provider: ProviderDriverKind): boolean {
- return provider === "codex" || provider === "kimi";
+ return provider === "codex" || provider === "kimi" || provider === "opencodeGo";
+}
+
+function disabledProviderError(
+ operation: string,
+ providerInstanceId: ProviderInstanceId,
+): ProviderValidationError {
+ return new ProviderValidationError({
+ operation,
+ issue: `Provider instance '${providerInstanceId}' is disabled in Akeru Bot settings.`,
+ });
}
function subscriptionProviderForDriver(
@@ -405,6 +420,8 @@ function subscriptionProviderForDriver(
return "xai";
case "kimi":
return "kimi-for-coding";
+ case "opencodeGo":
+ return "opencode-go";
default:
return undefined;
}
@@ -691,16 +708,32 @@ const make = (options?: AgentControllerLiveOptions) =>
makeMastraHarness({
authStorage,
getKimiAccess: () => subscriptionAuth.getKimiForCodingAccess(),
+ getOpenCodeGoApiKey: () => subscriptionAuth.getAccessToken("opencode-go"),
memoryDbPath: NodePath.join(config.stateDir, "mastra-observational-memory.sqlite"),
syncThreadToolApproval: async (threadId, toolName, protectedAction) => {
const active = sessions.get(threadId);
- if (!active || (!protectedAction && !active.connectorSessionApprovals.has(toolName))) {
+ const activeTurn = active?.activeTurn;
+ if (
+ !active ||
+ !activeTurn ||
+ (!protectedAction && !active.connectorSessionApprovals.has(toolName))
+ ) {
return;
}
- await active.session.permissions.setForTool({
- toolName,
- policy: protectedAction ? "ask" : "allow",
- });
+ const update = await runPromise(
+ legacyProviderBridge.dispatchIfEnabled(
+ active.providerInstanceId,
+ "AgentController.syncThreadToolApproval",
+ () => {
+ if (sessions.get(threadId) !== active || active.activeTurn !== activeTurn) return;
+ return active.session.permissions.setForTool({
+ toolName,
+ policy: protectedAction ? "ask" : "allow",
+ });
+ },
+ ),
+ );
+ await update;
},
getThreadTools: (threadId) => sessionResources.getConnectorTools(threadId),
...(routineDispatcher
@@ -1003,9 +1036,9 @@ const make = (options?: AgentControllerLiveOptions) =>
toolRuntime.clearApprovals(String(threadId));
};
- const startPendingTurn = (
+ const beginPendingTurn = (
active: ActiveSession,
- { threadId, turnId, message, botUsage }: PendingTurn,
+ { threadId, turnId, botUsage }: PendingTurn,
) => {
const key = String(threadId);
if (botUsage) {
@@ -1031,36 +1064,89 @@ const make = (options?: AgentControllerLiveOptions) =>
payload: { model: active.model },
});
publishSessionState(threadId, active, "running");
- void active.session
- .sendMessage(message)
+ };
+
+ const failActiveTurn = async (
+ active: ActiveSession,
+ threadId: ThreadId,
+ turnId: TurnId,
+ cause: unknown,
+ ) => {
+ if (active.activeTurn?.turnId !== turnId) return;
+ const detail = sessionFailureDetail(active, cause);
+ publish({
+ ...baseEvent(threadId, active, turnId),
+ type: "runtime.error",
+ payload: { message: detail, class: "provider_error" },
+ });
+ finishTurn(threadId, active, "failed", detail);
+ await runPromise(
+ stopSessionWithResources({ threadId }, false).pipe(
+ Effect.catchCause((resetCause) =>
+ Effect.logWarning("provider session reset failed", {
+ threadId,
+ cause: resetCause,
+ }),
+ ),
+ ),
+ );
+ };
+
+ const handlePendingTurnFailure = (
+ active: ActiveSession,
+ pending: PendingTurn,
+ cause: unknown,
+ ) => {
+ const ownsAdmission = active.admittingTurn?.turnId === pending.turnId;
+ const ownsActiveTurn = active.activeTurn?.turnId === pending.turnId;
+ if (!ownsAdmission && !ownsActiveTurn) return Promise.resolve();
+ if (ownsAdmission) {
+ active.admittingTurn = null;
+ }
+ if (!active.activeTurn) beginPendingTurn(active, pending);
+ return failActiveTurn(active, pending.threadId, pending.turnId, cause);
+ };
+
+ const startAdmittedPendingTurn = (active: ActiveSession, pending: PendingTurn) => {
+ const { threadId, turnId, message } = pending;
+ if (active.admittingTurn?.turnId !== turnId) return;
+ active.admittingTurn = null;
+ beginPendingTurn(active, pending);
+ const dispatch = active.session.sendMessage(message);
+ void dispatch
.then(() => {
const turn = active.activeTurn;
if (turn?.turnId === turnId && !turn.waiting) {
finishTurn(threadId, active, "completed");
}
})
- .catch(async (cause: unknown) => {
- if (active.activeTurn?.turnId !== turnId) return;
- const detail = sessionFailureDetail(active, cause);
- publish({
- ...baseEvent(threadId, active, turnId),
- type: "runtime.error",
- payload: { message: detail, class: "provider_error" },
- });
- finishTurn(threadId, active, "failed", detail);
- await runPromise(
- stopSessionWithResources({ threadId }, false).pipe(
- Effect.catchCause((resetCause) =>
- Effect.logWarning("provider session reset failed", {
- threadId,
- cause: resetCause,
- }),
- ),
- ),
- );
- });
+ .catch((cause: unknown) => handlePendingTurnFailure(active, pending, cause));
+ };
+
+ const admitPendingTurn = (active: ActiveSession, pending: PendingTurn) => {
+ active.admittingTurn = pending;
+ return legacyProviderBridge
+ .dispatchIfEnabled(active.providerInstanceId, "AgentController.startPendingTurn", () =>
+ startAdmittedPendingTurn(active, pending),
+ )
+ .pipe(
+ Effect.onInterrupt(() =>
+ Effect.sync(() => {
+ if (active.admittingTurn?.turnId !== pending.turnId) return;
+ active.admittingTurn = null;
+ const nextTurn = active.pendingTurns.shift();
+ if (nextTurn) startPendingTurn(active, nextTurn);
+ }),
+ ),
+ );
};
+ function startPendingTurn(active: ActiveSession, pending: PendingTurn) {
+ void runPromise(admitPendingTurn(active, pending)).catch((cause: unknown) =>
+ handlePendingTurnFailure(active, pending, cause),
+ );
+ }
+
const finishTurn = (
threadId: ThreadId,
active: ActiveSession,
@@ -1280,9 +1366,21 @@ const make = (options?: AgentControllerLiveOptions) =>
!oneUseApproval &&
permissionPolicy(active.runtimeMode, akeruToolCategory(event.toolName)) === "allow"
) {
- active.session.respondToToolApproval({
- toolCallId: event.toolCallId,
- decision: "approve",
+ void runPromise(
+ legacyProviderBridge.dispatchIfEnabled(
+ active.providerInstanceId,
+ "AgentController.handleControllerEvent",
+ () => {
+ if (active.activeTurn !== turn || turn.finished) return;
+ active.session.respondToToolApproval({
+ toolCallId: event.toolCallId,
+ decision: "approve",
+ });
+ },
+ ),
+ ).catch((cause: unknown) => {
+ if (active.activeTurn !== turn || turn.finished) return;
+ void failActiveTurn(active, threadId, turn.turnId, cause);
});
return;
}
@@ -1463,6 +1561,12 @@ const make = (options?: AgentControllerLiveOptions) =>
const routing = yield* legacyProviderBridge
.getInstanceInfo(modelSelection.instanceId)
.pipe(Effect.mapError(unavailable));
+ if (usesMastraCode(routing.driverKind) && !routing.enabled) {
+ return yield* disabledProviderError(
+ "AgentController.inspectEngine",
+ modelSelection.instanceId,
+ );
+ }
const capabilities = usesMastraCode(routing.driverKind)
? { sessionModelSwitch: "in-session" as const }
: yield* legacyProviderBridge
@@ -1586,6 +1690,15 @@ const make = (options?: AgentControllerLiveOptions) =>
detail: `Thread '${threadId}' has no resolved engine.`,
});
}
+ if (usesMastraCode(resolved.provider)) {
+ const routing = yield* legacyProviderBridge.getInstanceInfo(resolved.providerInstanceId);
+ if (!routing.enabled) {
+ return yield* disabledProviderError(
+ "AgentController.startSession",
+ resolved.providerInstanceId,
+ );
+ }
+ }
if (
mcpServers.some((server) => isCodexComputerUseServer(String(server.id))) &&
resolved.provider !== ProviderDriverKind.make("codex")
@@ -1918,6 +2031,7 @@ const make = (options?: AgentControllerLiveOptions) =>
model: resolved.modelSelection.model,
status: "ready" as const,
activeTurn: null,
+ admittingTurn: null,
pendingTurns: [],
toolNames: new Map<string, string>(),
approvalRequests: new Map(),
@@ -1941,6 +2055,16 @@ const make = (options?: AgentControllerLiveOptions) =>
const sendTurn: AgentControllerShape["sendTurn"] = Effect.fn("AgentController.sendTurn")(
function* (input) {
const key = String(input.threadId);
+ const resolved = resolvedByThread.get(key);
+ if (resolved && usesMastraCode(resolved.provider)) {
+ const routing = yield* legacyProviderBridge.getInstanceInfo(resolved.providerInstanceId);
+ if (!routing.enabled) {
+ return yield* disabledProviderError(
+ "AgentController.sendTurn",
+ resolved.providerInstanceId,
+ );
+ }
+ }
const active = sessions.get(key);
if (!active) {
if (
@@ -1951,7 +2075,6 @@ const make = (options?: AgentControllerLiveOptions) =>
detail: `Mastra session for thread '${input.threadId}' is not running.`,
});
}
- const resolved = resolvedByThread.get(key);
const { botUsage: _, ...providerInput } = input;
return yield* legacyProviderBridge.sendTurn(
resolved?.botConversation === true && String(resolved.provider) !== "claudeAgent"
@@ -2009,9 +2132,15 @@ const make = (options?: AgentControllerLiveOptions) =>
message: { content, ...(files.length > 0 ? { files } : {}) },
botUsage: input.botUsage,
});
- if (!active.activeTurn) {
+ if (!active.activeTurn && !active.admittingTurn) {
const nextTurn = active.pendingTurns.shift();
- if (nextTurn) startPendingTurn(active, nextTurn);
+ if (nextTurn) {
+ yield* admitPendingTurn(active, nextTurn).pipe(
+ Effect.tapError((cause) =>
+ Effect.promise(() => handlePendingTurnFailure(active, nextTurn, cause)),
+ ),
+ );
+ }
}
return { threadId: input.threadId, turnId };
},
@@ -2031,6 +2160,7 @@ const make = (options?: AgentControllerLiveOptions) =>
return yield* legacyProviderBridge.interruptTurn(input);
}
active.pendingTurns.length = 0;
+ active.admittingTurn = null;
active.session.abort();
finishTurn(input.threadId, active, "interrupted");
});
@@ -2051,6 +2181,13 @@ const make = (options?: AgentControllerLiveOptions) =>
}
return yield* legacyProviderBridge.respondToRequest(input);
}
+ const routing = yield* legacyProviderBridge.getInstanceInfo(active.providerInstanceId);
+ if (!routing.enabled) {
+ return yield* disabledProviderError(
+ "AgentController.respondToRequest",
+ active.providerInstanceId,
+ );
+ }
if (!active.activeTurn) {
return yield* new AgentControllerRuntimeError({
operation: "respondToRequest",
@@ -2100,44 +2237,62 @@ const make = (options?: AgentControllerLiveOptions) =>
const toolRequest = active.approvalRequests.get(toolCallId);
const pendingApproval = active.pendingApprovals.get(toolCallId);
if (!toolRequest || !pendingApproval) return;
- active.approvalRequests.delete(toolCallId);
- active.pendingApprovals.delete(toolCallId);
const { name: toolName, input: toolInput } = toolRequest;
const akeruTool = AKERU_TOOL_CATALOG.find((tool) => tool.id === toolName);
const runtimeToolId = akeruTool?.id ?? (isMemoryToolId(toolName) ? toolName : undefined);
- if (runtimeToolId && input.decision !== "decline" && input.decision !== "cancel") {
- toolRuntime.grantApproval({
- threadId: key,
- toolCallId,
- toolId: runtimeToolId,
- input: toolInput,
- });
- }
- if (
+ const acceptForSession =
input.decision === "acceptForSession" &&
!runtimeToolId &&
!isCodexComputerUseTool(toolName) &&
!akeruActionNeedsApproval(toolName, toolInput) &&
- toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME
- ) {
- active.connectorSessionApprovals.add(toolName);
- yield* runMastra("permissions.setForTool", () =>
- active.session.permissions.setForTool({ toolName, policy: "allow" }),
- );
- }
+ toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME;
const target = pendingApproval.toolName;
const decision =
input.decision === "acceptForSession" || input.decision === "acceptAlways"
? "accept"
: input.decision;
- if (active.activeTurn) active.activeTurn.waiting = false;
- active.session.respondToToolApproval({
- toolCallId,
- decision:
- runtimeToolId && input.decision !== "decline" && input.decision !== "cancel"
- ? "approve"
- : approvalDecision(decision),
- });
+ const admitted = yield* legacyProviderBridge.dispatchIfEnabled(
+ active.providerInstanceId,
+ "AgentController.respondToRequest",
+ () => {
+ if (!active.activeTurn || active.approvalRequests.get(toolCallId) !== toolRequest) {
+ return { _tag: "Stale" as const };
+ }
+ active.approvalRequests.delete(toolCallId);
+ active.pendingApprovals.delete(toolCallId);
+ if (runtimeToolId && input.decision !== "decline" && input.decision !== "cancel") {
+ toolRuntime.grantApproval({
+ threadId: key,
+ toolCallId,
+ toolId: runtimeToolId,
+ input: toolInput,
+ });
+ }
+ const update = acceptForSession
+ ? active.session.permissions.setForTool({ toolName, policy: "allow" })
+ : undefined;
+ if (acceptForSession) active.connectorSessionApprovals.add(toolName);
+ if (active.activeTurn) active.activeTurn.waiting = false;
+ active.session.respondToToolApproval({
+ toolCallId,
+ decision:
+ runtimeToolId && input.decision !== "decline" && input.decision !== "cancel"
+ ? "approve"
+ : approvalDecision(decision),
+ });
+ return { _tag: "Dispatched" as const, permissionUpdate: update };
+ },
+ );
+ if (admitted._tag === "Stale") {
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToRequest",
+ detail: `Stale pending approval request: ${input.requestId}. The agent turn has ended. Send the request again.`,
+ });
+ }
+ const permissionUpdate = admitted.permissionUpdate;
+ if (permissionUpdate) {
+ yield* runMastra("permissions.setForTool", () => permissionUpdate);
+ }
publish({
...baseEvent(input.threadId, active, active.activeTurn?.turnId),
requestId: RuntimeRequestId.make(toolCallId),
@@ -2170,6 +2325,13 @@ const make = (options?: AgentControllerLiveOptions) =>
}
return yield* legacyProviderBridge.respondToUserInput(input);
}
+ const routing = yield* legacyProviderBridge.getInstanceInfo(active.providerInstanceId);
+ if (!routing.enabled) {
+ return yield* disabledProviderError(
+ "AgentController.respondToUserInput",
+ active.providerInstanceId,
+ );
+ }
const toolCallId = String(input.requestId);
const answer = input.answers[toolCallId];
if (answer === undefined) {
@@ -2178,7 +2340,7 @@ const make = (options?: AgentControllerLiveOptions) =>
detail: `No answer was supplied for pending user-input request '${toolCallId}'.`,
});
}
- if (active.activeTurn) active.activeTurn.waiting = false;
+ const activeTurn = active.activeTurn;
let resumeFailure: string | undefined;
const unsubscribe = active.session.subscribe((event) => {
if (event.type === "tool_suspension_cancelled" && event.toolCallId === toolCallId) {
@@ -2187,9 +2349,29 @@ const make = (options?: AgentControllerLiveOptions) =>
resumeFailure ??= event.error.message;
}
});
- yield* runMastra("respondToToolSuspension", () =>
- active.session.respondToToolSuspension({ toolCallId, resumeData: answer }),
- ).pipe(Effect.ensuring(Effect.sync(unsubscribe)));
+ yield* Effect.gen(function* () {
+ const admitted = yield* legacyProviderBridge.dispatchIfEnabled(
+ active.providerInstanceId,
+ "AgentController.respondToUserInput",
+ () => {
+ if (!activeTurn || active.activeTurn !== activeTurn) {
+ return { _tag: "Stale" as const };
+ }
+ if (active.activeTurn) active.activeTurn.waiting = false;
+ return {
+ _tag: "Dispatched" as const,
+ resume: active.session.respondToToolSuspension({ toolCallId, resumeData: answer }),
+ };
+ },
+ );
+ if (admitted._tag === "Stale") {
+ return yield* new AgentControllerRuntimeError({
+ operation: "respondToUserInput",
+ detail: `Unknown pending user-input request: ${input.requestId}. The agent turn has ended. Send the request again.`,
+ });
+ }
+ yield* runMastra("respondToToolSuspension", () => admitted.resume);
+ }).pipe(Effect.ensuring(Effect.sync(unsubscribe)));
if (resumeFailure !== undefined) {
return yield* new AgentControllerRuntimeError({
operation: "respondToToolSuspension",
@@ -2240,6 +2422,7 @@ const make = (options?: AgentControllerLiveOptions) =>
return yield* legacyProviderBridge.stopSession(input);
}
active.pendingTurns.length = 0;
+ active.admittingTurn = null;
active.session.abort();
if (active.activeTurn) {
finishTurn(input.threadId, active, "interrupted");
@@ -2288,6 +2471,7 @@ const make = (options?: AgentControllerLiveOptions) =>
Effect.gen(function* () {
for (const [threadId, active] of sessions) {
active.pendingTurns.length = 0;
+ active.admittingTurn = null;
active.session.abort();
if (active.activeTurn) {
finishTurn(ThreadId.make(threadId), active, "interrupted");
diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts
index 280601275..466f42f3f 100644
--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts
+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.test.ts
@@ -139,6 +139,12 @@ const fakeInstances: ReadonlyArray<ProviderInstance> = [
const fakeInstanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
getInstance: (instanceId) =>
Effect.succeed(fakeInstances.find((instance) => instance.instanceId === instanceId)),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ fakeInstances.some((instance) => instance.instanceId === instanceId)
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed(fakeInstances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
diff --git a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
index 469d433f7..6b32480d2 100644
--- a/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
+++ b/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts
@@ -66,6 +66,11 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
),
);
+ const dispatchIfEnabled: ProviderAdapterRegistryShape["dispatchIfEnabled"] = (
+ instanceId,
+ dispatch,
+ ) => registry.dispatchIfEnabled(instanceId, dispatch);
+
const listInstances: ProviderAdapterRegistryShape["listInstances"] = () =>
registry.listInstances.pipe(
Effect.map((instances) => instances.map((instance) => instance.instanceId)),
@@ -91,6 +96,7 @@ const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(fun
return {
getByInstance,
getInstanceInfo,
+ dispatchIfEnabled,
listInstances,
listProviders,
// Proxy directly — the facade has no state of its own; the instance
diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts
index 7b9578f15..a85310343 100644
--- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts
+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.test.ts
@@ -251,6 +251,56 @@ describe("ProviderInstanceRegistryLive — multi-instance codex slice", () => {
}).pipe(Effect.provide(testLayer)),
);
+ it.live("blocks dispatch after disable without awaiting the provider promise", () =>
+ Effect.gen(function* () {
+ const instanceId = ProviderInstanceId.make("codex_atomic");
+ const enabledConfig: ProviderInstanceConfigMap = {
+ [instanceId]: {
+ driver: ProviderDriverKind.make("codex"),
+ enabled: true,
+ config: makeCodexConfig({ enabled: true }),
+ },
+ };
+ const disabledConfig: ProviderInstanceConfigMap = {
+ [instanceId]: {
+ driver: ProviderDriverKind.make("codex"),
+ enabled: false,
+ config: makeCodexConfig({ enabled: false }),
+ },
+ };
+ const { registry, mutator } = yield* makeProviderInstanceRegistry({
+ drivers: [CodexDriver],
+ configMap: enabledConfig,
+ });
+ let dispatchCalls = 0;
+ let resolveDispatch!: () => void;
+ const pendingDispatch = new Promise<void>((resolve) => {
+ resolveDispatch = resolve;
+ });
+
+ const admitted = yield* registry.dispatchIfEnabled(instanceId, () => {
+ dispatchCalls += 1;
+ return pendingDispatch;
+ });
+ expect(admitted._tag).toBe("Dispatched");
+ expect(dispatchCalls).toBe(1);
+
+ yield* mutator.reconcile(disabledConfig);
+ const disabled = yield* registry.dispatchIfEnabled(instanceId, () => {
+ dispatchCalls += 1;
+ });
+ expect(disabled._tag).toBe("Disabled");
+ expect(dispatchCalls).toBe(1);
+
+ const missing = yield* registry.dispatchIfEnabled(ProviderInstanceId.make("missing"), () => {
+ dispatchCalls += 1;
+ });
+ expect(missing._tag).toBe("Missing");
+ expect(dispatchCalls).toBe(1);
+ resolveDispatch();
+ }).pipe(Effect.provide(testLayer)),
+ );
+
it.live(
"shadows instances whose driver is not registered in this build without failing boot",
() =>
diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts
index fb75652e3..e7959918f 100644
--- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts
+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts
@@ -50,6 +50,7 @@ import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
+import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { buildUnavailableProviderSnapshot } from "../unavailableProviderSnapshot.ts";
@@ -367,12 +368,15 @@ export const makeProviderInstanceRegistry = <R>(input: {
const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());
const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());
const changes = yield* PubSub.unbounded<void>();
+ const reconciliationLock = yield* Semaphore.make(1);
yield* Effect.addFinalizer(() => PubSub.shutdown(changes));
const state: RegistryState = { entries, unavailable, changes };
const reconcileWithR = makeReconcile({ state, driversById, parentScope });
const reconcile: ProviderInstanceRegistryMutatorShape["reconcile"] = (configMap) =>
- reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));
+ reconciliationLock.withPermits(1)(
+ reconcileWithR(configMap).pipe(Effect.provideContext(driverContext)),
+ );
// Hydrate the initial configMap synchronously so callers can read
// `listInstances` immediately after this effect completes.
@@ -380,6 +384,15 @@ export const makeProviderInstanceRegistry = <R>(input: {
const registry: ProviderInstanceRegistryShape = {
getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),
+ dispatchIfEnabled: (id, dispatch) =>
+ reconciliationLock.withPermits(1)(
+ Effect.gen(function* () {
+ const instance = (yield* Ref.get(entries)).get(id)?.instance;
+ if (!instance) return { _tag: "Missing" as const };
+ if (!instance.enabled) return { _tag: "Disabled" as const };
+ return { _tag: "Dispatched" as const, value: yield* Effect.sync(dispatch) };
+ }),
+ ),
listInstances: Ref.get(entries).pipe(
Effect.map(
(map) =>
diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts
index 5fc95d2b1..678ac3a38 100644
--- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts
@@ -869,6 +869,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === codexInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
@@ -958,6 +964,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === cursorInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === cursorInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
@@ -1087,6 +1099,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === openCodeInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
@@ -1194,6 +1212,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
{
getInstance: (instanceId) =>
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === codexInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed([instance]),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
@@ -1297,6 +1321,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
instances.find((instance) => instance.instanceId === instanceId),
),
),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Ref.get(instancesRef).pipe(
+ Effect.map((instances) =>
+ instances.some((instance) => instance.instanceId === instanceId)
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
+ ),
listInstances: Effect.gen(function* () {
const shouldFail = yield* Ref.get(failNextList);
if (shouldFail) {
@@ -1744,6 +1776,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
"grok",
"kimi",
"opencode",
+ "opencodeGo",
]);
assert.strictEqual(cursorSpawned, false);
}).pipe(Effect.provide(runtimeServices));
diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts
index 3f8474c6d..893fd5761 100644
--- a/apps/server/src/provider/Layers/ProviderService.test.ts
+++ b/apps/server/src/provider/Layers/ProviderService.test.ts
@@ -454,6 +454,16 @@ it.effect(
new ProviderUnsupportedError({
provider: driverKind,
});
+ const instanceInfo = {
+ instanceId,
+ driverKind,
+ displayName: "Codex Personal",
+ enabled: true,
+ continuationIdentity: {
+ driverKind,
+ continuationKey: "codex:/Users/example/.codex",
+ },
+ } as const;
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
getByInstance: (requestedInstanceId) =>
requestedInstanceId === instanceId
@@ -461,17 +471,14 @@ it.effect(
: Effect.fail(unsupported()),
getInstanceInfo: (requestedInstanceId) =>
requestedInstanceId === instanceId
- ? Effect.succeed({
- instanceId,
- driverKind,
- displayName: "Codex Personal",
- enabled: true,
- continuationIdentity: {
- driverKind,
- continuationKey: "codex:/Users/example/.codex",
- },
- })
+ ? Effect.succeed(instanceInfo)
: Effect.fail(unsupported()),
+ dispatchIfEnabled: (requestedInstanceId, dispatch) =>
+ Effect.sync(() =>
+ requestedInstanceId === instanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: () => Effect.succeed([instanceId]),
listProviders: () => Effect.succeed([driverKind] as const),
streamChanges: Stream.empty,
@@ -533,6 +540,16 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
new ProviderUnsupportedError({
provider: ProviderDriverKind.make("codex"),
});
+ const instanceInfo = {
+ instanceId,
+ driverKind,
+ displayName: "Codex Personal",
+ enabled: false,
+ continuationIdentity: {
+ driverKind,
+ continuationKey: "codex:/Users/example/.codex",
+ },
+ } as const;
const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = {
getByInstance: (requestedInstanceId) =>
requestedInstanceId === instanceId
@@ -540,17 +557,14 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
: Effect.fail(unsupported()),
getInstanceInfo: (requestedInstanceId) =>
requestedInstanceId === instanceId
- ? Effect.succeed({
- instanceId,
- driverKind,
- displayName: "Codex Personal",
- enabled: false,
- continuationIdentity: {
- driverKind,
- continuationKey: "codex:/Users/example/.codex",
- },
- })
+ ? Effect.succeed(instanceInfo)
: Effect.fail(unsupported()),
+ dispatchIfEnabled: (requestedInstanceId, dispatch) =>
+ Effect.sync(() =>
+ requestedInstanceId === instanceId
+ ? ({ _tag: "Disabled" } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: () => Effect.succeed([instanceId]),
listProviders: () => Effect.succeed([CODEX_DRIVER] as const),
streamChanges: Stream.empty,
diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts
index 000536968..40c391da5 100644
--- a/apps/server/src/provider/Layers/ProviderService.ts
+++ b/apps/server/src/provider/Layers/ProviderService.ts
@@ -48,7 +48,11 @@ import {
providerTurnMetricAttributes,
withMetrics,
} from "../../observability/Metrics.ts";
-import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts";
+import {
+ type ProviderAdapterError,
+ ProviderUnsupportedError,
+ ProviderValidationError,
+} from "../Errors.ts";
import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts";
import * as ProviderService from "../Services/ProviderService.ts";
@@ -1013,6 +1017,28 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) =>
registry.getInstanceInfo(instanceId);
+ const dispatchIfEnabled: ProviderServiceMethod<"dispatchIfEnabled"> = (
+ instanceId,
+ operation,
+ dispatch,
+ ) =>
+ Effect.gen(function* () {
+ const result = yield* registry.dispatchIfEnabled(instanceId, dispatch);
+ switch (result._tag) {
+ case "Dispatched":
+ return result.value;
+ case "Disabled":
+ return yield* toValidationError(
+ operation,
+ `Provider instance '${instanceId}' is disabled in Akeru Bot settings.`,
+ );
+ case "Missing":
+ return yield* new ProviderUnsupportedError({
+ provider: instanceId,
+ });
+ }
+ });
+
const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn(
"rollbackConversation",
)(function* (rawInput) {
@@ -1156,6 +1182,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
listSessions,
getCapabilities,
getInstanceInfo,
+ dispatchIfEnabled,
rollbackConversation,
uploadFeedback,
// Each access creates a fresh PubSub subscription so that multiple
diff --git a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts
index fe3ab6779..a642e94e9 100644
--- a/apps/server/src/provider/Services/ProviderAdapterRegistry.ts
+++ b/apps/server/src/provider/Services/ProviderAdapterRegistry.ts
@@ -29,6 +29,7 @@ import type * as Stream from "effect/Stream";
import type { ProviderAdapterError, ProviderUnsupportedError } from "../Errors.ts";
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
import type { ProviderContinuationIdentity } from "../ProviderDriver.ts";
+import type { ProviderInstanceDispatchResult } from "./ProviderInstanceRegistry.ts";
export interface ProviderInstanceRoutingInfo {
readonly instanceId: ProviderInstanceId;
@@ -58,6 +59,12 @@ export interface ProviderAdapterRegistryShape {
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;
+ /** Atomically check enabled state and invoke a provider method. */
+ readonly dispatchIfEnabled: <A>(
+ instanceId: ProviderInstanceId,
+ dispatch: () => A,
+ ) => Effect.Effect<ProviderInstanceDispatchResult<A>>;
+
/**
* List all live instance ids. Excludes unavailable/shadow instances —
* callers of this method want something they can pass to `getByInstance`.
diff --git a/apps/server/src/provider/Services/ProviderInstanceRegistry.ts b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts
index 454a11c36..aa01d1287 100644
--- a/apps/server/src/provider/Services/ProviderInstanceRegistry.ts
+++ b/apps/server/src/provider/Services/ProviderInstanceRegistry.ts
@@ -26,6 +26,11 @@ import type * as Stream from "effect/Stream";
import type { ProviderInstance } from "../ProviderDriver.ts";
+export type ProviderInstanceDispatchResult<A> =
+ | { readonly _tag: "Missing" }
+ | { readonly _tag: "Disabled" }
+ | { readonly _tag: "Dispatched"; readonly value: A };
+
export interface ProviderInstanceRegistryShape {
/**
* Look up one instance by id. Returns `undefined` (not Option) when the
@@ -35,6 +40,11 @@ export interface ProviderInstanceRegistryShape {
readonly getInstance: (
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstance | undefined>;
+ /** Check enabled state and invoke a provider method while reconciliation is blocked. */
+ readonly dispatchIfEnabled: <A>(
+ instanceId: ProviderInstanceId,
+ dispatch: () => A,
+ ) => Effect.Effect<ProviderInstanceDispatchResult<A>>;
/**
* Every available (driver-registered, successfully created) instance,
* in stable settings-author order.
diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts
index 043f2e781..fa2e80d1d 100644
--- a/apps/server/src/provider/Services/ProviderService.ts
+++ b/apps/server/src/provider/Services/ProviderService.ts
@@ -99,6 +99,17 @@ export interface ProviderServiceShape {
instanceId: ProviderInstanceId,
) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;
+ /**
+ * Check an instance and invoke a synchronous provider method as one
+ * admission step. A disable reconciliation cannot complete between the
+ * enabled check and the method invocation.
+ */
+ readonly dispatchIfEnabled: <A>(
+ instanceId: ProviderInstanceId,
+ operation: string,
+ dispatch: () => A,
+ ) => Effect.Effect<A, ProviderServiceError>;
+
/**
* Roll back provider conversation state by a number of turns.
*/
diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts
index 8220382d1..bc158102b 100644
--- a/apps/server/src/provider/builtInDrivers.ts
+++ b/apps/server/src/provider/builtInDrivers.ts
@@ -25,6 +25,7 @@ import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts";
import { GrokDriver, type GrokDriverEnv } from "./Drivers/GrokDriver.ts";
import { KimiDriver, type KimiDriverEnv } from "./Drivers/KimiDriver.ts";
import { OpenCodeDriver, type OpenCodeDriverEnv } from "./Drivers/OpenCodeDriver.ts";
+import { OpenCodeGoDriver, type OpenCodeGoDriverEnv } from "./Drivers/OpenCodeGoDriver.ts";
import type { AnyProviderDriver } from "./ProviderDriver.ts";
/**
@@ -37,7 +38,8 @@ export type BuiltInDriversEnv =
| CodexDriverEnv
| GrokDriverEnv
| KimiDriverEnv
- | OpenCodeDriverEnv;
+ | OpenCodeDriverEnv
+ | OpenCodeGoDriverEnv;
/**
* Ordered list of built-in drivers. Order matters only for tie-breaking in
@@ -50,4 +52,5 @@ export const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv
GrokDriver,
KimiDriver,
OpenCodeDriver,
+ OpenCodeGoDriver,
];
diff --git a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts
index c696a51c3..69dd38b66 100644
--- a/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts
+++ b/apps/server/src/provider/testUtils/providerAdapterRegistryMock.ts
@@ -57,28 +57,36 @@ export const makeAdapterRegistryMock = (adapters: KindAdapterMap): ProviderAdapt
);
};
+ const getInstanceInfo: ProviderAdapterRegistryShape["getInstanceInfo"] = (instanceId) => {
+ const adapter = byInstanceId.get(instanceId);
+ if (!adapter) {
+ return Effect.fail(
+ new ProviderUnsupportedError({
+ provider: ProviderDriverKind.make(instanceId),
+ }),
+ );
+ }
+ return Effect.succeed({
+ instanceId,
+ driverKind: ProviderDriverKind.make(adapter.provider),
+ displayName: undefined,
+ enabled: true,
+ continuationIdentity: {
+ driverKind: ProviderDriverKind.make(adapter.provider),
+ continuationKey: `${adapter.provider}:instance:${instanceId}`,
+ },
+ });
+ };
+
return {
getByInstance,
- getInstanceInfo: (instanceId) => {
- const adapter = byInstanceId.get(instanceId);
- if (!adapter) {
- return Effect.fail(
- new ProviderUnsupportedError({
- provider: ProviderDriverKind.make(instanceId),
- }),
- );
- }
- return Effect.succeed({
- instanceId,
- driverKind: ProviderDriverKind.make(adapter.provider),
- displayName: undefined,
- enabled: true,
- continuationIdentity: {
- driverKind: ProviderDriverKind.make(adapter.provider),
- continuationKey: `${adapter.provider}:instance:${instanceId}`,
- },
- });
- },
+ getInstanceInfo,
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ byInstanceId.has(instanceId)
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: () => Effect.succeed(Array.from(byInstanceId.keys())),
listProviders: () =>
Effect.succeed(
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index 2d443bcaa..e90d6552e 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -831,6 +831,22 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
+ it.effect("keeps OpenCode Go disabled after settings reload", () =>
+ Effect.gen(function* () {
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+
+ yield* fileSystem.writeFileString(
+ serverConfig.settingsPath,
+ '{"providers":{"opencodeGo":{"enabled":false}}}',
+ );
+
+ const settings = yield* serverSettings.getSettings;
+ assert.isFalse(settings.providers.opencodeGo.enabled);
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
+
it.effect("folds a legacy in-config enabled flag into the envelope on load", () =>
Effect.gen(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts
index 6368f8e64..453202ba7 100644
--- a/apps/server/src/serverSettings.ts
+++ b/apps/server/src/serverSettings.ts
@@ -278,6 +278,9 @@ const PersistedOptionalProviderSettings = Schema.Struct({
grok: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
kimi: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
opencode: Schema.optionalKey(Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) })),
+ opencodeGo: Schema.optionalKey(
+ Schema.Struct({ enabled: Schema.optionalKey(Schema.Boolean) }),
+ ),
}),
),
});
@@ -332,6 +335,10 @@ function restoreUsedProviders(
...settings.providers.opencode,
enabled: persisted.providers?.opencode?.enabled ?? usedProviders.has("opencode"),
},
+ opencodeGo: {
+ ...settings.providers.opencodeGo,
+ enabled: persisted.providers?.opencodeGo?.enabled ?? true,
+ },
},
providerInstances,
};
diff --git a/apps/server/src/subscription-auth/service.test.ts b/apps/server/src/subscription-auth/service.test.ts
index 3d6324570..432cb7cc6 100644
--- a/apps/server/src/subscription-auth/service.test.ts
+++ b/apps/server/src/subscription-auth/service.test.ts
@@ -67,6 +67,49 @@ describe("subscription auth storage", () => {
expect(NodeFS.readFileSync(authPath, "utf-8")).toBe(before);
});
+ it("stores an OpenCode Go API key without exposing it in status", async () => {
+ const { authPath } = fixture();
+ const service = new SubscriptionAuthService(authPath);
+ const started = await service.startLogin("opencode-go");
+
+ await expect(service.completeLogin(started.loginId, " go-secret-key ")).resolves.toEqual({
+ status: "connected",
+ });
+ await expect(service.getAccessToken("opencode-go")).resolves.toBe("go-secret-key");
+ expect(service.statuses().find((status) => status.provider === "opencode-go")).toMatchObject({
+ connected: true,
+ health: "detected",
+ reconnectAction: "Replace API key",
+ });
+ expect(JSON.stringify(service.statuses())).not.toContain("go-secret-key");
+ expect(NodeFS.statSync(authPath).mode & 0o777).toBe(0o600);
+ });
+
+ it("checks an OpenCode Go key against the entitlement endpoint", async () => {
+ const { authPath } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({ "opencode-go": { type: "api-key", access: "go-secret-key" } }),
+ );
+ const request = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
+ const headers = new Headers(init?.headers);
+ expect(headers.get("authorization")).toBe("Bearer go-secret-key");
+ expect(headers.get("user-agent")).toBe("akeru-bot/0.0.37");
+ return new Response("{}", { status: 200 });
+ });
+ vi.stubGlobal("fetch", request);
+
+ const service = new SubscriptionAuthService(authPath);
+ await service.testHealth("opencode-go");
+
+ expect(request).toHaveBeenCalledWith("https://opencode.ai/zen/go/v1/usage", expect.any(Object));
+ expect(service.statuses().find((status) => status.provider === "opencode-go")).toMatchObject({
+ health: "healthy",
+ healthTest: { status: "passed" },
+ });
+ vi.unstubAllGlobals();
+ });
+
it("returns Kimi access only with its persisted device identity", async () => {
const { authPath } = fixture();
NodeFS.writeFileSync(
diff --git a/apps/server/src/subscription-auth/service.ts b/apps/server/src/subscription-auth/service.ts
index 54f4bf7e7..ef7760c33 100644
--- a/apps/server/src/subscription-auth/service.ts
+++ b/apps/server/src/subscription-auth/service.ts
@@ -1,12 +1,12 @@
-// @effect-diagnostics nodeBuiltinImport:off globalDate:off
+// @effect-diagnostics nodeBuiltinImport:off globalDate:off globalFetch:off
/**
- * Subscription auth service: one API over five login flows.
+ * Subscription auth service: one API over OAuth and API-key login flows.
*
* Storage follows Mastra Code's `AuthStorage` (mastra-ai/mastra,
* `mastracode/sdk/src/auth/storage.ts`, Apache-2.0): a mode-0600 JSON file of
- * OAuth credentials. It lives in the server's secrets directory, never inside
- * a workspace or sandbox — a sandbox (E2B or local worktree) receives a
- * short-lived access token per run and holds no refresh token.
+ * Provider credentials. They live in the server's secrets directory, never inside
+ * a workspace or sandbox. Provider runtimes request credentials from this
+ * service and do not copy refresh credentials into a sandbox.
*
* Login flows are client-driven: `start` returns a URL (and user code) to
* show, then the client calls `poll` until the flow settles. Every pending
@@ -51,12 +51,17 @@ import {
} from "./providers/xai.ts";
import type { OAuthCredential, OAuthCredentials, SubscriptionAuthData } from "./types.ts";
+const OPENCODE_GO_AUTH_URL = "https://opencode.ai/auth";
+const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
+const OPENCODE_GO_USER_AGENT = "akeru-bot/0.0.37";
+
export const SUBSCRIPTION_PROVIDER_IDS = [
"anthropic",
"openai-codex",
"cursor",
"xai",
"kimi-for-coding",
+ "opencode-go",
] as const;
export type SubscriptionProviderId = (typeof SUBSCRIPTION_PROVIDER_IDS)[number];
@@ -138,7 +143,8 @@ type PendingLogin =
| { provider: "openai-codex"; pending: CodexDeviceLoginPending }
| { provider: "cursor"; pending: CursorLoginPending }
| { provider: "xai"; pending: XAIDeviceLoginPending }
- | { provider: "kimi-for-coding"; pending: KimiDeviceLoginPending };
+ | { provider: "kimi-for-coding"; pending: KimiDeviceLoginPending }
+ | { provider: "opencode-go" };
/** A completed login that the client has not observed yet must not be re-runnable. */
const PENDING_LOGIN_CAP = 16;
@@ -239,7 +245,7 @@ export class SubscriptionAuthService {
return SUBSCRIPTION_PROVIDER_IDS.map((provider) => {
const credential = this.data[provider];
const health = this.health[provider];
- const expired = credential !== undefined && credential.expires <= now;
+ const expired = credential?.type === "oauth" && credential.expires <= now;
const failedAfterSuccess =
health?.lastFailedRequest !== undefined &&
(health.lastSuccessfulRequestAt === undefined ||
@@ -266,14 +272,21 @@ export class SubscriptionAuthService {
return {
provider,
connected: credential !== undefined,
- ...(credential ? { expiresAt: credential.expires } : {}),
+ ...(credential?.type === "oauth" ? { expiresAt: credential.expires } : {}),
health: state,
...(health?.lastSuccessfulRequestAt
? { lastSuccessfulRequestAt: health.lastSuccessfulRequestAt }
: {}),
...(health?.lastFailedRequest ? { lastFailedRequest: health.lastFailedRequest } : {}),
...(health?.nextRetryAt ? { nextRetryAt: health.nextRetryAt } : {}),
- reconnectAction: credential ? "Reconnect account" : "Connect account",
+ reconnectAction:
+ provider === "opencode-go"
+ ? credential
+ ? "Replace API key"
+ : "Connect API key"
+ : credential
+ ? "Reconnect account"
+ : "Connect account",
healthTest: health?.healthTest ?? { status: "not-run" },
...(health?.oauthCheck ? { oauthCheck: health.oauthCheck } : {}),
dependentBots: dependentBots
@@ -409,6 +422,33 @@ export class SubscriptionAuthService {
this.recordOAuthFailure(provider, "No account is connected.");
return;
}
+ if (provider === "opencode-go") {
+ try {
+ const response = await fetch(OPENCODE_GO_USAGE_URL, {
+ headers: {
+ Authorization: `Bearer ${credential.access}`,
+ "User-Agent": OPENCODE_GO_USER_AGENT,
+ "x-opencode-client": "akeru-bot",
+ },
+ });
+ if (!response.ok) {
+ throw new Error(`OpenCode Go rejected the API key (${response.status}).`);
+ }
+ this.recordRequestSuccess(provider);
+ } catch (cause) {
+ this.recordRequestFailure(
+ provider,
+ cause instanceof Error ? cause.message : "OpenCode Go rejected the API key.",
+ undefined,
+ oauthFailureKind(cause),
+ );
+ }
+ return;
+ }
+ if (credential.type !== "oauth") {
+ this.recordOAuthFailure(provider, "The stored credential has the wrong type.");
+ return;
+ }
try {
const refreshed = await this.runRefresh(provider, credential);
this.setCredential(provider, refreshed);
@@ -514,6 +554,17 @@ export class SubscriptionAuthService {
};
break;
}
+ case "opencode-go": {
+ this.pendingLogins.set(loginId, { provider });
+ started = {
+ loginId,
+ provider,
+ url: OPENCODE_GO_AUTH_URL,
+ instructions: "Subscribe to OpenCode Go, copy the API key, then paste it here.",
+ completion: "paste",
+ };
+ break;
+ }
}
// Drop the oldest abandoned login rather than growing without bound.
@@ -564,6 +615,8 @@ export class SubscriptionAuthService {
}
return this.foldPoll(loginId, login.provider, result);
}
+ case "opencode-go":
+ return { status: "pending", nextPollMs: 2000 };
}
}
@@ -597,10 +650,22 @@ export class SubscriptionAuthService {
if (!login) {
return { status: "failed", error: "Login expired or already completed. Start again." };
}
- if (login.provider !== "anthropic") {
+ if (login.provider !== "anthropic" && login.provider !== "opencode-go") {
return { status: "failed", error: "This login completes by polling, not with a code." };
}
+ if (login.provider === "opencode-go") {
+ const apiKey = code.trim();
+ if (apiKey.length === 0) {
+ return { status: "failed", error: "Paste an OpenCode Go API key." };
+ }
+ this.pendingLogins.delete(loginId);
+ this.savePending();
+ this.data["opencode-go"] = { type: "api-key", access: apiKey };
+ this.save();
+ return { status: "connected" };
+ }
+
try {
const credentials = await completeAnthropicLogin(code, login.verifier);
this.pendingLogins.delete(loginId);
@@ -643,6 +708,8 @@ export class SubscriptionAuthService {
const credential = this.data[provider];
if (!credential) return undefined;
+ if (credential.type === "api-key") return credential.access;
+
if (Date.now() < credential.expires) {
return credential.access;
}
@@ -663,7 +730,7 @@ export class SubscriptionAuthService {
this.reload();
const accessToken = await this.getAccessToken("openai-codex");
const credential = this.data["openai-codex"];
- const accountId = credential?.accountId;
+ const accountId = credential?.type === "oauth" ? credential.accountId : undefined;
return accessToken && typeof accountId === "string" && accountId.length > 0
? { accessToken, accountId }
: undefined;
@@ -674,7 +741,8 @@ export class SubscriptionAuthService {
> {
this.reload();
const accessToken = await this.getAccessToken("kimi-for-coding");
- const deviceId = this.data["kimi-for-coding"]?.deviceId;
+ const credential = this.data["kimi-for-coding"];
+ const deviceId = credential?.type === "oauth" ? credential.deviceId : undefined;
return accessToken && isKimiCodingDeviceId(deviceId) ? { accessToken, deviceId } : undefined;
}
@@ -717,6 +785,8 @@ export class SubscriptionAuthService {
undefined,
typeof credential.deviceId === "string" ? credential.deviceId : undefined,
);
+ case "opencode-go":
+ throw new Error("OpenCode Go API keys do not refresh.");
}
}
}
diff --git a/apps/server/src/subscription-auth/snapshot.ts b/apps/server/src/subscription-auth/snapshot.ts
index aca1d31f1..84be5e923 100644
--- a/apps/server/src/subscription-auth/snapshot.ts
+++ b/apps/server/src/subscription-auth/snapshot.ts
@@ -21,6 +21,7 @@ const SUBSCRIPTION_DRIVER: Readonly<Record<SubscriptionProviderId, string>> = {
cursor: "cursor",
xai: "grok",
"kimi-for-coding": "kimi",
+ "opencode-go": "opencodeGo",
};
export function subscriptionDependentBots(
diff --git a/apps/server/src/subscription-auth/types.ts b/apps/server/src/subscription-auth/types.ts
index b81cdf3da..02d911fbd 100644
--- a/apps/server/src/subscription-auth/types.ts
+++ b/apps/server/src/subscription-auth/types.ts
@@ -3,8 +3,8 @@
*
* Ported from Mastra Code (mastra-ai/mastra, `mastracode/sdk/src/auth`),
* Apache-2.0. A provider here is a consumer subscription (Claude Pro/Max,
- * ChatGPT, Cursor, Kimi For Coding, X Premium) that the agent runtime spends,
- * not an API key with usage billing.
+ * ChatGPT, Cursor, Kimi For Coding, X Premium, or OpenCode Go) that the agent
+ * runtime uses. Most providers use OAuth. OpenCode Go uses an API key.
*/
export interface OAuthCredentials {
@@ -19,4 +19,11 @@ export type OAuthCredential = {
type: "oauth";
} & OAuthCredentials;
-export type SubscriptionAuthData = Record<string, OAuthCredential>;
+export interface ApiKeyCredential {
+ readonly type: "api-key";
+ readonly access: string;
+}
+
+export type SubscriptionCredential = OAuthCredential | ApiKeyCredential;
+
+export type SubscriptionAuthData = Record<string, SubscriptionCredential>;
diff --git a/apps/server/src/textGeneration/TextGeneration.test.ts b/apps/server/src/textGeneration/TextGeneration.test.ts
index 9bccb9c1f..99ade880f 100644
--- a/apps/server/src/textGeneration/TextGeneration.test.ts
+++ b/apps/server/src/textGeneration/TextGeneration.test.ts
@@ -48,6 +48,12 @@ const makeStubRegistry = (
const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const));
return {
getInstance: (id) => Effect.succeed(byId.get(id)),
+ dispatchIfEnabled: (id, dispatch) =>
+ Effect.sync(() =>
+ byId.has(id)
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
listInstances: Effect.succeed(instances),
listUnavailable: Effect.succeed([]),
streamChanges: Stream.empty,
diff --git a/apps/server/src/usage/usagePlanLimits.test.ts b/apps/server/src/usage/usagePlanLimits.test.ts
index 4781414a2..3d55322ea 100644
--- a/apps/server/src/usage/usagePlanLimits.test.ts
+++ b/apps/server/src/usage/usagePlanLimits.test.ts
@@ -182,4 +182,24 @@ describe("readPlanLimits cache", () => {
},
]);
});
+
+ it("shows a connected OpenCode Go card without calling an unsupported usage endpoint", async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ const limits = await readPlanLimits(async (provider) =>
+ provider === "opencode-go" ? "go-key" : undefined,
+ );
+
+ expect(limits).toEqual([
+ {
+ provider: "opencode-go",
+ status: "ok",
+ plan: null,
+ message: null,
+ windows: [],
+ },
+ ]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/usage/usagePlanLimits.ts b/apps/server/src/usage/usagePlanLimits.ts
index adb41c0a2..345e2c0e6 100644
--- a/apps/server/src/usage/usagePlanLimits.ts
+++ b/apps/server/src/usage/usagePlanLimits.ts
@@ -31,6 +31,7 @@ const PLAN_PROVIDER_ORDER: readonly SubscriptionProviderId[] = [
"cursor",
"xai",
"kimi-for-coding",
+ "opencode-go",
];
export type GetAccessToken = (provider: SubscriptionProviderId) => Promise<string | undefined>;
@@ -538,6 +539,8 @@ async function fetchProvider(
return fetchGrok(accessToken);
case "kimi-for-coding":
return fetchKimi(accessToken);
+ case "opencode-go":
+ return null;
}
}
diff --git a/apps/web/src/components/chat/providerIconUtils.ts b/apps/web/src/components/chat/providerIconUtils.ts
index 504c80be3..534f9043d 100644
--- a/apps/web/src/components/chat/providerIconUtils.ts
+++ b/apps/web/src/components/chat/providerIconUtils.ts
@@ -6,6 +6,7 @@ export const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>
[ProviderDriverKind.make("codex")]: OpenAI,
[ProviderDriverKind.make("claudeAgent")]: ClaudeAI,
[ProviderDriverKind.make("opencode")]: OpenCodeIcon,
+ [ProviderDriverKind.make("opencodeGo")]: OpenCodeIcon,
[ProviderDriverKind.make("cursor")]: CursorIcon,
[ProviderDriverKind.make("grok")]: GrokIcon,
[ProviderDriverKind.make("kimi")]: KimiIcon,
diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx
index e4fddd068..5ff639a86 100644
--- a/apps/web/src/components/settings/ProviderModelsSection.tsx
+++ b/apps/web/src/components/settings/ProviderModelsSection.tsx
@@ -36,6 +36,7 @@ const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, strin
[ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
[ProviderDriverKind.make("kimi")]: "k3-256k",
[ProviderDriverKind.make("opencode")]: "openai/gpt-5",
+ [ProviderDriverKind.make("opencodeGo")]: "gpt-5.6-luna",
};
interface ProviderModelsSectionProps {
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
index ece9759a3..9cd070eab 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts
+++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
@@ -57,6 +57,13 @@ describe("ProviderSettingsForm helpers", () => {
expect(DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("cursor")]).toBeUndefined();
});
+ it("registers OpenCode Go in the provider picker", () => {
+ const openCodeGo = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencodeGo")];
+
+ expect(openCodeGo).toMatchObject({ label: "OpenCode Go" });
+ expect(deriveProviderSettingsFields(openCodeGo!)).toEqual([]);
+ });
+
it("preserves unknown config keys while omitting empty configurable fields", () => {
const opencode = DRIVER_OPTION_BY_VALUE[ProviderDriverKind.make("opencode")];
expect(opencode).toBeDefined();
diff --git a/apps/web/src/components/settings/ProvidersPanel.test.tsx b/apps/web/src/components/settings/ProvidersPanel.test.tsx
index ed4b45b32..1af98e059 100644
--- a/apps/web/src/components/settings/ProvidersPanel.test.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.test.tsx
@@ -8,6 +8,7 @@ describe("subscription providers", () => {
it("offers Kimi subscription login without Cursor", () => {
const providers = SUBSCRIPTION_PROVIDERS.map((provider) => provider.id);
expect(providers).toContain("kimi-for-coding");
+ expect(providers).toContain("opencode-go");
expect(providers).not.toContain("cursor");
});
diff --git a/apps/web/src/components/settings/ProvidersPanel.tsx b/apps/web/src/components/settings/ProvidersPanel.tsx
index 5d74f9cc0..80e7d1f60 100644
--- a/apps/web/src/components/settings/ProvidersPanel.tsx
+++ b/apps/web/src/components/settings/ProvidersPanel.tsx
@@ -19,7 +19,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
-import { ClaudeAI, type Icon } from "../Icons";
+import { ClaudeAI, OpenCodeIcon, type Icon } from "../Icons";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
interface SubscriptionProviderDefinition {
@@ -59,6 +59,13 @@ export const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProviderDefinition[] =
description: "Use Kimi coding models through your Moonshot subscription.",
icon: "/provider-icons/kimi-for-coding.svg",
},
+ {
+ id: "opencode-go",
+ label: "OpenCode Go",
+ subscription: "OpenCode Go API key",
+ description: "Use OpenCode Go models with an API key from OpenCode.",
+ icon: OpenCodeIcon,
+ },
];
interface ActiveLogin {
@@ -148,7 +155,7 @@ export function ProviderLoginCard({
) : (
<RefreshCwIcon className="size-3.5" />
)}
- Check OAuth
+ {definition.id === "opencode-go" ? "Check key" : "Check OAuth"}
</Button>
<Button size="xs" variant="ghost-muted" disabled={busy} onClick={onConnect}>
Reconnect
@@ -190,6 +197,7 @@ function ActiveLoginPanel({
readonly completing: boolean;
}) {
const { flow } = login;
+ const isApiKey = flow.provider === "opencode-go";
return (
<div className="mx-3 mb-3 space-y-3 rounded-xl border bg-muted/30 p-4 sm:mx-4">
<div className="flex items-center justify-between gap-3">
@@ -201,7 +209,7 @@ function ActiveLoginPanel({
variant="outline"
render={<a href={flow.url} target="_blank" rel="noreferrer" />}
>
- Open sign-in
+ {isApiKey ? "Open OpenCode" : "Open sign-in"}
<ExternalLinkIcon className="size-3.5" />
</Button>
</div>
@@ -225,8 +233,8 @@ function ActiveLoginPanel({
<Input
value={pastedCode}
onChange={(event) => onPastedCodeChange(event.currentTarget.value)}
- placeholder="Paste the authorization code"
- aria-label="Authorization code"
+ placeholder={isApiKey ? "Paste the API key" : "Paste the authorization code"}
+ aria-label={isApiKey ? "API key" : "Authorization code"}
className="flex-1"
/>
<Button
diff --git a/apps/web/src/components/settings/providerDriverMeta.ts b/apps/web/src/components/settings/providerDriverMeta.ts
index 7c7f459de..6070215f4 100644
--- a/apps/web/src/components/settings/providerDriverMeta.ts
+++ b/apps/web/src/components/settings/providerDriverMeta.ts
@@ -3,6 +3,7 @@ import {
CodexSettings,
GrokSettings,
KimiSettings,
+ OpenCodeGoSettings,
OpenCodeSettings,
ProviderDriverKind,
} from "@t3tools/contracts";
@@ -67,6 +68,12 @@ export const PROVIDER_CLIENT_DEFINITIONS: readonly ProviderClientDefinition[] =
icon: OpenCodeIcon,
settingsSchema: OpenCodeSettings,
},
+ {
+ value: ProviderDriverKind.make("opencodeGo"),
+ label: "OpenCode Go",
+ icon: OpenCodeIcon,
+ settingsSchema: OpenCodeGoSettings,
+ },
];
export const PROVIDER_CLIENT_DEFINITION_BY_VALUE: Partial<
diff --git a/apps/web/src/components/usage/UsageCharts.tsx b/apps/web/src/components/usage/UsageCharts.tsx
index c9d9994ed..4ccf142ab 100644
--- a/apps/web/src/components/usage/UsageCharts.tsx
+++ b/apps/web/src/components/usage/UsageCharts.tsx
@@ -18,7 +18,7 @@ import { Grid } from "../dither-kit/grid";
import { Tooltip } from "../dither-kit/tooltip";
import { XAxis } from "../dither-kit/x-axis";
import { YAxis } from "../dither-kit/y-axis";
-import { ClaudeAI, CursorIcon, GrokIcon, type Icon, OpenAI } from "../Icons";
+import { ClaudeAI, CursorIcon, GrokIcon, OpenCodeIcon, type Icon, OpenAI } from "../Icons";
import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";
export const PLAN_PROVIDER_PRESENTATION: Record<
@@ -38,6 +38,7 @@ export const PLAN_PROVIDER_PRESENTATION: Record<
icon: "/provider-icons/kimi-for-coding.svg",
color: "purple",
},
+ "opencode-go": { label: "OpenCode Go", icon: OpenCodeIcon, color: "grey" },
};
export const PLAN_PROVIDER_ORDER: readonly SubscriptionProviderId[] = [
@@ -46,6 +47,7 @@ export const PLAN_PROVIDER_ORDER: readonly SubscriptionProviderId[] = [
"cursor",
"xai",
"kimi-for-coding",
+ "opencode-go",
];
function formatReset(resetsAt: string | null): string {
diff --git a/apps/web/src/lib/contextWindow.ts b/apps/web/src/lib/contextWindow.ts
index 3ba24cb2c..b62653e53 100644
--- a/apps/web/src/lib/contextWindow.ts
+++ b/apps/web/src/lib/contextWindow.ts
@@ -38,6 +38,8 @@ export function formatProviderDisplayName(provider: string | null | undefined):
return "Cursor";
case "opencode":
return "OpenCode";
+ case "opencodeGo":
+ return "OpenCode Go";
default: {
// Title-case unknown driver kinds so they read reasonably.
const trimmed = provider.replace(/Agent$/i, "").trim();
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 8a897cb4a..ce29d3098 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -55,6 +55,12 @@ export const PROVIDER_OPTIONS: Array<{
available: true,
pickerSidebarBadge: "new",
},
+ {
+ value: ProviderDriverKind.make("opencodeGo"),
+ label: "OpenCode Go",
+ available: true,
+ pickerSidebarBadge: "new",
+ },
];
export type WorkLogToolLifecycleStatus =
diff --git a/docs/internals/glossary.md b/docs/internals/glossary.md
index cb0d612f6..5a3ea9d81 100644
--- a/docs/internals/glossary.md
+++ b/docs/internals/glossary.md
@@ -91,15 +91,15 @@ A typed signal emitted when an async milestone completes, such as `checkpoint.ba
### Subscription provider
-A consumer AI account that a user connects through OAuth, such as ChatGPT, Claude, Grok, or Kimi For Coding. The environment server stores the credential and gives a run only the short-lived access token it needs. See [subscription authentication](./subscription-auth.md).
+A consumer AI account that a user connects through OAuth, such as ChatGPT, Claude, Grok, or Kimi For Coding. OpenCode Go uses an API key instead of OAuth. The environment server stores the credential and gives a run only the access token it needs. See [subscription authentication](./subscription-auth.md).
## Provider runtime
-The live backend agent implementation and its event stream. Desktop turns cross [AgentController][25]. Codex and Kimi use Akeru's Mastra Core controller, custom workspace and MCP tools, server-owned subscription access, and normalized Mastra runtime events. Claude, Grok, and OpenCode keep their existing adapters behind the legacy bridge. The adapter contract is [ProviderAdapter.ts][15], and the overview is in [providers.md][16].
+The live backend agent implementation and its event stream. Desktop turns cross [AgentController][25]. Codex, Kimi, and OpenCode Go use Akeru's Mastra Core controller, custom workspace and MCP tools, server-owned subscription access, and normalized Mastra runtime events. Claude, Grok, and OpenCode keep their existing adapters behind the legacy bridge. The adapter contract is [ProviderAdapter.ts][15], and the overview is in [providers.md][16].
#### Provider
-The backend agent runtime that actually performs work. Five drivers ship built in: Codex, Claude, Grok, Kimi For Coding, and OpenCode. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17] as a representative adapter.
+The backend agent runtime that actually performs work. Six drivers ship built in: Codex, Claude, Grok, Kimi For Coding, OpenCode, and OpenCode Go. See [ProviderService.ts][14], [ProviderAdapter.ts][15], and [CodexAdapter.ts][17] as a representative adapter.
#### Session
diff --git a/docs/internals/overview.md b/docs/internals/overview.md
index d88ccdfb0..d7ae80f4e 100644
--- a/docs/internals/overview.md
+++ b/docs/internals/overview.md
@@ -106,8 +106,8 @@ build production behavior on receipts.
## Provider drivers
-Five drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
-Codex, Claude, Grok, Kimi For Coding, and OpenCode. A driver declares its kind and config schema and creates a
+Six drivers ship built in, registered in [`builtInDrivers.ts`][drivers] as `BUILT_IN_DRIVERS`:
+Codex, Claude, Grok, Kimi For Coding, OpenCode, and OpenCode Go. A driver declares its kind and config schema and creates a
scoped adapter; `ProviderInstanceRegistry` owns live instances and `ProviderAdapterRegistry` resolves
an instance to its adapter, so `ProviderService` routes session and turn operations without knowing
which agent is behind them. See [providers.md](./providers.md).
diff --git a/docs/internals/providers.md b/docs/internals/providers.md
index 71e7e51fc..c8d518848 100644
--- a/docs/internals/providers.md
+++ b/docs/internals/providers.md
@@ -7,15 +7,16 @@ orchestration layer does not know which one is behind a thread.
## Built-in drivers
-[`builtInDrivers.ts`][drivers] exports `BUILT_IN_DRIVERS` with five entries:
+[`builtInDrivers.ts`][drivers] exports `BUILT_IN_DRIVERS` with six entries:
-| Driver kind | Driver source |
-| ------------- | --------------------------------------- |
-| `codex` | [`Drivers/CodexDriver.ts`][codex] |
-| `claudeAgent` | [`Drivers/ClaudeDriver.ts`][claude] |
-| `grok` | [`Drivers/GrokDriver.ts`][grok] |
-| `kimi` | [`Drivers/KimiDriver.ts`][kimi] |
-| `opencode` | [`Drivers/OpenCodeDriver.ts`][opencode] |
+| Driver kind | Driver source |
+| ------------- | -------------------------------------------- |
+| `codex` | [`Drivers/CodexDriver.ts`][codex] |
+| `claudeAgent` | [`Drivers/ClaudeDriver.ts`][claude] |
+| `grok` | [`Drivers/GrokDriver.ts`][grok] |
+| `kimi` | [`Drivers/KimiDriver.ts`][kimi] |
+| `opencode` | [`Drivers/OpenCodeDriver.ts`][opencode] |
+| `opencodeGo` | [`Drivers/OpenCodeGoDriver.ts`][opencode-go] |
Each driver declares its `driverKind`, a `configSchema`, and a `create` function that builds an
adapter in a child scope. Adapter implementations live beside them in
@@ -119,6 +120,7 @@ when a request opens (approval) or user input is requested, via
[grok]: ../../apps/server/src/provider/Drivers/GrokDriver.ts
[kimi]: ../../apps/server/src/provider/Drivers/KimiDriver.ts
[opencode]: ../../apps/server/src/provider/Drivers/OpenCodeDriver.ts
+[opencode-go]: ../../apps/server/src/provider/Drivers/OpenCodeGoDriver.ts
[adapter]: ../../apps/server/src/provider/Services/ProviderAdapter.ts
[instances]: ../../apps/server/src/provider/Services/ProviderInstanceRegistry.ts
[registry]: ../../apps/server/src/provider/Services/ProviderAdapterRegistry.ts
diff --git a/docs/user/install.md b/docs/user/install.md
index 2751bfa2e..76059e092 100644
--- a/docs/user/install.md
+++ b/docs/user/install.md
@@ -44,24 +44,26 @@ Open **Settings > Providers** on any connected client. The **Subscriptions** sec
| Claude | Pro or Max |
| Grok | Shared xAI login |
| Kimi For Coding | Kimi For Coding plan |
+| OpenCode Go | OpenCode Go API key |
Select **Connect** and finish the provider's sign-in flow. ChatGPT, Grok, and Kimi use a device code.
-Claude asks you to paste the returned authorization code into Akeru.
+Claude asks you to paste the returned authorization code into Akeru. OpenCode Go asks you to paste an API key.
-The environment server owns the connection, so you sign in once per environment. It stores access
-and refresh tokens outside the workspace. Web, desktop, and mobile clients only receive connection
+The environment server owns the connection, so you connect once per environment. It stores provider
+credentials outside the workspace. Web, desktop, and mobile clients only receive connection
status and sign-in progress.
-After sign-in, select **Check OAuth** to test the stored login. Use **Reconnect** after a revoked or
-expired login. Akeru cannot verify whether an xAI login includes SuperGrok or X Premium+.
+After sign-in, select **Check OAuth** to test an OAuth login or **Check key** to test OpenCode Go.
+Use **Reconnect** after a revoked or expired login. Akeru cannot verify whether an xAI login includes
+SuperGrok or X Premium+.
## What Akeru runs
Codex and Kimi use Akeru's custom Mastra-based runtime. Akeru supplies the workspace, memory,
plugins, approval rules, and subscription access for each thread.
-Claude, Grok, and OpenCode use their provider adapters. These adapters keep provider-specific
-session and permission behavior behind the same Akeru thread interface.
+Claude, Grok, and OpenCode use their provider adapters. OpenCode Go uses Akeru's Mastra-based runtime.
+Both paths keep provider-specific session and permission behavior behind the same Akeru thread interface.
## Next steps
diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts
index 22d1aab71..90b8cc0db 100644
--- a/packages/contracts/src/model.ts
+++ b/packages/contracts/src/model.ts
@@ -133,6 +133,7 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const KIMI_DRIVER_KIND = ProviderDriverKind.make("kimi");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
+const OPENCODE_GO_DRIVER_KIND = ProviderDriverKind.make("opencodeGo");
export const DEFAULT_MODEL = "gpt-5.6-sol";
@@ -155,6 +156,7 @@ export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, strin
[GROK_DRIVER_KIND]: "grok-build",
[KIMI_DRIVER_KIND]: "k3",
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
+ [OPENCODE_GO_DRIVER_KIND]: "gpt-5.6-luna",
};
/** Per-provider text generation model defaults. */
@@ -214,6 +216,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
"opus-4.5": "claude-opus-4-5",
},
[OPENCODE_DRIVER_KIND]: {},
+ [OPENCODE_GO_DRIVER_KIND]: {},
};
// ── Provider display names ────────────────────────────────────────────
@@ -225,4 +228,5 @@ export const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>>
[GROK_DRIVER_KIND]: "Grok",
[KIMI_DRIVER_KIND]: "Kimi For Coding",
[OPENCODE_DRIVER_KIND]: "OpenCode",
+ [OPENCODE_GO_DRIVER_KIND]: "OpenCode Go",
};
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index df03c44c2..5d2a18d56 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -392,12 +392,14 @@ describe("provider enabled defaults", () => {
expect(decoded.providers.cursor.enabled).toBe(false);
expect(decoded.providers.grok.enabled).toBe(false);
expect(decoded.providers.opencode.enabled).toBe(false);
+ expect(decoded.providers.opencodeGo.enabled).toBe(true);
});
it("derives per-driver defaults from the settings schemas", () => {
expect(defaultEnabledForDriver(ProviderDriverKind.make("codex"))).toBe(true);
expect(defaultEnabledForDriver(ProviderDriverKind.make("cursor"))).toBe(false);
expect(defaultEnabledForDriver(ProviderDriverKind.make("grok"))).toBe(false);
+ expect(defaultEnabledForDriver(ProviderDriverKind.make("opencodeGo"))).toBe(true);
// Unknown fork drivers stay enabled; their own build decides otherwise.
expect(defaultEnabledForDriver(ProviderDriverKind.make("ollama"))).toBe(true);
});
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 3a3212ea1..55ac05588 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -549,6 +549,18 @@ export const KimiSettings = makeProviderSettingsSchema({
});
export type KimiSettings = typeof KimiSettings.Type;
+export const OpenCodeGoSettings = makeProviderSettingsSchema({
+ enabled: Schema.Boolean.pipe(
+ Schema.withDecodingDefault(Effect.succeed(true)),
+ Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
+ ),
+ customModels: Schema.Array(Schema.String).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
+ ),
+});
+export type OpenCodeGoSettings = typeof OpenCodeGoSettings.Type;
+
export const OpenCodeSettings = makeProviderSettingsSchema(
{
// Off by default (like Cursor and Grok): the binding is not yet stable
@@ -816,6 +828,7 @@ export const ServerSettings = Schema.Struct({
grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
kimi: KimiSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
+ opencodeGo: OpenCodeGoSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
}).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
// New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
// are `ProviderInstanceConfig` envelopes. The driver-specific config blob
@@ -973,6 +986,11 @@ const KimiSettingsPatch = Schema.Struct({
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
+const OpenCodeGoSettingsPatch = Schema.Struct({
+ enabled: Schema.optionalKey(Schema.Boolean),
+ customModels: Schema.optionalKey(Schema.Array(Schema.String)),
+});
+
const OpenCodeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(TrimmedString),
@@ -1060,6 +1078,7 @@ const ServerSettingsPatchFields = {
grok: Schema.optionalKey(GrokSettingsPatch),
kimi: Schema.optionalKey(KimiSettingsPatch),
opencode: Schema.optionalKey(OpenCodeSettingsPatch),
+ opencodeGo: Schema.optionalKey(OpenCodeGoSettingsPatch),
}),
),
// Whole-map replacement for the new instance config. Patching individual
diff --git a/packages/contracts/src/subscriptionAuth.ts b/packages/contracts/src/subscriptionAuth.ts
index f19787e09..5a7575107 100644
--- a/packages/contracts/src/subscriptionAuth.ts
+++ b/packages/contracts/src/subscriptionAuth.ts
@@ -16,6 +16,7 @@ export const SubscriptionProviderId = Schema.Literals([
"cursor",
"xai",
"kimi-for-coding",
+ "opencode-go",
]);
export type SubscriptionProviderId = typeof SubscriptionProviderId.Type;
@@ -154,7 +155,7 @@ export type SubscriptionAuthStartInput = typeof SubscriptionAuthStartInput.Type;
/**
* A started login. `completion` says how it finishes: "poll" flows settle by
- * repeated `poll` calls; "paste" flows need the user to paste a code into
+ * repeated `poll` calls; "paste" flows need the user to paste a code or key into
* `complete`.
*/
export const SubscriptionAuthStartResult = Schema.Struct({
@@ -174,7 +175,7 @@ export type SubscriptionAuthPollInput = typeof SubscriptionAuthPollInput.Type;
export const SubscriptionAuthCompleteInput = Schema.Struct({
loginId: Schema.String,
- /** Pasted authorization input: full URL, `code#state`, or bare code. */
+ /** Pasted authorization input or API key. */
code: Schema.String,
});
export type SubscriptionAuthCompleteInput = typeof SubscriptionAuthCompleteInput.Type;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e2cc34241..b28f474d1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -450,6 +450,12 @@ importers:
'@ai-sdk/anthropic':
specifier: 3.0.113
version: 3.0.113([email protected])
+ '@ai-sdk/openai':
+ specifier: 3.0.101
+ version: 3.0.101([email protected])
+ '@ai-sdk/openai-compatible':
+ specifier: 2.0.72
+ version: 2.0.72([email protected])
'@anthropic-ai/claude-agent-sdk':
specifier: ^0.3.170
version: 0.3.170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])