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

OpenCode2TextGeneration.ts

221 lines8.6 KB

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