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

textGeneration.ts

202 lines7.8 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 = (
36 connection: OpenCode2Server.OpenCode2Connection,
37 input: TextGenerationOperations.Request<Schema.Top>,
38) =>
39 Effect.gen(function* () {
40 const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;
41 const { client } = connection;
42 const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
43 if (parsed === null) {
44 return yield* new TextGenerationError({
45 operation: input.operation,
46 detail: "OpenCode model selection must use the 'provider/model' format.",
47 });
48 }
49 const variant = getModelSelectionStringOptionValue(input.modelSelection, "variant");
50 const outcome = yield* Deferred.make<Outcome>();
51 let sessionId: string | undefined;
52 const texts = new Map<string, string>();
53 // Subscribed first: the stream is volatile, and the reply arrives on it.
54 const events = yield* connection.events;
55 yield* events.pipe(
56 Stream.runForEach((event) => {
57 // An execution end a newer server sent in a shape this build cannot
58 // read still ends the generation, as it ends a turn in the adapter.
59 if (event.type === "unreadable.execution.ended") {
60 if (event.sessionID !== sessionId) return Effect.void;
61 return Deferred.succeed(
62 outcome,
63 event.executionType === "session.execution.succeeded"
64 ? { _tag: "text", text: [...texts.values()].join("\n").trim() }
65 : {
66 _tag: "failed",
67 detail: "OpenCode ended the generation in a way this version cannot read.",
68 cause: event,
69 },
70 );
71 }
72 if (
73 sessionId === undefined ||
74 !("data" in event) ||
75 !("sessionID" in event.data) ||
76 event.data.sessionID !== sessionId
77 ) {
78 return Effect.void;
79 }
80 switch (event.type) {
81 case "session.text.ended":
82 texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);
83 return Effect.void;
84 case "permission.asked":
85 return client.permission
86 .reply({
87 sessionID: event.data.sessionID,
88 requestID: event.data.id,
89 decision: "reject",
90 message: "Tools are not available while generating text.",
91 })
92 .pipe(Effect.ignore({ log: true }));
93 case "session.execution.succeeded":
94 return Deferred.succeed(outcome, {
95 _tag: "text",
96 text: [...texts.values()].join("\n").trim(),
97 });
98 case "session.execution.failed":
99 return Deferred.succeed(outcome, {
100 _tag: "failed",
101 detail: "OpenCode could not generate the text.",
102 cause: event.data.error,
103 });
104 case "session.execution.interrupted":
105 return Deferred.succeed(outcome, {
106 _tag: "failed",
107 detail: "OpenCode stopped the generation.",
108 });
109 default:
110 return Effect.void;
111 }
112 }),
113 // The reply only arrives on this stream, so a lost stream ends the wait.
114 Effect.exit,
115 Effect.flatMap((exit) =>
116 Deferred.succeed(outcome, {
117 _tag: "failed",
118 detail: "The OpenCode event stream was lost.",
119 cause: exit,
120 }),
121 ),
122 Effect.forkScoped,
123 );
124 const session = yield* client.session.create({
125 title: `T3 Code ${input.operation}`,
126 location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
127 model: Model.Ref.make({
128 providerID: Provider.ID.make(parsed.providerID),
129 id: Model.ID.make(parsed.modelID),
130 ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
131 }),
132 permissions: GENERATION_PERMISSIONS,
133 });
134 sessionId = session.id;
135 yield* Effect.addFinalizer(() =>
136 client.session
137 .remove({ sessionID: session.id })
138 .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
139 );
140 const images = (input.attachments ?? []).flatMap((attachment) => {
141 if (attachment.type !== "image") return [];
142 const path = resolveAttachmentPath(attachment);
143 return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];
144 });
145 yield* client.session.prompt({
146 sessionID: session.id,
147 text: input.prompt,
148 ...(images.length === 0 ? {} : { files: images }),
149 });
150 const result = yield* Deferred.await(outcome).pipe(
151 Effect.timeoutOrElse({
152 duration: GENERATION_TIMEOUT,
153 orElse: () =>
154 client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(
155 Effect.ignore,
156 Effect.as<Outcome>({
157 _tag: "failed",
158 detail: "OpenCode did not finish generating in time.",
159 }),
160 ),
161 }),
162 );
163 if (result._tag === "failed") {
164 return yield* new TextGenerationError({
165 operation: input.operation,
166 detail: result.detail,
167 ...(result.cause === undefined ? {} : { cause: result.cause }),
168 });
169 }
170 if (result.text.length === 0) {
171 return yield* new TextGenerationError({
172 operation: input.operation,
173 detail: "OpenCode returned empty output.",
174 });
175 }
176 return result.text;
177 }).pipe(Effect.scoped);
178​
179export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
180 const server = yield* OpenCode2Server.OpenCode2Server;
181 const host = yield* ProviderHost.ProviderHost;
182 const run: TextGenerationOperations.Runner = (input) =>
183 server
184 .withConnection((connection) => runOnServer(connection, input))
185 .pipe(
186 Effect.provideService(ProviderHost.ProviderHost, host),
187 Effect.mapError((cause) =>
188 isTextGenerationError(cause)
189 ? cause
190 : new TextGenerationError({
191 operation: input.operation,
192 detail: "OpenCode text generation failed.",
193 cause,
194 }),
195 ),
196 Effect.flatMap((raw) => TextGenerationOperations.decodeJsonReply(input, "OpenCode", raw)),
197 );
198 return TextGenerationOperations.fromRunner(
199 "OpenCode2TextGeneration",
200 TextGenerationOperations.withoutInvestigation("OpenCode", run),
201 );
202});