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

OpenCodeTextGeneration.ts

620 lines21.2 KB

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