Open History to see the last commit
1/**
2 * OpenCodeDriver — `ProviderDriver` for the OpenCode runtime.
3 *
4 * Mirrors the Codex / Claude drivers: a plain value whose `create()`
5 * bundles `snapshot` / `adapter` / `textGeneration` closures over the
6 * per-instance `OpenCodeSettings`.
7 *
8 * Two instances with different `serverUrl`s therefore talk to independent
9 * OpenCode servers; when no `serverUrl` is set, the adapter + text-generation
10 * shares spin up their own scoped child processes, and those child
11 * processes are released when the registry scope closes.
12 *
13 * @module provider/Drivers/OpenCodeDriver
14 */
15import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";
16import * as Crypto from "effect/Crypto";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import * as Schema from "effect/Schema";
21import { HttpClient } from "effect/unstable/http";
22import { ChildProcessSpawner } from "effect/unstable/process";
23
24import { makeOpenCodeTextGeneration } from "../../textGeneration/OpenCodeTextGeneration.ts";
25import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
26import { ServerConfig } from "../../config.ts";
27import { ServerSettingsService } from "../../serverSettings.ts";
28import { ProviderDriverError } from "../Errors.ts";
29import { makeOpenCodeAdapter } from "../Layers/OpenCodeAdapter.ts";
30import {
31 checkOpenCodeProviderStatus,
32 makePendingOpenCodeProvider,
33} from "../Layers/OpenCodeProvider.ts";
34import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
35import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
36import { OpenCodeRuntime } from "../opencodeRuntime.ts";
37import {
38 defaultProviderContinuationIdentity,
39 type ProviderDriver,
40 type ProviderInstance,
41} from "../ProviderDriver.ts";
42import type { ServerProviderDraft } from "../providerSnapshot.ts";
43import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
44import {
45 enrichProviderSnapshotWithVersionAdvisory,
46 makePackageManagedProviderMaintenanceResolver,
47 normalizeCommandPath,
48 resolveProviderMaintenanceCapabilitiesEffect,
49} from "../providerMaintenance.ts";
50import {
51 haveProviderSnapshotSettingsChanged,
52 makeProviderSnapshotSettingsSource,
53 type ProviderSnapshotSettings,
54} from "../providerUpdateSettings.ts";
55const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
56
57const DRIVER_KIND = ProviderDriverKind.make("opencode");
58
59function isOpenCodeNativeCommandPath(commandPath: string): boolean {
60 const normalized = normalizeCommandPath(commandPath);
61 return (
62 normalized.endsWith("/.opencode/bin/opencode") ||
63 normalized.endsWith("/.opencode/bin/opencode.exe")
64 );
65}
66
67const UPDATE = makePackageManagedProviderMaintenanceResolver({
68 provider: DRIVER_KIND,
69 npmPackageName: "opencode-ai",
70 homebrewFormula: "anomalyco/tap/opencode",
71 nativeUpdate: {
72 executable: "opencode",
73 args: ["upgrade"],
74 lockKey: "opencode-native",
75 isCommandPath: isOpenCodeNativeCommandPath,
76 },
77});
78
79export type OpenCodeDriverEnv =
80 | BackgroundPolicy.BackgroundPolicy
81 | ChildProcessSpawner.ChildProcessSpawner
82 | Crypto.Crypto
83 | FileSystem.FileSystem
84 | HttpClient.HttpClient
85 | OpenCodeRuntime
86 | Path.Path
87 | ProviderEventLoggers
88 | ServerConfig
89 | ServerSettingsService;
90
91const withInstanceIdentity =
92 (input: {
93 readonly instanceId: ProviderInstance["instanceId"];
94 readonly displayName: string | undefined;
95 readonly accentColor: string | undefined;
96 readonly continuationGroupKey: string;
97 }) =>
98 (snapshot: ServerProviderDraft): ServerProvider => ({
99 ...snapshot,
100 instanceId: input.instanceId,
101 driver: DRIVER_KIND,
102 ...(input.displayName ? { displayName: input.displayName } : {}),
103 ...(input.accentColor ? { accentColor: input.accentColor } : {}),
104 continuation: { groupKey: input.continuationGroupKey },
105 });
106
107export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
108 driverKind: DRIVER_KIND,
109 metadata: {
110 displayName: "OpenCode",
111 supportsMultipleInstances: true,
112 },
113 configSchema: OpenCodeSettings,
114 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
115 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
116 Effect.gen(function* () {
117 const openCodeRuntime = yield* OpenCodeRuntime;
118 const serverConfig = yield* ServerConfig;
119 const httpClient = yield* HttpClient.HttpClient;
120 const serverSettings = yield* ServerSettingsService;
121 const eventLoggers = yield* ProviderEventLoggers;
122 const fileSystem = yield* FileSystem.FileSystem;
123 const path = yield* Path.Path;
124 const processEnv = mergeProviderInstanceEnvironment(environment);
125 const continuationIdentity = defaultProviderContinuationIdentity({
126 driverKind: DRIVER_KIND,
127 instanceId,
128 });
129 const stampIdentity = withInstanceIdentity({
130 instanceId,
131 displayName,
132 accentColor,
133 continuationGroupKey: continuationIdentity.continuationKey,
134 });
135 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
136 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
137 binaryPath: effectiveConfig.binaryPath,
138 env: processEnv,
139 });
140
141 const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
142 instanceId,
143 environment: processEnv,
144 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
145 });
146 const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);
147
148 const checkProvider = checkOpenCodeProviderStatus(
149 effectiveConfig,
150 serverConfig.cwd,
151 processEnv,
152 ).pipe(
153 Effect.map(stampIdentity),
154 Effect.provideService(OpenCodeRuntime, openCodeRuntime),
155 Effect.provideService(FileSystem.FileSystem, fileSystem),
156 Effect.provideService(Path.Path, path),
157 );
158
159 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
160 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
161 {
162 maintenanceCapabilities,
163 getSettings: snapshotSettings.getSettings,
164 streamSettings: snapshotSettings.streamSettings,
165 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
166 initialSnapshot: (settings) =>
167 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
168 checkProvider,
169 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
170 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
171 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
172 }).pipe(
173 Effect.provideService(HttpClient.HttpClient, httpClient),
174 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
175 ),
176 },
177 ).pipe(
178 Effect.mapError(
179 (cause) =>
180 new ProviderDriverError({
181 driver: DRIVER_KIND,
182 instanceId,
183 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
184 cause,
185 }),
186 ),
187 );
188
189 return {
190 instanceId,
191 driverKind: DRIVER_KIND,
192 continuationIdentity,
193 displayName,
194 accentColor,
195 enabled,
196 snapshot,
197 adapter,
198 textGeneration,
199 } satisfies ProviderInstance;
200 }),
201};