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

main
ts 317 lines 11.1 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_v1";
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 parentBefore,
12 parseResourceName,
13 sameJson,
14 sameStringList,
15 toResourceId,
16 } from "./internal.ts";
17
18 export type CollectionsEnginesControlProps = {
19 /**
20 * Parent Engine resource name
21 * `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`.
22 * Immutable — changing it replaces the control.
23 */
24 engine: string;
25 /**
26 * Control id (1-63 characters, `a-z`, `_`, `-`). If omitted, a unique
27 * id is generated. Immutable — changing it replaces the control.
28 */
29 controlId?: string;
30 /**
31 * Human-readable name.
32 */
33 displayName?: string;
34 /**
35 * Solution the control belongs to. Immutable.
36 * @default "SOLUTION_TYPE_SEARCH"
37 */
38 solutionType?: discoveryengine.GoogleCloudDiscoveryengineV1ControlSolutionTypeEnum;
39 /**
40 * Use cases. Required when `solutionType` is `SOLUTION_TYPE_SEARCH`.
41 * @default ["SEARCH_USE_CASE_SEARCH"]
42 */
43 useCases?: discoveryengine.GoogleCloudDiscoveryengineV1ControlUseCasesItemEnumList;
44 /**
45 * Conditions that must match before the action runs.
46 */
47 conditions?: discoveryengine.GoogleCloudDiscoveryengineV1ConditionList;
48 /**
49 * Redirect-type action.
50 */
51 redirectAction?: discoveryengine.GoogleCloudDiscoveryengineV1ControlRedirectAction;
52 /**
53 * Filter-type action.
54 */
55 filterAction?: discoveryengine.GoogleCloudDiscoveryengineV1ControlFilterAction;
56 /**
57 * Synonyms-type action.
58 */
59 synonymsAction?: discoveryengine.GoogleCloudDiscoveryengineV1ControlSynonymsAction;
60 /**
61 * Boost-type action.
62 */
63 boostAction?: discoveryengine.GoogleCloudDiscoveryengineV1ControlBoostAction;
64 /**
65 * Promote-type action.
66 */
67 promoteAction?: discoveryengine.GoogleCloudDiscoveryengineV1ControlPromoteAction;
68 };
69
70 export type CollectionsEnginesControl = Resource<
71 "GCP.DiscoveryEngine.CollectionsEnginesControl",
72 CollectionsEnginesControlProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Control id (last path segment). */
77 controlId: string;
78 /** Parent engine resource name. */
79 engine: string;
80 /** Project id. */
81 project: string;
82 /** Location id. */
83 location: string;
84 /** Collection id. */
85 collectionId: string;
86 /** Display name. */
87 displayName: string | undefined;
88 /** Solution type. */
89 solutionType: string | undefined;
90 /** Use cases. */
91 useCases: string[];
92 /** Serving configs this control is attached to. */
93 associatedServingConfigIds: string[];
94 },
95 never,
96 Providers
97 >;
98
99 /**
100 * A Discovery Engine Control on a collection Engine — redirects,
101 * filters, synonyms, boosts, or promotions applied at serving time.
102 *
103 * Without labels, ownership rests on the deterministic id: `read` reports a
104 * resource it finds without prior state as unowned (adopt it with `--adopt`).
105 * Parent engine, control id, and solution type are immutable, and so is the
106 * action (changing it replaces the control); display name, use cases, and
107 * conditions update in place.
108 *
109 * ### Creating a Control
110 * **Example:** Synonym control
111 * ```typescript
112 * const control = yield* GCP.DiscoveryEngine.CollectionsEnginesControl(
113 * "Synonyms",
114 * {
115 * engine: engine.name,
116 * displayName: "hello-hi",
117 * synonymsAction: { synonyms: ["hello", "hi"] },
118 * },
119 * );
120 * ```
121 *
122 * ### Updating a Control
123 * **Example:** Change synonyms
124 * ```typescript
125 * // Same logical id as before; only the changed props differ.
126 * const control = yield* GCP.DiscoveryEngine.CollectionsEnginesControl(
127 * "Synonyms",
128 * {
129 * engine: engine.name,
130 * synonymsAction: { synonyms: ["hello", "hi", "hey"] },
131 * },
132 * );
133 * ```
134 *
135 * @resource
136 * @category DiscoveryEngine
137 */
138 export const CollectionsEnginesControl = Resource<CollectionsEnginesControl>(
139 "GCP.DiscoveryEngine.CollectionsEnginesControl",
140 );
141
142 export class CollectionsEnginesControlNotResolved extends Data.TaggedError(
143 "GCP.DiscoveryEngine.CollectionsEnginesControlNotResolved",
144 )<{
145 resourceName: string;
146 }> {}
147
148 const resourceName = (engine: string, controlId: string) => `${engine}/controls/${controlId}`;
149
150 const solutionOf = (
151 value: discoveryengine.GoogleCloudDiscoveryengineV1ControlSolutionTypeEnum | undefined,
152 ) => value ?? "SOLUTION_TYPE_SEARCH";
153
154 const useCasesOf = (
155 value: discoveryengine.GoogleCloudDiscoveryengineV1ControlUseCasesItemEnumList | undefined,
156 solutionType: string,
157 ): discoveryengine.GoogleCloudDiscoveryengineV1ControlUseCasesItemEnumList | undefined => {
158 if (value && value.length > 0) return value;
159 if (solutionType === "SOLUTION_TYPE_SEARCH") {
160 return ["SEARCH_USE_CASE_SEARCH"];
161 }
162 return undefined;
163 };
164
165 const getByName = (name: string) =>
166 discoveryengine
167 .getProjectsLocationsCollectionsEnginesControls({ name })
168 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
169
170 const toAttrs = (control: discoveryengine.GoogleCloudDiscoveryengineV1Control, project: string) => {
171 const name = control.name ?? "";
172 const parsed = parseResourceName(name, "controls");
173 return {
174 name,
175 controlId: parsed.id,
176 engine: parentBefore(name, "controls"),
177 project: parsed.project || project,
178 location: parsed.location,
179 collectionId: parsed.collectionId,
180 displayName: control.displayName,
181 solutionType: control.solutionType,
182 useCases: [...(control.useCases ?? [])],
183 associatedServingConfigIds: [...(control.associatedServingConfigIds ?? [])],
184 };
185 };
186
187 const bodyOf = (
188 news: CollectionsEnginesControlProps,
189 displayName: string,
190 solutionType: discoveryengine.GoogleCloudDiscoveryengineV1ControlSolutionTypeEnum,
191 useCases: discoveryengine.GoogleCloudDiscoveryengineV1ControlUseCasesItemEnumList | undefined,
192 ): discoveryengine.GoogleCloudDiscoveryengineV1Control => ({
193 displayName,
194 solutionType,
195 useCases,
196 conditions: news.conditions,
197 redirectAction: news.redirectAction,
198 filterAction: news.filterAction,
199 synonymsAction: news.synonymsAction,
200 boostAction: news.boostAction,
201 promoteAction: news.promoteAction,
202 });
203
204 export const CollectionsEnginesControlProvider = () =>
205 Provider.succeed(CollectionsEnginesControl, {
206 stables: ["name", "controlId", "engine", "project", "location", "collectionId", "solutionType"],
207
208 diff: Effect.fn(function* ({ news, olds, output }) {
209 if (!isResolved(news)) return undefined;
210 const previousEngine = olds?.engine ?? output?.engine;
211 const previousId = olds?.controlId ?? output?.controlId;
212 const nextId = news.controlId ?? previousId;
213 const previousSolution = solutionOf(
214 olds?.solutionType ??
215 (output?.solutionType as CollectionsEnginesControlProps["solutionType"]),
216 );
217 const nextSolution = solutionOf(
218 news.solutionType ??
219 (output?.solutionType as CollectionsEnginesControlProps["solutionType"]),
220 );
221 if (
222 (previousEngine !== undefined && news.engine !== previousEngine) ||
223 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
224 previousSolution !== nextSolution
225 ) {
226 return { action: "replace" as const, deleteFirst: false };
227 }
228 // A control's action is immutable ("updateMask contains an immutable
229 // path synonyms_action"), so any action change replaces it.
230 if (
231 olds !== undefined &&
232 (!sameJson(olds.redirectAction, news.redirectAction) ||
233 !sameJson(olds.filterAction, news.filterAction) ||
234 !sameJson(olds.synonymsAction, news.synonymsAction) ||
235 !sameJson(olds.boostAction, news.boostAction) ||
236 !sameJson(olds.promoteAction, news.promoteAction))
237 ) {
238 return { action: "replace" as const, deleteFirst: true };
239 }
240 return undefined;
241 }),
242
243 read: Effect.fn(function* ({ id, olds, output, previous }) {
244 const env = yield* GcpEnvironment.current;
245 const parent = olds?.engine ?? output?.engine;
246 const childId = yield* toResourceId(id, olds?.controlId, output?.controlId);
247 const name =
248 output?.name ?? (parent !== undefined ? resourceName(parent, childId) : undefined);
249 if (name === undefined) return undefined;
250 const existing = yield* getByName(name);
251 if (existing === undefined) return undefined;
252 const attrs = toAttrs(existing, env.project);
253 // No labels field: without prior state it may not be ours.
254 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
255 }),
256
257 reconcile: Effect.fn(function* ({ id, news, output }) {
258 const env = yield* GcpEnvironment.current;
259 const controlId = yield* toResourceId(id, news.controlId, output?.controlId);
260 const displayName = news.displayName ?? controlId;
261 const solutionType = solutionOf(news.solutionType);
262 const useCases = useCasesOf(news.useCases, solutionType);
263 const fallbackName = output?.name ?? resourceName(news.engine, controlId);
264 const desired = bodyOf(news, displayName, solutionType, useCases);
265
266 let current = yield* getByName(fallbackName);
267
268 if (current === undefined) {
269 const created = yield* discoveryengine
270 .createProjectsLocationsCollectionsEnginesControls({
271 parent: news.engine,
272 controlId,
273 body: desired,
274 })
275 .pipe(Effect.catchTag("Conflict", () => getByName(fallbackName)));
276 current = created ?? undefined;
277 }
278
279 if (current === undefined) {
280 return yield* new CollectionsEnginesControlNotResolved({
281 resourceName: fallbackName,
282 });
283 }
284
285 const name = current.name ?? fallbackName;
286 const displayNameChanged = (current.displayName ?? "") !== displayName;
287 const useCasesChanged = !sameStringList(current.useCases, useCases);
288 const conditionsChanged = !sameJson(current.conditions, news.conditions);
289
290 // Actions are immutable; diff replaces the control when they change.
291 if (displayNameChanged || useCasesChanged || conditionsChanged) {
292 current = yield* discoveryengine.patchProjectsLocationsCollectionsEnginesControls({
293 name,
294 updateMask: [
295 displayNameChanged ? "display_name" : undefined,
296 useCasesChanged ? "use_cases" : undefined,
297 conditionsChanged ? "conditions" : undefined,
298 ]
299 .filter((field): field is string => field !== undefined)
300 .join(","),
301 body: { name, ...desired },
302 });
303 }
304
305 return toAttrs(current, env.project);
306 }),
307
308 delete: Effect.fn(function* ({ output }) {
309 const existing = yield* getByName(output.name);
310 if (existing === undefined) return;
311 yield* discoveryengine
312 .deleteProjectsLocationsCollectionsEnginesControls({
313 name: output.name,
314 })
315 .pipe(Effect.catchTag("NotFound", () => Effect.void));
316 }),
317 });