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

main
ts 331 lines 10.9 KB
Raw
1 import * as dialogflow from "@distilled.cloud/gcp/dialogflow_v3";
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 encodeOwnership,
12 listAgents,
13 listEnvironments,
14 listExperiments,
15 ownedByAlchemy,
16 ownershipLabels,
17 ownershipText,
18 parseOwnership,
19 parseResourceName,
20 sameJson,
21 sameText,
22 updateMaskOf,
23 retryQuota,
24 } from "./internal.ts";
25
26 export type ExperimentVariant = {
27 /** Flow version resource name. */
28 version: string;
29 /** Traffic fraction in `[0, 1]`. */
30 trafficAllocation?: number;
31 /** Whether this variant is the control group. */
32 isControlGroup?: boolean;
33 };
34
35 export type ExperimentDefinition = {
36 /** Condition selecting sessions that enter the experiment. */
37 condition?: string;
38 /** Version variants and traffic split. */
39 versionVariants?: {
40 variants?: ExperimentVariant[];
41 };
42 };
43
44 export type AgentsEnvironmentsExperimentProps = {
45 /**
46 * Parent environment resource name
47 * `projects/{project}/locations/{location}/agents/{agent}/environments/{environment}`.
48 * Immutable — changing it replaces the experiment.
49 */
50 environment: string;
51 /**
52 * Experiment id. Server-assigned on create. Immutable — changing it
53 * replaces the experiment.
54 */
55 experimentId?: string;
56 /** Human-readable name, unique within the environment. */
57 displayName?: string;
58 /**
59 * Description. Experiments have no labels field, so Alchemy stamps
60 * ownership into this field for `list` / nuke.
61 */
62 description?: string;
63 /** Experiment definition (condition and version variants). */
64 definition?: ExperimentDefinition;
65 /** Experiment duration (e.g. `"86400s"`). */
66 experimentLength?: string;
67 };
68
69 export type AgentsEnvironmentsExperiment = Resource<
70 "GCP.Dialogflow.AgentsEnvironmentsExperiment",
71 AgentsEnvironmentsExperimentProps,
72 {
73 /** Full resource name. */
74 name: string;
75 /** Experiment id (last path segment). */
76 experimentId: string;
77 /** Parent environment resource name. */
78 environment: string;
79 /** Project id. */
80 project: string;
81 /** Location id. */
82 location: string;
83 /** Display name. */
84 displayName: string | undefined;
85 /** User description with the Alchemy ownership prefix stripped. */
86 description: string | undefined;
87 /** Experiment definition. */
88 definition: ExperimentDefinition | undefined;
89 /** Experiment duration. */
90 experimentLength: string | undefined;
91 /** Experiment state. */
92 state: string | undefined;
93 /** RFC3339 creation timestamp. */
94 createTime: string | undefined;
95 },
96 never,
97 Providers
98 >;
99
100 /**
101 * A Dialogflow CX experiment under an environment.
102 *
103 * Experiments have no labels field, so Alchemy stamps ownership into
104 * `description` for `list` / nuke. Parent environment and experiment id
105 * are immutable. Display name, description, definition, and length
106 * update in place.
107 *
108 * ### Creating an Experiment
109 * **Example:** A/B test two flow versions
110 * ```typescript
111 * const experiment = yield* GCP.Dialogflow.AgentsEnvironmentsExperiment(
112 * "Ab",
113 * {
114 * environment: environment.name,
115 * displayName: "checkout-ab",
116 * definition: {
117 * versionVariants: {
118 * variants: [
119 * {
120 * version: control.name,
121 * trafficAllocation: 0.5,
122 * isControlGroup: true,
123 * },
124 * { version: treatment.name, trafficAllocation: 0.5 },
125 * ],
126 * },
127 * },
128 * },
129 * );
130 * ```
131 *
132 * @resource
133 * @category Dialogflow
134 */
135 export const AgentsEnvironmentsExperiment = Resource<AgentsEnvironmentsExperiment>(
136 "GCP.Dialogflow.AgentsEnvironmentsExperiment",
137 );
138
139 export class AgentsEnvironmentsExperimentNotResolved extends Data.TaggedError(
140 "GCP.Dialogflow.AgentsEnvironmentsExperimentNotResolved",
141 )<{
142 resourceName: string;
143 }> {}
144
145 const definitionOf = (
146 definition: dialogflow.GoogleCloudDialogflowCxV3ExperimentDefinition | undefined,
147 ): ExperimentDefinition | undefined => {
148 if (definition === undefined) return undefined;
149 return {
150 condition: definition.condition,
151 versionVariants: definition.versionVariants
152 ? {
153 variants: (definition.versionVariants.variants ?? []).map((variant) => ({
154 version: variant.version ?? "",
155 trafficAllocation: variant.trafficAllocation,
156 isControlGroup: variant.isControlGroup,
157 })),
158 }
159 : undefined,
160 };
161 };
162
163 const toAttrs = (experiment: dialogflow.GoogleCloudDialogflowCxV3Experiment, project: string) => {
164 const name = experiment.name ?? "";
165 const parsed = parseResourceName(name, "experiments");
166 return {
167 name,
168 experimentId: parsed.id,
169 environment: parsed.environment || parsed.parent,
170 project: parsed.project || project,
171 location: parsed.location,
172 displayName: experiment.displayName,
173 description: parseOwnership(experiment.description).text,
174 definition: definitionOf(experiment.definition),
175 experimentLength: experiment.experimentLength,
176 state: experiment.state,
177 createTime: experiment.createTime,
178 };
179 };
180
181 const getByName = (name: string) =>
182 name.length === 0
183 ? Effect.undefined
184 : dialogflow
185 .getProjectsLocationsAgentsEnvironmentsExperiments({ name })
186 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
187
188 const findOwned = (id: string, environment: string, hinted?: string) =>
189 Effect.gen(function* () {
190 if (hinted !== undefined && hinted.length > 0) {
191 const existing = yield* getByName(hinted);
192 if (existing !== undefined) return existing;
193 }
194 const experiments = yield* listExperiments(environment);
195 for (const experiment of experiments) {
196 if (yield* ownedByAlchemy(id, ownershipText(experiment))) {
197 return experiment;
198 }
199 }
200 return undefined as dialogflow.GoogleCloudDialogflowCxV3Experiment | undefined;
201 });
202
203 const listOwned = (project: string) =>
204 Effect.gen(function* () {
205 const agents = yield* listAgents(project);
206 const environments = (yield* Effect.forEach(
207 agents,
208 (agent) => (agent.name ? listEnvironments(agent.name) : Effect.succeed([])),
209 { concurrency: 4 },
210 )).flat();
211 const experiments = (yield* Effect.forEach(
212 environments,
213 (environment) => (environment.name ? listExperiments(environment.name) : Effect.succeed([])),
214 { concurrency: 4 },
215 )).flat();
216 return experiments
217 .filter(
218 (experiment) =>
219 parseOwnership(experiment.description).labels["alchemy-id"] !== undefined ||
220 parseOwnership(experiment.displayName).labels["alchemy-id"] !== undefined,
221 )
222 .map((experiment) => toAttrs(experiment, project));
223 });
224
225 export const AgentsEnvironmentsExperimentProvider = () =>
226 Provider.succeed(AgentsEnvironmentsExperiment, {
227 stables: ["name", "experimentId", "environment", "project", "location", "createTime"],
228
229 diff: Effect.fn(function* ({ news, olds, output }) {
230 if (!isResolved(news)) return undefined;
231 const previousParent = olds?.environment ?? output?.environment;
232 const previousId = olds?.experimentId ?? output?.experimentId;
233 if (
234 (previousParent !== undefined && news.environment !== previousParent) ||
235 (previousId !== undefined &&
236 news.experimentId !== undefined &&
237 news.experimentId !== previousId)
238 ) {
239 return {
240 action: "replace" as const,
241 deleteFirst:
242 previousParent === news.environment &&
243 previousId !== undefined &&
244 news.experimentId === previousId,
245 };
246 }
247 return undefined;
248 }),
249
250 read: Effect.fn(function* ({ id, olds, output }) {
251 const env = yield* GcpEnvironment.current;
252 const environment = olds?.environment ?? output?.environment;
253 const existing =
254 output?.name !== undefined
255 ? yield* getByName(output.name)
256 : environment !== undefined
257 ? yield* findOwned(id, environment)
258 : undefined;
259 if (existing === undefined) return undefined;
260 const attrs = toAttrs(existing, env.project);
261 return (yield* ownedByAlchemy(id, ownershipText(existing))) ? attrs : Unowned(attrs);
262 }),
263
264 list: () =>
265 Effect.gen(function* () {
266 const env = yield* GcpEnvironment.current;
267 return yield* listOwned(env.project);
268 }),
269
270 reconcile: Effect.fn(function* ({ id, news, output }) {
271 const env = yield* GcpEnvironment.current;
272 const environment = news.environment;
273 const ownership = yield* ownershipLabels(id);
274 const description = encodeOwnership(ownership, news.description);
275 const displayName = news.displayName ?? "experiment";
276 const body: dialogflow.GoogleCloudDialogflowCxV3Experiment = {
277 displayName,
278 description,
279 definition: news.definition,
280 experimentLength: news.experimentLength,
281 };
282
283 let current = yield* findOwned(id, environment, output?.name);
284
285 if (current === undefined) {
286 const created = yield* dialogflow
287 .createProjectsLocationsAgentsEnvironmentsExperiments({
288 parent: environment,
289 body,
290 })
291 .pipe(Effect.catchTag("Conflict", () => findOwned(id, environment, output?.name)));
292 current = created ?? undefined;
293 }
294
295 if (current === undefined) {
296 return yield* new AgentsEnvironmentsExperimentNotResolved({
297 resourceName:
298 output?.name ?? `${environment}/experiments/${news.experimentId ?? "unknown"}`,
299 });
300 }
301
302 const currentName = current.name ?? output?.name ?? "";
303 const displayChanged = !sameText(current.displayName, displayName);
304 const descriptionChanged = !sameText(current.description, description);
305 const definitionChanged = !sameJson(definitionOf(current.definition), news.definition);
306 const lengthChanged = !sameText(current.experimentLength, news.experimentLength);
307
308 if (displayChanged || descriptionChanged || definitionChanged || lengthChanged) {
309 current = yield* dialogflow.patchProjectsLocationsAgentsEnvironmentsExperiments({
310 name: currentName,
311 updateMask: updateMaskOf(
312 displayChanged ? "display_name" : undefined,
313 descriptionChanged ? "description" : undefined,
314 definitionChanged ? "definition" : undefined,
315 lengthChanged ? "experiment_length" : undefined,
316 ),
317 body: { ...body, name: currentName },
318 });
319 }
320
321 return toAttrs(current, env.project);
322 }, retryQuota),
323
324 delete: Effect.fn(function* ({ output }) {
325 yield* dialogflow
326 .deleteProjectsLocationsAgentsEnvironmentsExperiments({
327 name: output.name,
328 })
329 .pipe(Effect.catchTag("NotFound", () => Effect.void));
330 }, retryQuota),
331 });