fix(opencode): handle child approvals, stops, and model catalogs (#8480)
This commit is contained in:
1 parent
0009aacdf1
commit
cb49e5d720
42 files changed
+7889
-581
No files matched your search
@@ -34,6 +34,7 @@ import {
|
||||
import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import { OpenCodeRuntime } from "../opencodeRuntime.ts";
|
||||
import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
|
||||
import {
|
||||
defaultProviderContinuationIdentity,
|
||||
type ProviderDriver,
|
||||
@@ -141,13 +142,27 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
environment: processEnv,
|
||||
...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
|
||||
});
|
||||
const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);
|
||||
const serverOwner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: effectiveConfig.binaryPath,
|
||||
directory: serverConfig.cwd,
|
||||
...(effectiveConfig.serverPassword
|
||||
? { serverPassword: effectiveConfig.serverPassword }
|
||||
: {}),
|
||||
environment: processEnv,
|
||||
});
|
||||
const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
|
||||
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
|
||||
);
|
||||
|
||||
const checkProvider = checkOpenCodeProviderStatus(
|
||||
effectiveConfig,
|
||||
serverConfig.cwd,
|
||||
processEnv,
|
||||
).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));
|
||||
).pipe(
|
||||
Effect.map(stampIdentity),
|
||||
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
|
||||
Effect.provideService(OpenCodeRuntime, openCodeRuntime),
|
||||
);
|
||||
|
||||
const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
|
||||
const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
|
||||
@@ -156,6 +171,8 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>
|
||||
getSettings: snapshotSettings.getSettings,
|
||||
streamSettings: snapshotSettings.streamSettings,
|
||||
haveSettingsChanged: haveProviderSnapshotSettingsChanged,
|
||||
checkProviderOnSettingsChange: () => false,
|
||||
refreshOnInterval: false,
|
||||
initialSnapshot: (settings) =>
|
||||
makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
|
||||
checkProvider,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -12,8 +12,10 @@ import { ServerConfig } from "../../config.ts";
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
resolveOpenCodeServerPassword,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
|
||||
import { checkOpenCodeProviderStatus } from "./OpenCodeProvider.ts";
|
||||
import type { OpenCodeInventory } from "../opencodeRuntime.ts";
|
||||
const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
|
||||
@@ -34,8 +36,14 @@ const runtimeMock = {
|
||||
runVersionError: null as Error | null,
|
||||
versionStdout: DEFAULT_VERSION_STDOUT,
|
||||
inventoryError: null as Error | null,
|
||||
connectionError: null as Error | null,
|
||||
inventoryCwd: null as string | null,
|
||||
closeCalls: 0,
|
||||
sdkClientInputs: [] as Array<{
|
||||
baseUrl: string;
|
||||
directory: string;
|
||||
serverPassword?: string;
|
||||
}>,
|
||||
inventory: {
|
||||
providerList: { connected: [] as string[], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
@@ -46,8 +54,10 @@ const runtimeMock = {
|
||||
this.state.runVersionError = null;
|
||||
this.state.versionStdout = DEFAULT_VERSION_STDOUT;
|
||||
this.state.inventoryError = null;
|
||||
this.state.connectionError = null;
|
||||
this.state.inventoryCwd = null;
|
||||
this.state.closeCalls = 0;
|
||||
this.state.sdkClientInputs.length = 0;
|
||||
this.state.inventory = {
|
||||
providerList: { connected: [], all: [] as unknown[], default: {} },
|
||||
agents: [] as unknown[],
|
||||
@@ -57,13 +67,37 @@ const runtimeMock = {
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.succeed({
|
||||
url: "http://127.0.0.1:4301",
|
||||
exitCode: Effect.never,
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
startOpenCodeServerProcess: ({ serverPassword, environment }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls += 1;
|
||||
}),
|
||||
);
|
||||
const effectiveServerPassword = resolveOpenCodeServerPassword({
|
||||
external: false,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
...(environment !== undefined ? { environment } : {}),
|
||||
});
|
||||
return {
|
||||
url: "http://127.0.0.1:4301",
|
||||
...(effectiveServerPassword !== undefined
|
||||
? { serverPassword: effectiveServerPassword }
|
||||
: {}),
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl, serverPassword }) =>
|
||||
Effect.gen(function* () {
|
||||
if (runtimeMock.state.connectionError) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: runtimeMock.state.connectionError.message,
|
||||
cause: runtimeMock.state.connectionError,
|
||||
});
|
||||
}
|
||||
if (!serverUrl) {
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
@@ -73,6 +107,8 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
}
|
||||
return {
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
...(serverPassword ? { serverPassword } : {}),
|
||||
version: "1.14.19",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
};
|
||||
@@ -87,8 +123,10 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: () =>
|
||||
({}) as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>,
|
||||
createOpenCodeSdkClient: (input) => {
|
||||
runtimeMock.state.sdkClientInputs.push(input);
|
||||
return {} as unknown as ReturnType<OpenCodeRuntimeShape["createOpenCodeSdkClient"]>;
|
||||
},
|
||||
loadOpenCodeInventory: () =>
|
||||
runtimeMock.state.inventoryError
|
||||
? Effect.fail(
|
||||
@@ -132,11 +170,31 @@ const makeOpenCodeSettings = (overrides?: Partial<OpenCodeSettings>): OpenCodeSe
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const checkProvider = Effect.fn("checkProvider")(function* (
|
||||
settings: OpenCodeSettings,
|
||||
cwd = process.cwd(),
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
return yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const serverOwner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: settings.binaryPath,
|
||||
directory: cwd,
|
||||
...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
|
||||
...(environment ? { environment } : {}),
|
||||
});
|
||||
return yield* checkOpenCodeProviderStatus(settings, cwd, environment).pipe(
|
||||
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
it.effect("shows a codex-style missing binary message", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
const snapshot = yield* checkProvider(makeOpenCodeSettings());
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
NodeAssert.equal(snapshot.installed, false);
|
||||
@@ -150,7 +208,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
const snapshot = yield* checkProvider(makeOpenCodeSettings());
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
NodeAssert.equal(snapshot.installed, true);
|
||||
@@ -190,7 +248,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
],
|
||||
};
|
||||
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
const snapshot = yield* checkProvider(makeOpenCodeSettings());
|
||||
const model = snapshot.models.find((entry) => entry.slug === "openai/gpt-5.4");
|
||||
|
||||
NodeAssert.ok(model);
|
||||
@@ -253,7 +311,7 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
],
|
||||
};
|
||||
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
const snapshot = yield* checkProvider(makeOpenCodeSettings());
|
||||
|
||||
NodeAssert.deepEqual(
|
||||
snapshot.skills.map((skill) => ({
|
||||
@@ -280,41 +338,109 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not spawn a local server for health check (uses CLI instead)", () =>
|
||||
it.effect("loads local inventory from a scoped OpenCode server", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
yield* checkProvider(makeOpenCodeSettings({ serverPassword: "secret-password" }));
|
||||
|
||||
NodeAssert.equal(runtimeMock.state.closeCalls, 0);
|
||||
NodeAssert.equal(runtimeMock.state.inventoryCwd, process.cwd());
|
||||
NodeAssert.deepEqual(runtimeMock.state.sdkClientInputs, [
|
||||
{
|
||||
baseUrl: "http://127.0.0.1:4301",
|
||||
directory: process.cwd(),
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
]);
|
||||
NodeAssert.equal(runtimeMock.state.closeCalls, 1);
|
||||
NodeAssert.equal(runtimeMock.state.inventoryCwd, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses an environment-only password for local inventory", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* checkProvider(makeOpenCodeSettings(), process.cwd(), {
|
||||
OPENCODE_SERVER_PASSWORD: "environment-password",
|
||||
});
|
||||
|
||||
NodeAssert.deepEqual(runtimeMock.state.sdkClientInputs, [
|
||||
{
|
||||
baseUrl: "http://127.0.0.1:4301",
|
||||
directory: process.cwd(),
|
||||
serverPassword: "environment-password",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the settings password when local environment auth differs", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* checkProvider(
|
||||
makeOpenCodeSettings({ serverPassword: "settings-password" }),
|
||||
process.cwd(),
|
||||
{ OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
);
|
||||
|
||||
NodeAssert.equal(runtimeMock.state.sdkClientInputs[0]?.serverPassword, "settings-password");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports local model inventory failures without treating them as empty", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("opencode models failed");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd());
|
||||
const snapshot = yield* checkProvider(makeOpenCodeSettings());
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
NodeAssert.equal(snapshot.installed, true);
|
||||
NodeAssert.equal(snapshot.models.length, 0);
|
||||
NodeAssert.equal(
|
||||
snapshot.message,
|
||||
"Failed to execute OpenCode CLI health check: opencode models failed",
|
||||
"Failed to load OpenCode provider inventory: opencode models failed",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (it) => {
|
||||
it.effect("does not send a local environment password to a configured server", () =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* checkProvider(
|
||||
makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999" }),
|
||||
process.cwd(),
|
||||
{ OPENCODE_SERVER_PASSWORD: "local-secret" },
|
||||
);
|
||||
|
||||
NodeAssert.equal(snapshot.version, "1.14.19");
|
||||
NodeAssert.deepEqual(runtimeMock.state.sdkClientInputs, [
|
||||
{
|
||||
baseUrl: "http://127.0.0.1:9999",
|
||||
directory: process.cwd(),
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects an unsupported server before loading inventory", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.connectionError = new Error(
|
||||
"OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
|
||||
);
|
||||
const snapshot = yield* checkProvider(
|
||||
makeOpenCodeSettings({ serverUrl: "http://127.0.0.1:9999" }),
|
||||
);
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
NodeAssert.equal(snapshot.models.length, 0);
|
||||
NodeAssert.match(snapshot.message ?? "", /v1\.14\.18 is too old/);
|
||||
NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly auth error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
runtimeMock.state.connectionError = new Error("401 Unauthorized");
|
||||
const snapshot = yield* checkProvider(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
);
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
@@ -328,15 +454,14 @@ it.layer(testLayer)("checkOpenCodeProviderStatus with configured server URL", (i
|
||||
|
||||
it.effect("surfaces a friendly connection error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error(
|
||||
runtimeMock.state.connectionError = new Error(
|
||||
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
|
||||
);
|
||||
const snapshot = yield* checkOpenCodeProviderStatus(
|
||||
const snapshot = yield* checkProvider(
|
||||
makeOpenCodeSettings({
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
}),
|
||||
process.cwd(),
|
||||
);
|
||||
|
||||
NodeAssert.equal(snapshot.status, "error");
|
||||
|
||||
@@ -19,17 +19,18 @@ import {
|
||||
type ServerProviderDraft,
|
||||
} from "../providerSnapshot.ts";
|
||||
import {
|
||||
MINIMUM_OPENCODE_VERSION,
|
||||
OpenCodeRuntime,
|
||||
openCodeRuntimeErrorDetail,
|
||||
type OpenCodeInventory,
|
||||
} from "../opencodeRuntime.ts";
|
||||
import type { Agent, ProviderListResponse } from "@opencode-ai/sdk/v2";
|
||||
import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
|
||||
|
||||
const OPENCODE_PRESENTATION = {
|
||||
displayName: "OpenCode",
|
||||
showInteractionModeToggle: false,
|
||||
} as const;
|
||||
const MINIMUM_OPENCODE_VERSION = "1.14.19";
|
||||
|
||||
class OpenCodeProbeError extends Data.TaggedError("OpenCodeProbeError")<{
|
||||
readonly cause: unknown;
|
||||
@@ -65,6 +66,7 @@ function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
function formatOpenCodeProbeError(input: {
|
||||
readonly cause: unknown;
|
||||
readonly isExternalServer: boolean;
|
||||
readonly phase: "version" | "inventory";
|
||||
readonly serverUrl: string;
|
||||
}): { readonly installed: boolean; readonly message: string } {
|
||||
const detail = normalizedErrorMessage(input.cause);
|
||||
@@ -127,11 +129,13 @@ function formatOpenCodeProbeError(input: {
|
||||
};
|
||||
}
|
||||
|
||||
const failureLabel =
|
||||
input.phase === "inventory"
|
||||
? "Failed to load OpenCode provider inventory"
|
||||
: "Failed to execute OpenCode CLI health check";
|
||||
return {
|
||||
installed: true,
|
||||
message: detail
|
||||
? `Failed to execute OpenCode CLI health check: ${detail}`
|
||||
: "Failed to execute OpenCode CLI health check.",
|
||||
message: detail ? `${failureLabel}: ${detail}` : `${failureLabel}.`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -326,17 +330,27 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
cwd: string,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {
|
||||
): Effect.fn.Return<
|
||||
ServerProviderDraft,
|
||||
never,
|
||||
OpenCodeRuntime | OpenCodeServerOwner.OpenCodeServerOwner
|
||||
> {
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
const checkedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const customModels = openCodeSettings.customModels;
|
||||
const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const fallback = (
|
||||
cause: unknown,
|
||||
version: string | null = null,
|
||||
phase: "version" | "inventory" = "version",
|
||||
) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
phase,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
@@ -417,48 +431,52 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
|
||||
}
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
(isExternalServer
|
||||
? Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const server = yield* openCodeRuntime.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
environment: resolvedEnvironment,
|
||||
});
|
||||
return yield* openCodeRuntime.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
)
|
||||
: openCodeRuntime.loadInventoryFromCli({
|
||||
const loadInventory = (server: {
|
||||
readonly url: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly version: string;
|
||||
}) =>
|
||||
openCodeRuntime
|
||||
.loadOpenCodeInventory(
|
||||
openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: cwd,
|
||||
...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
|
||||
}),
|
||||
)
|
||||
.pipe(Effect.map((inventory) => ({ inventory, version: server.version })));
|
||||
const inventoryEffect = isExternalServer
|
||||
? openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
cwd,
|
||||
environment: resolvedEnvironment,
|
||||
directory: cwd,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
...(openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
})
|
||||
).pipe(
|
||||
.pipe(Effect.flatMap(loadInventory), Effect.scoped)
|
||||
: serverOwner.withServer(loadInventory);
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
inventoryEffect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
return fallback(Cause.squash(inventoryExit.cause), version, "inventory");
|
||||
}
|
||||
|
||||
version = inventoryExit.value.version;
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
flattenOpenCodeModels(inventoryExit.value.inventory),
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const skills = flattenOpenCodeSkills(inventoryExit.value);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
const skills = flattenOpenCodeSkills(inventoryExit.value.inventory);
|
||||
const connectedCount = inventoryExit.value.inventory.providerList.connected.length;
|
||||
return buildServerProvider({
|
||||
presentation: OPENCODE_PRESENTATION,
|
||||
enabled: true,
|
||||
|
||||
@@ -589,18 +589,35 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
slashCommands: [{ name: "review", description: "Review changes" }],
|
||||
skills: [
|
||||
{
|
||||
name: "typescript",
|
||||
description: "TypeScript help",
|
||||
path: "/skills/typescript/SKILL.md",
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, refreshedProvider).slashCommands,
|
||||
[],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, refreshedProvider).skills,
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it("drops stale OpenCode models missing from a successful refresh", () => {
|
||||
@@ -670,8 +687,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
slashCommands: [{ name: "review", description: "Review changes" }],
|
||||
skills: [
|
||||
{
|
||||
name: "typescript",
|
||||
description: "TypeScript help",
|
||||
path: "/skills/typescript/SKILL.md",
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
@@ -685,6 +709,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, refreshedProvider).slashCommands,
|
||||
previousProvider.slashCommands,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, refreshedProvider).skills,
|
||||
previousProvider.skills,
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies pending, logout, uninstall, and reconnect OpenCode inventories", () => {
|
||||
@@ -713,8 +745,15 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
slashCommands: [{ name: "review", description: "Review changes" }],
|
||||
skills: [
|
||||
{
|
||||
name: "typescript",
|
||||
description: "TypeScript help",
|
||||
path: "/skills/typescript/SKILL.md",
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
} as const satisfies ServerProvider;
|
||||
const pendingProvider = {
|
||||
...previousProvider,
|
||||
@@ -732,6 +771,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-07-17T00:02:00.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
message: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
} satisfies ServerProvider;
|
||||
const missingProvider = {
|
||||
@@ -765,6 +806,14 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
mergeProviderSnapshot(previousProvider, loggedOutProvider).models,
|
||||
[],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, loggedOutProvider).slashCommands,
|
||||
[],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
mergeProviderSnapshot(previousProvider, loggedOutProvider).skills,
|
||||
[],
|
||||
);
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, missingProvider).models, []);
|
||||
|
||||
const afterRemoval = mergeProviderSnapshot(previousProvider, authoritativeProvider);
|
||||
@@ -896,6 +945,182 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refreshes OpenCode catalogs and preserves other providers", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const openCodeDriver = ProviderDriverKind.make("opencode");
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
const openCodeInstanceId = ProviderInstanceId.make("opencode");
|
||||
const codexRefreshCalls = yield* Ref.make(0);
|
||||
const openCodeRefreshCalls = yield* Ref.make(0);
|
||||
const codexProvider = {
|
||||
instanceId: codexInstanceId,
|
||||
driver: codexDriver,
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-06-10T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const failedOpenCodeProvider = {
|
||||
instanceId: openCodeInstanceId,
|
||||
driver: openCodeDriver,
|
||||
status: "error",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-06-10T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
message: "Failed to refresh OpenCode models.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const recoveredOpenCodeProvider = {
|
||||
...failedOpenCodeProvider,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-06-10T00:01:00.000Z",
|
||||
message: "One upstream provider connected through OpenCode.",
|
||||
models: [
|
||||
{
|
||||
slug: "github/gpt-5",
|
||||
name: "GPT-5",
|
||||
subProvider: "GitHub",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
} as const satisfies ServerProvider;
|
||||
const changedCatalogProvider = {
|
||||
...recoveredOpenCodeProvider,
|
||||
checkedAt: "2026-06-10T00:02:00.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "anthropic/claude-sonnet-4",
|
||||
name: "Claude Sonnet 4",
|
||||
subProvider: "Anthropic",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
} as const satisfies ServerProvider;
|
||||
const catalogSnapshot = yield* Ref.make<ServerProvider>(recoveredOpenCodeProvider);
|
||||
const instances = [
|
||||
{
|
||||
instanceId: codexInstanceId,
|
||||
driverKind: codexDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: codexDriver,
|
||||
continuationKey: "codex:instance:codex",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(codexProvider),
|
||||
refresh: Ref.update(codexRefreshCalls, (count) => count + 1).pipe(
|
||||
Effect.as(codexProvider),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
},
|
||||
{
|
||||
instanceId: openCodeInstanceId,
|
||||
driverKind: openCodeDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: openCodeDriver,
|
||||
continuationKey: "opencode:instance:opencode",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: openCodeDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(failedOpenCodeProvider),
|
||||
refresh: Ref.update(openCodeRefreshCalls, (count) => count + 1).pipe(
|
||||
Effect.andThen(Ref.get(catalogSnapshot)),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderInstance>;
|
||||
const instanceRegistryLayer = Layer.succeed(
|
||||
ProviderInstanceRegistry.ProviderInstanceRegistry,
|
||||
{
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instances.find((instance) => instance.instanceId === instanceId)),
|
||||
listInstances: Effect.succeed(instances),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
|
||||
},
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-reconnect-refresh-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const initialProviders = yield* registry.getProviders;
|
||||
assert.strictEqual(
|
||||
initialProviders.find((provider) => provider.instanceId === openCodeInstanceId)
|
||||
?.status,
|
||||
"error",
|
||||
);
|
||||
|
||||
const recoveredProviders = yield* registry.refresh();
|
||||
assert.deepStrictEqual(
|
||||
recoveredProviders.find((provider) => provider.instanceId === openCodeInstanceId)
|
||||
?.models,
|
||||
recoveredOpenCodeProvider.models,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
recoveredProviders.find((provider) => provider.instanceId === codexInstanceId),
|
||||
codexProvider,
|
||||
);
|
||||
|
||||
yield* Ref.set(catalogSnapshot, changedCatalogProvider);
|
||||
const changedProviders = yield* registry.refresh();
|
||||
assert.deepStrictEqual(
|
||||
changedProviders.find((provider) => provider.instanceId === openCodeInstanceId)
|
||||
?.models,
|
||||
changedCatalogProvider.models,
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
changedProviders.find((provider) => provider.instanceId === codexInstanceId),
|
||||
codexProvider,
|
||||
);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
|
||||
assert.strictEqual(yield* Ref.get(codexRefreshCalls), 2);
|
||||
assert.strictEqual(yield* Ref.get(openCodeRefreshCalls), 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("persists the merged snapshot when a live update has empty models", () =>
|
||||
Effect.gen(function* () {
|
||||
const cursorDriver = ProviderDriverKind.make("cursor");
|
||||
|
||||
@@ -95,6 +95,10 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean =>
|
||||
return isPendingInitialProbe || didInstalledProviderProbeFail;
|
||||
};
|
||||
|
||||
const shouldRetainMissingOpenCodeMetadata = (provider: ServerProvider): boolean =>
|
||||
provider.driver === ProviderDriverKind.make("opencode") &&
|
||||
shouldRetainMissingProviderModels(provider);
|
||||
|
||||
const mergeProviderModels = (
|
||||
provider: ServerProvider,
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
@@ -132,6 +136,16 @@ export const mergeProviderSnapshot = (
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
|
||||
...(shouldRetainMissingOpenCodeMetadata(nextProvider)
|
||||
? {
|
||||
slashCommands:
|
||||
nextProvider.slashCommands.length === 0
|
||||
? previousProvider.slashCommands
|
||||
: nextProvider.slashCommands,
|
||||
skills:
|
||||
nextProvider.skills.length === 0 ? previousProvider.skills : nextProvider.skills,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshots = (
|
||||
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { it, assert, describe, vi } from "@effect/vitest";
|
||||
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -1531,6 +1533,67 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not persist running after a concurrent send is interrupted", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService.ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
|
||||
const sendStarted = yield* Deferred.make<void>();
|
||||
const interrupted = yield* Deferred.make<void>();
|
||||
routing.codex.sendTurn.mockImplementationOnce(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* Deferred.succeed(sendStarted, undefined);
|
||||
yield* Deferred.await(interrupted);
|
||||
return yield* Effect.interrupt;
|
||||
}),
|
||||
);
|
||||
routing.codex.interruptTurn.mockImplementationOnce(() =>
|
||||
Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
|
||||
);
|
||||
|
||||
const threadId = asThreadId("thread-interrupted-send-directory");
|
||||
const session = yield* provider.startSession(threadId, {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const sendExitFiber = yield* provider
|
||||
.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hold this prompt",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.exit, Effect.forkChild);
|
||||
yield* Deferred.await(sendStarted);
|
||||
yield* provider.interruptTurn({ threadId: session.threadId });
|
||||
const sendExit = yield* Fiber.join(sendExitFiber);
|
||||
|
||||
assert.equal(Exit.isFailure(sendExit), true);
|
||||
if (Exit.isFailure(sendExit)) {
|
||||
assert.equal(Cause.hasInterruptsOnly(sendExit.cause), true);
|
||||
}
|
||||
const persisted = yield* runtimeRepository.getByThreadId({
|
||||
threadId: session.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(persisted), true);
|
||||
if (Option.isSome(persisted)) {
|
||||
// The directory folds both adapter "ready" and "running" into its
|
||||
// runtime "running" state. The payload proves sendTurn did not upsert.
|
||||
assert.equal(persisted.value.status, "running");
|
||||
const payload = persisted.value.runtimePayload;
|
||||
assert.equal(payload !== null && typeof payload === "object", true);
|
||||
if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) {
|
||||
const runtimePayload = payload as {
|
||||
activeTurnId?: string | null;
|
||||
lastRuntimeEvent?: string | null;
|
||||
};
|
||||
assert.equal(runtimePayload.activeTurnId ?? null, null);
|
||||
assert.notEqual(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses persisted resume cursor when startSession is called after a restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = NodeFS.mkdtempSync(
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { expect } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
OpenCodeRuntime,
|
||||
OpenCodeRuntimeError,
|
||||
type OpenCodeRuntimeShape,
|
||||
} from "./opencodeRuntime.ts";
|
||||
import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
|
||||
|
||||
const unusedRuntimeMethod = () =>
|
||||
Effect.fail(
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "unused",
|
||||
detail: "unused test method",
|
||||
}),
|
||||
);
|
||||
|
||||
const makeRuntime = Effect.gen(function* () {
|
||||
const starts = yield* Ref.make(0);
|
||||
const closes = yield* Ref.make(0);
|
||||
const failNextStart = yield* Ref.make(false);
|
||||
const started = yield* Deferred.make<void>();
|
||||
const closed = yield* Deferred.make<void>();
|
||||
const runtime: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.gen(function* () {
|
||||
if (yield* Ref.getAndSet(failNextStart, false)) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "startOpenCodeServerProcess",
|
||||
detail: "start failed",
|
||||
});
|
||||
}
|
||||
const index = yield* Ref.updateAndGet(starts, (count) => count + 1);
|
||||
yield* Deferred.succeed(started, undefined).pipe(Effect.ignore);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Ref.update(closes, (count) => count + 1).pipe(
|
||||
Effect.andThen(Deferred.succeed(closed, undefined)),
|
||||
Effect.ignore,
|
||||
),
|
||||
);
|
||||
return {
|
||||
url: `http://127.0.0.1:${index}`,
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: unusedRuntimeMethod,
|
||||
runOpenCodeCommand: unusedRuntimeMethod,
|
||||
createOpenCodeSdkClient: () => ({}) as never,
|
||||
loadOpenCodeInventory: unusedRuntimeMethod,
|
||||
loadInventoryFromCli: unusedRuntimeMethod,
|
||||
};
|
||||
return { runtime, starts, closes, failNextStart, started, closed };
|
||||
});
|
||||
|
||||
it.effect("shares concurrent borrowers and closes after the idle TTL", () =>
|
||||
Effect.gen(function* () {
|
||||
const testRuntime = yield* makeRuntime;
|
||||
const release = yield* Deferred.make<void>();
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
const useServer = owner.withServer((server) =>
|
||||
Deferred.await(release).pipe(Effect.as(server.url)),
|
||||
);
|
||||
const fibers = yield* Effect.all([useServer, useServer], {
|
||||
concurrency: "unbounded",
|
||||
}).pipe(Effect.forkChild);
|
||||
yield* Deferred.await(testRuntime.started);
|
||||
expect(yield* Ref.get(testRuntime.starts)).toBe(1);
|
||||
yield* Deferred.succeed(release, undefined);
|
||||
expect(yield* Fiber.join(fibers)).toEqual(["http://127.0.0.1:1", "http://127.0.0.1:1"]);
|
||||
yield* TestClock.adjust(Duration.seconds(31));
|
||||
yield* Deferred.await(testRuntime.closed);
|
||||
expect(yield* Ref.get(testRuntime.closes)).toBe(1);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, testRuntime.runtime));
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("retries a failed start and closes on owner scope shutdown", () =>
|
||||
Effect.gen(function* () {
|
||||
const testRuntime = yield* makeRuntime;
|
||||
yield* Ref.set(testRuntime.failNextStart, true);
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
expect(
|
||||
(yield* Effect.exit(owner.withServer((server) => Effect.succeed(server.url))))._tag,
|
||||
).toBe("Failure");
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:1",
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, testRuntime.runtime));
|
||||
expect(yield* Ref.get(testRuntime.starts)).toBe(1);
|
||||
expect(yield* Ref.get(testRuntime.closes)).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("invalidates an exited process so the next borrower starts a new one", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Ref.make(0);
|
||||
const processExits: Array<Deferred.Deferred<number>> = [];
|
||||
const processClosed = yield* Deferred.make<void>();
|
||||
const runtime: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.updateAndGet(starts, (count) => count + 1);
|
||||
const exitCode = yield* Deferred.make<number>();
|
||||
processExits.push(exitCode);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Deferred.succeed(processClosed, undefined).pipe(Effect.ignore),
|
||||
);
|
||||
return {
|
||||
url: `http://127.0.0.1:${index}`,
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Deferred.await(exitCode),
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: unusedRuntimeMethod,
|
||||
runOpenCodeCommand: unusedRuntimeMethod,
|
||||
createOpenCodeSdkClient: () => ({}) as never,
|
||||
loadOpenCodeInventory: unusedRuntimeMethod,
|
||||
loadInventoryFromCli: unusedRuntimeMethod,
|
||||
};
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:1",
|
||||
);
|
||||
yield* Deferred.succeed(processExits[0]!, 1);
|
||||
yield* Deferred.await(processClosed);
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:2",
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, runtime));
|
||||
expect(yield* Ref.get(starts)).toBe(2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("replaces a dead cached process before its exit watcher runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Ref.make(0);
|
||||
const closes = yield* Ref.make(0);
|
||||
const processRunning: Array<Ref.Ref<boolean>> = [];
|
||||
const runtime: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.updateAndGet(starts, (count) => count + 1);
|
||||
const isRunning = yield* Ref.make(true);
|
||||
processRunning.push(isRunning);
|
||||
yield* Effect.addFinalizer(() => Ref.update(closes, (count) => count + 1));
|
||||
return {
|
||||
url: `http://127.0.0.1:${index}`,
|
||||
version: "1.14.19",
|
||||
isRunning: Ref.get(isRunning),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: unusedRuntimeMethod,
|
||||
runOpenCodeCommand: unusedRuntimeMethod,
|
||||
createOpenCodeSdkClient: () => ({}) as never,
|
||||
loadOpenCodeInventory: unusedRuntimeMethod,
|
||||
loadInventoryFromCli: unusedRuntimeMethod,
|
||||
};
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:1",
|
||||
);
|
||||
yield* Ref.set(processRunning[0]!, false);
|
||||
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:2",
|
||||
);
|
||||
expect(yield* Ref.get(starts)).toBe(2);
|
||||
expect(yield* Ref.get(closes)).toBe(1);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, runtime));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("cleans up an interrupted startup and allows a retry", () =>
|
||||
Effect.gen(function* () {
|
||||
const starts = yield* Ref.make(0);
|
||||
const firstStartEntered = yield* Deferred.make<void>();
|
||||
const firstStartClosed = yield* Deferred.make<void>();
|
||||
const runtime: OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: () =>
|
||||
Effect.gen(function* () {
|
||||
const index = yield* Ref.updateAndGet(starts, (count) => count + 1);
|
||||
yield* Effect.addFinalizer(() =>
|
||||
index === 1
|
||||
? Deferred.succeed(firstStartClosed, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
);
|
||||
if (index === 1) {
|
||||
yield* Deferred.succeed(firstStartEntered, undefined);
|
||||
return yield* Effect.never;
|
||||
}
|
||||
return {
|
||||
url: `http://127.0.0.1:${index}`,
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: unusedRuntimeMethod,
|
||||
runOpenCodeCommand: unusedRuntimeMethod,
|
||||
createOpenCodeSdkClient: () => ({}) as never,
|
||||
loadOpenCodeInventory: unusedRuntimeMethod,
|
||||
loadInventoryFromCli: unusedRuntimeMethod,
|
||||
};
|
||||
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
const firstBorrower = yield* owner
|
||||
.withServer((server) => Effect.succeed(server.url))
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(firstStartEntered);
|
||||
yield* Fiber.interrupt(firstBorrower);
|
||||
yield* Deferred.await(firstStartClosed);
|
||||
expect(yield* owner.withServer((server) => Effect.succeed(server.url))).toBe(
|
||||
"http://127.0.0.1:2",
|
||||
);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, runtime));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("releases an interrupted borrower and closes after the idle TTL", () =>
|
||||
Effect.gen(function* () {
|
||||
const testRuntime = yield* makeRuntime;
|
||||
const borrowerEntered = yield* Deferred.make<void>();
|
||||
yield* Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const owner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: "opencode",
|
||||
directory: "/project",
|
||||
});
|
||||
const borrower = yield* owner
|
||||
.withServer(() =>
|
||||
Deferred.succeed(borrowerEntered, undefined).pipe(Effect.andThen(Effect.never)),
|
||||
)
|
||||
.pipe(Effect.forkChild);
|
||||
yield* Deferred.await(borrowerEntered);
|
||||
yield* Fiber.interrupt(borrower);
|
||||
yield* TestClock.adjust(Duration.seconds(31));
|
||||
yield* Deferred.await(testRuntime.closed);
|
||||
expect(yield* Ref.get(testRuntime.closes)).toBe(1);
|
||||
}),
|
||||
).pipe(Effect.provideService(OpenCodeRuntime, testRuntime.runtime));
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
@@ -0,0 +1,184 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import * as OpenCodeRuntime from "./opencodeRuntime.ts";
|
||||
|
||||
export const OPENCODE_SERVER_IDLE_TTL = "30 seconds";
|
||||
|
||||
interface OpenCodeServerOwnerState {
|
||||
server: OpenCodeRuntime.OpenCodeServerProcess | null;
|
||||
serverScope: Scope.Closeable | null;
|
||||
borrowers: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
}
|
||||
|
||||
export class OpenCodeServerOwner extends Context.Service<
|
||||
OpenCodeServerOwner,
|
||||
{
|
||||
readonly withServer: <A, E, R>(
|
||||
use: (server: OpenCodeRuntime.OpenCodeServerProcess) => Effect.Effect<A, E, R>,
|
||||
) => Effect.Effect<A, E | OpenCodeRuntime.OpenCodeRuntimeError, R>;
|
||||
}
|
||||
>()("t3/provider/OpenCodeServerOwner") {}
|
||||
|
||||
/** Owns the lazy local OpenCode server shared by one provider instance. */
|
||||
export const make = Effect.fn("OpenCodeServerOwner.make")(function* (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) {
|
||||
const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const ownerScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const mutex = yield* Semaphore.make(1);
|
||||
const state: OpenCodeServerOwnerState = {
|
||||
server: null,
|
||||
serverScope: null,
|
||||
borrowers: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const cancelIdleClose = Effect.fn("OpenCodeServerOwner.cancelIdleClose")(function* () {
|
||||
const fiber = state.idleCloseFiber;
|
||||
state.idleCloseFiber = null;
|
||||
if (fiber !== null) {
|
||||
yield* Fiber.interrupt(fiber).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const closeServer = Effect.fn("OpenCodeServerOwner.closeServer")(function* (
|
||||
expected?: OpenCodeRuntime.OpenCodeServerProcess,
|
||||
) {
|
||||
if (expected !== undefined && state.server !== expected) {
|
||||
return;
|
||||
}
|
||||
const scope = state.serverScope;
|
||||
state.server = null;
|
||||
state.serverScope = null;
|
||||
if (scope !== null) {
|
||||
yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const watchServerExit = Effect.fn("OpenCodeServerOwner.watchServerExit")(function* (
|
||||
server: OpenCodeRuntime.OpenCodeServerProcess,
|
||||
) {
|
||||
yield* server.exitCode;
|
||||
yield* mutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (state.server !== server) {
|
||||
return;
|
||||
}
|
||||
yield* cancelIdleClose();
|
||||
yield* closeServer(server);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const acquireServer = mutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleClose();
|
||||
if (state.server !== null) {
|
||||
if (yield* state.server.isRunning) {
|
||||
state.borrowers += 1;
|
||||
return state.server;
|
||||
}
|
||||
yield* closeServer(state.server);
|
||||
}
|
||||
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
const serverScope = yield* Scope.make();
|
||||
const started = yield* Effect.exit(
|
||||
restore(
|
||||
runtime
|
||||
.startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword !== undefined
|
||||
? { serverPassword: input.serverPassword }
|
||||
: {}),
|
||||
...(input.environment ? { environment: input.environment } : {}),
|
||||
})
|
||||
.pipe(Effect.provideService(Scope.Scope, serverScope)),
|
||||
),
|
||||
);
|
||||
if (Exit.isFailure(started)) {
|
||||
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
|
||||
return yield* Effect.failCause(started.cause);
|
||||
}
|
||||
|
||||
const server = started.value;
|
||||
state.server = server;
|
||||
state.serverScope = serverScope;
|
||||
state.borrowers = 1;
|
||||
yield* watchServerExit(server).pipe(Effect.forkIn(ownerScope));
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>
|
||||
mutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (state.server !== server) {
|
||||
return;
|
||||
}
|
||||
state.borrowers = Math.max(0, state.borrowers - 1);
|
||||
if (state.borrowers > 0) {
|
||||
return;
|
||||
}
|
||||
yield* cancelIdleClose();
|
||||
state.idleCloseFiber = yield* Effect.sleep(OPENCODE_SERVER_IDLE_TTL).pipe(
|
||||
Effect.andThen(
|
||||
mutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (state.server !== server || state.borrowers > 0) {
|
||||
return;
|
||||
}
|
||||
state.idleCloseFiber = null;
|
||||
yield* closeServer(server);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.forkIn(ownerScope),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
mutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleClose();
|
||||
state.borrowers = 0;
|
||||
yield* closeServer();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return OpenCodeServerOwner.of({
|
||||
withServer: (use) =>
|
||||
Effect.uninterruptibleMask((restore) =>
|
||||
restore(acquireServer).pipe(
|
||||
Effect.flatMap((server) =>
|
||||
restore(use(server)).pipe(Effect.ensuring(releaseServer(server))),
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
}) => Layer.effect(OpenCodeServerOwner, make(input));
|
||||
@@ -250,6 +250,40 @@ describe("makeManagedServerProvider", () => {
|
||||
).pipe(Effect.provide(Layer.mergeAll(AlwaysRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("keeps manual refresh when interval refresh is disabled", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => Effect.succeed(initialSnapshot),
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.tap((count) =>
|
||||
count === 1
|
||||
? Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: "1 second",
|
||||
refreshOnInterval: false,
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* TestClock.adjust("5 minutes");
|
||||
yield* Effect.yieldNow;
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
|
||||
yield* provider.refresh;
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(AlwaysRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("wakes a sleeping provider refresh loop when its interval changes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
@@ -355,6 +389,41 @@ describe("makeManagedServerProvider", () => {
|
||||
).pipe(Effect.provide(AlwaysRunTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("can update settings and disable periodic checks without probing again", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const settingsChanges = yield* PubSub.unbounded<TestSettings>();
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const initialCheckDone = yield* Deferred.make<void>();
|
||||
const enrichmentCalls = yield* Ref.make(0);
|
||||
yield* makeManagedServerProvider<TestSettings>({
|
||||
maintenanceCapabilities,
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
checkProviderOnSettingsChange: () => false,
|
||||
refreshOnInterval: false,
|
||||
initialSnapshot: () => Effect.succeed(initialSnapshot),
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.tap(() => Deferred.succeed(initialCheckDone, undefined).pipe(Effect.ignore)),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
enrichSnapshot: () => Ref.update(enrichmentCalls, (count) => count + 1),
|
||||
refreshInterval: "1 second",
|
||||
});
|
||||
|
||||
yield* Deferred.await(initialCheckDone);
|
||||
yield* PubSub.publish(settingsChanges, { enabled: false });
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust("1 second");
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
assert.strictEqual(yield* Ref.get(enrichmentCalls), 2);
|
||||
}),
|
||||
).pipe(Effect.provide(Layer.mergeAll(AlwaysRunTestLayer, TestClock.layer()))),
|
||||
);
|
||||
|
||||
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -40,6 +40,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
readonly refreshOnInterval?: boolean;
|
||||
readonly checkProviderOnSettingsChange?: (previous: Settings, next: Settings) => boolean;
|
||||
}): Effect.fn.Return<
|
||||
ServerProviderShape,
|
||||
ServerSettingsError,
|
||||
@@ -121,6 +123,21 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
|
||||
}
|
||||
|
||||
if (
|
||||
!forceRefresh &&
|
||||
input.checkProviderOnSettingsChange?.(previousSettings, nextSettings) === false
|
||||
) {
|
||||
const state = yield* Ref.get(snapshotStateRef);
|
||||
const nextGeneration = state.enrichmentGeneration + 1;
|
||||
yield* Ref.set(snapshotStateRef, {
|
||||
...state,
|
||||
enrichmentGeneration: nextGeneration,
|
||||
});
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* restartSnapshotEnrichment(nextSettings, state.snapshot, nextGeneration);
|
||||
return state.snapshot;
|
||||
}
|
||||
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
|
||||
const generation = input.enrichSnapshot
|
||||
@@ -199,7 +216,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),
|
||||
).pipe(
|
||||
Effect.flatMap((intervalElapsed) =>
|
||||
intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
|
||||
input.refreshOnInterval !== false &&
|
||||
intervalElapsed &&
|
||||
Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0
|
||||
? hasProviderStatusDemand.pipe(
|
||||
Effect.flatMap((shouldRefresh) =>
|
||||
shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
import type { OpencodeClient } from "@opencode-ai/sdk/v2";
|
||||
import { it as effectIt } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveOpenCodeConfigContent } from "./opencodeRuntime.ts";
|
||||
import {
|
||||
OpenCodeRuntimeError,
|
||||
resolveOpenCodeConfigContent,
|
||||
resolveOpenCodeServerPassword,
|
||||
verifyOpenCodeServerVersion,
|
||||
} from "./opencodeRuntime.ts";
|
||||
|
||||
describe("resolveOpenCodeConfigContent", () => {
|
||||
it("prefers the caller environment over the inherited environment", () => {
|
||||
@@ -21,3 +31,122 @@ describe("resolveOpenCodeConfigContent", () => {
|
||||
expect(resolveOpenCodeConfigContent(undefined, {})).toBe("{}");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveOpenCodeServerPassword", () => {
|
||||
it("uses the local environment password when settings do not provide one", () => {
|
||||
expect(
|
||||
resolveOpenCodeServerPassword(
|
||||
{ external: false, environment: { OPENCODE_SERVER_PASSWORD: " env password " } },
|
||||
{},
|
||||
),
|
||||
).toBe(" env password ");
|
||||
});
|
||||
|
||||
it("uses the settings password for a local server", () => {
|
||||
expect(
|
||||
resolveOpenCodeServerPassword({ external: false, serverPassword: " settings password " }, {}),
|
||||
).toBe(" settings password ");
|
||||
});
|
||||
|
||||
it("uses the settings password when local settings and environment differ", () => {
|
||||
expect(
|
||||
resolveOpenCodeServerPassword(
|
||||
{
|
||||
external: false,
|
||||
serverPassword: "settings-password",
|
||||
environment: { OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
},
|
||||
{},
|
||||
),
|
||||
).toBe("settings-password");
|
||||
});
|
||||
|
||||
it("does not send an inherited local password to an external server", () => {
|
||||
expect(
|
||||
resolveOpenCodeServerPassword(
|
||||
{ external: true, environment: { OPENCODE_SERVER_PASSWORD: "local-secret" } },
|
||||
{ OPENCODE_SERVER_PASSWORD: "inherited-secret" },
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
function makeHealthClient(
|
||||
result: (options?: { readonly signal?: AbortSignal }) => Promise<unknown>,
|
||||
): OpencodeClient {
|
||||
return {
|
||||
global: {
|
||||
health: result,
|
||||
},
|
||||
} as unknown as OpencodeClient;
|
||||
}
|
||||
|
||||
describe("verifyOpenCodeServerVersion", () => {
|
||||
effectIt.effect("accepts a supported server version", () =>
|
||||
Effect.gen(function* () {
|
||||
const version = yield* verifyOpenCodeServerVersion(
|
||||
makeHealthClient(() => Promise.resolve({ data: { healthy: true, version: "1.14.19" } })),
|
||||
);
|
||||
expect(version).toBe("1.14.19");
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("rejects a server below the supported version", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* verifyOpenCodeServerVersion(
|
||||
makeHealthClient(() => Promise.resolve({ data: { healthy: true, version: "1.14.18" } })),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(OpenCodeRuntimeError);
|
||||
expect(error.detail).toContain("v1.14.18 is too old");
|
||||
}),
|
||||
);
|
||||
|
||||
for (const data of [
|
||||
{ healthy: true },
|
||||
{ healthy: true, version: "not-a-version" },
|
||||
{ healthy: false, version: "1.14.19" },
|
||||
]) {
|
||||
effectIt.effect(`rejects an invalid health response: ${JSON.stringify(data)}`, () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* verifyOpenCodeServerVersion(
|
||||
makeHealthClient(() => Promise.resolve({ data })),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(OpenCodeRuntimeError);
|
||||
expect(error.detail).toContain("requires OpenCode v1.14.19 or newer");
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
effectIt.effect("preserves an unauthorized health error", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* verifyOpenCodeServerVersion(
|
||||
makeHealthClient(() =>
|
||||
Promise.reject({ response: { status: 401 }, error: { message: "Unauthorized" } }),
|
||||
),
|
||||
).pipe(Effect.flip);
|
||||
expect(error).toBeInstanceOf(OpenCodeRuntimeError);
|
||||
expect(error.detail).toContain("status=401");
|
||||
expect(error.detail).toContain("Unauthorized");
|
||||
}),
|
||||
);
|
||||
|
||||
effectIt.effect("aborts a health request when the version check times out", () =>
|
||||
Effect.gen(function* () {
|
||||
let requestSignal: AbortSignal | undefined;
|
||||
const checkFiber = yield* verifyOpenCodeServerVersion(
|
||||
makeHealthClient((options) => {
|
||||
requestSignal = options?.signal;
|
||||
return new Promise(() => undefined);
|
||||
}),
|
||||
).pipe(Effect.flip, Effect.forkChild);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
expect(requestSignal).toBeDefined();
|
||||
yield* TestClock.adjust("6 seconds");
|
||||
|
||||
const error = yield* Fiber.join(checkFiber);
|
||||
expect(error.detail).toBe("Timed out while checking the OpenCode server version.");
|
||||
expect(requestSignal?.aborted).toBe(true);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
});
|
||||
@@ -18,6 +18,34 @@ import { OpenCodeRuntime, OpenCodeRuntimeLive } from "./opencodeRuntime.ts";
|
||||
const testLayer = OpenCodeRuntimeLive.pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
it.layer(testLayer)("OpenCodeRuntime inventory", (it) => {
|
||||
it.effect("keeps provider inventory when agent discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* OpenCodeRuntime;
|
||||
const client = {
|
||||
provider: {
|
||||
list: () =>
|
||||
Promise.resolve({
|
||||
data: {
|
||||
connected: ["openai"],
|
||||
all: [],
|
||||
default: {},
|
||||
},
|
||||
}),
|
||||
},
|
||||
app: {
|
||||
agents: () => Promise.reject(new Error("agents endpoint unavailable")),
|
||||
skills: () => Promise.resolve({ data: [] }),
|
||||
},
|
||||
} as unknown as OpencodeClient;
|
||||
|
||||
const inventory = yield* runtime.loadOpenCodeInventory(client);
|
||||
|
||||
NodeAssert.deepEqual(inventory.providerList.connected, ["openai"]);
|
||||
NodeAssert.deepEqual(inventory.agents, []);
|
||||
NodeAssert.deepEqual(inventory.skills, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps provider inventory when skill discovery fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* OpenCodeRuntime;
|
||||
|
||||
@@ -39,6 +39,7 @@ describe("buildOpenCodePermissionRules", () => {
|
||||
it("allows everything only under full access", () => {
|
||||
NodeAssert.deepEqual(buildOpenCodePermissionRules("full-access"), [
|
||||
{ permission: "*", pattern: "*", action: "allow" },
|
||||
{ permission: "external_directory", pattern: "*", action: "allow" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -33,10 +33,20 @@ import { isWindowsCommandNotFound } from "../processRunner.ts";
|
||||
import { collectStreamAsString } from "./providerSnapshot.ts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
|
||||
const OPENCODE_EMPTY_CONFIG_CONTENT = "{}";
|
||||
|
||||
export const MINIMUM_OPENCODE_VERSION = "1.14.19";
|
||||
const OPENCODE_HEALTH_TIMEOUT = "5 seconds";
|
||||
|
||||
const OpenCodeHealthSchema = Schema.Struct({
|
||||
healthy: Schema.Literal(true),
|
||||
version: Schema.String,
|
||||
});
|
||||
const decodeOpenCodeHealth = Schema.decodeUnknownEffect(OpenCodeHealthSchema);
|
||||
|
||||
export function resolveOpenCodeConfigContent(
|
||||
inputEnvironment: Readonly<Record<string, string | undefined>> | undefined,
|
||||
inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
@@ -48,17 +58,41 @@ export function resolveOpenCodeConfigContent(
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveOpenCodeServerPassword(
|
||||
input: {
|
||||
readonly external: boolean;
|
||||
readonly serverPassword?: string;
|
||||
readonly environment?: Readonly<Record<string, string | undefined>>;
|
||||
},
|
||||
inheritedEnvironment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): string | undefined {
|
||||
if (input.serverPassword !== undefined) {
|
||||
return input.serverPassword;
|
||||
}
|
||||
if (input.external) {
|
||||
return undefined;
|
||||
}
|
||||
return input.environment === undefined
|
||||
? inheritedEnvironment.OPENCODE_SERVER_PASSWORD
|
||||
: input.environment.OPENCODE_SERVER_PASSWORD;
|
||||
}
|
||||
|
||||
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
|
||||
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_HOSTNAME = "127.0.0.1";
|
||||
const OPENCODE_SKILL_DISCOVERY_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
export interface OpenCodeServerProcess {
|
||||
readonly url: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly version: string;
|
||||
readonly isRunning: Effect.Effect<boolean>;
|
||||
readonly exitCode: Effect.Effect<number, never>;
|
||||
}
|
||||
|
||||
export interface OpenCodeServerConnection {
|
||||
readonly url: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly version: string;
|
||||
readonly exitCode: Effect.Effect<number, never> | null;
|
||||
readonly external: boolean;
|
||||
}
|
||||
@@ -96,7 +130,7 @@ export function openCodeRuntimeErrorDetail(cause: unknown): string {
|
||||
|
||||
export const runOpenCodeSdk = <A>(
|
||||
operation: string,
|
||||
fn: () => Promise<A>,
|
||||
fn: (signal: AbortSignal) => Promise<A>,
|
||||
): Effect.Effect<A, OpenCodeRuntimeError> =>
|
||||
Effect.tryPromise({
|
||||
try: fn,
|
||||
@@ -104,6 +138,44 @@ export const runOpenCodeSdk = <A>(
|
||||
new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),
|
||||
}).pipe(Effect.withSpan(`opencode.${operation}`));
|
||||
|
||||
export const verifyOpenCodeServerVersion = Effect.fn("verifyOpenCodeServerVersion")(function* (
|
||||
client: OpencodeClient,
|
||||
) {
|
||||
const healthOption = yield* runOpenCodeSdk("global.health", (signal) =>
|
||||
client.global.health({ signal }),
|
||||
).pipe(Effect.timeoutOption(OPENCODE_HEALTH_TIMEOUT));
|
||||
if (Option.isNone(healthOption)) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: "Timed out while checking the OpenCode server version.",
|
||||
});
|
||||
}
|
||||
|
||||
const health = yield* decodeOpenCodeHealth(healthOption.value.data).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: `OpenCode server returned an invalid health response. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (parseSemver(health.version) === null) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: `OpenCode server returned an invalid version. T3 Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
});
|
||||
}
|
||||
if (compareSemverVersions(health.version, MINIMUM_OPENCODE_VERSION) < 0) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: `OpenCode v${health.version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,
|
||||
});
|
||||
}
|
||||
return health.version;
|
||||
});
|
||||
|
||||
export interface OpenCodeCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
@@ -145,6 +217,8 @@ export interface OpenCodeRuntimeShape {
|
||||
*/
|
||||
readonly startOpenCodeServerProcess: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
@@ -157,7 +231,9 @@ export interface OpenCodeRuntimeShape {
|
||||
*/
|
||||
readonly connectToOpenCodeServer: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly directory: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly serverPassword?: string;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
@@ -398,7 +474,10 @@ export function toOpenCodeFileParts(input: {
|
||||
|
||||
export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
|
||||
if (runtimeMode === "full-access") {
|
||||
return [{ permission: "*", pattern: "*", action: "allow" }];
|
||||
return [
|
||||
{ permission: "*", pattern: "*", action: "allow" },
|
||||
{ permission: "external_directory", pattern: "*", action: "allow" },
|
||||
];
|
||||
}
|
||||
|
||||
// "Auto-accept edits" is documented as "auto-approve edits, ask before other
|
||||
@@ -514,6 +593,20 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
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 startOpenCodeServerProcess: OpenCodeRuntimeShape["startOpenCodeServerProcess"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
// Bind this server's lifetime to the caller's scope. When the caller's
|
||||
@@ -537,6 +630,11 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);
|
||||
const serverPassword = resolveOpenCodeServerPassword({
|
||||
external: false,
|
||||
...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
|
||||
...(input.environment !== undefined ? { environment: input.environment } : {}),
|
||||
});
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
@@ -545,6 +643,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
shell: spawnCommand.shell,
|
||||
env: {
|
||||
...input.environment,
|
||||
...(serverPassword !== undefined ? { OPENCODE_SERVER_PASSWORD: serverPassword } : {}),
|
||||
// Respect an OPENCODE_CONFIG_CONTENT provided by the caller or
|
||||
// the inherited process environment, only falling back to the
|
||||
// empty config when neither is set. Setting it unconditionally
|
||||
@@ -670,8 +769,20 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const url = readyOption.value;
|
||||
const version = yield* verifyOpenCodeServerVersion(
|
||||
createOpenCodeSdkClient({
|
||||
baseUrl: url,
|
||||
directory: input.directory,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
url: readyOption.value,
|
||||
url,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
version,
|
||||
isRunning: child.isRunning.pipe(Effect.orElseSucceed(() => false)),
|
||||
exitCode: child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
@@ -682,16 +793,31 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
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,
|
||||
const serverPassword = resolveOpenCodeServerPassword({
|
||||
external: true,
|
||||
...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
|
||||
});
|
||||
return verifyOpenCodeServerVersion(
|
||||
createOpenCodeSdkClient({
|
||||
baseUrl: serverUrl,
|
||||
directory: input.directory,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
}),
|
||||
).pipe(
|
||||
Effect.map((version) => ({
|
||||
url: serverUrl,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
version,
|
||||
exitCode: null,
|
||||
external: true,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword !== undefined ? { serverPassword: input.serverPassword } : {}),
|
||||
...(input.environment !== undefined ? { environment: input.environment } : {}),
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
@@ -699,26 +825,14 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
}).pipe(
|
||||
Effect.map((server) => ({
|
||||
url: server.url,
|
||||
...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
|
||||
version: server.version,
|
||||
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(
|
||||
@@ -738,6 +852,7 @@ const makeOpenCodeRuntime = Effect.gen(function* () {
|
||||
const loadAgents = (client: OpencodeClient) =>
|
||||
runOpenCodeSdk("app.agents", () => client.app.agents()).pipe(
|
||||
Effect.map((result) => result.data ?? []),
|
||||
Effect.orElseSucceed((): ReadonlyArray<Agent> => []),
|
||||
);
|
||||
|
||||
const loadSkills = (client: OpencodeClient) =>
|
||||
|
||||
@@ -57,6 +57,7 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
@@ -4918,6 +4919,51 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("refreshes providers for each subscribeServerConfig connection", () =>
|
||||
Effect.gen(function* () {
|
||||
const refreshCalls = yield* Ref.make(0);
|
||||
const firstRefreshDone = yield* Deferred.make<void>();
|
||||
const secondRefreshDone = yield* Deferred.make<void>();
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
providerRegistry: {
|
||||
refresh: () =>
|
||||
Ref.updateAndGet(refreshCalls, (count) => count + 1).pipe(
|
||||
Effect.tap((count) =>
|
||||
Deferred.succeed(
|
||||
count === 1 ? firstRefreshDone : secondRefreshDone,
|
||||
undefined,
|
||||
).pipe(Effect.ignore),
|
||||
),
|
||||
Effect.as([]),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.gen(function* () {
|
||||
yield* client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.runHead);
|
||||
yield* Deferred.await(firstRefreshDone);
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
Effect.gen(function* () {
|
||||
yield* client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.runHead);
|
||||
yield* Deferred.await(secondRefreshDone);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.equal(yield* Ref.get(refreshCalls), 2);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("routes websocket resource telemetry through the subscription", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* buildAppUnderTest();
|
||||
|
||||
@@ -11,6 +11,7 @@ import { beforeEach, expect } from "vite-plus/test";
|
||||
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
import * as OpenCodeServerOwner from "../provider/OpenCodeServerOwner.ts";
|
||||
import * as OpenCodeTextGeneration from "./OpenCodeTextGeneration.ts";
|
||||
import * as TextGeneration from "./TextGeneration.ts";
|
||||
|
||||
@@ -21,6 +22,8 @@ const runtimeMock = {
|
||||
promptParts: [] as ReadonlyArray<unknown>[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
sessionCreateCalls: 0,
|
||||
connectionError: undefined as Error | undefined,
|
||||
sessionCreateError: undefined as unknown,
|
||||
sessionResult: undefined as { data?: { id: string } } | undefined,
|
||||
promptRequestError: undefined as unknown,
|
||||
@@ -34,6 +37,8 @@ const runtimeMock = {
|
||||
this.state.promptParts.length = 0;
|
||||
this.state.authHeaders.length = 0;
|
||||
this.state.closeCalls.length = 0;
|
||||
this.state.sessionCreateCalls = 0;
|
||||
this.state.connectionError = undefined;
|
||||
this.state.sessionCreateError = undefined;
|
||||
this.state.sessionResult = undefined;
|
||||
this.state.promptRequestError = undefined;
|
||||
@@ -42,7 +47,7 @@ const runtimeMock = {
|
||||
};
|
||||
|
||||
const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
startOpenCodeServerProcess: ({ binaryPath }) =>
|
||||
startOpenCodeServerProcess: ({ binaryPath, serverPassword, environment }) =>
|
||||
Effect.gen(function* () {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
@@ -54,22 +59,43 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntimeShape = {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
}),
|
||||
);
|
||||
const effectiveServerPassword = OpenCodeRuntime.resolveOpenCodeServerPassword({
|
||||
external: false,
|
||||
...(serverPassword !== undefined ? { serverPassword } : {}),
|
||||
...(environment !== undefined ? { environment } : {}),
|
||||
});
|
||||
return {
|
||||
url,
|
||||
...(effectiveServerPassword !== undefined
|
||||
? { serverPassword: effectiveServerPassword }
|
||||
: {}),
|
||||
version: "1.14.19",
|
||||
isRunning: Effect.succeed(true),
|
||||
exitCode: Effect.never,
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
connectToOpenCodeServer: ({ serverUrl, serverPassword }) =>
|
||||
runtimeMock.state.connectionError
|
||||
? Effect.fail(
|
||||
new OpenCodeRuntime.OpenCodeRuntimeError({
|
||||
operation: "global.health",
|
||||
detail: runtimeMock.state.connectionError.message,
|
||||
cause: runtimeMock.state.connectionError,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
...(serverPassword ? { serverPassword } : {}),
|
||||
version: "1.14.19",
|
||||
exitCode: null,
|
||||
external: Boolean(serverUrl),
|
||||
}),
|
||||
runOpenCodeCommand: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
|
||||
createOpenCodeSdkClient: ({ baseUrl, serverPassword }) =>
|
||||
({
|
||||
session: {
|
||||
create: async () => {
|
||||
runtimeMock.state.sessionCreateCalls += 1;
|
||||
if (runtimeMock.state.sessionCreateError !== undefined) {
|
||||
throw runtimeMock.state.sessionCreateError;
|
||||
}
|
||||
@@ -163,18 +189,35 @@ const OpenCodeTextGenerationExistingServerTestLayer = Layer.succeed(
|
||||
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
});
|
||||
const LOCAL_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverPassword: "secret-password",
|
||||
});
|
||||
const EXISTING_SERVER_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
});
|
||||
const EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
});
|
||||
|
||||
function withOpenCodeTextGeneration<A, E, R>(
|
||||
settings: OpenCodeSettings,
|
||||
effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect<A, E, R>,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings);
|
||||
const serverOwner = yield* OpenCodeServerOwner.make({
|
||||
binaryPath: settings.binaryPath,
|
||||
directory: process.cwd(),
|
||||
...(settings.serverPassword ? { serverPassword: settings.serverPassword } : {}),
|
||||
...(environment ? { environment } : {}),
|
||||
});
|
||||
const textGeneration = yield* OpenCodeTextGeneration.makeOpenCodeTextGeneration(settings).pipe(
|
||||
Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
|
||||
);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
}
|
||||
@@ -229,6 +272,49 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("passes configured authentication to a locally spawned server", () =>
|
||||
withOpenCodeTextGeneration(LOCAL_AUTH_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses an environment-only password for a locally spawned server", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
DEFAULT_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:environment-password")}`,
|
||||
]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses settings auth when the local environment password differs", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
LOCAL_AUTH_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "environment-password" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
withOpenCodeTextGeneration(DEFAULT_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -460,6 +546,36 @@ it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGeneration", (it) => {
|
||||
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||
"OpenCodeTextGeneration with configured server URL",
|
||||
(it) => {
|
||||
it.effect("does not send a local environment password to a configured server", () =>
|
||||
withOpenCodeTextGeneration(
|
||||
EXTERNAL_SERVER_WITHOUT_AUTH_OPENCODE_SETTINGS,
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
yield* textGeneration.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([null]);
|
||||
}),
|
||||
{ OPENCODE_SERVER_PASSWORD: "local-secret" },
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not create a session when the server version is unsupported", () =>
|
||||
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.connectionError = new Error(
|
||||
"OpenCode v1.14.18 is too old. Upgrade to v1.14.19 or newer.",
|
||||
);
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage(DEFAULT_COMMIT_MESSAGE_INPUT)
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(TextGenerationError);
|
||||
expect(error.message).toContain("v1.14.18 is too old");
|
||||
expect(runtimeMock.state.sessionCreateCalls).toBe(0);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||
withOpenCodeTextGeneration(EXISTING_SERVER_OPENCODE_SETTINGS, (textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
NonNegativeInt,
|
||||
@@ -31,8 +27,7 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
|
||||
import * as OpenCodeServerOwner from "../provider/OpenCodeServerOwner.ts";
|
||||
|
||||
const OpenCodeTextGenerationOperation = Schema.Literals([
|
||||
"generateCommitMessage",
|
||||
@@ -175,188 +170,12 @@ function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): str
|
||||
.trim();
|
||||
}
|
||||
|
||||
interface SharedOpenCodeTextGenerationServerState {
|
||||
server: OpenCodeRuntime.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;
|
||||
}
|
||||
|
||||
export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
|
||||
openCodeSettings: OpenCodeSettings,
|
||||
environment?: NodeJS.ProcessEnv,
|
||||
) {
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
|
||||
const resolvedEnvironment = environment ?? process.env;
|
||||
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 = 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);
|
||||
}
|
||||
});
|
||||
|
||||
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
|
||||
const idleCloseFiber = sharedServerState.idleCloseFiber;
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
if (idleCloseFiber !== null) {
|
||||
yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
|
||||
server: OpenCodeRuntime.OpenCodeServerProcess,
|
||||
) {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.forkIn(idleFiberScope),
|
||||
);
|
||||
sharedServerState.idleCloseFiber = fiber;
|
||||
});
|
||||
|
||||
const acquireSharedServer = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
}) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
|
||||
const existingServer = sharedServerState.server;
|
||||
if (existingServer !== null) {
|
||||
if (
|
||||
sharedServerState.binaryPath !== input.binaryPath &&
|
||||
sharedServerState.activeRequests === 0
|
||||
) {
|
||||
yield* closeSharedServer();
|
||||
} else {
|
||||
if (sharedServerState.binaryPath !== input.binaryPath) {
|
||||
yield* Effect.logWarning(
|
||||
"OpenCode shared server binary path mismatch: requested " +
|
||||
input.binaryPath +
|
||||
" but active server uses " +
|
||||
sharedServerState.binaryPath +
|
||||
"; reusing existing server because there are active requests",
|
||||
);
|
||||
}
|
||||
sharedServerState.activeRequests += 1;
|
||||
return existingServer;
|
||||
}
|
||||
}
|
||||
|
||||
// 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,
|
||||
environment: resolvedEnvironment,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, serverScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (startedExit._tag === "Failure") {
|
||||
yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
|
||||
return yield* Effect.failCause(startedExit.cause);
|
||||
}
|
||||
|
||||
const server = startedExit.value;
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.serverScope = serverScope;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseSharedServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
|
||||
if (sharedServerState.activeRequests === 0) {
|
||||
yield* scheduleIdleClose(server);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// 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();
|
||||
sharedServerState.activeRequests = 0;
|
||||
yield* closeSharedServer();
|
||||
}),
|
||||
),
|
||||
);
|
||||
const serverOwner = yield* OpenCodeServerOwner.OpenCodeServerOwner;
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation: OpenCodeTextGenerationOperation;
|
||||
@@ -381,13 +200,16 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
});
|
||||
|
||||
const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
|
||||
function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
|
||||
function* (
|
||||
server: Pick<
|
||||
OpenCodeRuntime.OpenCodeServerConnection,
|
||||
"url" | "serverPassword" | "version"
|
||||
>,
|
||||
) {
|
||||
const client = openCodeRuntime.createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
...(server.serverPassword !== undefined ? { serverPassword: server.serverPassword } : {}),
|
||||
});
|
||||
const session = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
@@ -496,17 +318,31 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
}),
|
||||
);
|
||||
|
||||
const rawOutput =
|
||||
const serverOutput =
|
||||
openCodeSettings.serverUrl.length > 0
|
||||
? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
|
||||
: yield* Effect.acquireUseRelease(
|
||||
acquireSharedServer({
|
||||
? openCodeRuntime
|
||||
.connectToOpenCodeServer({
|
||||
binaryPath: openCodeSettings.binaryPath,
|
||||
directory: input.cwd,
|
||||
serverUrl: openCodeSettings.serverUrl,
|
||||
...(openCodeSettings.serverPassword
|
||||
? { serverPassword: openCodeSettings.serverPassword }
|
||||
: {}),
|
||||
})
|
||||
.pipe(Effect.flatMap(runAgainstServer), Effect.scoped)
|
||||
: serverOwner.withServer(runAgainstServer);
|
||||
const rawOutput = yield* serverOutput.pipe(
|
||||
Effect.catchTags({
|
||||
OpenCodeRuntimeError: (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
|
||||
cause,
|
||||
}),
|
||||
runAgainstServer,
|
||||
releaseSharedServer,
|
||||
);
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
|
||||
return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
|
||||
|
||||
Reference in new issue
Block a user