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

main
ts 302 lines 9.7 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_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 controlIdOf,
12 parentOf,
13 parseResourceName,
14 sameJson,
15 sameStringList,
16 toPhysical,
17 } from "./internal.ts";
18
19 export type ControlCondition = {
20 /** Query regex. Cannot be set together with `queryTerms`. */
21 queryRegex?: string;
22 /** Query terms to match. */
23 queryTerms?: Array<{
24 value: string;
25 fullMatch?: boolean;
26 }>;
27 };
28
29 export type CollectionsDataStoresControlProps = {
30 /**
31 * Parent data store resource name. Immutable — changing it replaces
32 * the control.
33 */
34 dataStore: string;
35 /**
36 * Control id (`[a-z-_]`, 1-63 characters). If omitted, a unique id is
37 * generated. Immutable — changing it replaces the control.
38 */
39 controlId?: string;
40 /**
41 * Human-readable name (max 128 characters).
42 */
43 displayName?: string;
44 /**
45 * Solution type. Immutable.
46 * @default "SOLUTION_TYPE_SEARCH"
47 */
48 solutionType?:
49 | "SOLUTION_TYPE_UNSPECIFIED"
50 | "SOLUTION_TYPE_RECOMMENDATION"
51 | "SOLUTION_TYPE_SEARCH"
52 | "SOLUTION_TYPE_CHAT"
53 | "SOLUTION_TYPE_GENERATIVE_CHAT"
54 | "SOLUTION_TYPE_AI_MODE"
55 | (string & {});
56 /**
57 * Search use cases. Required when `solutionType` is
58 * `SOLUTION_TYPE_SEARCH`.
59 * @default ["SEARCH_USE_CASE_SEARCH"]
60 */
61 useCases?: Array<
62 | "SEARCH_USE_CASE_UNSPECIFIED"
63 | "SEARCH_USE_CASE_SEARCH"
64 | "SEARCH_USE_CASE_BROWSE"
65 | (string & {})
66 >;
67 /**
68 * Synonym set (at least two terms).
69 */
70 synonyms?: string[];
71 /**
72 * Redirect URI for a redirect control.
73 */
74 redirectUri?: string;
75 /**
76 * Filter expression for a filter control.
77 */
78 filter?: string;
79 /**
80 * Data store name the filter applies to. Defaults to `dataStore`.
81 */
82 filterDataStore?: string;
83 /**
84 * Trigger conditions. Omit to always apply the action.
85 */
86 conditions?: ControlCondition[];
87 };
88
89 export type CollectionsDataStoresControl = Resource<
90 "GCP.DiscoveryEngine.CollectionsDataStoresControl",
91 CollectionsDataStoresControlProps,
92 {
93 /** Full resource name. */
94 name: string;
95 /** Control id. */
96 controlId: string;
97 /** Parent data store resource name. */
98 dataStore: string;
99 /** Project id. */
100 project: string;
101 /** Location id. */
102 location: string;
103 /** Display name. */
104 displayName: string | undefined;
105 /** Solution type. */
106 solutionType: string | undefined;
107 /** Search use cases. */
108 useCases: string[];
109 /** Synonym set. */
110 synonyms: string[];
111 /** Redirect URI. */
112 redirectUri: string | undefined;
113 /** Filter expression. */
114 filter: string | undefined;
115 /** Serving configs this control is attached to. */
116 associatedServingConfigIds: string[];
117 },
118 never,
119 Providers
120 >;
121
122 /**
123 * A Discovery Engine serving control on a collection data store.
124 *
125 * Without labels, ownership rests on the deterministic id: `read` reports a
126 * resource it finds without prior state as unowned (adopt it with `--adopt`).
127 * Parent, control id, and solution type are immutable. Display name,
128 * synonyms, redirect, filter, and conditions update in place.
129 *
130 * ### Creating a Control
131 * **Example:** Synonym control
132 * ```typescript
133 * const store = yield* GCP.DiscoveryEngine.CollectionsDataStore("Docs", {});
134 * const control = yield* GCP.DiscoveryEngine.CollectionsDataStoresControl(
135 * "Greetings",
136 * {
137 * dataStore: store.name,
138 * displayName: "greetings",
139 * synonyms: ["hello", "hi"],
140 * },
141 * );
142 * ```
143 *
144 * @resource
145 * @category DiscoveryEngine
146 */
147 export const CollectionsDataStoresControl = Resource<CollectionsDataStoresControl>(
148 "GCP.DiscoveryEngine.CollectionsDataStoresControl",
149 );
150
151 export class CollectionsDataStoresControlNotResolved extends Data.TaggedError(
152 "GCP.DiscoveryEngine.CollectionsDataStoresControlNotResolved",
153 )<{
154 resourceName: string;
155 }> {}
156
157 const toAttrs = (control: discoveryengine.GoogleCloudDiscoveryengineV1Control, project: string) => {
158 const name = control.name ?? "";
159 const parsed = parseResourceName(name, "controls");
160 return {
161 name,
162 controlId: parsed.id,
163 dataStore: parentOf(name, "controls"),
164 project: parsed.project || project,
165 location: parsed.location,
166 displayName: control.displayName,
167 solutionType: control.solutionType,
168 useCases: [...(control.useCases ?? [])],
169 synonyms: [...(control.synonymsAction?.synonyms ?? [])],
170 redirectUri: control.redirectAction?.redirectUri,
171 filter: control.filterAction?.filter,
172 associatedServingConfigIds: [...(control.associatedServingConfigIds ?? [])],
173 };
174 };
175
176 const resourceName = (dataStore: string, controlId: string) => `${dataStore}/controls/${controlId}`;
177
178 const toBody = (
179 news: CollectionsDataStoresControlProps,
180 displayName: string,
181 ): discoveryengine.GoogleCloudDiscoveryengineV1Control => ({
182 displayName,
183 solutionType: news.solutionType ?? "SOLUTION_TYPE_SEARCH",
184 useCases: news.useCases ?? ["SEARCH_USE_CASE_SEARCH"],
185 synonymsAction:
186 news.synonyms && news.synonyms.length > 0 ? { synonyms: news.synonyms } : undefined,
187 redirectAction: news.redirectUri ? { redirectUri: news.redirectUri } : undefined,
188 filterAction: news.filter
189 ? {
190 filter: news.filter,
191 dataStore: news.filterDataStore ?? news.dataStore,
192 }
193 : undefined,
194 conditions: news.conditions,
195 });
196
197 const getByName = (name: string) =>
198 name.length === 0
199 ? Effect.undefined
200 : discoveryengine
201 .getProjectsLocationsCollectionsDataStoresControls({ name })
202 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
203
204 export const CollectionsDataStoresControlProvider = () =>
205 Provider.succeed(CollectionsDataStoresControl, {
206 stables: ["name", "controlId", "dataStore", "project", "location", "solutionType"],
207
208 diff: Effect.fn(function* ({ news, olds, output }) {
209 if (!isResolved(news)) return undefined;
210 const previousParent = olds?.dataStore ?? output?.dataStore;
211 const previousId = olds?.controlId ?? output?.controlId;
212 const previousType = olds?.solutionType ?? output?.solutionType;
213 const nextType = news.solutionType ?? previousType;
214 if (
215 (previousParent !== undefined && news.dataStore !== previousParent) ||
216 (previousId !== undefined &&
217 news.controlId !== undefined &&
218 news.controlId !== previousId) ||
219 (previousType !== undefined && nextType !== undefined && previousType !== nextType)
220 ) {
221 return {
222 action: "replace" as const,
223 deleteFirst:
224 previousParent === news.dataStore &&
225 previousId !== undefined &&
226 news.controlId === previousId,
227 };
228 }
229 return undefined;
230 }),
231
232 read: Effect.fn(function* ({ id, olds, output }) {
233 const env = yield* GcpEnvironment.current;
234 const parent = olds?.dataStore ?? output?.dataStore;
235 const childId = yield* toPhysical(id, olds?.controlId, output?.controlId, controlIdOf);
236 const name =
237 output?.name ?? (parent !== undefined ? resourceName(parent, childId) : undefined);
238 if (name === undefined) return undefined;
239 const existing = yield* getByName(name);
240 if (existing === undefined) return undefined;
241 const attrs = toAttrs(existing, env.project);
242 // No labels field: without prior state it may not be ours.
243 return output !== undefined ? attrs : Unowned(attrs);
244 }),
245
246 reconcile: Effect.fn(function* ({ id, news, output }) {
247 const env = yield* GcpEnvironment.current;
248 const controlId = yield* toPhysical(id, news.controlId, output?.controlId, controlIdOf);
249 const name = resourceName(news.dataStore, controlId);
250 const displayName = news.displayName ?? controlId;
251 const body = toBody(news, displayName);
252
253 let current = yield* getByName(output?.name ?? name);
254
255 if (current === undefined) {
256 const created = yield* discoveryengine
257 .createProjectsLocationsCollectionsDataStoresControls({
258 parent: news.dataStore,
259 controlId,
260 body,
261 })
262 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
263 current = created ?? undefined;
264 }
265
266 if (current === undefined) {
267 return yield* new CollectionsDataStoresControlNotResolved({ resourceName: name });
268 }
269
270 const resource = current.name ?? name;
271 const displayNameChanged = (current.displayName ?? "") !== displayName;
272 const conditionsChanged = !sameJson(current.conditions, news.conditions);
273 const useCasesChanged = !sameStringList(
274 current.useCases,
275 news.useCases ?? ["SEARCH_USE_CASE_SEARCH"],
276 );
277
278 if (displayNameChanged || conditionsChanged || useCasesChanged) {
279 current = yield* discoveryengine.patchProjectsLocationsCollectionsDataStoresControls({
280 name: resource,
281 updateMask: [
282 displayNameChanged ? "display_name" : undefined,
283 conditionsChanged ? "conditions" : undefined,
284 useCasesChanged ? "use_cases" : undefined,
285 ]
286 .filter((field): field is string => field !== undefined)
287 .join(","),
288 body: { ...body, name: resource },
289 });
290 }
291
292 return toAttrs(current, env.project);
293 }),
294
295 delete: Effect.fn(function* ({ output }) {
296 yield* discoveryengine
297 .deleteProjectsLocationsCollectionsDataStoresControls({
298 name: output.name,
299 })
300 .pipe(Effect.catchTag("NotFound", () => Effect.void));
301 }),
302 });