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

main
ts 314 lines 10.4 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 expandName,
13 listAgents,
14 listEnvironments,
15 normalizeLocation,
16 ownedByAlchemy,
17 ownershipLabels,
18 ownershipText,
19 parseOwnership,
20 parseResourceName,
21 resourceNameFromOperation,
22 sameJson,
23 sameText,
24 updateMaskOf,
25 waitForOperation,
26 retryQuota,
27 } from "./internal.ts";
28
29 export type EnvironmentVersionConfig = {
30 /**
31 * Flow version resource name
32 * `projects/{project}/locations/{location}/agents/{agent}/flows/{flow}/versions/{version}`.
33 */
34 version: string;
35 };
36
37 export type AgentsEnvironmentProps = {
38 /**
39 * Parent agent resource name
40 * `projects/{project}/locations/{location}/agents/{agent}`. Immutable —
41 * changing it replaces the environment.
42 */
43 agent: string;
44 /**
45 * Environment id (the `{environment}` segment). Server-assigned on
46 * create. Immutable — changing it replaces the environment.
47 */
48 environmentId?: string;
49 /**
50 * Location used when `agent` is a bare id.
51 * @default "global"
52 */
53 location?: string;
54 /** Human-readable name, unique within the agent. */
55 displayName?: string;
56 /**
57 * Description. Environments have no labels field, so Alchemy stamps
58 * ownership into this field for `list` / nuke.
59 */
60 description?: string;
61 /**
62 * Flow versions served by this environment. Must include a version of
63 * every flow reachable from the start flow.
64 */
65 versionConfigs: EnvironmentVersionConfig[];
66 };
67
68 export type AgentsEnvironment = Resource<
69 "GCP.Dialogflow.AgentsEnvironment",
70 AgentsEnvironmentProps,
71 {
72 /** Full resource name. */
73 name: string;
74 /** Environment id (last path segment). */
75 environmentId: string;
76 /** Parent agent resource name. */
77 agent: string;
78 /** Project id. */
79 project: string;
80 /** Location id. */
81 location: string;
82 /** Display name. */
83 displayName: string | undefined;
84 /** User description with the Alchemy ownership prefix stripped. */
85 description: string | undefined;
86 /** Served flow versions. */
87 versionConfigs: EnvironmentVersionConfig[];
88 /** RFC3339 last-update timestamp. */
89 updateTime: string | undefined;
90 },
91 never,
92 Providers
93 >;
94
95 /**
96 * A Dialogflow CX environment under an agent.
97 *
98 * Environments have no labels field, so Alchemy stamps ownership into
99 * `description` for `list` / nuke. Parent agent and environment id are
100 * immutable. Display name, description, and version configs update in
101 * place. Create and update are long-running operations.
102 *
103 * ### Creating an Environment
104 * **Example:** Serve a flow version
105 * ```typescript
106 * const version = yield* GCP.Dialogflow.AgentsFlowsVersion("V1", {
107 * flow: agent.startFlow,
108 * displayName: "v1",
109 * });
110 * const environment = yield* GCP.Dialogflow.AgentsEnvironment("Prod", {
111 * agent: agent.name,
112 * displayName: "prod",
113 * versionConfigs: [{ version: version.name }],
114 * });
115 * ```
116 *
117 * @resource
118 * @category Dialogflow
119 */
120 export const AgentsEnvironment = Resource<AgentsEnvironment>("GCP.Dialogflow.AgentsEnvironment");
121
122 export class AgentsEnvironmentNotResolved extends Data.TaggedError(
123 "GCP.Dialogflow.AgentsEnvironmentNotResolved",
124 )<{
125 resourceName: string;
126 }> {}
127
128 const configsOf = (
129 list: readonly dialogflow.GoogleCloudDialogflowCxV3EnvironmentVersionConfig[] | undefined,
130 ): EnvironmentVersionConfig[] =>
131 (list ?? [])
132 .filter((config) => (config.version ?? "").length > 0)
133 .map((config) => ({ version: config.version ?? "" }));
134
135 const toAttrs = (environment: dialogflow.GoogleCloudDialogflowCxV3Environment, project: string) => {
136 const name = environment.name ?? "";
137 const parsed = parseResourceName(name, "environments");
138 return {
139 name,
140 environmentId: parsed.id,
141 agent: parsed.agent,
142 project: parsed.project || project,
143 location: parsed.location,
144 displayName: environment.displayName,
145 description: parseOwnership(environment.description).text,
146 versionConfigs: configsOf(environment.versionConfigs),
147 updateTime: environment.updateTime,
148 };
149 };
150
151 const getByName = (name: string) =>
152 name.length === 0
153 ? Effect.undefined
154 : dialogflow
155 .getProjectsLocationsAgentsEnvironments({ name })
156 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
157
158 const findOwned = (id: string, agent: string, hinted?: string) =>
159 Effect.gen(function* () {
160 if (hinted !== undefined && hinted.length > 0) {
161 const existing = yield* getByName(hinted);
162 if (existing !== undefined) return existing;
163 }
164 const environments = yield* listEnvironments(agent);
165 for (const environment of environments) {
166 if (yield* ownedByAlchemy(id, ownershipText(environment))) {
167 return environment;
168 }
169 }
170 return undefined as dialogflow.GoogleCloudDialogflowCxV3Environment | undefined;
171 });
172
173 const resolveFromOperation = (operation: dialogflow.GoogleLongrunningOperation) =>
174 Effect.gen(function* () {
175 const done = yield* waitForOperation(operation);
176 const name = resourceNameFromOperation(done) ?? resourceNameFromOperation(operation);
177 if (name === undefined) return undefined;
178 return yield* getByName(name);
179 });
180
181 export const AgentsEnvironmentProvider = () =>
182 Provider.succeed(AgentsEnvironment, {
183 stables: ["name", "environmentId", "agent", "project", "location"],
184
185 diff: Effect.fn(function* ({ news, olds, output }) {
186 if (!isResolved(news)) return undefined;
187 const previousAgent = olds?.agent ?? output?.agent;
188 const previousId = olds?.environmentId ?? output?.environmentId;
189 if (
190 (previousAgent !== undefined && news.agent !== previousAgent) ||
191 (previousId !== undefined &&
192 news.environmentId !== undefined &&
193 news.environmentId !== previousId)
194 ) {
195 return {
196 action: "replace" as const,
197 deleteFirst:
198 previousAgent === news.agent &&
199 previousId !== undefined &&
200 news.environmentId === previousId,
201 };
202 }
203 return undefined;
204 }),
205
206 read: Effect.fn(function* ({ id, olds, output }) {
207 const env = yield* GcpEnvironment.current;
208 const agent = olds?.agent ?? output?.agent;
209 const existing =
210 output?.name !== undefined
211 ? yield* getByName(output.name)
212 : agent !== undefined
213 ? yield* findOwned(id, agent)
214 : undefined;
215 if (existing === undefined) return undefined;
216 const attrs = toAttrs(existing, env.project);
217 return (yield* ownedByAlchemy(id, ownershipText(existing))) ? attrs : Unowned(attrs);
218 }),
219
220 list: () =>
221 Effect.gen(function* () {
222 const env = yield* GcpEnvironment.current;
223 const agents = yield* listAgents(env.project);
224 const pages = yield* Effect.forEach(
225 agents,
226 (agent) =>
227 agent.name
228 ? listEnvironments(agent.name).pipe(
229 Effect.map((environments) =>
230 environments
231 .filter(
232 (environment) =>
233 parseOwnership(environment.description).labels["alchemy-id"] !==
234 undefined ||
235 parseOwnership(environment.displayName).labels["alchemy-id"] !==
236 undefined,
237 )
238 .map((environment) => toAttrs(environment, env.project)),
239 ),
240 )
241 : Effect.succeed([]),
242 { concurrency: 4 },
243 );
244 return pages.flat();
245 }),
246
247 reconcile: Effect.fn(function* ({ id, news, output }) {
248 const env = yield* GcpEnvironment.current;
249 const location = normalizeLocation(news.location ?? output?.location);
250 const agent = expandName(news.agent, env.project, location, "agents");
251 const ownership = yield* ownershipLabels(id);
252 const description = encodeOwnership(ownership, news.description);
253 const displayName = news.displayName ?? "environment";
254 const versionConfigs = news.versionConfigs;
255 const body: dialogflow.GoogleCloudDialogflowCxV3Environment = {
256 displayName,
257 description,
258 versionConfigs,
259 };
260
261 let current = yield* findOwned(id, agent, output?.name);
262
263 if (current === undefined) {
264 const operation = yield* dialogflow
265 .createProjectsLocationsAgentsEnvironments({
266 parent: agent,
267 body,
268 })
269 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
270 if (operation !== undefined) {
271 current = yield* resolveFromOperation(operation);
272 }
273 if (current === undefined) {
274 current = yield* findOwned(id, agent, output?.name);
275 }
276 }
277
278 if (current === undefined) {
279 return yield* new AgentsEnvironmentNotResolved({
280 resourceName: output?.name ?? `${agent}/environments/${news.environmentId ?? "unknown"}`,
281 });
282 }
283
284 const currentName = current.name ?? output?.name ?? "";
285 const displayChanged = !sameText(current.displayName, displayName);
286 const descriptionChanged = !sameText(current.description, description);
287 const versionsChanged = !sameJson(
288 configsOf(current.versionConfigs),
289 configsOf(versionConfigs),
290 );
291
292 if (displayChanged || descriptionChanged || versionsChanged) {
293 const operation = yield* dialogflow.patchProjectsLocationsAgentsEnvironments({
294 name: currentName,
295 updateMask: updateMaskOf(
296 displayChanged ? "display_name" : undefined,
297 descriptionChanged ? "description" : undefined,
298 versionsChanged ? "version_configs" : undefined,
299 ),
300 body: { ...body, name: currentName },
301 });
302 const patched = yield* resolveFromOperation(operation);
303 current = patched ?? (yield* getByName(currentName)) ?? current;
304 }
305
306 return toAttrs(current, env.project);
307 }, retryQuota),
308
309 delete: Effect.fn(function* ({ output }) {
310 yield* dialogflow
311 .deleteProjectsLocationsAgentsEnvironments({ name: output.name })
312 .pipe(Effect.catchTag("NotFound", () => Effect.void));
313 }, retryQuota),
314 });