@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 258 lines 8.19 KB
Raw
1 import * as speech from "@distilled.cloud/gcp/speech_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_LOCATION,
12 deletePhraseSet,
13 getPhraseSet,
14 listOwnedPhraseSets,
15 locationParent,
16 markerFromPhrases,
17 normalizeLocation,
18 parseResourceName,
19 type Phrase,
20 replaceOnIdentity,
21 resourceNameOf,
22 sameNumber,
23 samePhrases,
24 stripOwnershipPhrases,
25 toPhysicalId,
26 updateMaskOf,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type { Phrase };
31
32 export type PhraseSetProps = {
33 /**
34 * Speech-to-Text Adaptation location. The global Speech endpoint
35 * accepts `global`; `us` and `eu` need matching regional endpoints.
36 * Immutable — changing it replaces the phrase set.
37 * @default "global"
38 */
39 location?: string;
40 /**
41 * Phrase set id (the `{phrase_set}` segment of
42 * `projects/{project}/locations/{location}/phraseSets/{phrase_set}`).
43 * If omitted, a unique id is generated. Letters, numbers, and hyphens;
44 * 4-63 characters; must start with a letter. Immutable — changing it
45 * replaces the phrase set.
46 */
47 phraseSetId?: string;
48 /**
49 * Phrase hints. Phrase values can reference a custom class as
50 * `${custom_class_id}`.
51 */
52 phrases?: Phrase[];
53 /**
54 * Hint boost applied to every phrase that does not set its own boost.
55 * Typical values are between 0 (exclusive) and 20.
56 */
57 boost?: number;
58 };
59
60 export type PhraseSet = Resource<
61 "GCP.Speech.PhraseSet",
62 PhraseSetProps,
63 {
64 /** Full resource name `projects/{project}/locations/{location}/phraseSets/{phrase_set}`. */
65 name: string;
66 /** Phrase set id (last path segment). */
67 phraseSetId: string;
68 /** Project id. */
69 project: string;
70 /** Adaptation location. */
71 location: string;
72 /** Phrase hints. */
73 phrases: Phrase[];
74 /** Phrase-set-level hint boost. */
75 boost: number | undefined;
76 /** Server-assigned uid, if present. */
77 uid: string | undefined;
78 /** Lifecycle state, if present. */
79 state: string | undefined;
80 /** KMS key encrypting phrase set content, if any. */
81 kmsKeyName: string | undefined;
82 },
83 never,
84 Providers
85 >;
86
87 /**
88 * A Speech-to-Text Adaptation phrase set. Phrase sets bias recognition
89 * toward listed words and phrases, including references to custom
90 * classes (`${custom_class_id}`).
91 *
92 * Speech-to-Text v1 phrase sets have no labels field and Alchemy does
93 * not write ownership into the phrases (they bias recognition). A
94 * generated id identifies the set; one with an explicit id that Alchemy
95 * has no state for is reported as unowned. Location and
96 * phrase set id are identity — changing either replaces the set.
97 * `phrases` and `boost` update in place.
98 *
99 * ### Creating a Phrase Set
100 * **Example:** Generated id
101 * ```typescript
102 * const hints = yield* GCP.Speech.PhraseSet("Hints", {
103 * phrases: [{ value: "weather", boost: 10 }],
104 * boost: 5,
105 * });
106 * ```
107 *
108 * **Example:** Explicit id with a custom class reference
109 * ```typescript
110 * const hints = yield* GCP.Speech.PhraseSet("Hints", {
111 * phraseSetId: "weather-hints",
112 * phrases: [{ value: "sail on ${passenger-ships}" }],
113 * });
114 * ```
115 *
116 * ### Updating a Phrase Set
117 * **Example:** Add a phrase and change boost
118 * ```typescript
119 * const hints = yield* GCP.Speech.PhraseSet("Hints", {
120 * phrases: [
121 * { value: "weather", boost: 15 },
122 * { value: "forecast" },
123 * ],
124 * boost: 8,
125 * });
126 * ```
127 *
128 * @resource
129 * @category Speech
130 */
131 export const PhraseSet = Resource<PhraseSet>("GCP.Speech.PhraseSet");
132
133 export class PhraseSetNotResolved extends Data.TaggedError("GCP.Speech.PhraseSetNotResolved")<{
134 resourceName: string;
135 }> {}
136
137 const phraseSetNameOf = (project: string, location: string, phraseSetId: string) =>
138 resourceNameOf(project, location, "phraseSets", phraseSetId);
139
140 const toAttrs = (phraseSet: speech.PhraseSet, project: string) => {
141 const name = phraseSet.name ?? "";
142 const parsed = parseResourceName(name, "phraseSets");
143 return {
144 name,
145 phraseSetId: parsed.id,
146 // Speech echoes names with the project number; report the project id.
147 project,
148 location: parsed.location,
149 phrases: stripOwnershipPhrases(phraseSet.phrases),
150 boost: phraseSet.boost,
151 uid: phraseSet.uid,
152 state: phraseSet.state,
153 kmsKeyName: phraseSet.kmsKeyName,
154 };
155 };
156
157 export const PhraseSetProvider = () =>
158 Provider.succeed(PhraseSet, {
159 stables: ["name", "phraseSetId", "project", "location", "uid"],
160
161 diff: Effect.fn(function* ({ news, olds, output }) {
162 if (!isResolved(news)) return undefined;
163 return replaceOnIdentity({
164 previousId: olds?.phraseSetId ?? output?.phraseSetId,
165 nextId: news.phraseSetId,
166 previousLocation: olds?.location ?? output?.location,
167 nextLocation: news.location ?? olds?.location ?? output?.location,
168 });
169 }),
170
171 read: Effect.fn(function* ({ id, olds, output }) {
172 const env = yield* GcpEnvironment.current;
173 const location = normalizeLocation(olds?.location ?? output?.location);
174 const phraseSetId = yield* toPhysicalId(id, olds?.phraseSetId, output?.phraseSetId);
175 const existing = yield* getPhraseSet(
176 output?.name ?? phraseSetNameOf(env.project, location, phraseSetId),
177 );
178 if (existing === undefined) return undefined;
179 const attrs = toAttrs(existing, env.project);
180 // No labels: a generated id derives from this stack, stage, logical
181 // id and instance; an explicit id is only ours when state has it.
182 return output !== undefined || olds?.phraseSetId === undefined ? attrs : Unowned(attrs);
183 }),
184
185 list: () =>
186 Effect.gen(function* () {
187 const env = yield* GcpEnvironment.current;
188 const phraseSets = yield* listOwnedPhraseSets(env.project);
189 return phraseSets.map((phraseSet) => toAttrs(phraseSet, env.project));
190 }),
191
192 reconcile: Effect.fn(function* ({ id, news, output }) {
193 const env = yield* GcpEnvironment.current;
194 const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION);
195 const phraseSetId = yield* toPhysicalId(id, news.phraseSetId, output?.phraseSetId);
196 const phrases = news.phrases ?? [];
197 const name = output?.name ?? phraseSetNameOf(env.project, location, phraseSetId);
198
199 let current = yield* getPhraseSet(name);
200
201 if (current === undefined) {
202 const created = yield* speech
203 .createProjectsLocationsPhraseSets({
204 parent: locationParent(env.project, location),
205 body: {
206 phraseSetId,
207 phraseSet: {
208 phrases,
209 boost: news.boost,
210 },
211 },
212 })
213 .pipe(
214 Effect.catchTag("Conflict", () =>
215 getPhraseSet(phraseSetNameOf(env.project, location, phraseSetId)),
216 ),
217 );
218 current = created ?? undefined;
219 if (current?.name) {
220 current = (yield* getPhraseSet(current.name)) ?? current;
221 }
222 }
223
224 if (current === undefined) {
225 return yield* new PhraseSetNotResolved({
226 resourceName: name || phraseSetNameOf(env.project, location, phraseSetId),
227 });
228 }
229
230 const currentName = current.name ?? name;
231 const updateMask = updateMaskOf(
232 markerFromPhrases(current.phrases) === undefined &&
233 samePhrases(current.phrases, news.phrases)
234 ? undefined
235 : "phrases",
236 sameNumber(current.boost, news.boost) ? undefined : "boost",
237 );
238 if (updateMask.length > 0) {
239 current = yield* speech.patchProjectsLocationsPhraseSets({
240 name: currentName,
241 updateMask,
242 body: {
243 name: currentName,
244 phrases,
245 boost: news.boost,
246 },
247 });
248 }
249
250 return toAttrs(current, env.project);
251 }),
252
253 delete: Effect.fn(function* ({ output }) {
254 if (!output.name) return;
255 yield* deletePhraseSet(output.name);
256 yield* waitUntilGone(getPhraseSet(output.name));
257 }),
258 });