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

OpenCodeTextGeneration.ts

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