The best way to control Claude Code, Codex and more from any computer or phone
| 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 Stream from "effect/Stream"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { |
| 12 | collectionParent, |
| 13 | DEFAULT_LOCATION, |
| 14 | encodeOwnershipLine, |
| 15 | expandAgent, |
| 16 | fingerprint, |
| 17 | hasOwnershipMarker, |
| 18 | internalLabels, |
| 19 | lastSegment, |
| 20 | locationOf, |
| 21 | MAX_ROUTE_GROUP_DISPLAY_NAME_LENGTH, |
| 22 | namedAgents, |
| 23 | normalizeLocation, |
| 24 | ownedByAlchemy, |
| 25 | parentOf, |
| 26 | parseOwnership, |
| 27 | projectOf, |
| 28 | sameText, |
| 29 | toResourceId, |
| 30 | updateMaskOf, |
| 31 | retryQuota, |
| 32 | } from "./internal.ts"; |
| 33 | |
| 34 | type TransitionRoute = { |
| 35 | /** Intent that triggers this route. */ |
| 36 | intent?: string; |
| 37 | /** Condition expression. At least one of `intent` or `condition` is required. */ |
| 38 | condition?: string; |
| 39 | /** Target flow resource name. */ |
| 40 | targetFlow?: string; |
| 41 | /** Target page resource name. */ |
| 42 | targetPage?: string; |
| 43 | /** Description of the route (max 500 characters). */ |
| 44 | description?: string; |
| 45 | /** Fulfillment run when the route matches. */ |
| 46 | triggerFulfillment?: { |
| 47 | messages?: Array<{ |
| 48 | text?: { text?: string[]; allowPlaybackInterruption?: boolean }; |
| 49 | }>; |
| 50 | tag?: string; |
| 51 | }; |
| 52 | }; |
| 53 | |
| 54 | export type AgentsTransitionRouteGroupProps = { |
| 55 | /** |
| 56 | * Parent agent resource name |
| 57 | * `projects/{project}/locations/{location}/agents/{agent}` or a bare |
| 58 | * agent id (combined with `location`). Immutable — changing it |
| 59 | * replaces the route group. |
| 60 | */ |
| 61 | agent: string; |
| 62 | /** |
| 63 | * Transition route group id (the `{transitionRouteGroup}` segment). |
| 64 | * Server-assigned on create. Immutable — changing it replaces the |
| 65 | * group. |
| 66 | */ |
| 67 | transitionRouteGroupId?: string; |
| 68 | /** |
| 69 | * Location used when `agent` is a bare id. |
| 70 | * @default "global" |
| 71 | */ |
| 72 | location?: string; |
| 73 | /** |
| 74 | * Human-readable name, unique within the agent (max 30 characters |
| 75 | * including Alchemy's ownership marker). Route groups have no labels |
| 76 | * field, so ownership is stored in a compact `[alc …]` prefix and |
| 77 | * stripped from attributes. |
| 78 | */ |
| 79 | displayName?: string; |
| 80 | /** Transition routes in the group. */ |
| 81 | transitionRoutes?: TransitionRoute[]; |
| 82 | /** Language code of the route group. */ |
| 83 | languageCode?: string; |
| 84 | }; |
| 85 | |
| 86 | export type AgentsTransitionRouteGroup = Resource< |
| 87 | "GCP.Dialogflow.AgentsTransitionRouteGroup", |
| 88 | AgentsTransitionRouteGroupProps, |
| 89 | { |
| 90 | /** Full resource name `.../agents/{agent}/transitionRouteGroups/{id}`. */ |
| 91 | name: string; |
| 92 | /** Route group id (last path segment). */ |
| 93 | transitionRouteGroupId: string; |
| 94 | /** Parent agent resource name. */ |
| 95 | agent: string; |
| 96 | /** Project id. */ |
| 97 | project: string; |
| 98 | /** Location id. */ |
| 99 | location: string; |
| 100 | /** User display name with the Alchemy ownership prefix stripped. */ |
| 101 | displayName: string | undefined; |
| 102 | /** Transition routes. */ |
| 103 | transitionRoutes: TransitionRoute[]; |
| 104 | }, |
| 105 | never, |
| 106 | Providers |
| 107 | >; |
| 108 | |
| 109 | /** |
| 110 | * A Dialogflow CX agent-level transition route group. |
| 111 | * |
| 112 | * Agent-level groups are shared across flows. Route groups have no labels |
| 113 | * field, so Alchemy stamps ownership into `displayName` (30-character |
| 114 | * limit; compact `[alc …]` marker) for `list` / nuke. Parent agent and id |
| 115 | * are immutable. Display name and routes update in place. |
| 116 | * |
| 117 | * ### Creating a Route Group |
| 118 | * **Example:** Fallback routes |
| 119 | * ```typescript |
| 120 | * const group = yield* GCP.Dialogflow.AgentsTransitionRouteGroup("Fallback", { |
| 121 | * agent: agent.name, |
| 122 | * displayName: "fb", |
| 123 | * transitionRoutes: [ |
| 124 | * { |
| 125 | * condition: "true", |
| 126 | * triggerFulfillment: { |
| 127 | * messages: [{ text: { text: ["I did not get that."] } }], |
| 128 | * }, |
| 129 | * }, |
| 130 | * ], |
| 131 | * }); |
| 132 | * ``` |
| 133 | * |
| 134 | * ### Updating a Route Group |
| 135 | * Change props on the same logical id; the engine keeps the physical id. |
| 136 | * |
| 137 | * **Example:** Rename |
| 138 | * ```typescript |
| 139 | * const group = yield* GCP.Dialogflow.AgentsTransitionRouteGroup("Fallback", { |
| 140 | * agent: agent.name, |
| 141 | * displayName: "g2", |
| 142 | * transitionRoutes: [ |
| 143 | * { |
| 144 | * condition: "true", |
| 145 | * triggerFulfillment: { |
| 146 | * messages: [{ text: { text: ["Sorry."] } }], |
| 147 | * }, |
| 148 | * }, |
| 149 | * ], |
| 150 | * }); |
| 151 | * ``` |
| 152 | * |
| 153 | * @resource |
| 154 | * @category Dialogflow |
| 155 | */ |
| 156 | export const AgentsTransitionRouteGroup = Resource<AgentsTransitionRouteGroup>( |
| 157 | "GCP.Dialogflow.AgentsTransitionRouteGroup", |
| 158 | ); |
| 159 | |
| 160 | export class AgentsTransitionRouteGroupNotResolved extends Data.TaggedError( |
| 161 | "GCP.Dialogflow.AgentsTransitionRouteGroupNotResolved", |
| 162 | )<{ |
| 163 | resourceName: string; |
| 164 | }> {} |
| 165 | |
| 166 | const resourceName = (agent: string, transitionRouteGroupId: string) => |
| 167 | `${agent}/transitionRouteGroups/${transitionRouteGroupId}`; |
| 168 | |
| 169 | const routesOf = ( |
| 170 | list: readonly dialogflow.GoogleCloudDialogflowCxV3TransitionRoute[] | undefined, |
| 171 | ): TransitionRoute[] => |
| 172 | (list ?? []).map((route) => ({ |
| 173 | intent: route.intent, |
| 174 | condition: route.condition, |
| 175 | targetFlow: route.targetFlow, |
| 176 | targetPage: route.targetPage, |
| 177 | description: route.description, |
| 178 | triggerFulfillment: route.triggerFulfillment |
| 179 | ? { |
| 180 | messages: route.triggerFulfillment.messages?.map((message) => ({ |
| 181 | text: message.text |
| 182 | ? { |
| 183 | text: [...(message.text.text ?? [])], |
| 184 | allowPlaybackInterruption: message.text.allowPlaybackInterruption, |
| 185 | } |
| 186 | : undefined, |
| 187 | })), |
| 188 | tag: route.triggerFulfillment.tag, |
| 189 | } |
| 190 | : undefined, |
| 191 | })); |
| 192 | |
| 193 | const toAttrs = ( |
| 194 | group: dialogflow.GoogleCloudDialogflowCxV3TransitionRouteGroup, |
| 195 | project: string, |
| 196 | agentHint?: string, |
| 197 | ) => { |
| 198 | const name = group.name ?? ""; |
| 199 | return { |
| 200 | name, |
| 201 | transitionRouteGroupId: lastSegment(name), |
| 202 | agent: name.includes("/transitionRouteGroups/") |
| 203 | ? collectionParent(name, "agents") |
| 204 | : (agentHint ?? parentOf(name)), |
| 205 | project: projectOf(name) || project, |
| 206 | location: locationOf(name), |
| 207 | displayName: parseOwnership(group.displayName).text, |
| 208 | transitionRoutes: routesOf(group.transitionRoutes), |
| 209 | }; |
| 210 | }; |
| 211 | |
| 212 | const getByName = (name: string) => |
| 213 | name.length === 0 |
| 214 | ? Effect.undefined |
| 215 | : dialogflow |
| 216 | .getProjectsLocationsAgentsTransitionRouteGroups({ name }) |
| 217 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 218 | |
| 219 | const listAt = (parent: string, project: string) => |
| 220 | dialogflow.listProjectsLocationsAgentsTransitionRouteGroups.pages({ parent, pageSize: 100 }).pipe( |
| 221 | Stream.flatMap((page) => Stream.fromIterable(page.transitionRouteGroups ?? [])), |
| 222 | Stream.filter((group) => hasOwnershipMarker(group.displayName)), |
| 223 | Stream.map((group) => toAttrs(group, project, parent)), |
| 224 | Stream.runCollect, |
| 225 | Effect.map((chunk) => Array.from(chunk)), |
| 226 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 227 | ); |
| 228 | |
| 229 | const findByDisplayName = (parent: string, displayName: string) => |
| 230 | dialogflow.listProjectsLocationsAgentsTransitionRouteGroups.pages({ parent, pageSize: 100 }).pipe( |
| 231 | Stream.flatMap((page) => Stream.fromIterable(page.transitionRouteGroups ?? [])), |
| 232 | Stream.filter((group) => group.displayName === displayName), |
| 233 | Stream.runHead, |
| 234 | Effect.map((option) => (option._tag === "Some" ? option.value : undefined)), |
| 235 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 236 | ); |
| 237 | |
| 238 | export const AgentsTransitionRouteGroupProvider = () => |
| 239 | Provider.succeed(AgentsTransitionRouteGroup, { |
| 240 | stables: ["name", "transitionRouteGroupId", "agent", "project", "location"], |
| 241 | |
| 242 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 243 | if (!isResolved(news)) return undefined; |
| 244 | const previousAgent = olds?.agent ?? output?.agent; |
| 245 | if (previousAgent !== undefined && news.agent !== previousAgent) { |
| 246 | return { action: "replace" as const, deleteFirst: false }; |
| 247 | } |
| 248 | const previousId = olds?.transitionRouteGroupId ?? output?.transitionRouteGroupId; |
| 249 | if ( |
| 250 | previousId !== undefined && |
| 251 | news.transitionRouteGroupId !== undefined && |
| 252 | news.transitionRouteGroupId !== previousId |
| 253 | ) { |
| 254 | return { action: "replace" as const, deleteFirst: false }; |
| 255 | } |
| 256 | const previousLocation = olds?.location ?? output?.location; |
| 257 | if ( |
| 258 | previousLocation !== undefined && |
| 259 | news.location !== undefined && |
| 260 | normalizeLocation(previousLocation) !== normalizeLocation(news.location) |
| 261 | ) { |
| 262 | return { action: "replace" as const, deleteFirst: false }; |
| 263 | } |
| 264 | return undefined; |
| 265 | }), |
| 266 | |
| 267 | read: Effect.fn(function* ({ id, olds, output }) { |
| 268 | const env = yield* GcpEnvironment.current; |
| 269 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 270 | const agent = olds?.agent ? expandAgent(olds.agent, env.project, location) : output?.agent; |
| 271 | const transitionRouteGroupId = yield* toResourceId( |
| 272 | id, |
| 273 | olds?.transitionRouteGroupId, |
| 274 | output?.transitionRouteGroupId, |
| 275 | ); |
| 276 | const name = |
| 277 | output?.name ?? (agent !== undefined ? resourceName(agent, transitionRouteGroupId) : ""); |
| 278 | let existing = yield* getByName(name); |
| 279 | if (existing === undefined && agent !== undefined) { |
| 280 | const ownership = yield* internalLabels(id); |
| 281 | existing = yield* findByDisplayName( |
| 282 | agent, |
| 283 | encodeOwnershipLine(ownership, olds?.displayName, MAX_ROUTE_GROUP_DISPLAY_NAME_LENGTH), |
| 284 | ); |
| 285 | } |
| 286 | if (existing === undefined) return undefined; |
| 287 | const attrs = toAttrs(existing, env.project, agent); |
| 288 | return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs); |
| 289 | }), |
| 290 | |
| 291 | list: () => |
| 292 | Effect.gen(function* () { |
| 293 | const env = yield* GcpEnvironment.current; |
| 294 | const agents = yield* namedAgents(env.project); |
| 295 | const pages = yield* Effect.forEach(agents, (agent) => listAt(agent.name, env.project), { |
| 296 | concurrency: 4, |
| 297 | }); |
| 298 | return pages.flat(); |
| 299 | }), |
| 300 | |
| 301 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 302 | const env = yield* GcpEnvironment.current; |
| 303 | const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION); |
| 304 | const agent = expandAgent(news.agent, env.project, location); |
| 305 | const transitionRouteGroupId = yield* toResourceId( |
| 306 | id, |
| 307 | news.transitionRouteGroupId, |
| 308 | output?.transitionRouteGroupId, |
| 309 | ); |
| 310 | const name = output?.name ?? resourceName(agent, transitionRouteGroupId); |
| 311 | const ownership = yield* internalLabels(id); |
| 312 | const displayName = encodeOwnershipLine( |
| 313 | ownership, |
| 314 | news.displayName, |
| 315 | MAX_ROUTE_GROUP_DISPLAY_NAME_LENGTH, |
| 316 | ); |
| 317 | const body: dialogflow.GoogleCloudDialogflowCxV3TransitionRouteGroup = { |
| 318 | displayName, |
| 319 | transitionRoutes: news.transitionRoutes, |
| 320 | }; |
| 321 | |
| 322 | let current = yield* getByName(output?.name ?? name); |
| 323 | if (current === undefined) { |
| 324 | current = yield* findByDisplayName(agent, displayName); |
| 325 | } |
| 326 | |
| 327 | if (current === undefined) { |
| 328 | const created = yield* dialogflow |
| 329 | .createProjectsLocationsAgentsTransitionRouteGroups({ |
| 330 | parent: agent, |
| 331 | languageCode: news.languageCode, |
| 332 | body, |
| 333 | }) |
| 334 | .pipe(Effect.catchTag("Conflict", () => findByDisplayName(agent, displayName))); |
| 335 | current = created ?? undefined; |
| 336 | } |
| 337 | |
| 338 | if (current === undefined) { |
| 339 | return yield* new AgentsTransitionRouteGroupNotResolved({ resourceName: name }); |
| 340 | } |
| 341 | |
| 342 | const currentName = current.name ?? name; |
| 343 | const displayChanged = !sameText(current.displayName, displayName); |
| 344 | const routesChanged = |
| 345 | fingerprint(routesOf(current.transitionRoutes)) !== fingerprint(news.transitionRoutes); |
| 346 | |
| 347 | if (displayChanged || routesChanged) { |
| 348 | current = yield* dialogflow.patchProjectsLocationsAgentsTransitionRouteGroups({ |
| 349 | name: currentName, |
| 350 | languageCode: news.languageCode, |
| 351 | updateMask: updateMaskOf( |
| 352 | displayChanged ? "display_name" : undefined, |
| 353 | routesChanged ? "transition_routes" : undefined, |
| 354 | ), |
| 355 | body: { ...body, name: currentName }, |
| 356 | }); |
| 357 | } |
| 358 | |
| 359 | return toAttrs(current, env.project, agent); |
| 360 | }, retryQuota), |
| 361 | |
| 362 | delete: Effect.fn(function* ({ output }) { |
| 363 | yield* dialogflow |
| 364 | .deleteProjectsLocationsAgentsTransitionRouteGroups({ |
| 365 | name: output.name, |
| 366 | force: true, |
| 367 | }) |
| 368 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 369 | }, retryQuota), |
| 370 | }); |