Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCodeDriver.ts

246 lines9.4 KB

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 makePackageManagedProviderMaintenanceResolver,
49 normalizeCommandPath,
50 resolveProviderMaintenanceCapabilitiesEffect,
51} from "../providerMaintenance.ts";
52import {
53 haveProviderSnapshotSettingsChanged,
54 makeProviderSnapshotSettingsSource,
55 type ProviderSnapshotSettings,
56} from "../providerUpdateSettings.ts";
57const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
58​
59const DRIVER_KIND = ProviderDriverKind.make("opencode");
60​
61function isOpenCodeNativeCommandPath(commandPath: string): boolean {
62 const normalized = normalizeCommandPath(commandPath);
63 return (
64 normalized.endsWith("/.opencode/bin/opencode") ||
65 normalized.endsWith("/.opencode/bin/opencode.exe")
66 );
68​
69const UPDATE = makePackageManagedProviderMaintenanceResolver({
70 provider: DRIVER_KIND,
71 npmPackageName: "opencode-ai",
72 homebrewFormula: "anomalyco/tap/opencode",
73 nativeUpdate: {
74 executable: "opencode",
75 args: ["upgrade"],
76 lockKey: "opencode-native",
77 isCommandPath: isOpenCodeNativeCommandPath,
78 },
79});
80​
81export type OpenCodeDriverEnv =
82 | BackgroundPolicy.BackgroundPolicy
83 | ChildProcessSpawner.ChildProcessSpawner
84 | Crypto.Crypto
85 | FileSystem.FileSystem
86 | HttpClient.HttpClient
87 | OpenCodeRuntime
88 | Path.Path
89 | ProviderEventLoggers
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 openCodeRuntime = yield* OpenCodeRuntime;
104 const serverConfig = yield* ServerConfig;
105 const httpClient = yield* HttpClient.HttpClient;
106 const serverSettings = yield* ServerSettingsService;
107 const eventLoggers = yield* ProviderEventLoggers;
108 const processEnv = mergeProviderInstanceEnvironment(environment);
109 const continuationIdentity = defaultProviderContinuationIdentity({
110 driverKind: DRIVER_KIND,
111 instanceId,
112 });
113 const stampIdentity = withInstanceIdentity({
114 instanceId,
115 driverKind: DRIVER_KIND,
116 displayName,
117 accentColor,
118 continuationGroupKey: continuationIdentity.continuationKey,
119 });
120 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
121 const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {
122 binaryPath: effectiveConfig.binaryPath,
123 env: processEnv,
124 });
125​
126 const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {
127 instanceId,
128 environment: processEnv,
129 ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),
130 });
131 const serverOwner = yield* OpenCodeServerOwner.make({
132 binaryPath: effectiveConfig.binaryPath,
133 directory: serverConfig.cwd,
134 ...(effectiveConfig.serverPassword
135 ? { serverPassword: effectiveConfig.serverPassword }
136 : {}),
137 environment: processEnv,
138 });
139 const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
140 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
141 );
142​
143 const checkProvider = checkOpenCodeProviderStatus(
144 effectiveConfig,
145 serverConfig.cwd,
146 processEnv,
147 ).pipe(
148 Effect.map(stampIdentity),
149 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
150 Effect.provideService(OpenCodeRuntime, openCodeRuntime),
151 );
152 const loadSkillsForCwd = (cwd: string) =>
153 effectiveConfig.serverUrl.trim().length > 0
154 ? Effect.scoped(
155 Effect.gen(function* () {
156 const server = yield* openCodeRuntime.connectToOpenCodeServer({
157 binaryPath: effectiveConfig.binaryPath,
158 directory: cwd,
159 serverUrl: effectiveConfig.serverUrl,
160 ...(effectiveConfig.serverPassword
161 ? { serverPassword: effectiveConfig.serverPassword }
162 : {}),
163 environment: processEnv,
164 });
165 const client = openCodeRuntime.createOpenCodeSdkClient({
166 baseUrl: server.url,
167 directory: cwd,
168 ...(effectiveConfig.serverPassword
169 ? { serverPassword: effectiveConfig.serverPassword }
170 : {}),
171 });
172 return yield* openCodeRuntime.loadOpenCodeSkills(client);
173 }),
174 )
175 : openCodeRuntime.loadSkillsFromCli({
176 binaryPath: effectiveConfig.binaryPath,
177 cwd,
178 environment: processEnv,
179 });
180​
181 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
182 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
183 {
184 maintenanceCapabilities,
185 getSettings: snapshotSettings.getSettings,
186 streamSettings: snapshotSettings.streamSettings,
187 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
188 checkProviderOnSettingsChange: () => false,
189 refreshOnInterval: false,
190 initialSnapshot: (settings) =>
191 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
192 checkProvider,
193 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
194 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
195 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
196 }).pipe(
197 Effect.provideService(HttpClient.HttpClient, httpClient),
198 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
199 ),
200 },
201 ).pipe(
202 Effect.mapError(
203 (cause) =>
204 new ProviderDriverError({
205 driver: DRIVER_KIND,
206 instanceId,
207 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
208 cause,
209 }),
210 ),
211 );
212​
213 return {
214 instanceId,
215 driverKind: DRIVER_KIND,
216 continuationIdentity,
217 displayName,
218 accentColor,
219 enabled,
220 snapshot,
221 snapshotForCwd: (cwd) =>
222 !effectiveConfig.enabled
223 ? snapshot.getSnapshot
224 : Effect.all([
225 snapshot.getSnapshot,
226 loadSkillsForCwd(cwd).pipe(Effect.timeout("20 seconds")),
227 ]).pipe(
228 Effect.map(([machineSnapshot, skills]) => ({
229 ...machineSnapshot,
230 skills: openCodeSkillsToServerProviderSkills(skills),
231 })),
232 Effect.mapError(
233 (cause) =>
234 new ProviderDriverError({
235 driver: DRIVER_KIND,
236 instanceId,
237 detail: `Failed to probe OpenCode skills for '${cwd}'`,
238 cause,
239 }),
240 ),
241 ),
242 adapter,
243 textGeneration,
244 } satisfies ProviderInstance;
245 }),
246};