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

textGeneration.ts

201 lines7.5 KB

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