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

main
ts 360 lines 12.4 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 expandDataStore,
12 parseResourceName,
13 sameStringList,
14 servingConfigIdOf,
15 toPhysical,
16 } from "./internal.ts";
17
18 export type DataStoresServingConfigProps = {
19 /**
20 * Parent Data Store resource name
21 * `projects/{project}/locations/{location}/dataStores/{dataStore}`.
22 * Immutable — changing it replaces the serving config.
23 */
24 dataStore: string;
25 /**
26 * Serving config id (4-63 characters, `a-zA-Z0-9`). If omitted, a
27 * unique id is generated. Immutable — changing it replaces the config.
28 */
29 servingConfigId?: string;
30 /**
31 * Human-readable name (max 128 characters).
32 */
33 displayName?: string;
34 /**
35 * Solution type. Immutable — changing it replaces the config.
36 * @default "SOLUTION_TYPE_SEARCH"
37 */
38 solutionType?: string;
39 /**
40 * Filter control ids applied on the serving path. Maximum 20.
41 */
42 filterControlIds?: string[];
43 /**
44 * Boost control ids applied on the serving path. Maximum 20.
45 */
46 boostControlIds?: string[];
47 /**
48 * Redirect control ids. Only the first triggered redirect is applied.
49 */
50 redirectControlIds?: string[];
51 /**
52 * Synonyms control ids.
53 */
54 synonymsControlIds?: string[];
55 /**
56 * One-way synonyms control ids.
57 */
58 onewaySynonymsControlIds?: string[];
59 /**
60 * Dissociate control ids.
61 */
62 dissociateControlIds?: string[];
63 /**
64 * Replacement control ids.
65 */
66 replacementControlIds?: string[];
67 /**
68 * Ignore control ids.
69 */
70 ignoreControlIds?: string[];
71 /**
72 * Promote control ids.
73 */
74 promoteControlIds?: string[];
75 /**
76 * Ranking expression, for example
77 * `0.5 * relevance_score + 0.3 * dotProduct(doc_embedding)`.
78 */
79 rankingExpression?: string;
80 /**
81 * Recommendation model id. Required when `solutionType` is
82 * `SOLUTION_TYPE_RECOMMENDATION`.
83 */
84 modelId?: string;
85 /**
86 * Diversity level for recommendation results
87 * (`no-diversity`, `low-diversity`, `medium-diversity`,
88 * `high-diversity`, `auto-diversity`).
89 */
90 diversityLevel?: string;
91 };
92
93 export type DataStoresServingConfig = Resource<
94 "GCP.DiscoveryEngine.DataStoresServingConfig",
95 DataStoresServingConfigProps,
96 {
97 /** Full resource name `.../dataStores/{dataStore}/servingConfigs/{id}`. */
98 name: string;
99 /** Serving config id (last path segment). */
100 servingConfigId: string;
101 /** Parent data store resource name. */
102 dataStore: string;
103 /** Project id. */
104 project: string;
105 /** Location id. */
106 location: string;
107 /** Display name. */
108 displayName: string | undefined;
109 /** Solution type. */
110 solutionType: string | undefined;
111 /** Filter control ids. */
112 filterControlIds: string[];
113 /** Boost control ids. */
114 boostControlIds: string[];
115 /** Ranking expression, if set. */
116 rankingExpression: string | undefined;
117 /** Recommendation model id, if set. */
118 modelId: string | undefined;
119 /** Diversity level, if set. */
120 diversityLevel: string | undefined;
121 /** RFC3339 creation timestamp. */
122 createTime: string | undefined;
123 /** RFC3339 last-update timestamp. */
124 updateTime: string | undefined;
125 },
126 never,
127 Providers
128 >;
129
130 /**
131 * A Vertex AI Search ServingConfig attached to a Data Store.
132 *
133 * Without labels, ownership rests on the deterministic id: `read` reports a
134 * resource it finds without prior state as unowned (adopt it with `--adopt`).
135 * Parent, id, and solution type are immutable; display name, attached
136 * controls, and ranking update in place. The console only shows the default
137 * serving config — additional configs are API-only.
138 *
139 * ### Creating a Serving Config
140 * **Example:** Search serving config
141 * ```typescript
142 * const config = yield* GCP.DiscoveryEngine.DataStoresServingConfig("Search", {
143 * dataStore: dataStore.name,
144 * displayName: "web-search",
145 * solutionType: "SOLUTION_TYPE_SEARCH",
146 * });
147 * ```
148 *
149 * ### Updating a Serving Config
150 * **Example:** Attach filter controls
151 * ```typescript
152 * // Same logical id as before; only the changed props differ.
153 * const config = yield* GCP.DiscoveryEngine.DataStoresServingConfig("Search", {
154 * dataStore: dataStore.name,
155 * displayName: "web-search",
156 * filterControlIds: [control.controlId],
157 * });
158 * ```
159 *
160 * @resource
161 * @category DiscoveryEngine
162 */
163 export const DataStoresServingConfig = Resource<DataStoresServingConfig>(
164 "GCP.DiscoveryEngine.DataStoresServingConfig",
165 );
166
167 export class DataStoresServingConfigNotResolved extends Data.TaggedError(
168 "GCP.DiscoveryEngine.DataStoresServingConfigNotResolved",
169 )<{
170 resourceName: string;
171 }> {}
172
173 const DEFAULT_SOLUTION = "SOLUTION_TYPE_SEARCH";
174
175 const resourceName = (dataStore: string, servingConfigId: string) =>
176 `${dataStore}/servingConfigs/${servingConfigId}`;
177
178 const toAttrs = (
179 config: discoveryengine.GoogleCloudDiscoveryengineV1ServingConfig,
180 project: string,
181 dataStoreHint?: string,
182 ) => {
183 const name = config.name ?? "";
184 const parsed = parseResourceName(name, "servingConfigs");
185 const dataStore = parsed.dataStore.includes("/dataStores/")
186 ? parsed.dataStore
187 : (dataStoreHint ?? parsed.dataStore);
188 return {
189 name,
190 servingConfigId: parsed.id,
191 dataStore,
192 project: parsed.project || project,
193 location: parsed.location,
194 displayName: config.displayName,
195 solutionType: config.solutionType,
196 filterControlIds: [...(config.filterControlIds ?? [])],
197 boostControlIds: [...(config.boostControlIds ?? [])],
198 rankingExpression: config.rankingExpression,
199 modelId: config.modelId,
200 diversityLevel: config.diversityLevel,
201 createTime: config.createTime,
202 updateTime: config.updateTime,
203 };
204 };
205
206 const getByName = (name: string) =>
207 name.length === 0
208 ? Effect.undefined
209 : discoveryengine
210 .getProjectsLocationsDataStoresServingConfigs({ name })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 export const DataStoresServingConfigProvider = () =>
214 Provider.succeed(DataStoresServingConfig, {
215 stables: ["name", "servingConfigId", "dataStore", "project", "location", "createTime"],
216
217 diff: Effect.fn(function* ({ news, olds, output }) {
218 if (!isResolved(news)) return undefined;
219 const previousParent = olds?.dataStore ?? output?.dataStore;
220 if (previousParent !== undefined && news.dataStore !== previousParent) {
221 return { action: "replace" as const, deleteFirst: false };
222 }
223 const previousId = olds?.servingConfigId ?? output?.servingConfigId;
224 if (
225 previousId !== undefined &&
226 news.servingConfigId !== undefined &&
227 news.servingConfigId !== previousId
228 ) {
229 return { action: "replace" as const, deleteFirst: true };
230 }
231 const previousSolution = olds?.solutionType ?? output?.solutionType ?? DEFAULT_SOLUTION;
232 const nextSolution = news.solutionType ?? previousSolution;
233 if (previousSolution !== nextSolution) {
234 return { action: "replace" as const, deleteFirst: true };
235 }
236 return undefined;
237 }),
238
239 read: Effect.fn(function* ({ id, olds, output, previous }) {
240 const env = yield* GcpEnvironment.current;
241 const servingConfigId = yield* toPhysical(
242 id,
243 olds?.servingConfigId,
244 output?.servingConfigId,
245 servingConfigIdOf,
246 );
247 const parent = olds?.dataStore
248 ? expandDataStore(olds.dataStore, env.project, output?.location ?? "global")
249 : undefined;
250 const name = output?.name ?? (parent ? resourceName(parent, servingConfigId) : "");
251 const existing = yield* getByName(name);
252 if (existing === undefined) return undefined;
253 const attrs = toAttrs(existing, env.project);
254 // No labels field: without prior state it may not be ours.
255 return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name");
256 }),
257
258 reconcile: Effect.fn(function* ({ id, news, output }) {
259 const env = yield* GcpEnvironment.current;
260 const parent = expandDataStore(news.dataStore, env.project, output?.location ?? "global");
261 const servingConfigId = yield* toPhysical(
262 id,
263 news.servingConfigId,
264 output?.servingConfigId,
265 servingConfigIdOf,
266 );
267 const name = resourceName(parent, servingConfigId);
268 const displayName = news.displayName ?? servingConfigId;
269 const solutionType = news.solutionType ?? DEFAULT_SOLUTION;
270
271 let current = yield* getByName(output?.name ?? name);
272
273 if (current === undefined) {
274 const created = yield* discoveryengine
275 .createProjectsLocationsDataStoresServingConfigs({
276 parent,
277 servingConfigId,
278 body: {
279 displayName,
280 solutionType,
281 filterControlIds: news.filterControlIds,
282 boostControlIds: news.boostControlIds,
283 redirectControlIds: news.redirectControlIds,
284 synonymsControlIds: news.synonymsControlIds,
285 onewaySynonymsControlIds: news.onewaySynonymsControlIds,
286 dissociateControlIds: news.dissociateControlIds,
287 replacementControlIds: news.replacementControlIds,
288 ignoreControlIds: news.ignoreControlIds,
289 promoteControlIds: news.promoteControlIds,
290 rankingExpression: news.rankingExpression,
291 modelId: news.modelId,
292 diversityLevel: news.diversityLevel,
293 },
294 })
295 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
296 current = created ?? undefined;
297 }
298
299 if (current === undefined) {
300 return yield* new DataStoresServingConfigNotResolved({ resourceName: name });
301 }
302
303 const displayChanged = (current.displayName ?? "") !== displayName;
304 const filterChanged = !sameStringList(current.filterControlIds, news.filterControlIds);
305 const boostChanged = !sameStringList(current.boostControlIds, news.boostControlIds);
306 const rankingChanged = (current.rankingExpression ?? "") !== (news.rankingExpression ?? "");
307 const modelChanged = (current.modelId ?? "") !== (news.modelId ?? "");
308 const diversityChanged = (current.diversityLevel ?? "") !== (news.diversityLevel ?? "");
309 const redirectChanged = !sameStringList(current.redirectControlIds, news.redirectControlIds);
310 const synonymsChanged = !sameStringList(current.synonymsControlIds, news.synonymsControlIds);
311
312 if (
313 displayChanged ||
314 filterChanged ||
315 boostChanged ||
316 rankingChanged ||
317 modelChanged ||
318 diversityChanged ||
319 redirectChanged ||
320 synonymsChanged
321 ) {
322 current = yield* discoveryengine.patchProjectsLocationsDataStoresServingConfigs({
323 name: current.name ?? name,
324 updateMask: [
325 displayChanged ? "display_name" : undefined,
326 filterChanged ? "filter_control_ids" : undefined,
327 boostChanged ? "boost_control_ids" : undefined,
328 rankingChanged ? "ranking_expression" : undefined,
329 modelChanged ? "model_id" : undefined,
330 diversityChanged ? "diversity_level" : undefined,
331 redirectChanged ? "redirect_control_ids" : undefined,
332 synonymsChanged ? "synonyms_control_ids" : undefined,
333 ]
334 .filter((field): field is string => field !== undefined)
335 .join(","),
336 body: {
337 name: current.name ?? name,
338 displayName,
339 filterControlIds: news.filterControlIds,
340 boostControlIds: news.boostControlIds,
341 redirectControlIds: news.redirectControlIds,
342 synonymsControlIds: news.synonymsControlIds,
343 rankingExpression: news.rankingExpression,
344 modelId: news.modelId,
345 diversityLevel: news.diversityLevel,
346 },
347 });
348 }
349
350 return toAttrs(current, env.project, parent);
351 }),
352
353 delete: Effect.fn(function* ({ output }) {
354 const existing = yield* getByName(output.name);
355 if (existing === undefined) return;
356 yield* discoveryengine
357 .deleteProjectsLocationsDataStoresServingConfigs({ name: output.name })
358 .pipe(Effect.catchTag("NotFound", () => Effect.void));
359 }),
360 });