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

driver.ts

531 lines20.6 KB

1import { ProviderDriverKind } from "@t3tools/contracts";
2import { OpenCodeSettings } from "../settings.ts";
3import * as Crypto from "effect/Crypto";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Option from "effect/Option";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import * as HttpClient from "effect/http/HttpClient";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13​
14import * as OpenCode2TextGeneration from "./v2/textGeneration.ts";
15import { makeOpenCodeTextGeneration } from "./textGeneration.ts";
16import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
17import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
18import * as OpenCodeAdapterV2 from "./adapter.ts";
19import * as OpenCode2AdapterV2 from "./v2/adapter.ts";
20import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration";
22import { ProviderDriverError } from "@t3tools/provider-core/server/errors";
23import { openCodeUsageReader, type OpenCodeUsageReaderEnv } from "./usage.ts";
24import { readOpenCodeGoUsageLimits } from "./usageLimits.ts";
25import { loadOpenCode2Catalog } from "./openCode2Catalog.ts";
26import {
27 checkOpenCodeProviderStatus,
28 loadOpenCode2Workspace,
29 makeOpenCode2ModelLoader,
30 makePendingOpenCodeProvider,
31 openCode2CommandsToServerProviderSlashCommands,
32 openCode2SkillsToServerProviderSkills,
33 openCodeSkillsToServerProviderSkills,
34 openCodeCommandsToServerProviderSlashCommands,
35} from "./status.ts";
36import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider";
37import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
38import {
39 makeOpenCodeRuntimeProbe,
40 probeOpenCodeRuntime,
41 type ProbedOpenCode,
42} from "./versionProbe.ts";
43import * as OpenCodeServerOwner from "./OpenCodeServerOwner.ts";
44import * as OpenCode2Client from "./v2/OpenCode2Client.ts";
45import * as OpenCode2Server from "./v2/OpenCode2Server.ts";
46import {
47 defaultProviderContinuationIdentity,
48 type ProviderDriver,
49 type ProviderInstance,
50} from "@t3tools/provider-core/server/driver";
51import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity";
52import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
53import {
54 enrichProviderSnapshotWithVersionAdvisory,
55 makeCachedProviderMaintenanceResolution,
56 makeManualOnlyProviderMaintenanceCapabilities,
57 makePackageManagedProviderMaintenanceResolver,
58 normalizeCommandPath,
59 resolveProviderMaintenanceCapabilitiesEffect,
60} from "@t3tools/provider-core/server/maintenanceResolver";
61import {
62 haveProviderSnapshotSettingsChanged,
63 makeProviderSnapshotSettingsSource,
64 type ProviderSnapshotSettings,
65} from "@t3tools/provider-core/server/snapshotSettings";
66const decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);
67​
68const DRIVER_KIND = ProviderDriverKind.make("opencode");
69​
70function isOpenCodeNativeCommandPath(commandPath: string): boolean {
71 const normalized = normalizeCommandPath(commandPath);
72 return (
73 normalized.endsWith("/.opencode/bin/opencode") ||
74 normalized.endsWith("/.opencode/bin/opencode.exe")
75 );
77​
78/**
79 * OpenCode 1.x ships as `opencode-ai` and 2.x as `@opencode/cli`. An install is
80 * only ever updated within its own package: T3 never moves a 1.x install onto
81 * 2.x or back, since 2.x converts the shared database in place.
82 */
83export const openCodeUpdateFor = (generation: ProbedOpenCode["generation"]) =>
84 makePackageManagedProviderMaintenanceResolver({
85 provider: DRIVER_KIND,
86 npmPackageName: generation === "v2" ? "@opencode/cli" : "opencode-ai",
87 nativeUpdate: {
88 args: ["upgrade"],
89 isCommandPath: isOpenCodeNativeCommandPath,
90 },
91 });
92​
93type OpenCodeRuntimeProbe = Effect.Success<
94 ReturnType<typeof makeOpenCodeRuntimeProbe<OpenCodeRuntime.OpenCodeRuntimeError>>
95>;
96​
97function byOpenCodeRuntime<A, E, R, PE>(
98 probed: Effect.Effect<ProbedOpenCode | undefined, PE>,
99 paths: { readonly v1: Effect.Effect<A, E, R>; readonly v2: Effect.Effect<A, E, R> },
100): Effect.Effect<A, E, R> {
101 return probed.pipe(
102 Effect.orElseSucceed(() => undefined),
103 Effect.flatMap((result) => (result?.generation === "v2" ? paths.v2 : paths.v1)),
104 );
106​
107/**
108 * Capability and selection reads are hot, so they use the last successful probe (1.x before one
109 * lands) and never wait on a slow server. Opening a session waits for a probe, so each server is
110 * spoken to in its own protocol.
111 */
112function selectOpenCodeRuntimeAdapter(input: {
113 readonly probe: OpenCodeRuntimeProbe;
114 readonly v1: ProviderAdapter.ProviderAdapterV2["Service"];
115 readonly v2: ProviderAdapter.ProviderAdapterV2["Service"];
116}): ProviderAdapter.ProviderAdapterV2["Service"] {
117 const pick = <PE>(probed: Effect.Effect<ProbedOpenCode | undefined, PE>) =>
118 byOpenCodeRuntime(probed, { v1: Effect.succeed(input.v1), v2: Effect.succeed(input.v2) });
119 const hot = pick(Effect.map(input.probe.lastSuccess, Option.getOrUndefined));
120 return {
121 instanceId: input.v1.instanceId,
122 driver: DRIVER_KIND,
123 getCapabilities: () => Effect.flatMap(hot, (adapter) => adapter.getCapabilities()),
124 planSelectionTransition: (transition) =>
125 Effect.flatMap(hot, (adapter) => adapter.planSelectionTransition(transition)),
126 openSession: (session) =>
127 Effect.flatMap(pick(input.probe.get), (adapter) => adapter.openSession(session)),
128 };
130​
131function selectOpenCodeRuntimeTextGeneration(
132 probe: OpenCodeRuntimeProbe,
133 v1: ProviderTextGeneration,
134 v2: ProviderTextGeneration,
135): ProviderTextGeneration {
136 return {
137 generateCommitMessage: (input) =>
138 byOpenCodeRuntime(probe.get, {
139 v1: v1.generateCommitMessage(input),
140 v2: v2.generateCommitMessage(input),
141 }),
142 generatePrContent: (input) =>
143 byOpenCodeRuntime(probe.get, {
144 v1: v1.generatePrContent(input),
145 v2: v2.generatePrContent(input),
146 }),
147 generateBranchName: (input) =>
148 byOpenCodeRuntime(probe.get, {
149 v1: v1.generateBranchName(input),
150 v2: v2.generateBranchName(input),
151 }),
152 generateThreadTitle: (input) =>
153 byOpenCodeRuntime(probe.get, {
154 v1: v1.generateThreadTitle(input),
155 v2: v2.generateThreadTitle(input),
156 }),
157 generateReviewGuide: (input) =>
158 byOpenCodeRuntime(probe.get, {
159 v1: v1.generateReviewGuide(input),
160 v2: v2.generateReviewGuide(input),
161 }),
162 };
164​
165export type OpenCodeDriverEnv =
166 | OpenCodeAdapterV2.OpenCodeAdapterV2DriverEnv
167 | ProviderHost.ProviderHost
168 | ChildProcessSpawner.ChildProcessSpawner
169 | Crypto.Crypto
170 | FileSystem.FileSystem
171 | HttpClient.HttpClient
172 | ProviderLatestVersions.ProviderLatestVersions
173 | OpenCodeRuntime.OpenCodeRuntime
174 | Path.Path;
175​
176export const OpenCodeDriver: ProviderDriver<
177 OpenCodeSettings,
178 OpenCodeDriverEnv,
179 OpenCodeUsageReaderEnv
180> = {
181 driverKind: DRIVER_KIND,
182 metadata: {
183 displayName: "OpenCode",
184 supportsMultipleInstances: true,
185 },
186 configSchema: OpenCodeSettings,
187 defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),
188 usage: openCodeUsageReader,
189 create: Effect.fn("OpencodeDriver.create")(function* ({
190 instanceId,
191 displayName,
192 accentColor,
193 environment,
194 enabled,
195 config,
196 }) {
197 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
198 const fileSystem = yield* FileSystem.FileSystem;
199 const pathService = yield* Path.Path;
200 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
201 const httpClient = yield* HttpClient.HttpClient;
202 const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions;
203 const crypto = yield* Crypto.Crypto;
204 const host = yield* ProviderHost.ProviderHost;
205 const processEnv = yield* mergeProviderInstanceEnvironment(environment);
206 const continuationIdentity = defaultProviderContinuationIdentity({
207 driverKind: DRIVER_KIND,
208 instanceId,
209 });
210 const stampIdentity = withInstanceIdentity({
211 instanceId,
212 driverKind: DRIVER_KIND,
213 displayName,
214 accentColor,
215 continuationGroupKey: continuationIdentity.continuationKey,
216 });
217 const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;
218 const runtimeProbe = yield* makeOpenCodeRuntimeProbe(
219 probeOpenCodeRuntime(effectiveConfig, processEnv).pipe(
220 Effect.provideService(HttpClient.HttpClient, httpClient),
221 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
222 ),
223 );
224 const noUpdate = makeManualOnlyProviderMaintenanceCapabilities({
225 provider: DRIVER_KIND,
226 packageName: null,
227 });
228 const maintenanceFor = (probed: typeof runtimeProbe.get) =>
229 probed.pipe(
230 Effect.map((result) => result.generation),
231 Effect.option,
232 Effect.flatMap((generation) =>
233 Option.isNone(generation)
234 ? Effect.succeed(noUpdate)
235 : resolveProviderMaintenanceCapabilitiesEffect(openCodeUpdateFor(generation.value), {
236 binaryPath: effectiveConfig.binaryPath,
237 env: processEnv,
238 }),
239 ),
240 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
241 Effect.provideService(FileSystem.FileSystem, fileSystem),
242 Effect.provideService(Path.Path, pathService),
243 );
244 const cachedMaintenance = yield* makeCachedProviderMaintenanceResolution(
245 maintenanceFor(runtimeProbe.get),
246 );
247 const resolveMaintenance = (options?: { readonly fresh?: boolean }) =>
248 !effectiveConfig.enabled
249 ? Effect.succeed(noUpdate)
250 : options?.fresh === true
251 ? runtimeProbe.refresh.pipe(
252 Effect.ignore,
253 Effect.andThen(cachedMaintenance({ fresh: true })),
254 )
255 : cachedMaintenance();
256 const openCodeV1Adapter = yield* OpenCodeAdapterV2.OpenCodeAdapterV2Driver.create({
257 instanceId,
258 displayName,
259 accentColor,
260 environment,
261 enabled,
262 config,
263 }).pipe(
264 Effect.mapError(
265 (cause) =>
266 new ProviderDriverError({
267 driver: DRIVER_KIND,
268 instanceId,
269 detail: "Failed to build OpenCode orchestration adapter.",
270 cause,
271 }),
272 ),
273 );
274 const openCode2Server = yield* OpenCode2Server.make({
275 binaryPath: effectiveConfig.binaryPath,
276 serverUrl: effectiveConfig.serverUrl,
277 serverPassword: effectiveConfig.serverPassword,
278 directory: host.paths.cwd,
279 environment: processEnv,
280 }).pipe(
281 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
282 Effect.provideService(
283 OpenCode2Client.OpenCode2Client,
284 yield* OpenCode2Client.make.pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),
285 ),
286 );
287 const orchestrationAdapter = selectOpenCodeRuntimeAdapter({
288 probe: runtimeProbe,
289 v1: openCodeV1Adapter,
290 v2: yield* OpenCode2AdapterV2.make(instanceId).pipe(
291 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
292 ),
293 });
294 const loadOpenCode2Models = yield* makeOpenCode2ModelLoader(
295 openCode2Server.withConnection(({ client }) => loadOpenCode2Catalog(client, host.paths.cwd)),
296 );
297 const listOpenCode2Workspace = (cwd: string) =>
298 openCode2Server.withConnection(({ client, events }) =>
299 Effect.gen(function* () {
300 const location = { directory: cwd };
301 const scanned = yield* Deferred.make<void>();
302 const pending = new Set(["command.updated", "skill.updated"]);
303 const stream = yield* events.pipe(Effect.option);
304 if (stream._tag === "Some") {
305 yield* stream.value.pipe(
306 Stream.runForEach((event) =>
307 "location" in event &&
308 event.location?.directory === cwd &&
309 pending.delete(event.type) &&
310 pending.size === 0
311 ? Deferred.succeed(scanned, undefined)
312 : Effect.void,
313 ),
314 Effect.ignore,
315 Effect.forkScoped,
316 );
317 }
318 return yield* loadOpenCode2Workspace(
319 Effect.all(
320 {
321 skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)),
322 commands: client.command.list({ location }).pipe(Effect.map((list) => list.data)),
323 },
324 { concurrency: "unbounded" },
325 ),
326 Deferred.await(scanned),
327 );
328 }).pipe(Effect.scoped),
329 );
330 const serverOwner = yield* OpenCodeServerOwner.make({
331 binaryPath: effectiveConfig.binaryPath,
332 directory: host.paths.cwd,
333 ...(effectiveConfig.serverPassword ? { serverPassword: effectiveConfig.serverPassword } : {}),
334 environment: processEnv,
335 });
336 const textGeneration = selectOpenCodeRuntimeTextGeneration(
337 runtimeProbe,
338 yield* makeOpenCodeTextGeneration(effectiveConfig).pipe(
339 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
340 ),
341 yield* OpenCode2TextGeneration.make().pipe(
342 Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server),
343 ),
344 );
345​
346 const checkProvider = Effect.all(
347 {
348 provider: checkOpenCodeProviderStatus(
349 effectiveConfig,
350 host.paths.cwd,
351 runtimeProbe.refresh,
352 loadOpenCode2Models,
353 ),
354 usageLimits: readOpenCodeGoUsageLimits({
355 enabled: effectiveConfig.enabled,
356 serverUrl: effectiveConfig.serverUrl,
357 environment: processEnv,
358 }),
359 },
360 { concurrency: "unbounded" },
361 ).pipe(
362 Effect.map(({ provider, usageLimits }) => ({ ...provider, usageLimits })),
363 Effect.map(stampIdentity),
364 Effect.provideService(FileSystem.FileSystem, fileSystem),
365 Effect.provideService(Path.Path, pathService),
366 Effect.provideService(HttpClient.HttpClient, httpClient),
367 Effect.provideService(Crypto.Crypto, crypto),
368 Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, serverOwner),
369 Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, openCodeRuntime),
370 );
371 // The CLI writes its full JSON inventory to stdout, but the Bun-compiled binary does not
372 // flush more than one 64KB pipe buffer to a non-TTY stdout, so the piped output arrives
373 // truncated and unparseable — which degrades to an empty skill list and poisons the workspace
374 // snapshot the `$` picker reads.
375 const loadWorkspaceInventory = (
376 client: Parameters<typeof OpenCodeRuntime.loadOpenCodeCommands>[0],
377 ) =>
378 Effect.all(
379 {
380 skills: openCodeRuntime.loadOpenCodeSkills(client),
381 commandInventory: OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
382 Effect.timeoutOption("10 seconds"),
383 Effect.map((commands) => ({
384 commands: Option.getOrElse(commands, () => []),
385 slashCommandsPending: Option.isNone(commands),
386 })),
387 // SDK errors leave command discovery to the provider's health.
388 Effect.orElseSucceed(() => ({
389 commands: [],
390 slashCommandsPending: undefined,
391 })),
392 ),
393 },
394 { concurrency: "unbounded" },
395 ).pipe(
396 Effect.map(({ skills, commandInventory }) => ({
397 skills,
398 ...commandInventory,
399 })),
400 );
401 const loadWorkspaceForCwd = (cwd: string) =>
402 effectiveConfig.serverUrl.trim().length > 0
403 ? Effect.scoped(
404 Effect.gen(function* () {
405 const server = yield* openCodeRuntime.connectToOpenCodeServer({
406 binaryPath: effectiveConfig.binaryPath,
407 directory: cwd,
408 serverUrl: effectiveConfig.serverUrl,
409 ...(effectiveConfig.serverPassword
410 ? { serverPassword: effectiveConfig.serverPassword }
411 : {}),
412 environment: processEnv,
413 });
414 const client = openCodeRuntime.createOpenCodeSdkClient({
415 baseUrl: server.url,
416 directory: cwd,
417 ...(effectiveConfig.serverPassword
418 ? { serverPassword: effectiveConfig.serverPassword }
419 : {}),
420 });
421 return yield* loadWorkspaceInventory(client);
422 }),
423 )
424 : serverOwner.withServer((server) =>
425 loadWorkspaceInventory(
426 openCodeRuntime.createOpenCodeSdkClient({
427 baseUrl: server.url,
428 directory: cwd,
429 ...(server.serverPassword !== undefined
430 ? { serverPassword: server.serverPassword }
431 : {}),
432 }),
433 ),
434 );
435​
436 const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig);
437 const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>({
438 resolveMaintenance,
439 getSettings: snapshotSettings.getSettings,
440 streamSettings: snapshotSettings.streamSettings,
441 haveSettingsChanged: haveProviderSnapshotSettingsChanged,
442 checkProviderOnSettingsChange: () => false,
443 refreshOnInterval: false,
444 initialSnapshot: (settings) =>
445 makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),
446 checkProvider,
447 enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>
448 resolveMaintenance().pipe(
449 Effect.flatMap((maintenanceCapabilities) =>
450 enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {
451 enableProviderUpdateChecks: settings.enableProviderUpdateChecks,
452 }),
453 ),
454 Effect.provideService(HttpClient.HttpClient, httpClient),
455 Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions),
456 Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),
457 ),
458 }).pipe(
459 Effect.mapError(
460 (cause) =>
461 new ProviderDriverError({
462 driver: DRIVER_KIND,
463 instanceId,
464 detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,
465 cause,
466 }),
467 ),
468 );
469​
470 return {
471 instanceId,
472 driverKind: DRIVER_KIND,
473 continuationIdentity,
474 displayName,
475 accentColor,
476 enabled,
477 snapshot,
478 snapshotForCwd: (cwd) =>
479 !effectiveConfig.enabled
480 ? snapshot.getSnapshot
481 : byOpenCodeRuntime(runtimeProbe.get, {
482 v2: Effect.all([
483 snapshot.getSnapshot,
484 listOpenCode2Workspace(cwd).pipe(
485 Effect.timeout("20 seconds"),
486 Effect.mapError(
487 (cause) =>
488 new ProviderDriverError({
489 driver: DRIVER_KIND,
490 instanceId,
491 detail: `Failed to list OpenCode commands and skills for '${cwd}'`,
492 cause,
493 }),
494 ),
495 ),
496 ]).pipe(
497 Effect.map(([machineSnapshot, { skills, commands }]) => ({
498 ...machineSnapshot,
499 skills: openCode2SkillsToServerProviderSkills(skills),
500 slashCommands: openCode2CommandsToServerProviderSlashCommands(commands),
501 // A finished scan lists at least the built-ins. None means it
502 // timed out, so the registry decides from the provider's health.
503 slashCommandsPending: commands.length > 0 ? false : undefined,
504 })),
505 ),
506 v1: Effect.all([
507 snapshot.getSnapshot,
508 loadWorkspaceForCwd(cwd).pipe(Effect.timeout("20 seconds")),
509 ]).pipe(
510 Effect.map(([machineSnapshot, { skills, commands, slashCommandsPending }]) => ({
511 ...machineSnapshot,
512 skills: openCodeSkillsToServerProviderSkills(skills),
513 slashCommands: openCodeCommandsToServerProviderSlashCommands(commands),
514 slashCommandsPending,
515 })),
516 Effect.mapError(
517 (cause) =>
518 new ProviderDriverError({
519 driver: DRIVER_KIND,
520 instanceId,
521 detail: `Failed to probe OpenCode commands and skills for '${cwd}'`,
522 cause,
523 }),
524 ),
525 ),
526 }),
527 orchestrationAdapter,
528 textGeneration,
529 } satisfies ProviderInstance;
530 }),
531};