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

textGeneration.ts

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