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

main
ts 319 lines 10.1 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 encodeOwnershipLine,
12 listAgents,
13 listFlows,
14 listTransitionRouteGroups,
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 TransitionRoute = {
27 /** Intent that triggers this route. */
28 intent?: string;
29 /** Condition expression. */
30 condition?: string;
31 /** Target flow resource name. */
32 targetFlow?: string;
33 /** Target page resource name. */
34 targetPage?: string;
35 /** Description of the route. */
36 description?: string;
37 /** Fulfillment run when the route matches. */
38 triggerFulfillment?: {
39 messages?: Array<{
40 text?: { text?: string[]; allowPlaybackInterruption?: boolean };
41 }>;
42 tag?: string;
43 };
44 };
45
46 export type AgentsFlowsTransitionRouteGroupProps = {
47 /**
48 * Parent flow resource name
49 * `projects/{project}/locations/{location}/agents/{agent}/flows/{flow}`.
50 * Immutable — changing it replaces the route group.
51 */
52 flow: string;
53 /**
54 * Transition route group id. Server-assigned on create. Immutable —
55 * changing it replaces the route group.
56 */
57 transitionRouteGroupId?: string;
58 /**
59 * Human-readable name, unique within the flow. Route groups have no
60 * labels or description field, so Alchemy stamps ownership into this
61 * field for `list` / nuke.
62 */
63 displayName?: string;
64 /** Transition routes in the group. */
65 transitionRoutes?: TransitionRoute[];
66 /** Language code of the route group. */
67 languageCode?: string;
68 };
69
70 export type AgentsFlowsTransitionRouteGroup = Resource<
71 "GCP.Dialogflow.AgentsFlowsTransitionRouteGroup",
72 AgentsFlowsTransitionRouteGroupProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Route group id (last path segment). */
77 transitionRouteGroupId: string;
78 /** Parent flow resource name. */
79 flow: string;
80 /** Project id. */
81 project: string;
82 /** Location id. */
83 location: string;
84 /** User display name with the Alchemy ownership prefix stripped. */
85 displayName: string | undefined;
86 /** Transition routes. */
87 transitionRoutes: TransitionRoute[];
88 },
89 never,
90 Providers
91 >;
92
93 /**
94 * A Dialogflow CX transition route group under a flow.
95 *
96 * Route groups have no labels field, so Alchemy stamps ownership into
97 * `displayName` for `list` / nuke. Parent flow and id are immutable.
98 * Display name and routes update in place.
99 *
100 * ### Creating a Route Group
101 * **Example:** Fallback routes
102 * ```typescript
103 * const group = yield* GCP.Dialogflow.AgentsFlowsTransitionRouteGroup(
104 * "Fallback",
105 * {
106 * flow: flow.name,
107 * displayName: "fallback",
108 * transitionRoutes: [
109 * {
110 * condition: "true",
111 * triggerFulfillment: {
112 * messages: [{ text: { text: ["I did not get that."] } }],
113 * },
114 * },
115 * ],
116 * },
117 * );
118 * ```
119 *
120 * @resource
121 * @category Dialogflow
122 */
123 export const AgentsFlowsTransitionRouteGroup = Resource<AgentsFlowsTransitionRouteGroup>(
124 "GCP.Dialogflow.AgentsFlowsTransitionRouteGroup",
125 );
126
127 export class AgentsFlowsTransitionRouteGroupNotResolved extends Data.TaggedError(
128 "GCP.Dialogflow.AgentsFlowsTransitionRouteGroupNotResolved",
129 )<{
130 resourceName: string;
131 }> {}
132
133 const routesOf = (
134 list: readonly dialogflow.GoogleCloudDialogflowCxV3TransitionRoute[] | undefined,
135 ): TransitionRoute[] =>
136 (list ?? []).map((route) => ({
137 intent: route.intent,
138 condition: route.condition,
139 targetFlow: route.targetFlow,
140 targetPage: route.targetPage,
141 description: route.description,
142 triggerFulfillment: route.triggerFulfillment
143 ? {
144 messages: route.triggerFulfillment.messages?.map((message) => ({
145 text: message.text
146 ? {
147 text: [...(message.text.text ?? [])],
148 allowPlaybackInterruption: message.text.allowPlaybackInterruption,
149 }
150 : undefined,
151 })),
152 tag: route.triggerFulfillment.tag,
153 }
154 : undefined,
155 }));
156
157 const toAttrs = (
158 group: dialogflow.GoogleCloudDialogflowCxV3TransitionRouteGroup,
159 project: string,
160 ) => {
161 const name = group.name ?? "";
162 const parsed = parseResourceName(name, "transitionRouteGroups");
163 return {
164 name,
165 transitionRouteGroupId: parsed.id,
166 flow: parsed.flow || parsed.parent,
167 project: parsed.project || project,
168 location: parsed.location,
169 displayName: parseOwnership(group.displayName).text,
170 transitionRoutes: routesOf(group.transitionRoutes),
171 };
172 };
173
174 const getByName = (name: string) =>
175 name.length === 0
176 ? Effect.undefined
177 : dialogflow
178 .getProjectsLocationsAgentsFlowsTransitionRouteGroups({ name })
179 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
180
181 const findOwned = (id: string, flow: string, hinted?: string) =>
182 Effect.gen(function* () {
183 if (hinted !== undefined && hinted.length > 0) {
184 const existing = yield* getByName(hinted);
185 if (existing !== undefined) return existing;
186 }
187 const groups = yield* listTransitionRouteGroups(flow);
188 for (const group of groups) {
189 if (yield* ownedByAlchemy(id, ownershipText(group))) return group;
190 }
191 return undefined as dialogflow.GoogleCloudDialogflowCxV3TransitionRouteGroup | undefined;
192 });
193
194 const listOwned = (project: string) =>
195 Effect.gen(function* () {
196 const agents = yield* listAgents(project);
197 const flows = (yield* Effect.forEach(
198 agents,
199 (agent) => (agent.name ? listFlows(agent.name) : Effect.succeed([])),
200 { concurrency: 4 },
201 )).flat();
202 const groups = (yield* Effect.forEach(
203 flows,
204 (flow) => (flow.name ? listTransitionRouteGroups(flow.name) : Effect.succeed([])),
205 { concurrency: 4 },
206 )).flat();
207 return groups
208 .filter((group) => parseOwnership(group.displayName).labels["alchemy-id"] !== undefined)
209 .map((group) => toAttrs(group, project));
210 });
211
212 export const AgentsFlowsTransitionRouteGroupProvider = () =>
213 Provider.succeed(AgentsFlowsTransitionRouteGroup, {
214 stables: ["name", "transitionRouteGroupId", "flow", "project", "location"],
215
216 diff: Effect.fn(function* ({ news, olds, output }) {
217 if (!isResolved(news)) return undefined;
218 const previousFlow = olds?.flow ?? output?.flow;
219 const previousId = olds?.transitionRouteGroupId ?? output?.transitionRouteGroupId;
220 if (
221 (previousFlow !== undefined && news.flow !== previousFlow) ||
222 (previousId !== undefined &&
223 news.transitionRouteGroupId !== undefined &&
224 news.transitionRouteGroupId !== previousId)
225 ) {
226 return {
227 action: "replace" as const,
228 deleteFirst:
229 previousFlow === news.flow &&
230 previousId !== undefined &&
231 news.transitionRouteGroupId === previousId,
232 };
233 }
234 return undefined;
235 }),
236
237 read: Effect.fn(function* ({ id, olds, output }) {
238 const env = yield* GcpEnvironment.current;
239 const flow = olds?.flow ?? output?.flow;
240 const existing =
241 output?.name !== undefined
242 ? yield* getByName(output.name)
243 : flow !== undefined
244 ? yield* findOwned(id, flow)
245 : undefined;
246 if (existing === undefined) return undefined;
247 const attrs = toAttrs(existing, env.project);
248 return (yield* ownedByAlchemy(id, ownershipText(existing))) ? attrs : Unowned(attrs);
249 }),
250
251 list: () =>
252 Effect.gen(function* () {
253 const env = yield* GcpEnvironment.current;
254 return yield* listOwned(env.project);
255 }),
256
257 reconcile: Effect.fn(function* ({ id, news, output }) {
258 const env = yield* GcpEnvironment.current;
259 const flow = news.flow;
260 const ownership = yield* ownershipLabels(id);
261 const displayName = encodeOwnershipLine(ownership, news.displayName ?? "routes");
262 const transitionRoutes = news.transitionRoutes;
263 const body: dialogflow.GoogleCloudDialogflowCxV3TransitionRouteGroup = {
264 displayName,
265 transitionRoutes,
266 };
267
268 let current = yield* findOwned(id, flow, output?.name);
269
270 if (current === undefined) {
271 const created = yield* dialogflow
272 .createProjectsLocationsAgentsFlowsTransitionRouteGroups({
273 parent: flow,
274 languageCode: news.languageCode,
275 body,
276 })
277 .pipe(Effect.catchTag("Conflict", () => findOwned(id, flow, output?.name)));
278 current = created ?? undefined;
279 }
280
281 if (current === undefined) {
282 return yield* new AgentsFlowsTransitionRouteGroupNotResolved({
283 resourceName:
284 output?.name ??
285 `${flow}/transitionRouteGroups/${news.transitionRouteGroupId ?? "unknown"}`,
286 });
287 }
288
289 const currentName = current.name ?? output?.name ?? "";
290 const displayChanged = !sameText(current.displayName, displayName);
291 const routesChanged = !sameJson(
292 routesOf(current.transitionRoutes),
293 routesOf(transitionRoutes),
294 );
295
296 if (displayChanged || routesChanged) {
297 current = yield* dialogflow.patchProjectsLocationsAgentsFlowsTransitionRouteGroups({
298 name: currentName,
299 languageCode: news.languageCode,
300 updateMask: updateMaskOf(
301 displayChanged ? "display_name" : undefined,
302 routesChanged ? "transition_routes" : undefined,
303 ),
304 body: { ...body, name: currentName },
305 });
306 }
307
308 return toAttrs(current, env.project);
309 }, retryQuota),
310
311 delete: Effect.fn(function* ({ output }) {
312 yield* dialogflow
313 .deleteProjectsLocationsAgentsFlowsTransitionRouteGroups({
314 name: output.name,
315 force: true,
316 })
317 .pipe(Effect.catchTag("NotFound", () => Effect.void));
318 }, retryQuota),
319 });