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

OpenCodeTextGeneration.ts

511 lines16.7 KB

1import { Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
2import * as Semaphore from "effect/Semaphore";
3​
4import {
5 TextGenerationError,
6 type ChatAttachment,
7 type OpenCodeModelSelection,
8} from "@t3tools/contracts";
9import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
10import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
11​
12import { ServerConfig } from "../../config.ts";
13import { resolveAttachmentPath } from "../../attachmentStore.ts";
14import { ServerSettingsService } from "../../serverSettings.ts";
15import {
16 buildBranchNamePrompt,
17 buildCommitMessagePrompt,
18 buildPrContentPrompt,
19 buildThreadTitlePrompt,
20} from "../Prompts.ts";
21import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
22import {
23 extractJsonObject,
24 sanitizeCommitSubject,
25 sanitizePrTitle,
26 sanitizeThreadTitle,
27} from "../Utils.ts";
28import {
29 OpenCodeRuntime,
30 type OpenCodeServerConnection,
31 type OpenCodeServerProcess,
32 openCodeRuntimeErrorDetail,
33 parseOpenCodeModelSlug,
34 toOpenCodeFileParts,
35} from "../../provider/opencodeRuntime.ts";
36​
37const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
38​
39function getOpenCodePromptErrorMessage(error: unknown): string | null {
40 if (!error || typeof error !== "object") {
41 return null;
42 }
43​
44 const message =
45 "data" in error &&
46 error.data &&
47 typeof error.data === "object" &&
48 "message" in error.data &&
49 typeof error.data.message === "string"
50 ? error.data.message.trim()
51 : "";
52 if (message.length > 0) {
53 return message;
54 }
55​
56 if ("name" in error && typeof error.name === "string") {
57 const name = error.name.trim();
58 return name.length > 0 ? name : null;
59 }
60​
61 return null;
63​
64function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
65 return (parts ?? [])
66 .flatMap((part) => {
67 if (!part || typeof part !== "object") {
68 return [];
69 }
70 if (!("type" in part) || part.type !== "text") {
71 return [];
72 }
73 if (!("text" in part) || typeof part.text !== "string") {
74 return [];
75 }
76 return [part.text];
77 })
78 .join("")
79 .trim();
81​
82interface SharedOpenCodeTextGenerationServerState {
83 server: OpenCodeServerProcess | null;
84 /**
85 * The scope that owns the shared server's lifetime. Closing this scope
86 * terminates the OpenCode child process and interrupts any fibers the
87 * runtime forked during startup. We don't hold a `close()` function on
88 * the server handle anymore — the scope is the only lifecycle handle.
89 */
90 serverScope: Scope.Closeable | null;
91 binaryPath: string | null;
92 activeRequests: number;
93 idleCloseFiber: Fiber.Fiber<void, never> | null;
95​
96const makeOpenCodeTextGeneration = Effect.gen(function* () {
97 const serverConfig = yield* ServerConfig;
98 const serverSettingsService = yield* ServerSettingsService;
99 const openCodeRuntime = yield* OpenCodeRuntime;
100 const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
101 Scope.close(scope, Exit.void),
102 );
103 const sharedServerMutex = yield* Semaphore.make(1);
104 const sharedServerState: SharedOpenCodeTextGenerationServerState = {
105 server: null,
106 serverScope: null,
107 binaryPath: null,
108 activeRequests: 0,
109 idleCloseFiber: null,
110 };
111​
112 const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
113 const scope = sharedServerState.serverScope;
114 sharedServerState.server = null;
115 sharedServerState.serverScope = null;
116 sharedServerState.binaryPath = null;
117 if (scope !== null) {
118 yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
119 }
120 });
121​
122 const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
123 const idleCloseFiber = sharedServerState.idleCloseFiber;
124 sharedServerState.idleCloseFiber = null;
125 if (idleCloseFiber !== null) {
126 yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
127 }
128 });
129​
130 const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
131 server: OpenCodeServerProcess,
132 ) {
133 yield* cancelIdleCloseFiber();
134 const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
135 Effect.andThen(
136 sharedServerMutex.withPermit(
137 Effect.gen(function* () {
138 if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
139 return;
140 }
141 sharedServerState.idleCloseFiber = null;
142 yield* closeSharedServer();
143 }),
144 ),
145 ),
146 Effect.forkIn(idleFiberScope),
147 );
148 sharedServerState.idleCloseFiber = fiber;
149 });
150​
151 const acquireSharedServer = (input: {
152 readonly binaryPath: string;
153 readonly operation:
154 | "generateCommitMessage"
155 | "generatePrContent"
156 | "generateBranchName"
157 | "generateThreadTitle";
158 }) =>
159 sharedServerMutex.withPermit(
160 Effect.gen(function* () {
161 yield* cancelIdleCloseFiber();
162​
163 const existingServer = sharedServerState.server;
164 if (existingServer !== null) {
165 if (
166 sharedServerState.binaryPath !== input.binaryPath &&
167 sharedServerState.activeRequests === 0
168 ) {
169 yield* closeSharedServer();
170 } else {
171 if (sharedServerState.binaryPath !== input.binaryPath) {
172 yield* Effect.logWarning(
173 "OpenCode shared server binary path mismatch: requested " +
174 input.binaryPath +
175 " but active server uses " +
176 sharedServerState.binaryPath +
177 "; reusing existing server because there are active requests",
178 );
179 }
180 sharedServerState.activeRequests += 1;
181 return existingServer;
182 }
183 }
184​
185 // Create a fresh scope that owns this shared server. The runtime
186 // will attach its child-process and fiber finalizers to this scope;
187 // closing it kills the server and interrupts those fibers.
188 //
189 // The `Scope.make` / spawn / record-or-close transitions run inside
190 // `uninterruptibleMask` so an interrupt arriving between any two
191 // steps can't orphan the scope (and the child process attached to
192 // it) before we either close it on failure or hand ownership to
193 // `sharedServerState`. `restore` keeps the actual spawn
194 // interruptible; an interrupt during the spawn is captured by
195 // `Effect.exit` and drives us through the failure branch that
196 // closes the fresh scope.
197 return yield* Effect.uninterruptibleMask((restore) =>
198 Effect.gen(function* () {
199 const serverScope = yield* Scope.make();
200 const startedExit = yield* Effect.exit(
201 restore(
202 openCodeRuntime
203 .startOpenCodeServerProcess({
204 binaryPath: input.binaryPath,
205 })
206 .pipe(
207 Effect.provideService(Scope.Scope, serverScope),
208 Effect.mapError(
209 (cause) =>
210 new TextGenerationError({
211 operation: input.operation,
212 detail: openCodeRuntimeErrorDetail(cause),
213 cause,
214 }),
215 ),
216 ),
217 ),
218 );
219 if (startedExit._tag === "Failure") {
220 yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
221 return yield* Effect.failCause(startedExit.cause);
222 }
223​
224 const server = startedExit.value;
225 sharedServerState.server = server;
226 sharedServerState.serverScope = serverScope;
227 sharedServerState.binaryPath = input.binaryPath;
228 sharedServerState.activeRequests = 1;
229 return server;
230 }),
231 );
232 }),
233 );
234​
235 const releaseSharedServer = (server: OpenCodeServerProcess) =>
236 sharedServerMutex.withPermit(
237 Effect.gen(function* () {
238 if (sharedServerState.server !== server) {
239 return;
240 }
241 sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
242 if (sharedServerState.activeRequests === 0) {
243 yield* scheduleIdleClose(server);
244 }
245 }),
246 );
247​
248 // Module-level finalizer: on layer shutdown, cancel the idle close fiber
249 // and close the shared server scope. Consumers therefore cannot leak
250 // the shared OpenCode server by forgetting to call anything.
251 yield* Effect.addFinalizer(() =>
252 sharedServerMutex.withPermit(
253 Effect.gen(function* () {
254 yield* cancelIdleCloseFiber();
255 sharedServerState.activeRequests = 0;
256 yield* closeSharedServer();
257 }),
258 ),
259 );
260​
261 const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
262 readonly operation:
263 | "generateCommitMessage"
264 | "generatePrContent"
265 | "generateBranchName"
266 | "generateThreadTitle";
267 readonly cwd: string;
268 readonly prompt: string;
269 readonly outputSchemaJson: S;
270 readonly modelSelection: OpenCodeModelSelection;
271 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
272 }) {
273 const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
274 if (!parsedModel) {
275 return yield* new TextGenerationError({
276 operation: input.operation,
277 detail: "OpenCode model selection must use the 'provider/model' format.",
278 });
279 }
280​
281 const settings = yield* serverSettingsService.getSettings.pipe(
282 Effect.map(
283 (value) =>
284 value.providers?.opencode ?? {
285 enabled: true,
286 binaryPath: "opencode",
287 serverUrl: "",
288 serverPassword: "",
289 customModels: [],
290 },
291 ),
292 Effect.orElseSucceed(() => ({
293 enabled: true,
294 binaryPath: "opencode",
295 serverUrl: "",
296 serverPassword: "",
297 customModels: [],
298 })),
299 );
300​
301 const fileParts = toOpenCodeFileParts({
302 attachments: input.attachments,
303 resolveAttachmentPath: (attachment) =>
304 resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
305 });
306​
307 const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
308 Effect.tryPromise({
309 try: async () => {
310 const client = openCodeRuntime.createOpenCodeSdkClient({
311 baseUrl: server.url,
312 directory: input.cwd,
313 ...(settings.serverUrl.length > 0 && settings.serverPassword
314 ? { serverPassword: settings.serverPassword }
315 : {}),
316 });
317 const session = await client.session.create({
318 title: `T3 Code ${input.operation}`,
319 permission: [{ permission: "*", pattern: "*", action: "deny" }],
320 });
321 if (!session.data) {
322 throw new Error("OpenCode session.create returned no session payload.");
323 }
324 const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
325 const selectedVariant = getModelSelectionStringOptionValue(
326 input.modelSelection,
327 "variant",
328 );
329​
330 const result = await client.session.prompt({
331 sessionID: session.data.id,
332 model: parsedModel,
333 ...(selectedAgent ? { agent: selectedAgent } : {}),
334 ...(selectedVariant ? { variant: selectedVariant } : {}),
335 parts: [{ type: "text", text: input.prompt }, ...fileParts],
336 });
337 const info = result.data?.info;
338 const errorMessage = getOpenCodePromptErrorMessage(info?.error);
339 if (errorMessage) {
340 throw new Error(errorMessage);
341 }
342 const rawText = getOpenCodeTextResponse(result.data?.parts);
343 if (rawText.length === 0) {
344 throw new Error("OpenCode returned empty output.");
345 }
346 return rawText;
347 },
348 catch: (cause) =>
349 new TextGenerationError({
350 operation: input.operation,
351 detail: openCodeRuntimeErrorDetail(cause),
352 cause,
353 }),
354 });
355​
356 const rawOutput =
357 settings.serverUrl.length > 0
358 ? yield* runAgainstServer({ url: settings.serverUrl })
359 : yield* Effect.acquireUseRelease(
360 acquireSharedServer({
361 binaryPath: settings.binaryPath,
362 operation: input.operation,
363 }),
364 runAgainstServer,
365 releaseSharedServer,
366 );
367​
368 return yield* Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson))(
369 extractJsonObject(rawOutput),
370 ).pipe(
371 Effect.catchTag("SchemaError", (cause) =>
372 Effect.fail(
373 new TextGenerationError({
374 operation: input.operation,
375 detail: "OpenCode returned invalid structured output.",
376 cause,
377 }),
378 ),
379 ),
380 );
381 });
382​
383 const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
384 "OpenCodeTextGeneration.generateCommitMessage",
385 )(function* (input) {
386 if (input.modelSelection.provider !== "opencode") {
387 return yield* new TextGenerationError({
388 operation: "generateCommitMessage",
389 detail: "Invalid model selection.",
390 });
391 }
392​
393 const { prompt, outputSchema } = buildCommitMessagePrompt({
394 branch: input.branch,
395 stagedSummary: input.stagedSummary,
396 stagedPatch: input.stagedPatch,
397 includeBranch: input.includeBranch === true,
398 });
399 const generated = yield* runOpenCodeJson({
400 operation: "generateCommitMessage",
401 cwd: input.cwd,
402 prompt,
403 outputSchemaJson: outputSchema,
404 modelSelection: input.modelSelection,
405 });
406​
407 return {
408 subject: sanitizeCommitSubject(generated.subject),
409 body: generated.body.trim(),
410 ...("branch" in generated && typeof generated.branch === "string"
411 ? { branch: sanitizeFeatureBranchName(generated.branch) }
412 : {}),
413 };
414 });
415​
416 const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
417 "OpenCodeTextGeneration.generatePrContent",
418 )(function* (input) {
419 if (input.modelSelection.provider !== "opencode") {
420 return yield* new TextGenerationError({
421 operation: "generatePrContent",
422 detail: "Invalid model selection.",
423 });
424 }
425​
426 const { prompt, outputSchema } = buildPrContentPrompt({
427 baseBranch: input.baseBranch,
428 headBranch: input.headBranch,
429 commitSummary: input.commitSummary,
430 diffSummary: input.diffSummary,
431 diffPatch: input.diffPatch,
432 });
433 const generated = yield* runOpenCodeJson({
434 operation: "generatePrContent",
435 cwd: input.cwd,
436 prompt,
437 outputSchemaJson: outputSchema,
438 modelSelection: input.modelSelection,
439 });
440​
441 return {
442 title: sanitizePrTitle(generated.title),
443 body: generated.body.trim(),
444 };
445 });
446​
447 const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
448 "OpenCodeTextGeneration.generateBranchName",
449 )(function* (input) {
450 if (input.modelSelection.provider !== "opencode") {
451 return yield* new TextGenerationError({
452 operation: "generateBranchName",
453 detail: "Invalid model selection.",
454 });
455 }
456​
457 const { prompt, outputSchema } = buildBranchNamePrompt({
458 message: input.message,
459 attachments: input.attachments,
460 });
461 const generated = yield* runOpenCodeJson({
462 operation: "generateBranchName",
463 cwd: input.cwd,
464 prompt,
465 outputSchemaJson: outputSchema,
466 modelSelection: input.modelSelection,
467 attachments: input.attachments,
468 });
469​
470 return {
471 branch: sanitizeBranchFragment(generated.branch),
472 };
473 });
474​
475 const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
476 "OpenCodeTextGeneration.generateThreadTitle",
477 )(function* (input) {
478 if (input.modelSelection.provider !== "opencode") {
479 return yield* new TextGenerationError({
480 operation: "generateThreadTitle",
481 detail: "Invalid model selection.",
482 });
483 }
484​
485 const { prompt, outputSchema } = buildThreadTitlePrompt({
486 message: input.message,
487 attachments: input.attachments,
488 });
489 const generated = yield* runOpenCodeJson({
490 operation: "generateThreadTitle",
491 cwd: input.cwd,
492 prompt,
493 outputSchemaJson: outputSchema,
494 modelSelection: input.modelSelection,
495 attachments: input.attachments,
496 });
497​
498 return {
499 title: sanitizeThreadTitle(generated.title),
500 };
501 });
502​
503 return {
504 generateCommitMessage,
505 generatePrContent,
506 generateBranchName,
507 generateThreadTitle,
508 } satisfies TextGenerationShape;
509});
510​
511export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);