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