Open History to see the last commit
1import { decodeSpeechPcmRequest } from "@t3tools/shared/speech";
2import {
3 AuthFilesystemReadScope,
4 AuthOrchestrationOperateScope,
5 AuthSettingsWriteScope,
6 type AuthEnvironmentScope,
7 EnvironmentAuthenticatedPrincipal,
8 EnvironmentHttpApi,
9 type EnvironmentSpeechModels,
10 EnvironmentVoiceBodyLimit,
11 SPEECH_MAX_OPTIONS_BYTES,
12 TextGenerationError,
13} from "@t3tools/contracts";
14import * as ByteSize from "effect/ByteSize";
15import * as Effect from "effect/Effect";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import * as HttpServerRequest from "effect/http/HttpServerRequest";
20import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
21
22import {
23 annotateEnvironmentRequest,
24 failEnvironmentInternal,
25 failEnvironmentInvalidRequest,
26 requireEnvironmentScope,
27} from "../auth/http.ts";
28import * as SpeechPostProcessing from "./postProcessing.ts";
29import * as CloudSpeech from "./CloudSpeech.ts";
30import * as SpeechService from "./SpeechService.ts";
31
32const MAX_TRANSCRIBE_BODY_BYTES = SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4;
33const parseAudio = Option.liftThrowable(decodeSpeechPcmRequest);
34const isTextGenerationError = Schema.is(TextGenerationError);
35
36const bodyLimit = Layer.succeed(EnvironmentVoiceBodyLimit, (effect) =>
37 Effect.gen(function* () {
38 const request = yield* HttpServerRequest.HttpServerRequest;
39 if (Number(request.headers["content-length"]) > MAX_TRANSCRIBE_BODY_BYTES)
40 return yield* failEnvironmentInvalidRequest("invalid_audio");
41 return yield* effect.pipe(
42 Effect.provideService(
43 HttpServerRequest.MaxBodySize,
44 ByteSize.bytes(MAX_TRANSCRIBE_BODY_BYTES),
45 ),
46 );
47 }),
48);
49
50const mapSpeechError = <A, R>(effect: Effect.Effect<A, SpeechService.SpeechError, R>) =>
51 effect.pipe(
52 Effect.catchTags({
53 SpeechInvalidAudioError: () => failEnvironmentInvalidRequest("invalid_audio"),
54 SpeechUnsupportedPlatformError: () => failEnvironmentInvalidRequest("speech_unavailable"),
55 SpeechBusyError: () => failEnvironmentInvalidRequest("speech_busy"),
56 SpeechDownloadCancelledError: () => failEnvironmentInvalidRequest("speech_busy"),
57 SpeechModelNotFoundError: () => failEnvironmentInvalidRequest("invalid_command"),
58 SpeechOperationError: (error) => failEnvironmentInternal("internal_error", error),
59 }),
60 );
61
62// A linked model's origin is a path on this machine; only filesystem readers may see it.
63// Untraced: it runs inside each handler's own span.
64const withoutHostPaths = Effect.fnUntraced(function* <Fields extends EnvironmentSpeechModels>({
65 models,
66 ...fields
67}: Fields) {
68 const session = yield* EnvironmentAuthenticatedPrincipal;
69 return {
70 ...fields,
71 models: session.scopes.has(AuthFilesystemReadScope)
72 ? models
73 : models.map(({ linkedFrom: _, ...model }) => model),
74 };
75});
76
77export const speechHttpApiLayer = HttpApiBuilder.group(
78 EnvironmentHttpApi,
79 "voice",
80 Effect.fnUntraced(function* (handlers) {
81 const speech = yield* SpeechService.SpeechService;
82 const cloud = yield* CloudSpeech.CloudSpeech;
83 const postProcessing = yield* SpeechPostProcessing.SpeechPostProcessing;
84 const guard = Effect.fnUntraced(function* (
85 endpoint: string,
86 scope: AuthEnvironmentScope = AuthOrchestrationOperateScope,
87 ) {
88 yield* annotateEnvironmentRequest(endpoint);
89 yield* requireEnvironmentScope(scope);
90 });
91 return handlers
92 .handle(
93 "cloudKeys",
94 Effect.fn("environment.voice.cloudKeys")(function* (args) {
95 yield* guard(args.endpoint.name);
96 return yield* cloud.configured.pipe(
97 Effect.catch((error) => failEnvironmentInternal("internal_error", error)),
98 );
99 }),
100 )
101 .handle(
102 "setCloudKey",
103 Effect.fn("environment.voice.setCloudKey")(function* (args) {
104 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
105 yield* cloud
106 .setKey(args.params.provider, args.payload.key)
107 .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error)));
108 }),
109 )
110 .handle(
111 "cloudModels",
112 Effect.fn("environment.voice.cloudModels")(function* (args) {
113 yield* guard(args.endpoint.name);
114 return { models: yield* cloud.models };
115 }),
116 )
117 .handle(
118 "transcribeCloud",
119 Effect.fn("environment.voice.transcribeCloud")(function* (args) {
120 yield* guard(args.endpoint.name);
121 const decoded = parseAudio(args.payload);
122 if (Option.isNone(decoded)) return yield* failEnvironmentInvalidRequest("invalid_audio");
123 const text = yield* cloud
124 .transcribe(
125 args.params.provider,
126 decoded.value.pcm,
127 decoded.value.options,
128 args.query.model,
129 )
130 .pipe(
131 Effect.catchTags({
132 ServerSettingsError: (error) => failEnvironmentInternal("internal_error", error),
133 SpeechInvalidAudioError: () => failEnvironmentInvalidRequest("invalid_audio"),
134 }),
135 );
136 return { text };
137 }),
138 )
139 .handle(
140 "status",
141 Effect.fn("environment.voice.status")(function* (args) {
142 yield* guard(args.endpoint.name);
143 return yield* speech.status.pipe(mapSpeechError);
144 }),
145 )
146 .handle(
147 "prepareModel",
148 Effect.fn("environment.voice.prepareModel")(function* (args) {
149 yield* guard(args.endpoint.name);
150 yield* speech.prepareModel.pipe(mapSpeechError);
151 }),
152 )
153 .handle(
154 "models",
155 Effect.fn("environment.voice.models")(function* (args) {
156 yield* guard(args.endpoint.name);
157 return yield* speech
158 .models(args.query.benchmarks === "1")
159 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
160 }),
161 )
162 .handle(
163 "downloadModel",
164 Effect.fn("environment.voice.downloadModel")(function* (args) {
165 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
166 return yield* speech
167 .downloadModel(args.payload.modelId)
168 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
169 }),
170 )
171 .handle(
172 "selectModel",
173 Effect.fn("environment.voice.selectModel")(function* (args) {
174 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
175 return yield* speech
176 .selectModel(args.payload.modelId)
177 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
178 }),
179 )
180 .handle(
181 "cancelModelDownload",
182 Effect.fn("environment.voice.cancelModelDownload")(function* (args) {
183 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
184 return yield* speech
185 .cancelDownload(args.payload.modelId)
186 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
187 }),
188 )
189 .handle(
190 "removeModel",
191 Effect.fn("environment.voice.removeModel")(function* (args) {
192 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
193 return yield* speech
194 .removeModel(args.payload.modelId)
195 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
196 }),
197 )
198 .handle(
199 "linkModels",
200 Effect.fn("environment.voice.linkModels")(function* (args) {
201 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
202 // The request names a path on this machine and the result reveals what is there.
203 yield* requireEnvironmentScope(AuthFilesystemReadScope);
204 return yield* speech.linkModels(args.payload.path).pipe(mapSpeechError);
205 }),
206 )
207 .handle(
208 "updateAcceleration",
209 Effect.fn("environment.voice.updateAcceleration")(function* (args) {
210 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
211 return yield* speech.updateAcceleration(args.payload.acceleration).pipe(mapSpeechError);
212 }),
213 )
214 .handle(
215 "updateModelUnloadTimeout",
216 Effect.fn("environment.voice.updateModelUnloadTimeout")(function* (args) {
217 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
218 return yield* speech.updateModelUnloadTimeout(args.payload.timeout).pipe(mapSpeechError);
219 }),
220 )
221 .handle(
222 "transcribe",
223 Effect.fn("environment.voice.transcribe")(function* (args) {
224 yield* guard(args.endpoint.name);
225 const decoded = parseAudio(args.payload);
226 if (Option.isNone(decoded)) return yield* failEnvironmentInvalidRequest("invalid_audio");
227 const text = yield* speech
228 .transcribe(decoded.value.pcm, decoded.value.options)
229 .pipe(mapSpeechError);
230 return { text };
231 }),
232 )
233 .handle(
234 "postProcess",
235 Effect.fn("environment.voice.postProcess")(function* (args) {
236 yield* guard(args.endpoint.name);
237 return yield* postProcessing
238 .process(args.payload)
239 .pipe(
240 Effect.catch((error) =>
241 failEnvironmentInternal(
242 "internal_error",
243 error,
244 isTextGenerationError(error.cause) ? error.cause.detail : undefined,
245 ),
246 ),
247 );
248 }),
249 );
250 }),
251).pipe(Layer.provide(bodyLimit), Layer.provide(SpeechPostProcessing.layer));