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

OpenCodeDriver.ts

260 lines10.2 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 // NOTE: the local branch intentionally uses the shared SDK server
153 // instead of `opencode debug skill` (loadSkillsFromCli). The CLI writes
154 // its full JSON inventory to stdout, but the Bun-compiled binary does
155 // not flush more than one 64KB pipe buffer to a non-TTY stdout, so the
156 // piped output arrives truncated and unparseable — which degrades to an
157 // empty skill list and poisons the workspace snapshot the `$` picker
158 // reads. The SDK `app.skills` endpoint honors the per-request directory
159 // and returns complete results regardless of size.
160 const loadSkillsForCwd = (cwd: string) =>
161 effectiveConfig.serverUrl.trim().length > 0
162 ? Effect.scoped(
163 Effect.gen(function* () {
164 const server = yield* openCodeRuntime.connectToOpenCodeServer({
165 binaryPath: effectiveConfig.binaryPath,
166 directory: cwd,
167 serverUrl: effectiveConfig.serverUrl,
168 ...(effectiveConfig.serverPassword
169 ? { serverPassword: effectiveConfig.serverPassword }
170 : {}),
171 environment: processEnv,
172 });
173 const client = openCodeRuntime.createOpenCodeSdkClient({
174 baseUrl: server.url,
175 directory: cwd,
176 ...(effectiveConfig.serverPassword
177 ? { serverPassword: effectiveConfig.serverPassword }
178 : {}),
179 });
180 return yield* openCodeRuntime.loadOpenCodeSkills(client);
181 }),
182 )
183 : serverOwner.withServer((server) =>
184 openCodeRuntime.loadOpenCodeSkills(
185 openCodeRuntime.createOpenCodeSdkClient({
186 baseUrl: server.url,
187 directory: cwd,
188 ...(server.serverPassword !== undefined
189 ? { serverPassword: server.serverPassword }
190 : {}),
191 }),
192 ),
193 );
194​
195 const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);
196 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(
197 {
198 maintenanceCapabilities,
199 getSettings: snapshotSettings.getSettings,
200 streamSettings: snapshotSettings.streamSettings,
201 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
202 checkProviderOnSettingsChange: () => false,
203 refreshOnInterval: false,
204 initialSnapshot: (settings) =>
205 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
206 checkProvider,
207 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
208 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
209 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
210 }).pipe(
211 Effect.provideService(HttpClient.HttpClient, httpClient),
212 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
213 ),
214 },
215 ).pipe(
216 Effect.mapError(
217 (cause) =>
218 new ProviderDriverError({
219 driver: DRIVER_KIND,
220 instanceId,
221 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
222 cause,
223 }),
224 ),
225 );
226​
227 return {
228 instanceId,
229 driverKind: DRIVER_KIND,
230 continuationIdentity,
231 displayName,
232 accentColor,
233 enabled,
234 snapshot,
235 snapshotForCwd: (cwd) =>
236 !effectiveConfig.enabled
237 ? snapshot.getSnapshot
238 : Effect.all([
239 snapshot.getSnapshot,
240 loadSkillsForCwd(cwd).pipe(Effect.timeout("20 seconds")),
241 ]).pipe(
242 Effect.map(([machineSnapshot, skills]) => ({
243 ...machineSnapshot,
244 skills: openCodeSkillsToServerProviderSkills(skills),
245 })),
246 Effect.mapError(
247 (cause) =>
248 new ProviderDriverError({
249 driver: DRIVER_KIND,
250 instanceId,
251 detail: `Failed to probe OpenCode skills for '${cwd}'`,
252 cause,
253 }),
254 ),
255 ),
256 adapter,
257 textGeneration,
258 } satisfies ProviderInstance;
259 }),
260};