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

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