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

main
ts 375 lines 11.3 KB
Raw
1 import * as retail from "@distilled.cloud/gcp/retail_v2";
2 import { unownedUnlessPrevious } 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 MAX_ID_LENGTH,
12 expandCatalog,
13 normalizeLocation,
14 parseResourceName,
15 replaceOnIdentity,
16 sameJson,
17 sameStringList,
18 slugNoDigits,
19 toPhysical,
20 updateMaskOf,
21 } from "./internal.ts";
22
23 export type ControlCondition = {
24 /** Query terms to match. */
25 queryTerms?: Array<{
26 value: string;
27 fullMatch?: boolean;
28 }>;
29 /** Browse page categories. */
30 pageCategories?: string[];
31 };
32
33 export type CatalogsControlProps = {
34 /**
35 * Parent catalog resource name
36 * `projects/{project}/locations/{location}/catalogs/{catalog}` or a
37 * catalog id (combined with `location`). Immutable — changing it
38 * replaces the control.
39 * @default "default_catalog"
40 */
41 catalog?: string;
42 /**
43 * Location used when `catalog` is a bare id. Immutable.
44 * @default "global"
45 */
46 location?: string;
47 /**
48 * Control id (`[a-z-_]`, 4-63 characters). If omitted, a unique id is
49 * generated. Immutable — changing it replaces the control.
50 */
51 controlId?: string;
52 /**
53 * Human-readable name (max 128 characters).
54 */
55 displayName?: string;
56 /**
57 * Solution types. Immutable. Only `SOLUTION_TYPE_SEARCH` is supported.
58 * @default ["SOLUTION_TYPE_SEARCH"]
59 */
60 solutionTypes?: Array<
61 | "SOLUTION_TYPE_UNSPECIFIED"
62 | "SOLUTION_TYPE_RECOMMENDATION"
63 | "SOLUTION_TYPE_SEARCH"
64 | (string & {})
65 >;
66 /**
67 * Search use cases.
68 * @default ["SEARCH_SOLUTION_USE_CASE_SEARCH"]
69 */
70 searchSolutionUseCase?: Array<
71 | "SEARCH_SOLUTION_USE_CASE_UNSPECIFIED"
72 | "SEARCH_SOLUTION_USE_CASE_SEARCH"
73 | "SEARCH_SOLUTION_USE_CASE_BROWSE"
74 | (string & {})
75 >;
76 /**
77 * Two-way synonym set (at least two terms).
78 */
79 synonyms?: string[];
80 /**
81 * Redirect URI.
82 */
83 redirectUri?: string;
84 /**
85 * Filter expression.
86 */
87 filter?: string;
88 /**
89 * Boost strength in `[-1, 1]`.
90 */
91 boost?: number;
92 /**
93 * Filter selecting products to boost. Used with `boost`.
94 */
95 productsFilter?: string;
96 /**
97 * Terms to drop from the query.
98 */
99 ignoreTerms?: string[];
100 /**
101 * Trigger conditions. Omit to always apply the action.
102 */
103 condition?: ControlCondition;
104 };
105
106 export type CatalogsControl = Resource<
107 "GCP.Retail.CatalogsControl",
108 CatalogsControlProps,
109 {
110 /** Full resource name. */
111 name: string;
112 /** Control id. */
113 controlId: string;
114 /** Parent catalog resource name. */
115 catalog: string;
116 /** Project id. */
117 project: string;
118 /** Location id. */
119 location: string;
120 /** Display name. */
121 displayName: string | undefined;
122 /** Solution types. */
123 solutionTypes: string[];
124 /** Search use cases. */
125 searchSolutionUseCase: string[];
126 /** Two-way synonyms. */
127 synonyms: string[];
128 /** Redirect URI. */
129 redirectUri: string | undefined;
130 /** Filter expression. */
131 filter: string | undefined;
132 /** Boost strength. */
133 boost: number | undefined;
134 /** Serving configs this control is attached to. */
135 associatedServingConfigIds: string[];
136 },
137 never,
138 Providers
139 >;
140
141 /**
142 * A Retail serving control on a catalog.
143 *
144 * Without labels, ownership rests on the deterministic id: `read` reports a
145 * resource it finds without prior state as unowned (adopt it with `--adopt`).
146 * Parent, control id, and solution types are immutable. Display name and rule
147 * actions update in place unless the action oneof changes, which replaces the
148 * control.
149 *
150 * ### Creating a Control
151 * **Example:** Two-way synonym control
152 * ```typescript
153 * const control = yield* GCP.Retail.CatalogsControl("Greetings", {
154 * displayName: "greetings",
155 * synonyms: ["hello", "hi"],
156 * });
157 * ```
158 *
159 * @resource
160 * @category Retail
161 */
162 export const CatalogsControl = Resource<CatalogsControl>("GCP.Retail.CatalogsControl");
163
164 export class CatalogsControlNotResolved extends Data.TaggedError(
165 "GCP.Retail.CatalogsControlNotResolved",
166 )<{
167 resourceName: string;
168 }> {}
169
170 const defaultSolutionTypes = ["SOLUTION_TYPE_SEARCH"] as const;
171 const defaultUseCase = ["SEARCH_SOLUTION_USE_CASE_SEARCH"] as const;
172
173 const actionKind = (input: {
174 synonyms?: string[];
175 redirectUri?: string;
176 filter?: string;
177 boost?: number;
178 ignoreTerms?: string[];
179 }) => {
180 if (input.redirectUri) return "redirect";
181 if (input.filter) return "filter";
182 if (input.boost !== undefined) return "boost";
183 if (input.ignoreTerms && input.ignoreTerms.length > 0) return "ignore";
184 return "synonyms";
185 };
186
187 const toAttrs = (control: retail.GoogleCloudRetailV2Control, project: string) => {
188 const name = control.name ?? "";
189 const parsed = parseResourceName(name, "controls");
190 return {
191 name,
192 controlId: parsed.id,
193 catalog: parsed.catalog,
194 project: parsed.project || project,
195 location: parsed.location,
196 displayName: control.displayName,
197 solutionTypes: [...(control.solutionTypes ?? [])],
198 searchSolutionUseCase: [...(control.searchSolutionUseCase ?? [])],
199 synonyms: [...(control.rule?.twowaySynonymsAction?.synonyms ?? [])],
200 redirectUri: control.rule?.redirectAction?.redirectUri,
201 filter: control.rule?.filterAction?.filter,
202 boost: control.rule?.boostAction?.boost,
203 associatedServingConfigIds: [...(control.associatedServingConfigIds ?? [])],
204 };
205 };
206
207 const resourceName = (catalog: string, controlId: string) => `${catalog}/controls/${controlId}`;
208
209 const toRule = (news: CatalogsControlProps): retail.GoogleCloudRetailV2Rule => {
210 const condition = news.condition;
211 const kind = actionKind(news);
212 return {
213 condition,
214 twowaySynonymsAction:
215 kind === "synonyms" ? { synonyms: news.synonyms ?? ["hello", "hi"] } : undefined,
216 redirectAction: kind === "redirect" ? { redirectUri: news.redirectUri } : undefined,
217 filterAction: kind === "filter" ? { filter: news.filter } : undefined,
218 boostAction:
219 kind === "boost" ? { boost: news.boost, productsFilter: news.productsFilter } : undefined,
220 ignoreAction: kind === "ignore" ? { ignoreTerms: news.ignoreTerms } : undefined,
221 };
222 };
223
224 const toBody = (
225 news: CatalogsControlProps,
226 displayName: string,
227 ): retail.GoogleCloudRetailV2Control => ({
228 displayName,
229 solutionTypes: news.solutionTypes ?? [...defaultSolutionTypes],
230 searchSolutionUseCase: news.searchSolutionUseCase ?? [...defaultUseCase],
231 rule: toRule(news),
232 });
233
234 const getByName = (name: string) =>
235 name.length === 0
236 ? Effect.undefined
237 : retail
238 .getProjectsLocationsCatalogsControls({ name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 export const CatalogsControlProvider = () =>
242 Provider.succeed(CatalogsControl, {
243 stables: ["name", "controlId", "catalog", "project", "location"],
244
245 diff: Effect.fn(function* ({ news, olds, output }) {
246 if (!isResolved(news)) return undefined;
247 const env = yield* GcpEnvironment.current;
248 const previousParent = olds?.catalog ?? output?.catalog;
249 const nextParent = expandCatalog(
250 news.catalog,
251 env.project,
252 normalizeLocation(news.location ?? output?.location),
253 );
254 const previousTypes = olds?.solutionTypes ?? output?.solutionTypes;
255 const nextTypes = news.solutionTypes ?? previousTypes;
256 const previousKind = actionKind({
257 synonyms: olds?.synonyms ?? output?.synonyms,
258 redirectUri: olds?.redirectUri ?? output?.redirectUri,
259 filter: olds?.filter ?? output?.filter,
260 boost: olds?.boost ?? output?.boost,
261 });
262 const nextKind = actionKind(news);
263 const identity = replaceOnIdentity({
264 previousId: olds?.controlId ?? output?.controlId,
265 nextId: news.controlId,
266 previousParent,
267 nextParent,
268 });
269 if (
270 identity !== undefined ||
271 (previousTypes !== undefined &&
272 nextTypes !== undefined &&
273 !sameStringList(previousTypes, nextTypes)) ||
274 previousKind !== nextKind
275 ) {
276 return (
277 identity ?? {
278 action: "replace" as const,
279 deleteFirst: true,
280 }
281 );
282 }
283 return undefined;
284 }),
285
286 read: Effect.fn(function* ({ id, olds, output, previous }) {
287 const env = yield* GcpEnvironment.current;
288 const catalog = olds?.catalog ?? output?.catalog;
289 const controlId = yield* toPhysical(
290 id,
291 olds?.controlId,
292 output?.controlId,
293 (name) => slugNoDigits(name, MAX_ID_LENGTH),
294 MAX_ID_LENGTH,
295 );
296 const name =
297 output?.name ??
298 (catalog !== undefined
299 ? resourceName(
300 expandCatalog(catalog, env.project, normalizeLocation(output?.location)),
301 controlId,
302 )
303 : undefined);
304 if (name === undefined) return undefined;
305 const existing = yield* getByName(name);
306 if (existing === undefined) return undefined;
307 const attrs = toAttrs(existing, env.project);
308 // No labels field: without prior state it may not be ours.
309 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
310 }),
311
312 reconcile: Effect.fn(function* ({ id, news, output }) {
313 const env = yield* GcpEnvironment.current;
314 const location = normalizeLocation(news.location ?? output?.location);
315 const catalog = expandCatalog(news.catalog, env.project, location);
316 const controlId = yield* toPhysical(
317 id,
318 news.controlId,
319 output?.controlId,
320 (name) => slugNoDigits(name, MAX_ID_LENGTH),
321 MAX_ID_LENGTH,
322 );
323 const name = resourceName(catalog, controlId);
324 const displayName = news.displayName ?? controlId;
325 const body = toBody(news, displayName);
326
327 let current = yield* getByName(output?.name ?? name);
328
329 if (current === undefined) {
330 const created = yield* retail
331 .createProjectsLocationsCatalogsControls({
332 parent: catalog,
333 controlId,
334 body,
335 })
336 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
337 current = created ?? undefined;
338 }
339
340 if (current === undefined) {
341 return yield* new CatalogsControlNotResolved({ resourceName: name });
342 }
343
344 const resource = current.name ?? name;
345 const rule = toRule(news);
346 const mask = updateMaskOf(
347 (current.displayName ?? "") !== displayName ? "display_name" : undefined,
348 sameJson(current.rule, rule) ? undefined : "rule",
349 sameStringList(
350 current.searchSolutionUseCase,
351 news.searchSolutionUseCase ?? [...defaultUseCase],
352 )
353 ? undefined
354 : "search_solution_use_case",
355 );
356
357 if (mask.length > 0) {
358 current = yield* retail.patchProjectsLocationsCatalogsControls({
359 name: resource,
360 updateMask: mask,
361 body: { ...body, name: resource },
362 });
363 }
364
365 return toAttrs(current, env.project);
366 }),
367
368 delete: Effect.fn(function* ({ output }) {
369 yield* retail
370 .deleteProjectsLocationsCatalogsControls({
371 name: output.name,
372 })
373 .pipe(Effect.catchTag("NotFound", () => Effect.void));
374 }),
375 });