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

textGeneration.ts

212 lines8.3 KB

1// Generate endpoints return 403 on the free tier; use and remove a temporary prompt session.
2import { AbsolutePath, Location, Model, Provider, Session } from "@opencode/client/effect";
3import { TextGenerationError } from "@t3tools/contracts";
4import * as NodeURL from "node:url";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10​
11import { isProviderNativeImageAttachment } from "@t3tools/provider-core/server/attachmentPrompt";
12import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
13import * as OpenCode2Server from "./OpenCode2Server.ts";
14import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
15import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
16​
17const isTextGenerationError = Schema.is(TextGenerationError);
18​
19const GENERATION_TIMEOUT = "3 minutes";
20​
21// Free models refuse denied read/shell permissions; ask and reject requests as they arrive.
22const GENERATION_PERMISSIONS = [{ action: "*", resource: "*", effect: "ask" }] as const;
23​
24// Provider error text stays in cause, outside detail.
25type Outcome =
26 | { readonly _tag: "text"; readonly text: string }
27 | { readonly _tag: "failed"; readonly detail: string; readonly cause?: unknown };
28​
29const runOnServer = Effect.fn("Opencode2TextGeneration.runOnServer")(function* (
30 connection: OpenCode2Server.OpenCode2Connection,
31 input: TextGenerationOperations.Request<Schema.Top>,
32) {
33 const { resolveAttachmentPath } = yield* ProviderHost.ProviderHost;
34 const fileSystem = yield* FileSystem.FileSystem;
35 const { client } = connection;
36 const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);
37 if (parsed === null) {
38 return yield* new TextGenerationError({
39 operation: input.operation,
40 detail: "OpenCode model selection must use the 'provider/model' format.",
41 });
42 }
43 const variant = OpenCodeRuntime.openCodeVariant(input.modelSelection);
44 const outcome = yield* Deferred.make<Outcome>();
45 let sessionId: string | undefined;
46 const texts = new Map<string, string>();
47 // Subscribed first: the stream is volatile, and the reply arrives on it.
48 const events = yield* connection.events;
49 yield* events.pipe(
50 Stream.runForEach((event) => {
51 // An execution end a newer server sent in a shape this build cannot
52 // read still ends the generation, as it ends a turn in the adapter.
53 if (event.type === "unreadable.execution.ended") {
54 if (event.sessionID !== sessionId) return Effect.void;
55 return Deferred.succeed(
56 outcome,
57 event.executionType === "session.execution.succeeded"
58 ? { _tag: "text", text: [...texts.values()].join("\n").trim() }
59 : {
60 _tag: "failed",
61 detail: "OpenCode ended the generation in a way this version cannot read.",
62 cause: event,
63 },
64 );
65 }
66 if (
67 sessionId === undefined ||
68 !("data" in event) ||
69 !("sessionID" in event.data) ||
70 event.data.sessionID !== sessionId
71 ) {
72 return Effect.void;
73 }
74 switch (event.type) {
75 case "session.text.ended":
76 texts.set(`${event.data.assistantMessageID}:${event.data.ordinal}`, event.data.text);
77 return Effect.void;
78 case "permission.asked":
79 return client.permission
80 .reply({
81 sessionID: event.data.sessionID,
82 requestID: event.data.id,
83 decision: "reject",
84 message: "Tools are not available while generating text.",
85 })
86 .pipe(Effect.ignore({ log: true }));
87 case "session.execution.succeeded":
88 return Deferred.succeed(outcome, {
89 _tag: "text",
90 text: [...texts.values()].join("\n").trim(),
91 });
92 case "session.execution.failed":
93 return Deferred.succeed(outcome, {
94 _tag: "failed",
95 detail: "OpenCode could not generate the text.",
96 cause: event.data.error,
97 });
98 case "session.execution.interrupted":
99 return Deferred.succeed(outcome, {
100 _tag: "failed",
101 detail: "OpenCode stopped the generation.",
102 });
103 default:
104 return Effect.void;
105 }
106 }),
107 // The reply only arrives on this stream, so a lost stream ends the wait.
108 Effect.exit,
109 Effect.flatMap((exit) =>
110 Deferred.succeed(outcome, {
111 _tag: "failed",
112 detail: "The OpenCode event stream was lost.",
113 cause: exit,
114 }),
115 ),
116 Effect.forkScoped,
117 );
118 // The limit covers creating the session and sending the prompt as well, since
119 // either request can stall while the event stream stays connected.
120 const generate = Effect.gen(function* () {
121 const session = yield* client.session.create({
122 title: `T3 Code ${input.operation}`,
123 location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
124 model: Model.Ref.make({
125 providerID: Provider.ID.make(parsed.providerID),
126 id: Model.ID.make(parsed.modelID),
127 ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
128 }),
129 permissions: GENERATION_PERMISSIONS,
130 });
131 sessionId = session.id;
132 yield* Effect.addFinalizer(() =>
133 client.session
134 .remove({ sessionID: session.id })
135 .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
136 );
137 const images: Array<{ uri: string; name: string }> = [];
138 // As in the adapter: an external server may not share T3's attachment directory, and
139 // OpenCode rejects the whole prompt if an attached file is missing.
140 for (const attachment of connection.external ? [] : (input.attachments ?? [])) {
141 if (!isProviderNativeImageAttachment(attachment)) continue;
142 const path = resolveAttachmentPath(attachment);
143 if (path === null) continue;
144 const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false));
145 if (exists) images.push({ uri: NodeURL.pathToFileURL(path).href, name: attachment.name });
146 }
147 yield* client.session.prompt({
148 sessionID: session.id,
149 text: input.prompt,
150 ...(images.length === 0 ? {} : { files: images }),
151 });
152 return yield* Deferred.await(outcome);
153 });
154 const result = yield* generate.pipe(
155 Effect.timeoutOrElse({
156 duration: GENERATION_TIMEOUT,
157 orElse: () =>
158 (sessionId === undefined
159 ? Effect.void
160 : client.session
161 .interrupt({ sessionID: Session.ID.make(sessionId) })
162 .pipe(Effect.timeout("5 seconds"), Effect.ignore)
163 ).pipe(
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}, Effect.scoped);
186​
187export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
188 const server = yield* OpenCode2Server.OpenCode2Server;
189 const host = yield* ProviderHost.ProviderHost;
190 const fileSystem = yield* FileSystem.FileSystem;
191 const run: TextGenerationOperations.Runner = (input) =>
192 server
193 .withConnection((connection) => runOnServer(connection, input))
194 .pipe(
195 Effect.provideService(ProviderHost.ProviderHost, host),
196 Effect.provideService(FileSystem.FileSystem, fileSystem),
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) => TextGenerationOperations.decodeJsonReply(input, "OpenCode", raw)),
207 );
208 return TextGenerationOperations.fromRunner(
209 "OpenCode2TextGeneration",
210 TextGenerationOperations.withoutInvestigation("OpenCode", run),
211 );
212});