Open History to see the last commit
1/**
2 * Text generation on an OpenCode 2 server. Both of its `generate` endpoints
3 * answer 403 on OpenCode's free tier ("free tier can only be used from within
4 * OpenCode"), so each request runs as a prompt in a temporary session, as 1.x
5 * does, and the session is removed afterwards.
6 *
7 * @module textGeneration/OpenCode2TextGeneration
8 */
9import { AbsolutePath, Location, Model, Provider, Session } from "@opencode/client/effect";
10import { TextGenerationError } from "@t3tools/contracts";
11import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16
17import * as ServerConfig from "../config.ts";
18import { resolveAttachmentPath } from "../attachmentStore.ts";
19import type { OpenCode2Connection } from "../provider/opencode2/OpenCode2Server.ts";
20import * as OpenCode2Server from "../provider/opencode2/OpenCode2Server.ts";
21import { parseOpenCodeModelSlug } from "../provider/opencodeRuntime.ts";
22import * as TextGenerationOperations from "./TextGenerationOperations.ts";
23
24const isTextGenerationError = Schema.is(TextGenerationError);
25
26/** A generation that takes this long is stuck; its session is stopped and removed. */
27const GENERATION_TIMEOUT = "3 minutes";
28
29/**
30 * Nothing in a text generation needs a tool, so every tool asks and T3 is not
31 * there to answer. Denying `shell` or `read` outright gets the whole session
32 * refused on OpenCode's free models, and an ask that is never answered would
33 * hang, so asks are rejected as they arrive.
34 */
35const GENERATION_PERMISSIONS = [{ action: "*", resource: "*", effect: "ask" }] as const;
36
37/** How a generation ended. A failure's cause is the provider's own error, kept out of `detail`. */
38type Outcome =
39 | { readonly _tag: "text"; readonly text: string }
40 | { readonly _tag: "failed"; readonly detail: string; readonly cause?: unknown };
41
42const runOnServer = (
43 connection: OpenCode2Connection,
44 input: TextGenerationOperations.Request<Schema.Top>,
45 attachmentsDir: string,
46) =>
47 Effect.gen(function* () {
48 const { client } = connection;
49 const parsed = parseOpenCodeModelSlug(input.modelSelection.model);
50 if (parsed === null) {
51 return yield* new TextGenerationError({
52 operation: input.operation,
53 detail: "OpenCode model selection must use the 'provider/model' format.",
54 });
55 }
56 const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
57 const outcome = yield* Deferred.make<Outcome>();
58 let sessionId: string | undefined;
59 const texts = new Map<string, string>();
60 // Subscribed first: the stream is volatile, and the reply arrives on it.
61 const events = yield* connection.events;
62 yield* events.pipe(
63 Stream.runForEach((event) => {
64 // An execution end a newer server sent in a shape this build cannot
65 // read still ends the generation, as it ends a turn in the adapter.
66 if (event.type === "unreadable.execution.ended") {
67 if (event.sessionID !== sessionId) return Effect.void;
68 return Deferred.succeed(
69 outcome,
70 event.executionType === "session.execution.succeeded"
71 ? { _tag: "text", text: [...texts.values()].join("\n").trim() }
72 : {
73 _tag: "failed",
74 detail: "OpenCode ended the generation in a way this version cannot read.",
75 cause: event,
76 },
77 );
78 }
79 if (
80 sessionId === undefined ||
81 !("data" in event) ||
82 !("sessionID" in event.data) ||
83 event.data.sessionID !== sessionId
84 ) {
85 return Effect.void;
86 }
87 switch (event.type) {
88 case "session.text.ended":
89 texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);
90 return Effect.void;
91 case "permission.asked":
92 return client.permission
93 .reply({
94 sessionID: event.data.sessionID,
95 requestID: event.data.id,
96 decision: "reject",
97 message: "Tools are not available while generating text.",
98 })
99 .pipe(Effect.ignore({ log: true }));
100 case "session.execution.succeeded":
101 return Deferred.succeed(outcome, {
102 _tag: "text",
103 text: [...texts.values()].join("\n").trim(),
104 });
105 case "session.execution.failed":
106 return Deferred.succeed(outcome, {
107 _tag: "failed",
108 detail: "OpenCode could not generate the text.",
109 cause: event.data.error,
110 });
111 case "session.execution.interrupted":
112 return Deferred.succeed(outcome, {
113 _tag: "failed",
114 detail: "OpenCode stopped the generation.",
115 });
116 default:
117 return Effect.void;
118 }
119 }),
120 // The reply only arrives on this stream, so a lost stream ends the wait.
121 Effect.exit,
122 Effect.flatMap((exit) =>
123 Deferred.succeed(outcome, {
124 _tag: "failed",
125 detail: "The OpenCode event stream was lost.",
126 cause: exit,
127 }),
128 ),
129 Effect.forkScoped,
130 );
131 const session = yield* client.session.create({
132 title: `T3 Code ${input.operation}`,
133 location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
134 model: Model.Ref.make({
135 providerID: Provider.ID.make(parsed.providerID),
136 id: Model.ID.make(parsed.modelID),
137 ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
138 }),
139 permissions: GENERATION_PERMISSIONS,
140 });
141 sessionId = session.id;
142 yield* Effect.addFinalizer(() =>
143 client.session
144 .remove({ sessionID: session.id })
145 .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
146 );
147 const images = (input.attachments ?? []).flatMap((attachment) => {
148 if (attachment.type !== "image") return [];
149 const path = resolveAttachmentPath({ attachmentsDir, attachment });
150 return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];
151 });
152 yield* client.session.prompt({
153 sessionID: session.id,
154 text: input.prompt,
155 ...(images.length === 0 ? {} : { files: images }),
156 });
157 const result = yield* Deferred.await(outcome).pipe(
158 Effect.timeoutOrElse({
159 duration: GENERATION_TIMEOUT,
160 orElse: () =>
161 client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(
162 Effect.ignore,
163 Effect.as<Outcome>({
164 _tag: "failed",
165 detail: "OpenCode did not finish generating in time.",
166 }),
167 ),
168 }),
169 );
170 if (result._tag === "failed") {
171 return yield* new TextGenerationError({
172 operation: input.operation,
173 detail: result.detail,
174 ...(result.cause === undefined ? {} : { cause: result.cause }),
175 });
176 }
177 if (result.text.length === 0) {
178 return yield* new TextGenerationError({
179 operation: input.operation,
180 detail: "OpenCode returned empty output.",
181 });
182 }
183 return result.text;
184 }).pipe(Effect.scoped);
185
186/** Text generation for an instance whose server is OpenCode 2. */
187export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
188 const server = yield* OpenCode2Server.OpenCode2Server;
189 const { attachmentsDir } = yield* ServerConfig.ServerConfig;
190 const run: TextGenerationOperations.Runner = (input) =>
191 server
192 .withConnection((connection) => runOnServer(connection, input, attachmentsDir))
193 .pipe(
194 Effect.mapError((cause) =>
195 isTextGenerationError(cause)
196 ? cause
197 : new TextGenerationError({
198 operation: input.operation,
199 detail: "OpenCode text generation failed.",
200 cause,
201 }),
202 ),
203 Effect.flatMap((raw) => TextGenerationOperations.decodeJsonReply(input, "OpenCode", raw)),
204 );
205 return TextGenerationOperations.fromRunner("OpenCode2TextGeneration", run);
206});