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

environment.ts

208 lines6.5 KB

1import { encodeSpeechPcmRequest } from "@t3tools/shared/speech";
2import * as Effect from "effect/Effect";
3import * as Redacted from "effect/Redacted";
4import { SPEECH_STREAM_PATH } from "@t3tools/contracts";
5import type {
6 SpeechAcceleration,
7 SpeechModelUnloadTimeout,
8 SpeechTranscriptionOptions,
9 SpeechPostProcessingOptions,
10} from "@t3tools/contracts";
11​
12import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
13import type { PreparedConnection } from "../connection/model.ts";
14import * as ManagedRelay from "../relay/managedRelay.ts";
15import {
16 makeEnvironmentHttpApiGroupClient,
17 makeEnvironmentHttpApiUrlBuilder,
18} from "../rpc/http.ts";
19import { executeAuthenticatedEnvironmentHttpRequest } from "../state/environmentHttpAuth.ts";
20​
21const INFERENCE_OR_DOWNLOAD_TIMEOUT_MS = 30 * 60_000;
22type EnvironmentApiClient<G extends "voice" | "auth"> = Effect.Success<
23 ReturnType<typeof makeEnvironmentHttpApiGroupClient<G>>
24>;
25​
26const request = Effect.fn("clientRuntime.voiceInput.environmentRequest")(function* <
27 A,
28 E,
29 G extends "voice" | "auth",
30>(input: {
31 readonly group: G;
32 readonly prepared: PreparedConnection;
33 readonly method: "GET" | "POST" | "DELETE";
34 readonly timeoutMs?: number;
35 readonly canSend?: () => boolean;
36 readonly path: (urls: ReturnType<typeof makeEnvironmentHttpApiUrlBuilder>[G]) => string;
37 readonly run: (input: {
38 readonly client: EnvironmentApiClient<G>;
39 readonly headers: { readonly authorization?: string; readonly dpop?: string };
40 }) => Effect.Effect<A, E>;
41}) {
42 return yield* executeAuthenticatedEnvironmentHttpRequest({
43 group: input.group,
44 prepared: input.prepared,
45 signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
46 remoteAuthorization: yield* Effect.serviceOption(
47 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
48 ),
49 method: input.method,
50 url: input.path,
51 timeoutMs: input.timeoutMs ?? 30_000,
52 // Audio and credentials never follow a redirect to another host.
53 requestInit: { redirect: "error" },
54 request: (args) =>
55 Effect.suspend(() => (input.canSend?.() === false ? Effect.interrupt : input.run(args))),
56 });
57});
58​
59export const getEnvironmentSpeechStatus = (prepared: PreparedConnection) =>
60 request({
61 group: "voice",
62 prepared,
63 method: "GET",
64 path: (urls) => urls.status(),
65 run: ({ client, headers }) => client.status({ headers }),
66 });
67​
68export const getEnvironmentSpeechStreamUrl = (prepared: PreparedConnection) => {
69 let endpoint = prepared.httpBaseUrl;
70 return request({
71 group: "auth",
72 prepared,
73 method: "POST",
74 path: (urls) => {
75 endpoint = urls.webSocketTicketFor({ params: { use: "media" } });
76 return endpoint;
77 },
78 run: ({ client, headers }) => client.webSocketTicketFor({ headers, params: { use: "media" } }),
79 }).pipe(
80 Effect.map(({ ticket }) => {
81 const url = new URL(SPEECH_STREAM_PATH, endpoint);
82 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
83 url.searchParams.set("wsTicket", Redacted.value(ticket));
84 return url.toString();
85 }),
86 );
87};
88​
89export const getEnvironmentSpeechModels = (
90 prepared: PreparedConnection,
91 includeBenchmarks = false,
92) => {
93 const query = includeBenchmarks ? { benchmarks: "1" as const } : {};
94 return request({
95 group: "voice",
96 prepared,
97 method: "GET",
98 path: (urls) => urls.models({ query }),
99 run: ({ client, headers }) => client.models({ headers, query }),
100 });
101};
102​
103export const downloadEnvironmentSpeechModel = (prepared: PreparedConnection, modelId: string) =>
104 request({
105 group: "voice",
106 prepared,
107 method: "POST",
108 path: (urls) => urls.downloadModel(),
109 timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS,
110 run: ({ client, headers }) => client.downloadModel({ headers, payload: { modelId } }),
111 });
112​
113export const selectEnvironmentSpeechModel = (prepared: PreparedConnection, modelId: string) =>
114 request({
115 group: "voice",
116 prepared,
117 method: "POST",
118 path: (urls) => urls.selectModel(),
119 run: ({ client, headers }) => client.selectModel({ headers, payload: { modelId } }),
120 });
121​
122export const cancelEnvironmentSpeechModelDownload = (
123 prepared: PreparedConnection,
124 modelId: string,
125) =>
126 request({
127 group: "voice",
128 prepared,
129 method: "POST",
130 path: (urls) => urls.cancelModelDownload(),
131 run: ({ client, headers }) => client.cancelModelDownload({ headers, payload: { modelId } }),
132 });
133​
134export const transcribeEnvironmentPcm = (
135 prepared: PreparedConnection,
136 pcm: Uint8Array,
137 options: SpeechTranscriptionOptions,
138 canSend: () => boolean,
139) =>
140 request({
141 group: "voice",
142 prepared,
143 method: "POST",
144 path: (urls) => urls.transcribe(),
145 canSend,
146 timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS,
147 run: ({ client, headers }) =>
148 client.transcribe({
149 headers,
150 payload: encodeSpeechPcmRequest(pcm, options),
151 }),
152 });
153​
154/** Sends the transcript and draft context to a provider on `prepared`; a separate opt-in. */
155export const postProcessEnvironmentTranscript = (
156 prepared: PreparedConnection,
157 transcript: string,
158 draft: {
159 readonly text: string;
160 readonly selection: { readonly start: number; readonly end: number };
161 },
162 options: SpeechPostProcessingOptions,
163 canSend: () => boolean,
164) =>
165 request({
166 group: "voice",
167 prepared,
168 method: "POST",
169 path: (urls) => urls.postProcess(),
170 canSend,
171 timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS,
172 run: ({ client, headers }) =>
173 client.postProcess({ headers, payload: { transcript, draft, options } }),
174 });
175​
176export const updateEnvironmentSpeechAcceleration = (
177 prepared: PreparedConnection,
178 acceleration: SpeechAcceleration,
179) =>
180 request({
181 group: "voice",
182 prepared,
183 method: "POST",
184 path: (urls) => urls.updateAcceleration(),
185 run: ({ client, headers }) => client.updateAcceleration({ headers, payload: { acceleration } }),
186 });
187​
188export const updateEnvironmentSpeechModelUnloadTimeout = (
189 prepared: PreparedConnection,
190 timeout: SpeechModelUnloadTimeout,
191) =>
192 request({
193 group: "voice",
194 prepared,
195 method: "POST",
196 path: (urls) => urls.updateModelUnloadTimeout(),
197 run: ({ client, headers }) =>
198 client.updateModelUnloadTimeout({ headers, payload: { timeout } }),
199 });
200​
201export const removeEnvironmentSpeechModel = (prepared: PreparedConnection, modelId: string) =>
202 request({
203 group: "voice",
204 prepared,
205 method: "POST",
206 path: (urls) => urls.removeModel(),
207 run: ({ client, headers }) => client.removeModel({ headers, payload: { modelId } }),
208 });