Refactor OpenCode lifecycle and structured output handling (#2218)
Co-authored-by: Claude Opus 4.7 <[email protected]>
This commit is contained in:
1 parent
3b98fe3548
commit
306ec4bb84
14 files changed
+1732
-1463
No files matched your search
@@ -1,18 +1,22 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, expect, vi } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { beforeEach, expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
startCalls: [] as string[],
|
||||
promptUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
@@ -20,69 +24,77 @@ const runtimeMock = vi.hoisted(() => {
|
||||
promptResult: undefined as
|
||||
| { data?: { info?: { error?: unknown }; parts?: Array<{ type: string; text?: string }> } }
|
||||
| undefined,
|
||||
};
|
||||
},
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
this.state.promptUrls.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.promptUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../provider/opencodeRuntime.ts", async () => {
|
||||
const actual = await vi.importActual<typeof import("../../provider/opencodeRuntime.ts")>(
|
||||
"../../provider/opencodeRuntime.ts",
|
||||
);
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
// The production runtime binds server lifetime to the caller's scope.
|
||||
// Mirror that here so the closeCalls probe observes scope close.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url,
|
||||
process: {} as ChildProcess,
|
||||
close: () => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
},
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => ({ data: { id: `${baseUrl}/session` } })),
|
||||
prompt: vi.fn(async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
subject: "Improve OpenCode reuse",
|
||||
body: "Reuse one server for the full action.",
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => ({ data: { id: `${baseUrl}/session` } }),
|
||||
prompt: async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
parts: [
|
||||
{
|
||||
type: "text",
|
||||
text: JSON.stringify({
|
||||
subject: "Improve OpenCode reuse",
|
||||
body: "Reuse one server for the full action.",
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
},
|
||||
},
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "opencode" as const,
|
||||
@@ -92,6 +104,7 @@ const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
@@ -106,10 +119,12 @@ const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
prefix: "t3code-opencode-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
@@ -126,6 +141,7 @@ const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive
|
||||
prefix: "t3code-opencode-text-generation-existing-server-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
@@ -25,15 +25,15 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
createOpenCodeSdkClient,
|
||||
OpenCodeRuntime,
|
||||
type OpenCodeServerConnection,
|
||||
type OpenCodeServerProcess,
|
||||
openCodeRuntimeErrorDetail,
|
||||
parseOpenCodeModelSlug,
|
||||
startOpenCodeServerProcess,
|
||||
toOpenCodeFileParts,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
|
||||
function getOpenCodePromptErrorMessage(error: unknown): string | null {
|
||||
if (!error || typeof error !== "object") {
|
||||
@@ -80,6 +80,13 @@ function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): str
|
||||
|
||||
interface SharedOpenCodeTextGenerationServerState {
|
||||
server: OpenCodeServerProcess | null;
|
||||
/**
|
||||
* The scope that owns the shared server's lifetime. Closing this scope
|
||||
* terminates the OpenCode child process and interrupts any fibers the
|
||||
* runtime forked during startup. We don't hold a `close()` function on
|
||||
* the server handle anymore — the scope is the only lifecycle handle.
|
||||
*/
|
||||
serverScope: Scope.Closeable | null;
|
||||
binaryPath: string | null;
|
||||
activeRequests: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
@@ -88,24 +95,28 @@ interface SharedOpenCodeTextGenerationServerState {
|
||||
const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const sharedServerMutex = yield* Semaphore.make(1);
|
||||
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
|
||||
server: null,
|
||||
serverScope: null,
|
||||
binaryPath: null,
|
||||
activeRequests: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const closeSharedServer = (server: OpenCodeServerProcess) => {
|
||||
if (sharedServerState.server === server) {
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
|
||||
const scope = sharedServerState.serverScope;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.serverScope = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
if (scope !== null) {
|
||||
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
server.close();
|
||||
};
|
||||
});
|
||||
|
||||
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
|
||||
const idleCloseFiber = sharedServerState.idleCloseFiber;
|
||||
@@ -119,15 +130,15 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
server: OpenCodeServerProcess,
|
||||
) {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const fiber = yield* Effect.sleep(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS)).pipe(
|
||||
const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.sync(() => {
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
closeSharedServer(server);
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -154,7 +165,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
sharedServerState.binaryPath !== input.binaryPath &&
|
||||
sharedServerState.activeRequests === 0
|
||||
) {
|
||||
closeSharedServer(existingServer);
|
||||
yield* closeSharedServer();
|
||||
} else {
|
||||
if (sharedServerState.binaryPath !== input.binaryPath) {
|
||||
yield* Effect.logWarning(
|
||||
@@ -170,20 +181,53 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
const server = yield* Effect.tryPromise({
|
||||
try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }),
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
// Create a fresh scope that owns this shared server. The runtime
|
||||
// will attach its child-process and fiber finalizers to this scope;
|
||||
// closing it kills the server and interrupts those fibers.
|
||||
//
|
||||
// The `Scope.make` / spawn / record-or-close transitions run inside
|
||||
// `uninterruptibleMask` so an interrupt arriving between any two
|
||||
// steps can't orphan the scope (and the child process attached to
|
||||
// it) before we either close it on failure or hand ownership to
|
||||
// `sharedServerState`. `restore` keeps the actual spawn
|
||||
// interruptible; an interrupt during the spawn is captured by
|
||||
// `Effect.exit` and drives us through the failure branch that
|
||||
// closes the fresh scope.
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const serverScope = yield* Scope.make();
|
||||
const startedExit = yield* Effect.exit(
|
||||
restore(
|
||||
openCodeRuntime
|
||||
.startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, serverScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (startedExit._tag === "Failure") {
|
||||
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
|
||||
return yield* Effect.failCause(startedExit.cause);
|
||||
}
|
||||
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
const server = startedExit.value;
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.serverScope = serverScope;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -200,17 +244,15 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
// Module-level finalizer: on layer shutdown, cancel the idle close fiber
|
||||
// and close the shared server scope. Consumers therefore cannot leak
|
||||
// the shared OpenCode server by forgetting to call anything.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const server = sharedServerState.server;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
sharedServerState.activeRequests = 0;
|
||||
if (server !== null) {
|
||||
server.close();
|
||||
}
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -264,7 +306,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(settings.serverUrl.length > 0 && settings.serverPassword
|
||||
@@ -304,8 +346,7 @@ const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail:
|
||||
cause instanceof Error ? cause.message : "OpenCode text generation request failed.",
|
||||
detail: openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -3,13 +3,18 @@ import assert from "node:assert/strict";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach } from "vitest";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapterLive,
|
||||
@@ -18,16 +23,16 @@ import {
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
};
|
||||
|
||||
const state = {
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
startCalls: [] as string[],
|
||||
sessionCreateUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
@@ -38,105 +43,118 @@ const runtimeMock = vi.hoisted(() => {
|
||||
closeError: null as Error | null,
|
||||
messages: [] as MessageEntry[],
|
||||
subscribedEvents: [] as unknown[],
|
||||
};
|
||||
},
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
this.state.sessionCreateUrls.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.abortCalls.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.revertCalls.length = 0;
|
||||
this.state.promptAsyncError = null;
|
||||
this.state.closeError = null;
|
||||
this.state.messages = [];
|
||||
this.state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.sessionCreateUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.abortCalls.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.revertCalls.length = 0;
|
||||
state.promptAsyncError = null;
|
||||
state.closeError = null;
|
||||
state.messages = [];
|
||||
state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
const url = "http://127.0.0.1:4301";
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url: "http://127.0.0.1:4301",
|
||||
process: {
|
||||
once() {},
|
||||
},
|
||||
close() {},
|
||||
url,
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {
|
||||
runtimeMock.state.closeCalls.push(serverUrl ?? "http://127.0.0.1:4301");
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
}),
|
||||
abort: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
}),
|
||||
promptAsync: vi.fn(async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
}),
|
||||
messages: vi.fn(async () => ({ data: runtimeMock.state.messages })),
|
||||
revert: vi.fn(
|
||||
async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.gen(function* () {
|
||||
const url = serverUrl ?? "http://127.0.0.1:4301";
|
||||
// Unconditionally register a scope finalizer for test observability —
|
||||
// preserves the `closeCalls` / `closeError` probes that the existing
|
||||
// suites rely on. Production code never attaches a finalizer to an
|
||||
// external server (it simply returns `Effect.succeed(...)`).
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return {
|
||||
url,
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
};
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
},
|
||||
abort: async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
},
|
||||
promptAsync: async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
},
|
||||
messages: async () => ({ data: runtimeMock.state.messages }),
|
||||
revert: async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
),
|
||||
},
|
||||
event: {
|
||||
subscribe: vi.fn(async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
}
|
||||
})(),
|
||||
})),
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
},
|
||||
event: {
|
||||
subscribe: async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
}
|
||||
})(),
|
||||
}),
|
||||
},
|
||||
}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: "OpenCodeRuntimeTestDouble.loadOpenCodeInventory not used in this test",
|
||||
cause: null,
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
@@ -148,6 +166,7 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
});
|
||||
|
||||
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -211,7 +230,7 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears session state when stopAll cleanup fails", () =>
|
||||
it.effect("clears session state even when cleanup finalizers throw", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
@@ -226,11 +245,14 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
});
|
||||
|
||||
runtimeMock.state.closeError = new Error("close failed");
|
||||
const error = yield* adapter.stopAll().pipe(Effect.flip);
|
||||
// `stopAll` relies on `stopOpenCodeContext`, which is typed as
|
||||
// never-failing. A throwing finalizer surfaces as a defect — `Effect.exit`
|
||||
// captures it so the assertions can still run. The key invariant we're
|
||||
// validating is "the sessions map and close-call probes reflect cleanup
|
||||
// attempts regardless of finalizer outcome".
|
||||
yield* Effect.exit(adapter.stopAll());
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterProcessError");
|
||||
assert.equal(error.detail, "Failed to stop 2 OpenCode sessions.");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, [
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
@@ -374,7 +396,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
const adapterLayer = makeOpenCodeAdapterLive({
|
||||
nativeEventLogger,
|
||||
}).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -450,7 +475,10 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
const adapterLayer = makeOpenCodeAdapterLive({
|
||||
nativeEventLogger,
|
||||
}).pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
@@ -467,7 +495,13 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const sessions = yield* Effect.gen(function* () {
|
||||
// Capture closeCalls *inside* the provided layer scope: the adapter's
|
||||
// layer finalizer now tears down any live sessions when the layer
|
||||
// closes (which is exactly what we want for leak prevention), so
|
||||
// inspecting closeCalls after `Effect.provide` completes would observe
|
||||
// the teardown — not the behavior under test. We care that the event
|
||||
// pump kept the session alive while logging was failing.
|
||||
const { sessions, closeCallsDuringRun } = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
@@ -475,12 +509,15 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return yield* adapter.listSessions();
|
||||
return {
|
||||
sessions: yield* adapter.listSessions(),
|
||||
closeCallsDuringRun: [...runtimeMock.state.closeCalls],
|
||||
};
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, []);
|
||||
assert.deepEqual(closeCallsDuringRun, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,66 +3,81 @@ import assert from "node:assert/strict";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
import { beforeEach } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { makeOpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
const runtimeMock = {
|
||||
state: {
|
||||
runVersionError: null as Error | null,
|
||||
inventoryError: null as Error | null,
|
||||
};
|
||||
inventory: {
|
||||
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
} as unknown,
|
||||
},
|
||||
reset() {
|
||||
this.state.runVersionError = null;
|
||||
this.state.inventoryError = null;
|
||||
this.state.inventory = {
|
||||
providerList: { connected: [], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.runVersionError = null;
|
||||
state.inventoryError = null;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
runOpenCodeCommand: vi.fn(async () => {
|
||||
if (runtimeMock.state.runVersionError) {
|
||||
throw runtimeMock.state.runVersionError;
|
||||
}
|
||||
return { stdout: "opencode 1.0.0\n", stderr: "", code: 0 };
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.succeed({
|
||||
url: "http://127.0.0.1:4301",
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(() => ({})),
|
||||
loadOpenCodeInventory: vi.fn(async () => {
|
||||
if (runtimeMock.state.inventoryError) {
|
||||
throw runtimeMock.state.inventoryError;
|
||||
}
|
||||
return {
|
||||
providerList: { connected: [], all: [] },
|
||||
agents: [],
|
||||
};
|
||||
}),
|
||||
flattenOpenCodeModels: vi.fn(() => []),
|
||||
};
|
||||
});
|
||||
runOpenCodeCommand: () =>
|
||||
runtimeMock.state.runVersionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: runtimeMock.state.runVersionError.message,
|
||||
cause: runtimeMock.state.runVersionError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({ stdout: "opencode 1.0.0\n", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: () =>
|
||||
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
loadOpenCodeInventory: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "loadOpenCodeInventory",
|
||||
detail: runtimeMock.state.inventoryError.message,
|
||||
cause: runtimeMock.state.inventoryError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
|
||||
makeOpenCodeProviderLive().pipe(
|
||||
OpenCodeProviderLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(OpenCodeRuntime, OpenCodeRuntimeTestDouble)),
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
@@ -92,6 +107,54 @@ it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
|
||||
assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits OpenCode variant defaults so trait picker can resolve a visible selection", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventory = {
|
||||
providerList: {
|
||||
connected: ["openai"],
|
||||
all: [
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
models: {
|
||||
"gpt-5.4": {
|
||||
id: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
variants: {
|
||||
none: {},
|
||||
low: {},
|
||||
medium: {},
|
||||
high: {},
|
||||
xhigh: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
default: {},
|
||||
},
|
||||
agents: [
|
||||
{ name: "build", hidden: false, mode: "primary" },
|
||||
{ name: "plan", hidden: false, mode: "primary" },
|
||||
],
|
||||
};
|
||||
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
|
||||
|
||||
assert.ok(model);
|
||||
assert.equal(
|
||||
model.capabilities?.variantOptions?.find((option) => option.isDefault)?.value,
|
||||
"medium",
|
||||
);
|
||||
assert.equal(
|
||||
model.capabilities?.agentOptions?.find((option) => option.isDefault)?.value,
|
||||
"build",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
|
||||
@@ -1,57 +1,58 @@
|
||||
import type { OpenCodeSettings, ServerProvider } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, Layer, Stream } from "effect";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
OpenCodeSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cause, Data, Effect, Equal, Layer, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
buildServerProvider,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import {
|
||||
connectToOpenCodeServer,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
createOpenCodeSdkClient,
|
||||
flattenOpenCodeModels,
|
||||
loadOpenCodeInventory,
|
||||
runOpenCodeCommand,
|
||||
OpenCodeRuntime,
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
|
||||
const PROVIDER = "opencode" as const;
|
||||
|
||||
class OpenCodeProbePromiseError extends Error {
|
||||
override readonly cause: unknown;
|
||||
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
|
||||
readonly cause: unknown;
|
||||
readonly detail: string;
|
||||
}> {}
|
||||
|
||||
constructor(cause: unknown) {
|
||||
super(cause instanceof Error ? cause.message : String(cause));
|
||||
this.cause = cause;
|
||||
this.name = "OpenCodeProbePromiseError";
|
||||
function normalizeProbeMessage(message: string): string | undefined {
|
||||
const trimmed = message.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function toOpenCodeProbeError(cause: unknown): OpenCodeProbePromiseError {
|
||||
return new OpenCodeProbePromiseError(cause);
|
||||
if (
|
||||
trimmed === "An error occurred in Effect.tryPromise" ||
|
||||
trimmed === "An error occurred in Effect.try"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
if (cause instanceof OpenCodeProbeError) {
|
||||
return normalizeProbeMessage(cause.detail);
|
||||
}
|
||||
|
||||
if (!(cause instanceof Error)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const message = cause.message.trim();
|
||||
if (message.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
message === "An error occurred in Effect.tryPromise" ||
|
||||
message === "An error occurred in Effect.try"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return message;
|
||||
return normalizeProbeMessage(cause.message);
|
||||
}
|
||||
|
||||
function formatOpenCodeProbeError(input: {
|
||||
@@ -59,8 +60,8 @@ function formatOpenCodeProbeError(input: {
|
||||
readonly isExternalServer: boolean;
|
||||
readonly serverUrl: string;
|
||||
}): { readonly installed: boolean; readonly message: string } {
|
||||
const lower = input.cause instanceof Error ? input.cause.message.toLowerCase() : "";
|
||||
const detail = normalizedErrorMessage(input.cause);
|
||||
const lower = detail?.toLowerCase() ?? "";
|
||||
|
||||
if (input.isExternalServer) {
|
||||
if (
|
||||
@@ -96,7 +97,7 @@ function formatOpenCodeProbeError(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (input.cause instanceof Error && isCommandMissingCause(input.cause)) {
|
||||
if (lower.includes("enoent") || lower.includes("notfound")) {
|
||||
return {
|
||||
installed: false,
|
||||
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
|
||||
@@ -127,6 +128,99 @@ function formatOpenCodeProbeError(input: {
|
||||
};
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
providerID: string,
|
||||
variants: ReadonlyArray<string>,
|
||||
): string | undefined {
|
||||
if (variants.length === 1) {
|
||||
return variants[0];
|
||||
}
|
||||
if (providerID === "anthropic" || providerID.startsWith("google")) {
|
||||
return variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {
|
||||
return agents.find((agent) => agent.name === "build")?.name ?? agents[0]?.name ?? undefined;
|
||||
}
|
||||
|
||||
const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
function openCodeCapabilitiesForModel(input: {
|
||||
readonly providerID: string;
|
||||
readonly model: ProviderListResponse["all"][number]["models"][string];
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}): ModelCapabilities {
|
||||
const variantValues = Object.keys(input.model.variants ?? {});
|
||||
const defaultVariant = inferDefaultVariant(input.providerID, variantValues);
|
||||
const variantOptions: ModelCapabilities["variantOptions"] = variantValues.map((value) =>
|
||||
Object.assign(
|
||||
{ value, label: titleCaseSlug(value) },
|
||||
defaultVariant === value ? { isDefault: true } : {},
|
||||
),
|
||||
);
|
||||
const primaryAgents = input.agents.filter(
|
||||
(agent) => !agent.hidden && (agent.mode === "primary" || agent.mode === "all"),
|
||||
);
|
||||
const defaultAgent = inferDefaultAgent(primaryAgents);
|
||||
const agentOptions: ModelCapabilities["agentOptions"] = primaryAgents.map((agent) =>
|
||||
Object.assign(
|
||||
{ value: agent.name, label: titleCaseSlug(agent.name) },
|
||||
defaultAgent === agent.name ? { isDefault: true } : {},
|
||||
),
|
||||
);
|
||||
return {
|
||||
...DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
...(variantOptions.length > 0 ? { variantOptions } : {}),
|
||||
...(agentOptions.length > 0 ? { agentOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
for (const provider of input.providerList.all) {
|
||||
if (!connected.has(provider.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const model of Object.values(provider.models)) {
|
||||
models.push({
|
||||
slug: `${provider.id}/${model.id}`,
|
||||
name: model.name,
|
||||
subProvider: provider.name,
|
||||
isCustom: false,
|
||||
capabilities: openCodeCapabilitiesForModel({
|
||||
providerID: provider.id,
|
||||
model,
|
||||
agents: input.agents,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return models.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
|
||||
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
@@ -170,173 +264,177 @@ const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): Server
|
||||
});
|
||||
};
|
||||
|
||||
export function checkOpenCodeProviderStatus(input: {
|
||||
readonly settings: OpenCodeSettings;
|
||||
readonly cwd: string;
|
||||
}): Effect.Effect<ServerProvider> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const customModels = input.settings.customModels;
|
||||
const isExternalServer = input.settings.serverUrl.trim().length > 0;
|
||||
export const OpenCodeProviderLive = Layer.effect(
|
||||
OpenCodeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatus")(function* (input: {
|
||||
readonly settings: OpenCodeSettings;
|
||||
readonly cwd: string;
|
||||
}): Effect.fn.Return<ServerProvider, never> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const customModels = input.settings.customModels;
|
||||
const isExternalServer = input.settings.serverUrl.trim().length > 0;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: failure.installed,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
if (!input.settings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: isExternalServer
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let version: string | null = null;
|
||||
if (!isExternalServer) {
|
||||
const versionExit = yield* Effect.exit(
|
||||
openCodeRuntime
|
||||
.runOpenCodeCommand({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
args: ["--version"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
}
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
return yield* openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(isExternalServer && input.settings.serverPassword
|
||||
? { serverPassword: input.settings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
}
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: failure.installed,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
if (!input.settings.enabled) {
|
||||
);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: isExternalServer
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
installed: true,
|
||||
version,
|
||||
status: connectedCount > 0 ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connectedCount > 0 ? "authenticated" : "unknown",
|
||||
type: "opencode",
|
||||
},
|
||||
message:
|
||||
connectedCount > 0
|
||||
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
|
||||
: isExternalServer
|
||||
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
|
||||
: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let version: string | null = null;
|
||||
if (!isExternalServer) {
|
||||
const versionExit = yield* Effect.exit(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runOpenCodeCommand({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
args: ["--version"],
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
}
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.acquireUseRelease(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
connectToOpenCodeServer({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
(server) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(isExternalServer && input.settings.serverPassword
|
||||
? { serverPassword: input.settings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
return await loadOpenCodeInventory(client);
|
||||
},
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
(server) => Effect.sync(() => server.close()),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
}
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: connectedCount > 0 ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connectedCount > 0 ? "authenticated" : "unknown",
|
||||
type: "opencode",
|
||||
},
|
||||
message:
|
||||
connectedCount > 0
|
||||
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
|
||||
: isExternalServer
|
||||
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
|
||||
: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function makeOpenCodeProviderLive() {
|
||||
return Layer.effect(
|
||||
OpenCodeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const getProviderSettings = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.opencode),
|
||||
);
|
||||
|
||||
const getProviderSettings = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.opencode),
|
||||
);
|
||||
|
||||
return yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
getSettings: getProviderSettings.pipe(Effect.orDie),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.opencode),
|
||||
return yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
getSettings: getProviderSettings.pipe(Effect.orDie),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.opencode),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingOpenCodeProvider,
|
||||
checkProvider: getProviderSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
checkOpenCodeProviderStatus({
|
||||
settings,
|
||||
cwd: serverConfig.cwd,
|
||||
}),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingOpenCodeProvider,
|
||||
checkProvider: getProviderSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
checkOpenCodeProviderStatus({
|
||||
settings,
|
||||
cwd: serverConfig.cwd,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const OpenCodeProviderLive = makeOpenCodeProviderLive();
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -16,6 +16,7 @@ import { CodexProvider } from "../Services/CodexProvider.ts";
|
||||
import { CursorProvider } from "../Services/CursorProvider.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import { OpenCodeRuntimeLive } from "../opencodeRuntime.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
PROVIDER_CACHE_IDS,
|
||||
@@ -287,6 +288,7 @@ export const ProviderRegistryLive = Layer.unwrap(
|
||||
Layer.provideMerge(CodexProviderLive),
|
||||
Layer.provideMerge(ClaudeProviderLive),
|
||||
Layer.provideMerge(OpenCodeProviderLive),
|
||||
Layer.provideMerge(OpenCodeRuntimeLive),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { DEFAULT_OPENCODE_MODEL_CAPABILITIES, flattenOpenCodeModels } from "./opencodeRuntime.ts";
|
||||
|
||||
describe("flattenOpenCodeModels", () => {
|
||||
it("keeps the canonical model name separate from the subprovider label", () => {
|
||||
const models = flattenOpenCodeModels({
|
||||
providerList: {
|
||||
connected: ["github-copilot"],
|
||||
all: [
|
||||
{
|
||||
id: "github-copilot",
|
||||
name: "GitHub Copilot",
|
||||
models: {
|
||||
"claude-opus-4.5": {
|
||||
id: "claude-opus-4.5",
|
||||
name: "Claude Opus 4.5",
|
||||
variants: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
agents: [],
|
||||
} as unknown as Parameters<typeof flattenOpenCodeModels>[0]);
|
||||
|
||||
expect(models).toEqual([
|
||||
{
|
||||
slug: "github-copilot/claude-opus-4.5",
|
||||
name: "Claude Opus 4.5",
|
||||
subProvider: "GitHub Copilot",
|
||||
isCustom: false,
|
||||
capabilities: DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,6 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
||||
import * as FS from "node:fs";
|
||||
import { createServer, type AddressInfo } from "node:net";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import type {
|
||||
ChatAttachment,
|
||||
ModelCapabilities,
|
||||
ProviderApprovalDecision,
|
||||
RuntimeMode,
|
||||
ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from "@t3tools/contracts";
|
||||
import {
|
||||
createOpencodeClient,
|
||||
type Agent,
|
||||
@@ -22,40 +11,80 @@ import {
|
||||
type QuestionAnswer,
|
||||
type QuestionRequest,
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
import {
|
||||
Cause,
|
||||
Context,
|
||||
Data,
|
||||
Deferred,
|
||||
Effect,
|
||||
Exit,
|
||||
Fiber,
|
||||
Layer,
|
||||
Option,
|
||||
Predicate as P,
|
||||
Ref,
|
||||
Result,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { collectStreamAsString } from "./providerSnapshot.ts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
|
||||
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
|
||||
const DEFAULT_HOSTNAME = "127.0.0.1";
|
||||
|
||||
const OPENAI_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"];
|
||||
const ANTHROPIC_VARIANTS = ["high", "max"];
|
||||
const GOOGLE_VARIANTS = ["low", "high"];
|
||||
|
||||
export const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
export interface OpenCodeServerProcess {
|
||||
readonly url: string;
|
||||
readonly process: ChildProcess;
|
||||
close(): void;
|
||||
readonly exitCode: Effect.Effect<number, never>;
|
||||
}
|
||||
|
||||
export interface OpenCodeServerConnection {
|
||||
readonly url: string;
|
||||
readonly process: ChildProcess | null;
|
||||
readonly exitCode: Effect.Effect<number, never> | null;
|
||||
readonly external: boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function buildOpenCodeBasicAuthorizationHeader(password: string): string {
|
||||
return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
|
||||
const OPENCODE_RUNTIME_ERROR_TAG = "OpenCodeRuntimeError";
|
||||
export class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{
|
||||
readonly operation: string;
|
||||
readonly cause?: unknown;
|
||||
readonly detail: string;
|
||||
}> {
|
||||
static readonly is = (u: unknown): u is OpenCodeRuntimeError =>
|
||||
P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);
|
||||
}
|
||||
|
||||
export function openCodeRuntimeErrorDetail(cause: unknown): string {
|
||||
if (OpenCodeRuntimeError.is(cause)) return cause.detail;
|
||||
if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();
|
||||
if (cause && typeof cause === "object") {
|
||||
// SDK v2 throws { response, request, error? } shapes — extract what's useful
|
||||
const anyCause = cause as Record<string, unknown>;
|
||||
const status = (anyCause.response as { status?: number } | undefined)?.status;
|
||||
const body = anyCause.error ?? anyCause.data ?? anyCause.body;
|
||||
try {
|
||||
return `status=${status ?? "?"} body=${JSON.stringify(body ?? cause)}`;
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
}
|
||||
return String(cause);
|
||||
}
|
||||
|
||||
export const runOpenCodeSdk = <A>(
|
||||
operation: string,
|
||||
fn: () => Promise<A>,
|
||||
): Effect.Effect<A, OpenCodeRuntimeError> =>
|
||||
Effect.tryPromise({
|
||||
try: fn,
|
||||
catch: (cause) =>
|
||||
new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
|
||||
}).pipe(Effect.withSpan(`opencode.${operation}`));
|
||||
|
||||
export interface OpenCodeCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
@@ -72,12 +101,43 @@ export interface ParsedOpenCodeModelSlug {
|
||||
readonly modelID: string;
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
export interface OpenCodeRuntimeShape {
|
||||
/**
|
||||
* Spawns a local OpenCode server process. Its lifetime is bound to the caller's
|
||||
* `Scope.Scope` — the child is killed automatically when that scope closes.
|
||||
* Consumers that want a long-lived server must create and hold a scope explicitly
|
||||
* (see {@link Scope.make}) and close it when done.
|
||||
*/
|
||||
readonly startOpenCodeServerProcess: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;
|
||||
/**
|
||||
* Returns a handle to either an externally-managed OpenCode server (when
|
||||
* `serverUrl` is provided — no lifetime is attached to the caller's scope) or a
|
||||
* freshly spawned local server whose lifetime is bound to the caller's scope.
|
||||
*/
|
||||
readonly connectToOpenCodeServer: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;
|
||||
readonly runOpenCodeCommand: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;
|
||||
readonly createOpenCodeSdkClient: (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
}) => OpencodeClient;
|
||||
readonly loadOpenCodeInventory: (
|
||||
client: OpencodeClient,
|
||||
) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;
|
||||
}
|
||||
|
||||
function parseServerUrlFromOutput(output: string): string | null {
|
||||
@@ -91,92 +151,6 @@ function parseServerUrlFromOutput(output: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPrimaryAgent(agent: Agent): boolean {
|
||||
return !agent.hidden && (agent.mode === "primary" || agent.mode === "all");
|
||||
}
|
||||
|
||||
function inferVariantValues(providerID: string): ReadonlyArray<string> {
|
||||
if (providerID === "anthropic") {
|
||||
return ANTHROPIC_VARIANTS;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return OPENAI_VARIANTS;
|
||||
}
|
||||
if (providerID.startsWith("google")) {
|
||||
return GOOGLE_VARIANTS;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
providerID: string,
|
||||
variants: ReadonlyArray<string>,
|
||||
): string | undefined {
|
||||
if (variants.length === 1) {
|
||||
return variants[0];
|
||||
}
|
||||
if (providerID === "anthropic" || providerID.startsWith("google")) {
|
||||
return variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildVariantOptions(
|
||||
providerID: string,
|
||||
model: ProviderListResponse["all"][number]["models"][string],
|
||||
) {
|
||||
const variantValues = Object.keys(model.variants ?? {});
|
||||
const resolvedValues =
|
||||
variantValues.length > 0 ? variantValues : [...inferVariantValues(providerID)];
|
||||
const defaultVariant = inferDefaultVariant(providerID, resolvedValues);
|
||||
|
||||
return resolvedValues.map((value) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value,
|
||||
label: titleCaseSlug(value),
|
||||
};
|
||||
if (defaultVariant === value) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function buildAgentOptions(agents: ReadonlyArray<Agent>) {
|
||||
const primaryAgents = agents.filter(isPrimaryAgent);
|
||||
const defaultAgent =
|
||||
primaryAgents.find((agent) => agent.name === "build")?.name ??
|
||||
primaryAgents[0]?.name ??
|
||||
undefined;
|
||||
return primaryAgents.map((agent) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value: agent.name,
|
||||
label: titleCaseSlug(agent.name),
|
||||
};
|
||||
if (defaultAgent === agent.name) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function openCodeCapabilitiesForModel(input: {
|
||||
readonly providerID: string;
|
||||
readonly model: ProviderListResponse["all"][number]["models"][string];
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}): ModelCapabilities {
|
||||
const variantOptions = buildVariantOptions(input.providerID, input.model);
|
||||
const agentOptions = buildAgentOptions(input.agents);
|
||||
return {
|
||||
...DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
...(variantOptions.length > 0 ? { variantOptions } : {}),
|
||||
...(agentOptions.length > 0 ? { agentOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseOpenCodeModelSlug(
|
||||
slug: string | null | undefined,
|
||||
): ParsedOpenCodeModelSlug | null {
|
||||
@@ -196,10 +170,6 @@ export function parseOpenCodeModelSlug(
|
||||
};
|
||||
}
|
||||
|
||||
export function toOpenCodeModelSlug(providerID: string, modelID: string): string {
|
||||
return `${providerID}/${modelID}`;
|
||||
}
|
||||
|
||||
export function openCodeQuestionId(
|
||||
index: number,
|
||||
question: QuestionRequest["questions"][number],
|
||||
@@ -286,289 +256,268 @@ export function toOpenCodeQuestionAnswers(
|
||||
});
|
||||
}
|
||||
|
||||
export async function findAvailablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, DEFAULT_HOSTNAME, () => resolve());
|
||||
});
|
||||
const address = server.address() as AddressInfo;
|
||||
const port = address.port;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
return port;
|
||||
function ensureRuntimeError(
|
||||
operation: OpenCodeRuntimeError["operation"],
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): OpenCodeRuntimeError {
|
||||
return OpenCodeRuntimeError.is(cause)
|
||||
? cause
|
||||
: new OpenCodeRuntimeError({ operation, detail, cause });
|
||||
}
|
||||
|
||||
export function resolveOpenCodeBinaryPath(binaryPath: string): string {
|
||||
if (Path.isAbsolute(binaryPath)) {
|
||||
return binaryPath;
|
||||
}
|
||||
return execFileSync("which", [binaryPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
}).trim();
|
||||
}
|
||||
const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const netService = yield* NetService;
|
||||
|
||||
export function detectMacosSigkillHint(binaryPath: string): string | null {
|
||||
try {
|
||||
// Check for quarantine xattr first.
|
||||
const resolvedPath = resolveOpenCodeBinaryPath(binaryPath);
|
||||
const xattr = execFileSync("xattr", ["-l", resolvedPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
});
|
||||
if (xattr.includes("com.apple.quarantine")) {
|
||||
return (
|
||||
`macOS quarantine is blocking the OpenCode binary. ` +
|
||||
`Run: xattr -d com.apple.quarantine ${resolvedPath}`
|
||||
const runOpenCodeCommand: OpenCodeRuntimeShape["runOpenCodeCommand"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.binaryPath, [...input.args], {
|
||||
shell: process.platform === "win32",
|
||||
env: process.env,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const [stdout, stderr, code] = yield* Effect.all(
|
||||
[collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
const exitCode = Number(code);
|
||||
if (isWindowsCommandNotFound(exitCode, stderr)) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "runOpenCodeCommand",
|
||||
detail: `spawn ${input.binaryPath} ENOENT`,
|
||||
});
|
||||
}
|
||||
return {
|
||||
stdout,
|
||||
stderr,
|
||||
code: exitCode,
|
||||
} satisfies OpenCodeCommandResult;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.mapError((cause) =>
|
||||
ensureRuntimeError(
|
||||
"runOpenCodeCommand",
|
||||
`Failed to execute '${input.binaryPath} ${input.args.join(" ")}': ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Look for a recent crash report with the termination reason.
|
||||
const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports");
|
||||
const binaryName = Path.basename(resolvedPath);
|
||||
const recentReports = FS.readdirSync(crashDir)
|
||||
.filter((f) => f.startsWith(binaryName) && f.endsWith(".ips"))
|
||||
.toSorted()
|
||||
.toReversed()
|
||||
.slice(0, 1);
|
||||
const startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
// Bind this server's lifetime to the caller's scope. When the caller's
|
||||
// scope closes, the spawned child is killed and all associated fibers
|
||||
// are interrupted automatically — no `close()` method needed.
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
|
||||
for (const report of recentReports) {
|
||||
const content = FS.readFileSync(Path.join(crashDir, report), "utf8");
|
||||
if (content.includes('"namespace":"CODESIGNING"')) {
|
||||
return (
|
||||
"macOS killed the process due to an invalid code signature. " +
|
||||
"The binary may be corrupted — try reinstalling OpenCode."
|
||||
const hostname = input.hostname ?? DEFAULT_HOSTNAME;
|
||||
const port =
|
||||
input.port ??
|
||||
(yield* netService.findAvailablePort(0).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
));
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(input.binaryPath, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
|
||||
},
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, runtimeScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const stdoutRef = yield* Ref.make("");
|
||||
const stderrRef = yield* Ref.make("");
|
||||
const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();
|
||||
|
||||
const setReadyFromStdoutChunk = (chunk: string) =>
|
||||
Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(
|
||||
Effect.flatMap((nextStdout) => {
|
||||
const parsed = parseServerUrlFromOutput(nextStdout);
|
||||
return parsed
|
||||
? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)
|
||||
: Effect.void;
|
||||
}),
|
||||
);
|
||||
|
||||
const stdoutFiber = yield* child.stdout.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runForEach(setReadyFromStdoutChunk),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
const stderrFiber = yield* child.stderr.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
|
||||
const exitFiber = yield* child.exitCode.pipe(
|
||||
Effect.flatMap((code) =>
|
||||
Effect.gen(function* () {
|
||||
const stdout = yield* Ref.get(stdoutRef);
|
||||
const stderr = yield* Ref.get(stderrRef);
|
||||
const exitCode = Number(code);
|
||||
yield* Deferred.fail(
|
||||
readyDeferred,
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: [
|
||||
`OpenCode server exited before startup completed (code: ${String(exitCode)}).`,
|
||||
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
|
||||
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
cause: { exitCode, stdout, stderr },
|
||||
}),
|
||||
).pipe(Effect.ignore);
|
||||
}),
|
||||
),
|
||||
Effect.ignore,
|
||||
Effect.forkIn(runtimeScope),
|
||||
);
|
||||
|
||||
const readyExit = yield* Effect.exit(
|
||||
Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),
|
||||
);
|
||||
|
||||
// Startup-time fibers are no longer needed once ready has resolved (either
|
||||
// way). The exit fiber is only interrupted on failure; on success it keeps
|
||||
// the caller's `exitCode` effect observable until the scope closes.
|
||||
yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);
|
||||
yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);
|
||||
|
||||
if (Exit.isFailure(readyExit)) {
|
||||
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
|
||||
const squashed = Cause.squash(readyExit.cause);
|
||||
return yield* ensureRuntimeError(
|
||||
"startOpenCodeServerProcess",
|
||||
`Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,
|
||||
squashed,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort detection — don't fail the original error path.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function startOpenCodeServerProcess(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerProcess> {
|
||||
const hostname = input.hostname ?? DEFAULT_HOSTNAME;
|
||||
const port = input.port ?? (await findAvailablePort());
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
const child = spawn(input.binaryPath, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
child.kill();
|
||||
};
|
||||
|
||||
const url = await new Promise<string>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
close();
|
||||
reject(new Error(`Timed out waiting for OpenCode server start after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("error", onError);
|
||||
child.off("close", onClose);
|
||||
};
|
||||
|
||||
const onStdout = (chunk: string) => {
|
||||
stdout += chunk;
|
||||
const parsed = parseServerUrlFromOutput(stdout);
|
||||
if (!parsed) {
|
||||
return;
|
||||
const readyOption = readyExit.value;
|
||||
if (Option.isNone(readyOption)) {
|
||||
yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,
|
||||
});
|
||||
}
|
||||
cleanup();
|
||||
resolve(parsed);
|
||||
};
|
||||
|
||||
const onStderr = (chunk: string) => {
|
||||
stderr += chunk;
|
||||
};
|
||||
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
cleanup();
|
||||
const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`;
|
||||
const hint =
|
||||
signal === "SIGKILL" && process.platform === "darwin"
|
||||
? detectMacosSigkillHint(input.binaryPath)
|
||||
: null;
|
||||
reject(
|
||||
new Error(
|
||||
[
|
||||
`OpenCode server exited before startup completed (${exitReason}).`,
|
||||
hint,
|
||||
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
|
||||
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
return {
|
||||
url: readyOption.value,
|
||||
exitCode: child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
),
|
||||
);
|
||||
};
|
||||
} satisfies OpenCodeServerProcess;
|
||||
});
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.once("error", onError);
|
||||
child.once("close", onClose);
|
||||
});
|
||||
|
||||
return {
|
||||
url,
|
||||
process: child,
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
export async function connectToOpenCodeServer(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerConnection> {
|
||||
const serverUrl = input.serverUrl?.trim();
|
||||
if (serverUrl) {
|
||||
return {
|
||||
url: serverUrl,
|
||||
process: null,
|
||||
external: true,
|
||||
close() {},
|
||||
};
|
||||
}
|
||||
|
||||
const server = await startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
url: server.url,
|
||||
process: server.process,
|
||||
external: false,
|
||||
close: () => server.close(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function runOpenCodeCommand(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}): Promise<OpenCodeCommandResult> {
|
||||
const child = spawn(input.binaryPath, [...input.args], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
|
||||
const stdoutChunks: Array<string> = [];
|
||||
const stderrChunks: Array<string> = [];
|
||||
|
||||
child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk));
|
||||
child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk));
|
||||
|
||||
const code = await new Promise<number>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", (exitCode) => resolve(exitCode ?? 0));
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: stdoutChunks.join(""),
|
||||
stderr: stderrChunks.join(""),
|
||||
code,
|
||||
};
|
||||
}
|
||||
|
||||
export function createOpenCodeSdkClient(input: {
|
||||
readonly baseUrl: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
}): OpencodeClient {
|
||||
return createOpencodeClient({
|
||||
baseUrl: input.baseUrl,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword
|
||||
? {
|
||||
headers: {
|
||||
Authorization: buildOpenCodeBasicAuthorizationHeader(input.serverPassword),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
throwOnError: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadOpenCodeInventory(client: OpencodeClient): Promise<OpenCodeInventory> {
|
||||
const [providerListResult, agentsResult] = await Promise.all([
|
||||
client.provider.list(),
|
||||
client.app.agents(),
|
||||
]);
|
||||
if (!providerListResult.data) {
|
||||
throw new Error("OpenCode provider inventory was empty.");
|
||||
}
|
||||
return {
|
||||
providerList: providerListResult.data,
|
||||
agents: agentsResult.data ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function flattenOpenCodeModels(
|
||||
input: OpenCodeInventory,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
for (const provider of input.providerList.all) {
|
||||
if (!connected.has(provider.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const model of Object.values(provider.models)) {
|
||||
models.push({
|
||||
slug: toOpenCodeModelSlug(provider.id, model.id),
|
||||
name: model.name,
|
||||
subProvider: provider.name,
|
||||
isCustom: false,
|
||||
capabilities: openCodeCapabilitiesForModel({
|
||||
providerID: provider.id,
|
||||
model,
|
||||
agents: input.agents,
|
||||
}),
|
||||
const connectToOpenCodeServer: OpenCodeRuntimeShape["connectToOpenCodeServer"] = (input) => {
|
||||
const serverUrl = input.serverUrl?.trim();
|
||||
if (serverUrl) {
|
||||
// We don't own externally-configured servers — no scope interaction.
|
||||
return Effect.succeed({
|
||||
url: serverUrl,
|
||||
exitCode: null,
|
||||
external: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return models.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
return startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
}).pipe(
|
||||
Effect.map((server) => ({
|
||||
url: server.url,
|
||||
exitCode: server.exitCode,
|
||||
external: false,
|
||||
})),
|
||||
);
|
||||
};
|
||||
|
||||
const createOpenCodeSdkClient: OpenCodeRuntimeShape["createOpenCodeSdkClient"] = (input) =>
|
||||
createOpencodeClient({
|
||||
baseUrl: input.baseUrl,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword
|
||||
? {
|
||||
headers: {
|
||||
Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, "utf8").toString("base64")}`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
throwOnError: true,
|
||||
});
|
||||
|
||||
const loadProviders = (client: OpencodeClient) =>
|
||||
runOpenCodeSdk("provider.list", () => client.provider.list()).pipe(
|
||||
Effect.filterMapOrFail(
|
||||
(list) =>
|
||||
list.data
|
||||
? Result.succeed(list.data)
|
||||
: Result.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "provider.list",
|
||||
detail: "OpenCode provider list was empty.",
|
||||
}),
|
||||
),
|
||||
(result) => result,
|
||||
),
|
||||
);
|
||||
|
||||
const loadAgents = (client: OpencodeClient) =>
|
||||
runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
|
||||
Effect.map((result) => result.data ?? []),
|
||||
);
|
||||
|
||||
const loadOpenCodeInventory: OpenCodeRuntimeShape["loadOpenCodeInventory"] = (client) =>
|
||||
Effect.all([loadProviders(client), loadAgents(client)], { concurrency: "unbounded" }).pipe(
|
||||
Effect.map(([providerList, agents]) => ({ providerList, agents })),
|
||||
);
|
||||
|
||||
return {
|
||||
startOpenCodeServerProcess,
|
||||
connectToOpenCodeServer,
|
||||
runOpenCodeCommand,
|
||||
createOpenCodeSdkClient,
|
||||
loadOpenCodeInventory,
|
||||
} satisfies OpenCodeRuntimeShape;
|
||||
});
|
||||
|
||||
export class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(
|
||||
"t3/provider/OpenCodeRuntime",
|
||||
) {}
|
||||
|
||||
export const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
@@ -1830,7 +1830,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
);
|
||||
|
||||
assertTrue(result._tag === "Failure");
|
||||
assertInclude(String(result.failure), "SocketOpenError");
|
||||
const failureMessage = String(result.failure);
|
||||
assertTrue(
|
||||
failureMessage.includes("SocketOpenError") || failureMessage.includes("SocketCloseError"),
|
||||
);
|
||||
assertTrue(
|
||||
failureMessage.includes("Unauthorized") ||
|
||||
failureMessage.includes("An error occurred during Open"),
|
||||
);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
|
||||
@@ -76,6 +76,7 @@ import {
|
||||
orchestrationDispatchRouteLayer,
|
||||
orchestrationSnapshotRouteLayer,
|
||||
} from "./orchestration/http.ts";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -243,6 +244,7 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe(
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(ServerLifecycleEventsLive),
|
||||
Layer.provide(NetService.layer),
|
||||
);
|
||||
|
||||
const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
|
||||
|
||||
@@ -630,7 +630,11 @@ describe("TraitsPicker (Codex)", () => {
|
||||
|
||||
// ── OpenCode TraitsPicker tests ───────────────────────────────────────
|
||||
|
||||
async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeModelOptions }) {
|
||||
async function mountOpenCodePicker(props: {
|
||||
model?: string;
|
||||
options?: OpenCodeModelOptions;
|
||||
models?: ServerProvider["models"];
|
||||
}) {
|
||||
const threadId = ThreadId.make("thread-opencode-traits");
|
||||
const threadRef = scopeThreadRef(LOCAL_ENVIRONMENT_ID, threadId);
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
@@ -665,7 +669,7 @@ async function mountOpenCodePicker(props: { model?: string; options?: OpenCodeMo
|
||||
const screen = await render(
|
||||
<TraitsPicker
|
||||
provider="opencode"
|
||||
models={findTestProvider("opencode").models}
|
||||
models={props.models ?? findTestProvider("opencode").models}
|
||||
threadRef={threadRef}
|
||||
model={model}
|
||||
prompt=""
|
||||
@@ -712,6 +716,41 @@ describe("TraitsPicker (OpenCode)", () => {
|
||||
expect(text).not.toContain("Medium · plan");
|
||||
});
|
||||
});
|
||||
|
||||
it("does not show a leading separator when only agent options are available", async () => {
|
||||
await using _ = await mountOpenCodePicker({
|
||||
model: "openai/gpt-5.4",
|
||||
models: [
|
||||
{
|
||||
slug: "openai/gpt-5.4",
|
||||
name: "OpenAI · GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
variantOptions: [],
|
||||
agentOptions: [
|
||||
{ value: "build", label: "Build", isDefault: true },
|
||||
{ value: "plan", label: "Plan" },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Agent");
|
||||
expect(text).toContain("Build (default)");
|
||||
expect(text).toContain("Plan");
|
||||
expect(document.querySelectorAll('[data-slot="menu-separator"]')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("TraitsPicker (Cursor)", () => {
|
||||
|
||||
@@ -91,7 +91,7 @@ function resolveNamedOption(
|
||||
return matchingOption;
|
||||
}
|
||||
}
|
||||
return options.find((option) => option.isDefault) ?? null;
|
||||
return options.find((option) => option.isDefault) ?? options[0] ?? null;
|
||||
}
|
||||
|
||||
function getRawContextWindow(
|
||||
@@ -301,6 +301,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
allowPromptInjectedEffort,
|
||||
});
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const showsEffortSection = showEffort;
|
||||
const showsThinkingSection = !showEffort && showThinking;
|
||||
const showsFastModeSection = showFastMode;
|
||||
const showsContextWindowSection = showContextWindow;
|
||||
const hasSectionsBeforeAgent =
|
||||
showsEffortSection || showsThinkingSection || showsFastModeSection || showsContextWindowSection;
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: string) => {
|
||||
@@ -348,7 +354,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
|
||||
return (
|
||||
<>
|
||||
{showEffort ? (
|
||||
{showsEffortSection ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
|
||||
@@ -378,7 +384,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : showThinking ? (
|
||||
) : showsThinkingSection ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
@@ -394,9 +400,9 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{showFastMode ? (
|
||||
{showsFastModeSection ? (
|
||||
<>
|
||||
{showEffort || showThinking ? <MenuDivider /> : null}
|
||||
{showsEffortSection || showsThinkingSection ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
@@ -413,9 +419,11 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
{showContextWindow ? (
|
||||
{showsContextWindowSection ? (
|
||||
<>
|
||||
{showEffort || showThinking || showFastMode ? <MenuDivider /> : null}
|
||||
{showsEffortSection || showsThinkingSection || showsFastModeSection ? (
|
||||
<MenuDivider />
|
||||
) : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Context Window
|
||||
@@ -442,7 +450,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
) : null}
|
||||
{agentOptions.length > 0 ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
{hasSectionsBeforeAgent ? <MenuDivider /> : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Agent</div>
|
||||
<MenuRadioGroup
|
||||
|
||||
@@ -134,7 +134,7 @@ function resolveLabeledOption(
|
||||
if (raw && options.some((option) => option.value === raw)) {
|
||||
return raw;
|
||||
}
|
||||
return options.find((option) => option.isDefault)?.value;
|
||||
return options.find((option) => option.isDefault)?.value ?? options[0]?.value;
|
||||
}
|
||||
|
||||
export function normalizeOpenCodeModelOptionsWithCapabilities(
|
||||
|
||||
Reference in new issue
Block a user