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

main
ts 281 lines 9.84 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 { parentBefore, parseResourceName, sameJson, toResourceId } from "./internal.ts";
11
12 export type CollectionsEnginesAssistantProps = {
13 /**
14 * Parent Engine resource name
15 * `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`.
16 * Immutable — changing it replaces the assistant.
17 */
18 engine: string;
19 /**
20 * Assistant id. If omitted, a unique RFC-1034 id is generated.
21 * Immutable — changing it replaces the assistant.
22 */
23 assistantId?: string;
24 /**
25 * User-facing display name (max 128 characters).
26 */
27 displayName?: string;
28 /**
29 * Configuration description.
30 */
31 description?: string;
32 /**
33 * Web grounding type.
34 */
35 webGroundingType?: discoveryengine.GoogleCloudDiscoveryengineV1AssistantWebGroundingTypeEnum;
36 /**
37 * When true, the default web-grounding toggle is off in the UI.
38 * @default false
39 */
40 defaultWebGroundingToggleOff?: boolean;
41 /**
42 * Generation configuration (language, model, system instruction).
43 */
44 generationConfig?: discoveryengine.GoogleCloudDiscoveryengineV1AssistantGenerationConfig;
45 /**
46 * Customer policy (banned phrases, Model Armor).
47 */
48 customerPolicy?: discoveryengine.GoogleCloudDiscoveryengineV1AssistantCustomerPolicy;
49 };
50
51 export type CollectionsEnginesAssistant = Resource<
52 "GCP.DiscoveryEngine.CollectionsEnginesAssistant",
53 CollectionsEnginesAssistantProps,
54 {
55 /** Full resource name. */
56 name: string;
57 /** Assistant id (last path segment). */
58 assistantId: string;
59 /** Parent engine resource name. */
60 engine: string;
61 /** Project id. */
62 project: string;
63 /** Location id. */
64 location: string;
65 /** Collection id. */
66 collectionId: string;
67 /** User display name. */
68 displayName: string | undefined;
69 /** Description. */
70 description: string | undefined;
71 /** Web grounding type. */
72 webGroundingType: string | undefined;
73 /** Whether the default web-grounding toggle is off. */
74 defaultWebGroundingToggleOff: boolean;
75 /** RFC3339 creation timestamp. */
76 createTime: string | undefined;
77 /** RFC3339 last-update timestamp. */
78 updateTime: string | undefined;
79 },
80 never,
81 Providers
82 >;
83
84 /**
85 * A Discovery Engine Assistant attached to a collection Engine.
86 *
87 * Without labels, ownership rests on the deterministic id: `read` reports a
88 * resource it finds without prior state as unowned (adopt it with `--adopt`).
89 * Parent engine and assistant id are immutable; display name, description,
90 * grounding, and generation config update in place.
91 *
92 * ### Creating an Assistant
93 * **Example:** Assistant on a search engine
94 * ```typescript
95 * const engine = yield* GCP.DiscoveryEngine.CollectionsEngine("Search", {
96 * dataStoreIds: [store.dataStoreId],
97 * });
98 * const assistant = yield* GCP.DiscoveryEngine.CollectionsEnginesAssistant(
99 * "Help",
100 * {
101 * engine: engine.name,
102 * displayName: "docs helper",
103 * },
104 * );
105 * ```
106 *
107 * ### Updating an Assistant
108 * **Example:** Rename
109 * ```typescript
110 * // Same logical id as before; only the changed props differ.
111 * const assistant = yield* GCP.DiscoveryEngine.CollectionsEnginesAssistant(
112 * "Help",
113 * {
114 * engine: engine.name,
115 * displayName: "docs helper prod",
116 * },
117 * );
118 * ```
119 *
120 * @resource
121 * @category DiscoveryEngine
122 */
123 export const CollectionsEnginesAssistant = Resource<CollectionsEnginesAssistant>(
124 "GCP.DiscoveryEngine.CollectionsEnginesAssistant",
125 );
126
127 export class CollectionsEnginesAssistantNotResolved extends Data.TaggedError(
128 "GCP.DiscoveryEngine.CollectionsEnginesAssistantNotResolved",
129 )<{
130 resourceName: string;
131 }> {}
132
133 const resourceName = (engine: string, assistantId: string) => `${engine}/assistants/${assistantId}`;
134
135 const getByName = (name: string) =>
136 discoveryengine
137 .getProjectsLocationsCollectionsEnginesAssistants({ name })
138 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
139
140 const toAttrs = (
141 assistant: discoveryengine.GoogleCloudDiscoveryengineV1Assistant,
142 project: string,
143 ) => {
144 const name = assistant.name ?? "";
145 const parsed = parseResourceName(name, "assistants");
146 return {
147 name,
148 assistantId: parsed.id,
149 engine: parentBefore(name, "assistants"),
150 project: parsed.project || project,
151 location: parsed.location,
152 collectionId: parsed.collectionId,
153 displayName: assistant.displayName,
154 description: assistant.description,
155 webGroundingType: assistant.webGroundingType,
156 defaultWebGroundingToggleOff: assistant.defaultWebGroundingToggleOff === true,
157 createTime: assistant.createTime,
158 updateTime: assistant.updateTime,
159 };
160 };
161
162 export const CollectionsEnginesAssistantProvider = () =>
163 Provider.succeed(CollectionsEnginesAssistant, {
164 stables: ["name", "assistantId", "engine", "project", "location", "collectionId", "createTime"],
165
166 diff: Effect.fn(function* ({ news, olds, output }) {
167 if (!isResolved(news)) return undefined;
168 const previousEngine = olds?.engine ?? output?.engine;
169 const previousId = olds?.assistantId ?? output?.assistantId;
170 const nextId = news.assistantId ?? previousId;
171 if (
172 (previousEngine !== undefined && news.engine !== previousEngine) ||
173 (previousId !== undefined && nextId !== undefined && nextId !== previousId)
174 ) {
175 return { action: "replace" as const, deleteFirst: false };
176 }
177 return undefined;
178 }),
179
180 read: Effect.fn(function* ({ id, olds, output }) {
181 const env = yield* GcpEnvironment.current;
182 const parent = olds?.engine ?? output?.engine;
183 const childId = yield* toResourceId(id, olds?.assistantId, output?.assistantId);
184 const name =
185 output?.name ?? (parent !== undefined ? resourceName(parent, childId) : undefined);
186 if (name === undefined) return undefined;
187 const existing = yield* getByName(name);
188 if (existing === undefined) return undefined;
189 const attrs = toAttrs(existing, env.project);
190 // No labels field: without prior state it may not be ours.
191 return output !== undefined ? attrs : Unowned(attrs);
192 }),
193
194 reconcile: Effect.fn(function* ({ id, news, output }) {
195 const env = yield* GcpEnvironment.current;
196 const assistantId = yield* toResourceId(id, news.assistantId, output?.assistantId);
197 const description = news.description;
198 const displayName = news.displayName ?? assistantId;
199 const fallbackName = output?.name ?? resourceName(news.engine, assistantId);
200 const groundingOff = news.defaultWebGroundingToggleOff === true;
201
202 let current = yield* getByName(fallbackName);
203
204 if (current === undefined) {
205 const created = yield* discoveryengine
206 .createProjectsLocationsCollectionsEnginesAssistants({
207 parent: news.engine,
208 assistantId,
209 body: {
210 displayName,
211 description,
212 webGroundingType: news.webGroundingType,
213 defaultWebGroundingToggleOff: groundingOff ? true : undefined,
214 generationConfig: news.generationConfig,
215 customerPolicy: news.customerPolicy,
216 },
217 })
218 .pipe(Effect.catchTag("Conflict", () => getByName(fallbackName)));
219 current = created ?? undefined;
220 }
221
222 if (current === undefined) {
223 return yield* new CollectionsEnginesAssistantNotResolved({
224 resourceName: fallbackName,
225 });
226 }
227
228 const name = current.name ?? fallbackName;
229 const displayNameChanged = (current.displayName ?? "") !== (displayName ?? "");
230 const descriptionChanged = (current.description ?? "") !== (description ?? "");
231 const groundingTypeChanged =
232 (current.webGroundingType ?? "") !== (news.webGroundingType ?? "");
233 const groundingOffChanged = (current.defaultWebGroundingToggleOff === true) !== groundingOff;
234 const generationChanged = !sameJson(current.generationConfig, news.generationConfig);
235 const policyChanged = !sameJson(current.customerPolicy, news.customerPolicy);
236
237 if (
238 displayNameChanged ||
239 descriptionChanged ||
240 groundingTypeChanged ||
241 groundingOffChanged ||
242 generationChanged ||
243 policyChanged
244 ) {
245 current = yield* discoveryengine.patchProjectsLocationsCollectionsEnginesAssistants({
246 name,
247 updateMask: [
248 displayNameChanged ? "display_name" : undefined,
249 descriptionChanged ? "description" : undefined,
250 groundingTypeChanged ? "web_grounding_type" : undefined,
251 groundingOffChanged ? "default_web_grounding_toggle_off" : undefined,
252 generationChanged ? "generation_config" : undefined,
253 policyChanged ? "customer_policy" : undefined,
254 ]
255 .filter((field): field is string => field !== undefined)
256 .join(","),
257 body: {
258 name,
259 displayName,
260 description,
261 webGroundingType: news.webGroundingType,
262 defaultWebGroundingToggleOff: groundingOff,
263 generationConfig: news.generationConfig,
264 customerPolicy: news.customerPolicy,
265 },
266 });
267 }
268
269 return toAttrs(current, env.project);
270 }),
271
272 delete: Effect.fn(function* ({ output }) {
273 const existing = yield* getByName(output.name);
274 if (existing === undefined) return;
275 yield* discoveryengine
276 .deleteProjectsLocationsCollectionsEnginesAssistants({
277 name: output.name,
278 })
279 .pipe(Effect.catchTag("NotFound", () => Effect.void));
280 }),
281 });