Open History to see the last commit
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 const session = yield* client.session.create({
116 title: `T3 Code ${input.operation}`,
117 location: Location.PublicRef.make({ directory: AbsolutePath.make(input.cwd) }),
118 model: Model.Ref.make({
119 providerID: Provider.ID.make(parsed.providerID),
120 id: Model.ID.make(parsed.modelID),
121 ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
122 }),
123 permissions: GENERATION_PERMISSIONS,
124 });
125 sessionId = session.id;
126 yield* Effect.addFinalizer(() =>
127 client.session
128 .remove({ sessionID: session.id })
129 .pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })),
130 );
131 const images = (input.attachments ?? []).flatMap((attachment) => {
132 if (attachment.type !== "image") return [];
133 const path = resolveAttachmentPath(attachment);
134 return path === null ? [] : [{ uri: `file://${path}`, name: attachment.name }];
135 });
136 yield* client.session.prompt({
137 sessionID: session.id,
138 text: input.prompt,
139 ...(images.length === 0 ? {} : { files: images }),
140 });
141 const result = yield* Deferred.await(outcome).pipe(
142 Effect.timeoutOrElse({
143 duration: GENERATION_TIMEOUT,
144 orElse: () =>
145 client.session.interrupt({ sessionID: Session.ID.make(session.id) }).pipe(
146 Effect.ignore,
147 Effect.as<Outcome>({
148 _tag: "failed",
149 detail: "OpenCode did not finish generating in time.",
150 }),
151 ),
152 }),
153 );
154 if (result._tag === "failed") {
155 return yield* new TextGenerationError({
156 operation: input.operation,
157 detail: result.detail,
158 ...(result.cause === undefined ? {} : { cause: result.cause }),
159 });
160 }
161 if (result.text.length === 0) {
162 return yield* new TextGenerationError({
163 operation: input.operation,
164 detail: "OpenCode returned empty output.",
165 });
166 }
167 return result.text;
168}, Effect.scoped);
169
170export const make = Effect.fn("OpenCode2TextGeneration.make")(function* () {
171 const server = yield* OpenCode2Server.OpenCode2Server;
172 const host = yield* ProviderHost.ProviderHost;
173 const run: TextGenerationOperations.Runner = (input) =>
174 server
175 .withConnection((connection) => runOnServer(connection, input))
176 .pipe(
177 Effect.provideService(ProviderHost.ProviderHost, host),
178 Effect.mapError((cause) =>
179 isTextGenerationError(cause)
180 ? cause
181 : new TextGenerationError({
182 operation: input.operation,
183 detail: "OpenCode text generation failed.",
184 cause,
185 }),
186 ),
187 Effect.flatMap((raw) => TextGenerationOperations.decodeJsonReply(input, "OpenCode", raw)),
188 );
189 return TextGenerationOperations.fromRunner(
190 "OpenCode2TextGeneration",
191 TextGenerationOperations.withoutInvestigation("OpenCode", run),
192 );
193});