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 } 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 {
28 OpenCodeAdapterV2Driver,
29 type OpenCodeAdapterV2DriverEnv,
30} from "../../orchestration-v2/Adapters/OpenCodeAdapterV2.ts";
31import { ServerSettingsService } from "../../serverSettings.ts";
32import { ProviderDriverError } from "../Errors.ts";
33import {
34 checkOpenCodeProviderStatus,
35 makePendingOpenCodeProvider,
36 openCodeSkillsToServerProviderSkills,
37} from "../Layers/OpenCodeProvider.ts";
38import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
39import { OpenCodeRuntime } from "../opencodeRuntime.ts";
40import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
41import {
42 defaultProviderContinuationIdentity,
43 type ProviderDriver,
44 type ProviderInstance,
45} from "../ProviderDriver.ts";
46import { withInstanceIdentity } from "./instanceIdentity.ts";
47import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
48import {
49 enrichProviderSnapshotWithVersionAdvisory,
50 makeCachedProviderMaintenanceResolution,
51 makePackageManagedProviderMaintenanceResolver,
52 normalizeCommandPath,
53 resolveProviderMaintenanceCapabilitiesEffect,
54} from "../providerMaintenance.ts";
55import {
56 haveProviderSnapshotSettingsChanged,
57 makeProviderSnapshotSettingsSource,
58 type ProviderSnapshotSettings,
59} from "../providerUpdateSettings.ts";
60const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
61
62const DRIVER_KIND = ProviderDriverKind.make("opencode");
63
64function isOpenCodeNativeCommandPath(commandPath: string): boolean {
65 const normalized = normalizeCommandPath(commandPath);
66 return (
67 normalized.endsWith("/.opencode/bin/opencode") ||
68 normalized.endsWith("/.opencode/bin/opencode.exe")
69 );
70}
71
72const UPDATE = makePackageManagedProviderMaintenanceResolver({
73 provider: DRIVER_KIND,
74 npmPackageName: "opencode-ai",
75 nativeUpdate: {
76 args: ["upgrade"],
77 isCommandPath: isOpenCodeNativeCommandPath,
78 },
79});
80
81export type OpenCodeDriverEnv =
82 | OpenCodeAdapterV2DriverEnv
83 | BackgroundPolicy.BackgroundPolicy
84 | ChildProcessSpawner.ChildProcessSpawner
85 | Crypto.Crypto
86 | FileSystem.FileSystem
87 | HttpClient.HttpClient
88 | OpenCodeRuntime
89 | Path.Path
90 | ServerConfig
91 | ServerSettingsService;
92
93export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {
94 driverKind: DRIVER_KIND,
95 metadata: {
96 displayName: "OpenCode",
97 supportsMultipleInstances: true,
98 },
99 configSchema: OpenCodeSettings,
100 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
101 create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
102 Effect.gen(function* () {
103 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
104 const fileSystem = yield* FileSystem.FileSystem;
105 const pathService = yield* Path.Path;
106 const openCodeRuntime = yield* OpenCodeRuntime;
107 const serverConfig = yield* ServerConfig;
108 const httpClient = yield* HttpClient.HttpClient;
109 const serverSettings = yield* ServerSettingsService;
110 const processEnv = mergeProviderInstanceEnvironment(environment);
111 const continuationIdentity = defaultProviderContinuationIdentity({
112 driverKind: DRIVER_KIND,
113 instanceId,
114 });
115 const stampIdentity = withInstanceIdentity({
116 instanceId,
117 driverKind: DRIVER_KIND,
118 displayName,
119 accentColor,
120 continuationGroupKey: continuationIdentity.continuationKey,
121 });
122 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
123 const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution(
124 resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
125 binaryPath: effectiveConfig.binaryPath,
126 env: processEnv,
127 }).pipe(
128 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
129 Effect.provideService(FileSystem.FileSystem, fileSystem),
130 Effect.provideService(Path.Path, pathService),
131 ),
132 );
133
134 const orchestrationAdapter = yield* OpenCodeAdapterV2Driver.create({
135 instanceId,
136 displayName,
137 accentColor,
138 environment,
139 enabled,
140 config,
141 }).pipe(
142 Effect.mapError(
143 (cause) =>
144 new ProviderDriverError({
145 driver: DRIVER_KIND,
146 instanceId,
147 detail: "Failed to build OpenCode orchestration adapter.",
148 cause,
149 }),
150 ),
151 );
152 const serverOwner = yield* OpenCodeServerOwner.make({
153 binaryPath: effectiveConfig.binaryPath,
154 directory: serverConfig.cwd,
155 ...(effectiveConfig.serverPassword
156 ? { serverPassword: effectiveConfig.serverPassword }
157 : {}),
158 environment: processEnv,
159 });
160 const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
161 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
162 );
163
164 const checkProvider = checkOpenCodeProviderStatus(
165 effectiveConfig,
166 serverConfig.cwd,
167 processEnv,
168 ).pipe(
169 Effect.map(stampIdentity),
170 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
171 Effect.provideService(OpenCodeRuntime, openCodeRuntime),
172 );
173 // NOTE: the local branch intentionally uses the shared SDK server
174 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
175 // its full JSON inventory to stdout, but the Bun-compiled binary does
176 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
177 // piped output arrives truncated and unparseable — which degrades to an
178 // empty skill list and poisons the workspace snapshot the `$` picker
179 // reads. The SDK `app.skills` endpoint honors the per-request directory
180 // and returns complete results regardless of size.
181 const loadSkillsForCwd = (cwd: string) =>
182 effectiveConfig.serverUrl.trim().length > 0
183 ? Effect.scoped(
184 Effect.gen(function* () {
185 const server = yield* openCodeRuntime.connectToOpenCodeServer({
186 binaryPath: effectiveConfig.binaryPath,
187 directory: cwd,
188 serverUrl: effectiveConfig.serverUrl,
189 ...(effectiveConfig.serverPassword
190 ? { serverPassword: effectiveConfig.serverPassword }
191 : {}),
192 environment: processEnv,
193 });
194 const client = openCodeRuntime.createOpenCodeSdkClient({
195 baseUrl: server.url,
196 directory: cwd,
197 ...(effectiveConfig.serverPassword
198 ? { serverPassword: effectiveConfig.serverPassword }
199 : {}),
200 });
201 return yield* openCodeRuntime.loadOpenCodeSkills(client);
202 }),
203 )
204 : serverOwner.withServer((server) =>
205 openCodeRuntime.loadOpenCodeSkills(
206 openCodeRuntime.createOpenCodeSdkClient({
207 baseUrl: server.url,
208 directory: cwd,
209 ...(server.serverPassword !== undefined
210 ? { serverPassword: server.serverPassword }
211 : {}),
212 }),
213 ),
214 );
215
216 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
217 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
218 {
219 resolveMaintenance,
220 getSettings: snapshotSettings.getSettings,
221 streamSettings: snapshotSettings.streamSettings,
222 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
223 checkProviderOnSettingsChange: () => false,
224 refreshOnInterval: false,
225 initialSnapshot: (settings) =>
226 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
227 checkProvider,
228 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
229 resolveMaintenance().pipe(
230 Effect.flatMap((maintenanceCapabilities) =>
231 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
232 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
233 }),
234 ),
235 Effect.provideService(HttpClient.HttpClient, httpClient),
236 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
237 ),
238 },
239 ).pipe(
240 Effect.mapError(
241 (cause) =>
242 new ProviderDriverError({
243 driver: DRIVER_KIND,
244 instanceId,
245 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
246 cause,
247 }),
248 ),
249 );
250
251 return {
252 instanceId,
253 driverKind: DRIVER_KIND,
254 continuationIdentity,
255 displayName,
256 accentColor,
257 enabled,
258 snapshot,
259 snapshotForCwd: (cwd) =>
260 !effectiveConfig.enabled
261 ? snapshot.getSnapshot
262 : Effect.all([
263 snapshot.getSnapshot,
264 loadSkillsForCwd(cwd).pipe(Effect.timeout("20 seconds")),
265 ]).pipe(
266 Effect.map(([machineSnapshot, skills]) => ({
267 ...machineSnapshot,
268 skills: openCodeSkillsToServerProviderSkills(skills),
269 })),
270 Effect.mapError(
271 (cause) =>
272 new ProviderDriverError({
273 driver: DRIVER_KIND,
274 instanceId,
275 detail: `Failed to probe OpenCode skills for '${cwd}'`,
276 cause,
277 }),
278 ),
279 ),
280 orchestrationAdapter,
281 textGeneration,
282 } satisfies ProviderInstance;
283 }),
284};