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