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

OpenCodeTextGeneration.ts

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