Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Exit from "effect/Exit";
3import * as Fiber from "effect/Fiber";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6import * as Semaphore from "effect/Semaphore";
7
8import {
9 NonNegativeInt,
10 TextGenerationError,
11 type ChatAttachment,
12 type ModelSelection,
13 type OpenCodeSettings,
14} from "@t3tools/contracts";
15import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
16import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
17import { extractJsonObject } from "@t3tools/shared/schemaJson";
18import { sanitizeTerminalValue } from "@t3tools/shared/stripTerminalEscapes";
19
20import * as ServerConfig from "../config.ts";
21import { resolveAttachmentPath } from "../attachmentStore.ts";
22import {
23 buildBranchNamePrompt,
24 buildCommitMessagePrompt,
25 buildPrContentPrompt,
26 buildThreadTitlePrompt,
27} from "./TextGenerationPrompts.ts";
28import * as TextGeneration from "./TextGeneration.ts";
29import {
30 sanitizeCommitSubject,
31 sanitizePrTitle,
32 sanitizeThreadTitle,
33} from "./TextGenerationUtils.ts";
34import * as OpenCodeRuntime from "../provider/opencodeRuntime.ts";
35
36const OPENCODE_TEXT_GENERATION_IDLE_TTL = "30 seconds";
37
38const OpenCodeTextGenerationOperation = Schema.Literals([
39 "generateCommitMessage",
40 "generatePrContent",
41 "generateBranchName",
42 "generateThreadTitle",
43]);
44
45type OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;
46
47const openCodeTextGenerationErrorContext = {
48 operation: OpenCodeTextGenerationOperation,
49 cwd: Schema.String,
50};
51
52export class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(
53 "OpenCodeTextGenerationSessionRequestError",
54 {
55 ...openCodeTextGenerationErrorContext,
56 cause: Schema.Defect(),
57 },
58) {
59 override get message(): string {
60 return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;
61 }
62}
63
64export class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(
65 "OpenCodeTextGenerationSessionPayloadError",
66 openCodeTextGenerationErrorContext,
67) {
68 override get message(): string {
69 return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;
70 }
71}
72
73const openCodePromptErrorContext = {
74 ...openCodeTextGenerationErrorContext,
75 sessionId: Schema.String,
76 providerId: Schema.String,
77 modelId: Schema.String,
78};
79
80export class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(
81 "OpenCodeTextGenerationPromptRequestError",
82 {
83 ...openCodePromptErrorContext,
84 cause: Schema.Defect(),
85 },
86) {
87 override get message(): string {
88 return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;
89 }
90}
91
92export class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(
93 "OpenCodeTextGenerationPromptResponseError",
94 {
95 ...openCodePromptErrorContext,
96 providerErrorName: Schema.optional(Schema.String),
97 providerMessage: Schema.String,
98 },
99) {
100 override get message(): string {
101 const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : "";
102 return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;
103 }
104}
105
106export class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(
107 "OpenCodeTextGenerationEmptyOutputError",
108 {
109 ...openCodePromptErrorContext,
110 responsePartCount: NonNegativeInt,
111 textPartCount: NonNegativeInt,
112 },
113) {
114 override get message(): string {
115 return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;
116 }
117}
118
119interface OpenCodePromptFailure {
120 readonly name?: string;
121 readonly message: string;
122}
123
124interface OpenCodeTextPart {
125 readonly type: "text";
126 readonly text: string;
127}
128
129function getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {
130 if (!error || typeof error !== "object") {
131 return null;
132 }
133
134 const name =
135 "name" in error && typeof error.name === "string" && error.name.trim().length > 0
136 ? error.name.trim()
137 : undefined;
138 const message =
139 "data" in error &&
140 error.data &&
141 typeof error.data === "object" &&
142 "message" in error.data &&
143 typeof error.data.message === "string"
144 ? error.data.message.trim()
145 : "";
146 if (message.length > 0) {
147 return {
148 ...(name ? { name } : {}),
149 message,
150 };
151 }
152
153 if (name) {
154 return { name, message: name };
155 }
156
157 return null;
158}
159
160function isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {
161 return (
162 part !== null &&
163 typeof part === "object" &&
164 "type" in part &&
165 part.type === "text" &&
166 "text" in part &&
167 typeof part.text === "string"
168 );
169}
170
171function getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {
172 return (parts ?? [])
173 .filter(isOpenCodeTextPart)
174 .map((part) => part.text)
175 .join("")
176 .trim();
177}
178
179interface SharedOpenCodeTextGenerationServerState {
180 server: OpenCodeRuntime.OpenCodeServerProcess | null;
181 /**
182 * The scope that owns the shared server's lifetime. Closing this scope
183 * terminates the OpenCode child process and interrupts any fibers the
184 * runtime forked during startup. We don't hold a `close()` function on
185 * the server handle anymore — the scope is the only lifecycle handle.
186 */
187 serverScope: Scope.Closeable | null;
188 binaryPath: string | null;
189 activeRequests: number;
190 idleCloseFiber: Fiber.Fiber<void, never> | null;
191}
192
193export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration")(function* (
194 openCodeSettings: OpenCodeSettings,
195 environment?: NodeJS.ProcessEnv,
196) {
197 const serverConfig = yield* ServerConfig.ServerConfig;
198 const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;
199 const resolvedEnvironment = environment ?? process.env;
200 const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
201 Scope.close(scope, Exit.void),
202 );
203 const sharedServerMutex = yield* Semaphore.make(1);
204 const sharedServerState: SharedOpenCodeTextGenerationServerState = {
205 server: null,
206 serverScope: null,
207 binaryPath: null,
208 activeRequests: 0,
209 idleCloseFiber: null,
210 };
211
212 const closeSharedServer = Effect.fn("closeSharedServer")(function* () {
213 const scope = sharedServerState.serverScope;
214 sharedServerState.server = null;
215 sharedServerState.serverScope = null;
216 sharedServerState.binaryPath = null;
217 if (scope !== null) {
218 yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);
219 }
220 });
221
222 const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
223 const idleCloseFiber = sharedServerState.idleCloseFiber;
224 sharedServerState.idleCloseFiber = null;
225 if (idleCloseFiber !== null) {
226 yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
227 }
228 });
229
230 const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
231 server: OpenCodeRuntime.OpenCodeServerProcess,
232 ) {
233 yield* cancelIdleCloseFiber();
234 const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(
235 Effect.andThen(
236 sharedServerMutex.withPermit(
237 Effect.gen(function* () {
238 if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
239 return;
240 }
241 sharedServerState.idleCloseFiber = null;
242 yield* closeSharedServer();
243 }),
244 ),
245 ),
246 Effect.forkIn(idleFiberScope),
247 );
248 sharedServerState.idleCloseFiber = fiber;
249 });
250
251 const acquireSharedServer = (input: {
252 readonly binaryPath: string;
253 readonly operation:
254 | "generateCommitMessage"
255 | "generatePrContent"
256 | "generateBranchName"
257 | "generateThreadTitle";
258 }) =>
259 sharedServerMutex.withPermit(
260 Effect.gen(function* () {
261 yield* cancelIdleCloseFiber();
262
263 const existingServer = sharedServerState.server;
264 if (existingServer !== null) {
265 if (
266 sharedServerState.binaryPath !== input.binaryPath &&
267 sharedServerState.activeRequests === 0
268 ) {
269 yield* closeSharedServer();
270 } else {
271 if (sharedServerState.binaryPath !== input.binaryPath) {
272 yield* Effect.logWarning(
273 "OpenCode shared server binary path mismatch: requested " +
274 input.binaryPath +
275 " but active server uses " +
276 sharedServerState.binaryPath +
277 "; reusing existing server because there are active requests",
278 );
279 }
280 sharedServerState.activeRequests += 1;
281 return existingServer;
282 }
283 }
284
285 // Create a fresh scope that owns this shared server. The runtime
286 // will attach its child-process and fiber finalizers to this scope;
287 // closing it kills the server and interrupts those fibers.
288 //
289 // The `Scope.make` / spawn / record-or-close transitions run inside
290 // `uninterruptibleMask` so an interrupt arriving between any two
291 // steps can't orphan the scope (and the child process attached to
292 // it) before we either close it on failure or hand ownership to
293 // `sharedServerState`. `restore` keeps the actual spawn
294 // interruptible; an interrupt during the spawn is captured by
295 // `Effect.exit` and drives us through the failure branch that
296 // closes the fresh scope.
297 return yield* Effect.uninterruptibleMask((restore) =>
298 Effect.gen(function* () {
299 const serverScope = yield* Scope.make();
300 const startedExit = yield* Effect.exit(
301 restore(
302 openCodeRuntime
303 .startOpenCodeServerProcess({
304 binaryPath: input.binaryPath,
305 environment: resolvedEnvironment,
306 })
307 .pipe(
308 Effect.provideService(Scope.Scope, serverScope),
309 Effect.mapError(
310 (cause) =>
311 new TextGenerationError({
312 operation: input.operation,
313 detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
314 cause,
315 }),
316 ),
317 ),
318 ),
319 );
320 if (startedExit._tag === "Failure") {
321 yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);
322 return yield* Effect.failCause(startedExit.cause);
323 }
324
325 const server = startedExit.value;
326 sharedServerState.server = server;
327 sharedServerState.serverScope = serverScope;
328 sharedServerState.binaryPath = input.binaryPath;
329 sharedServerState.activeRequests = 1;
330 return server;
331 }),
332 );
333 }),
334 );
335
336 const releaseSharedServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>
337 sharedServerMutex.withPermit(
338 Effect.gen(function* () {
339 if (sharedServerState.server !== server) {
340 return;
341 }
342 sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
343 if (sharedServerState.activeRequests === 0) {
344 yield* scheduleIdleClose(server);
345 }
346 }),
347 );
348
349 // Module-level finalizer: on layer shutdown, cancel the idle close fiber
350 // and close the shared server scope. Consumers therefore cannot leak
351 // the shared OpenCode server by forgetting to call anything.
352 yield* Effect.addFinalizer(() =>
353 sharedServerMutex.withPermit(
354 Effect.gen(function* () {
355 yield* cancelIdleCloseFiber();
356 sharedServerState.activeRequests = 0;
357 yield* closeSharedServer();
358 }),
359 ),
360 );
361
362 const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
363 readonly operation: OpenCodeTextGenerationOperation;
364 readonly cwd: string;
365 readonly prompt: string;
366 readonly outputSchemaJson: S;
367 readonly modelSelection: ModelSelection;
368 readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
369 }) {
370 const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
371 if (!parsedModel) {
372 return yield* new TextGenerationError({
373 operation: input.operation,
374 detail: "OpenCode model selection must use the 'provider/model' format.",
375 });
376 }
377
378 const fileParts = OpenCodeRuntime.toOpenCodeFileParts({
379 attachments: input.attachments,
380 resolveAttachmentPath: (attachment) =>
381 resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
382 });
383
384 const runAgainstServer = Effect.fn("runOpenCodeJson.runAgainstServer")(
385 function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, "url">) {
386 const client = openCodeRuntime.createOpenCodeSdkClient({
387 baseUrl: server.url,
388 directory: input.cwd,
389 ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword
390 ? { serverPassword: openCodeSettings.serverPassword }
391 : {}),
392 });
393 const session = yield* Effect.tryPromise({
394 try: () =>
395 client.session.create({
396 title: `T3 Code ${input.operation}`,
397 permission: [{ permission: "*", pattern: "*", action: "deny" }],
398 }),
399 catch: (cause) =>
400 new OpenCodeTextGenerationSessionRequestError({
401 operation: input.operation,
402 cwd: input.cwd,
403 cause,
404 }),
405 });
406 if (!session.data) {
407 return yield* new OpenCodeTextGenerationSessionPayloadError({
408 operation: input.operation,
409 cwd: input.cwd,
410 });
411 }
412 const rawAgent = getModelSelectionStringOptionValue(input.modelSelection, "agent");
413 const rawVariant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
414 const selectedAgent = rawAgent ? sanitizeTerminalValue(rawAgent) : undefined;
415 const selectedVariant = rawVariant ? sanitizeTerminalValue(rawVariant) : undefined;
416 const promptContext = {
417 operation: input.operation,
418 cwd: input.cwd,
419 sessionId: session.data.id,
420 providerId: parsedModel.providerID,
421 modelId: parsedModel.modelID,
422 };
423
424 const result = yield* Effect.tryPromise({
425 try: () =>
426 client.session.prompt({
427 sessionID: session.data.id,
428 model: parsedModel,
429 ...(selectedAgent ? { agent: selectedAgent } : {}),
430 ...(selectedVariant ? { variant: selectedVariant } : {}),
431 parts: [{ type: "text", text: input.prompt }, ...fileParts],
432 }),
433 catch: (cause) =>
434 new OpenCodeTextGenerationPromptRequestError({
435 ...promptContext,
436 cause,
437 }),
438 });
439 const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);
440 if (promptFailure) {
441 return yield* new OpenCodeTextGenerationPromptResponseError({
442 ...promptContext,
443 ...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),
444 providerMessage: promptFailure.message,
445 });
446 }
447 const responseParts = result.data?.parts ?? [];
448 const rawText = getOpenCodeTextResponse(responseParts);
449 if (rawText.length === 0) {
450 return yield* new OpenCodeTextGenerationEmptyOutputError({
451 ...promptContext,
452 responsePartCount: responseParts.length,
453 textPartCount: responseParts.filter(isOpenCodeTextPart).length,
454 });
455 }
456 return rawText;
457 },
458 Effect.catchTags({
459 OpenCodeTextGenerationSessionRequestError: (cause) =>
460 Effect.fail(
461 new TextGenerationError({
462 operation: cause.operation,
463 detail: "OpenCode session.create request failed.",
464 cause,
465 }),
466 ),
467 OpenCodeTextGenerationSessionPayloadError: (cause) =>
468 Effect.fail(
469 new TextGenerationError({
470 operation: cause.operation,
471 detail: "OpenCode session.create returned no session payload.",
472 cause,
473 }),
474 ),
475 OpenCodeTextGenerationPromptRequestError: (cause) =>
476 Effect.fail(
477 new TextGenerationError({
478 operation: cause.operation,
479 detail: "OpenCode session.prompt request failed.",
480 cause,
481 }),
482 ),
483 OpenCodeTextGenerationPromptResponseError: (cause) =>
484 Effect.fail(
485 new TextGenerationError({
486 operation: cause.operation,
487 detail: cause.providerMessage,
488 cause,
489 }),
490 ),
491 OpenCodeTextGenerationEmptyOutputError: (cause) =>
492 Effect.fail(
493 new TextGenerationError({
494 operation: cause.operation,
495 detail: "OpenCode returned empty output.",
496 cause,
497 }),
498 ),
499 }),
500 );
501
502 const rawOutput =
503 openCodeSettings.serverUrl.length > 0
504 ? yield* runAgainstServer({ url: openCodeSettings.serverUrl })
505 : yield* Effect.acquireUseRelease(
506 acquireSharedServer({
507 binaryPath: openCodeSettings.binaryPath,
508 operation: input.operation,
509 }),
510 runAgainstServer,
511 releaseSharedServer,
512 );
513
514 const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));
515 return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(
516 Effect.catchTags({
517 SchemaError: (cause) =>
518 Effect.fail(
519 new TextGenerationError({
520 operation: input.operation,
521 detail: "OpenCode returned invalid structured output.",
522 cause,
523 }),
524 ),
525 }),
526 );
527 });
528
529 const generateCommitMessage: TextGeneration.TextGeneration["Service"]["generateCommitMessage"] =
530 Effect.fn("OpenCodeTextGeneration.generateCommitMessage")(function* (input) {
531 const { prompt, outputSchema } = buildCommitMessagePrompt({
532 branch: input.branch,
533 stagedSummary: input.stagedSummary,
534 stagedPatch: input.stagedPatch,
535 includeBranch: input.includeBranch === true,
536 policy: input.policy,
537 });
538 const generated = yield* runOpenCodeJson({
539 operation: "generateCommitMessage",
540 cwd: input.cwd,
541 prompt,
542 outputSchemaJson: outputSchema,
543 modelSelection: input.modelSelection,
544 });
545
546 return {
547 subject: sanitizeCommitSubject(generated.subject),
548 body: generated.body.trim(),
549 ...("branch" in generated && typeof generated.branch === "string"
550 ? { branch: sanitizeFeatureBranchName(generated.branch) }
551 : {}),
552 };
553 });
554
555 const generatePrContent: TextGeneration.TextGeneration["Service"]["generatePrContent"] =
556 Effect.fn("OpenCodeTextGeneration.generatePrContent")(function* (input) {
557 const { prompt, outputSchema } = buildPrContentPrompt({
558 baseBranch: input.baseBranch,
559 headBranch: input.headBranch,
560 commitSummary: input.commitSummary,
561 diffSummary: input.diffSummary,
562 diffPatch: input.diffPatch,
563 policy: input.policy,
564 changeRequestTemplate: input.changeRequestTemplate,
565 });
566 const generated = yield* runOpenCodeJson({
567 operation: "generatePrContent",
568 cwd: input.cwd,
569 prompt,
570 outputSchemaJson: outputSchema,
571 modelSelection: input.modelSelection,
572 });
573
574 return {
575 title: sanitizePrTitle(generated.title),
576 body: generated.body.trim(),
577 };
578 });
579
580 const generateBranchName: TextGeneration.TextGeneration["Service"]["generateBranchName"] =
581 Effect.fn("OpenCodeTextGeneration.generateBranchName")(function* (input) {
582 const { prompt, outputSchema } = buildBranchNamePrompt({
583 message: input.message,
584 attachments: input.attachments,
585 });
586 const generated = yield* runOpenCodeJson({
587 operation: "generateBranchName",
588 cwd: input.cwd,
589 prompt,
590 outputSchemaJson: outputSchema,
591 modelSelection: input.modelSelection,
592 attachments: input.attachments,
593 });
594
595 return {
596 branch: sanitizeBranchFragment(generated.branch),
597 };
598 });
599
600 const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =
601 Effect.fn("OpenCodeTextGeneration.generateThreadTitle")(function* (input) {
602 const { prompt, outputSchema } = buildThreadTitlePrompt({
603 message: input.message,
604 previousTitle: input.previousTitle,
605 attachments: input.attachments,
606 });
607 const generated = yield* runOpenCodeJson({
608 operation: "generateThreadTitle",
609 cwd: input.cwd,
610 prompt,
611 outputSchemaJson: outputSchema,
612 modelSelection: input.modelSelection,
613 attachments: input.attachments,
614 });
615
616 return {
617 title: sanitizeThreadTitle(generated.title),
618 };
619 });
620
621 return {
622 generateCommitMessage,
623 generatePrContent,
624 generateBranchName,
625 generateThreadTitle,
626 } satisfies TextGeneration.TextGeneration["Service"];
627});