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 | namedAgents, |
| 22 | normalizeLocation, |
| 23 | ownedByAlchemy, |
| 24 | parentOf, |
| 25 | parseOwnership, |
| 26 | projectOf, |
| 27 | sameText, |
| 28 | toResourceId, |
| 29 | updateMaskOf, |
| 30 | retryQuota, |
| 31 | } from "./internal.ts"; |
| 32 | |
| 33 | export type WebhookHttpMethod = |
| 34 | | "HTTP_METHOD_UNSPECIFIED" |
| 35 | | "POST" |
| 36 | | "GET" |
| 37 | | "HEAD" |
| 38 | | "PUT" |
| 39 | | "DELETE" |
| 40 | | "PATCH" |
| 41 | | "OPTIONS"; |
| 42 | |
| 43 | export type WebhookType = "WEBHOOK_TYPE_UNSPECIFIED" | "STANDARD" | "FLEXIBLE"; |
| 44 | |
| 45 | export type WebhookServiceAgentAuth = |
| 46 | | "SERVICE_AGENT_AUTH_UNSPECIFIED" |
| 47 | | "NONE" |
| 48 | | "ID_TOKEN" |
| 49 | | "ACCESS_TOKEN"; |
| 50 | |
| 51 | export type WebhookOAuthConfig = { |
| 52 | /** OAuth token endpoint. */ |
| 53 | tokenEndpoint?: string; |
| 54 | /** OAuth client id. */ |
| 55 | clientId?: string; |
| 56 | /** OAuth client secret. Prefer `secretVersionForClientSecret`. */ |
| 57 | clientSecret?: string; |
| 58 | /** Secret Manager version holding the client secret. */ |
| 59 | secretVersionForClientSecret?: string; |
| 60 | /** OAuth scopes. */ |
| 61 | scopes?: string[]; |
| 62 | }; |
| 63 | |
| 64 | export type WebhookGenericWebService = { |
| 65 | /** HTTPS URI of the webhook. Required for generic web service. */ |
| 66 | uri?: string; |
| 67 | /** HTTP method. Defaults to POST for STANDARD webhooks. */ |
| 68 | httpMethod?: WebhookHttpMethod | (string & {}); |
| 69 | /** Webhook type. */ |
| 70 | webhookType?: WebhookType | (string & {}); |
| 71 | /** Request headers. */ |
| 72 | requestHeaders?: Record<string, string>; |
| 73 | /** Secret Manager versions used as request headers. */ |
| 74 | secretVersionsForRequestHeaders?: Record<string, { secretVersion?: string } | undefined>; |
| 75 | /** Allowed CA certificates (DER, base64). */ |
| 76 | allowedCaCerts?: string[]; |
| 77 | /** OAuth client-credentials config. */ |
| 78 | oauthConfig?: WebhookOAuthConfig; |
| 79 | /** Auth token minted from the Dialogflow service agent. */ |
| 80 | serviceAgentAuth?: WebhookServiceAgentAuth | (string & {}); |
| 81 | /** Service account used to generate ID tokens. */ |
| 82 | serviceAccountAuthConfig?: { serviceAccount?: string }; |
| 83 | /** Custom request body (FLEXIBLE webhooks). */ |
| 84 | requestBody?: string; |
| 85 | /** Map webhook response fields onto session parameters (FLEXIBLE). */ |
| 86 | parameterMapping?: Record<string, string>; |
| 87 | /** Secret Manager version holding username:password. */ |
| 88 | secretVersionForUsernamePassword?: string; |
| 89 | }; |
| 90 | |
| 91 | export type WebhookServiceDirectoryConfig = { |
| 92 | /** Service Directory service resource name. */ |
| 93 | service?: string; |
| 94 | /** Generic web service settings used with Service Directory. */ |
| 95 | genericWebService?: WebhookGenericWebService; |
| 96 | }; |
| 97 | |
| 98 | export type AgentsWebhookProps = { |
| 99 | /** |
| 100 | * Parent agent resource name |
| 101 | * `projects/{project}/locations/{location}/agents/{agent}` or a bare |
| 102 | * agent id (combined with `location`). Immutable — changing it |
| 103 | * replaces the webhook. |
| 104 | */ |
| 105 | agent: string; |
| 106 | /** |
| 107 | * Webhook id (the `{webhook}` segment). Server-assigned on create. |
| 108 | * Immutable — changing it replaces the webhook. |
| 109 | */ |
| 110 | webhookId?: string; |
| 111 | /** |
| 112 | * Location used when `agent` is a bare id. |
| 113 | * @default "global" |
| 114 | */ |
| 115 | location?: string; |
| 116 | /** |
| 117 | * Human-readable name, unique within the agent. Webhooks have no |
| 118 | * labels field, so Alchemy stamps ownership into this field for |
| 119 | * `list` / nuke. |
| 120 | */ |
| 121 | displayName?: string; |
| 122 | /** |
| 123 | * Webhook execution timeout (e.g. `"5s"`). Execution fails if |
| 124 | * Dialogflow does not receive a response before the timeout. |
| 125 | */ |
| 126 | timeout?: string; |
| 127 | /** |
| 128 | * When true, the webhook is not called. |
| 129 | * @default false |
| 130 | */ |
| 131 | disabled?: boolean; |
| 132 | /** |
| 133 | * Generic HTTPS webhook configuration. Mutually exclusive with |
| 134 | * `serviceDirectory`. |
| 135 | */ |
| 136 | genericWebService?: WebhookGenericWebService; |
| 137 | /** |
| 138 | * Service Directory webhook configuration. Mutually exclusive with |
| 139 | * `genericWebService`. |
| 140 | */ |
| 141 | serviceDirectory?: WebhookServiceDirectoryConfig; |
| 142 | }; |
| 143 | |
| 144 | export type AgentsWebhook = Resource< |
| 145 | "GCP.Dialogflow.AgentsWebhook", |
| 146 | AgentsWebhookProps, |
| 147 | { |
| 148 | /** Full resource name `.../agents/{agent}/webhooks/{webhook}`. */ |
| 149 | name: string; |
| 150 | /** Webhook id (last path segment). */ |
| 151 | webhookId: string; |
| 152 | /** Parent agent resource name. */ |
| 153 | agent: string; |
| 154 | /** Project id. */ |
| 155 | project: string; |
| 156 | /** Location id. */ |
| 157 | location: string; |
| 158 | /** User display name with the Alchemy ownership prefix stripped. */ |
| 159 | displayName: string | undefined; |
| 160 | /** Execution timeout. */ |
| 161 | timeout: string | undefined; |
| 162 | /** Whether the webhook is disabled. */ |
| 163 | disabled: boolean; |
| 164 | /** Generic HTTPS webhook configuration. */ |
| 165 | genericWebService: WebhookGenericWebService | undefined; |
| 166 | /** Service Directory webhook configuration. */ |
| 167 | serviceDirectory: WebhookServiceDirectoryConfig | undefined; |
| 168 | }, |
| 169 | never, |
| 170 | Providers |
| 171 | >; |
| 172 | |
| 173 | /** |
| 174 | * A Dialogflow CX webhook that hosts fulfillment business logic. |
| 175 | * |
| 176 | * Webhooks have no labels field, so Alchemy stamps ownership into |
| 177 | * `displayName` for `list` / nuke. Parent agent and id are immutable. |
| 178 | * Display name, timeout, disabled flag, and webhook config update in |
| 179 | * place. |
| 180 | * |
| 181 | * ### Creating a Webhook |
| 182 | * **Example:** Generic HTTPS webhook |
| 183 | * ```typescript |
| 184 | * const webhook = yield* GCP.Dialogflow.AgentsWebhook("Fulfillment", { |
| 185 | * agent: agent.name, |
| 186 | * displayName: "orders", |
| 187 | * genericWebService: { uri: "https://example.com/dialogflow" }, |
| 188 | * }); |
| 189 | * ``` |
| 190 | * |
| 191 | * ### Updating a Webhook |
| 192 | * Change props on the same logical id; the engine keeps the physical id. |
| 193 | * |
| 194 | * **Example:** Disable and retarget |
| 195 | * ```typescript |
| 196 | * const webhook = yield* GCP.Dialogflow.AgentsWebhook("Fulfillment", { |
| 197 | * agent: agent.name, |
| 198 | * displayName: "orders-v2", |
| 199 | * disabled: true, |
| 200 | * genericWebService: { uri: "https://example.com/dialogflow-v2" }, |
| 201 | * }); |
| 202 | * ``` |
| 203 | * |
| 204 | * @resource |
| 205 | * @category Dialogflow |
| 206 | */ |
| 207 | export const AgentsWebhook = Resource<AgentsWebhook>("GCP.Dialogflow.AgentsWebhook"); |
| 208 | |
| 209 | export class AgentsWebhookNotResolved extends Data.TaggedError( |
| 210 | "GCP.Dialogflow.AgentsWebhookNotResolved", |
| 211 | )<{ |
| 212 | resourceName: string; |
| 213 | }> {} |
| 214 | |
| 215 | const resourceName = (agent: string, webhookId: string) => `${agent}/webhooks/${webhookId}`; |
| 216 | |
| 217 | const stringMapOf = ( |
| 218 | value: Record<string, string | undefined> | undefined, |
| 219 | ): Record<string, string> | undefined => { |
| 220 | if (value === undefined) return undefined; |
| 221 | return Object.fromEntries( |
| 222 | Object.entries(value).filter((entry): entry is [string, string] => entry[1] !== undefined), |
| 223 | ); |
| 224 | }; |
| 225 | |
| 226 | const genericOf = ( |
| 227 | service: dialogflow.GoogleCloudDialogflowCxV3WebhookGenericWebService | undefined, |
| 228 | ): WebhookGenericWebService | undefined => { |
| 229 | if (service === undefined) return undefined; |
| 230 | return { |
| 231 | uri: service.uri, |
| 232 | httpMethod: service.httpMethod, |
| 233 | webhookType: service.webhookType, |
| 234 | requestHeaders: stringMapOf(service.requestHeaders), |
| 235 | secretVersionsForRequestHeaders: service.secretVersionsForRequestHeaders, |
| 236 | allowedCaCerts: service.allowedCaCerts ? [...service.allowedCaCerts] : undefined, |
| 237 | oauthConfig: service.oauthConfig |
| 238 | ? { |
| 239 | tokenEndpoint: service.oauthConfig.tokenEndpoint, |
| 240 | clientId: service.oauthConfig.clientId, |
| 241 | clientSecret: service.oauthConfig.clientSecret, |
| 242 | secretVersionForClientSecret: service.oauthConfig.secretVersionForClientSecret, |
| 243 | scopes: service.oauthConfig.scopes ? [...service.oauthConfig.scopes] : undefined, |
| 244 | } |
| 245 | : undefined, |
| 246 | serviceAgentAuth: service.serviceAgentAuth, |
| 247 | serviceAccountAuthConfig: service.serviceAccountAuthConfig |
| 248 | ? { serviceAccount: service.serviceAccountAuthConfig.serviceAccount } |
| 249 | : undefined, |
| 250 | requestBody: service.requestBody, |
| 251 | parameterMapping: stringMapOf(service.parameterMapping), |
| 252 | secretVersionForUsernamePassword: service.secretVersionForUsernamePassword, |
| 253 | }; |
| 254 | }; |
| 255 | |
| 256 | const directoryOf = ( |
| 257 | config: dialogflow.GoogleCloudDialogflowCxV3WebhookServiceDirectoryConfig | undefined, |
| 258 | ): WebhookServiceDirectoryConfig | undefined => { |
| 259 | if (config === undefined) return undefined; |
| 260 | return { |
| 261 | service: config.service, |
| 262 | genericWebService: genericOf(config.genericWebService), |
| 263 | }; |
| 264 | }; |
| 265 | |
| 266 | const toAttrs = ( |
| 267 | webhook: dialogflow.GoogleCloudDialogflowCxV3Webhook, |
| 268 | project: string, |
| 269 | agentHint?: string, |
| 270 | ) => { |
| 271 | const name = webhook.name ?? ""; |
| 272 | return { |
| 273 | name, |
| 274 | webhookId: lastSegment(name), |
| 275 | agent: name.includes("/webhooks/") |
| 276 | ? collectionParent(name, "agents") |
| 277 | : (agentHint ?? parentOf(name)), |
| 278 | project: projectOf(name) || project, |
| 279 | location: locationOf(name), |
| 280 | displayName: parseOwnership(webhook.displayName).text, |
| 281 | timeout: webhook.timeout, |
| 282 | disabled: webhook.disabled === true, |
| 283 | genericWebService: genericOf(webhook.genericWebService), |
| 284 | serviceDirectory: directoryOf(webhook.serviceDirectory), |
| 285 | }; |
| 286 | }; |
| 287 | |
| 288 | const getByName = (name: string) => |
| 289 | name.length === 0 |
| 290 | ? Effect.undefined |
| 291 | : dialogflow |
| 292 | .getProjectsLocationsAgentsWebhooks({ name }) |
| 293 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 294 | |
| 295 | const listAt = (parent: string, project: string) => |
| 296 | dialogflow.listProjectsLocationsAgentsWebhooks.pages({ parent, pageSize: 100 }).pipe( |
| 297 | Stream.flatMap((page) => Stream.fromIterable(page.webhooks ?? [])), |
| 298 | Stream.filter((webhook) => hasOwnershipMarker(webhook.displayName)), |
| 299 | Stream.map((webhook) => toAttrs(webhook, project, parent)), |
| 300 | Stream.runCollect, |
| 301 | Effect.map((chunk) => Array.from(chunk)), |
| 302 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 303 | ); |
| 304 | |
| 305 | const findByDisplayName = (parent: string, displayName: string) => |
| 306 | dialogflow.listProjectsLocationsAgentsWebhooks.pages({ parent, pageSize: 100 }).pipe( |
| 307 | Stream.flatMap((page) => Stream.fromIterable(page.webhooks ?? [])), |
| 308 | Stream.filter((webhook) => webhook.displayName === displayName), |
| 309 | Stream.runHead, |
| 310 | Effect.map((option) => (option._tag === "Some" ? option.value : undefined)), |
| 311 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 312 | ); |
| 313 | |
| 314 | export const AgentsWebhookProvider = () => |
| 315 | Provider.succeed(AgentsWebhook, { |
| 316 | stables: ["name", "webhookId", "agent", "project", "location"], |
| 317 | |
| 318 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 319 | if (!isResolved(news)) return undefined; |
| 320 | const previousAgent = olds?.agent ?? output?.agent; |
| 321 | if (previousAgent !== undefined && news.agent !== previousAgent) { |
| 322 | return { action: "replace" as const, deleteFirst: false }; |
| 323 | } |
| 324 | const previousId = olds?.webhookId ?? output?.webhookId; |
| 325 | if ( |
| 326 | previousId !== undefined && |
| 327 | news.webhookId !== undefined && |
| 328 | news.webhookId !== previousId |
| 329 | ) { |
| 330 | return { action: "replace" as const, deleteFirst: false }; |
| 331 | } |
| 332 | const previousLocation = olds?.location ?? output?.location; |
| 333 | if ( |
| 334 | previousLocation !== undefined && |
| 335 | news.location !== undefined && |
| 336 | normalizeLocation(previousLocation) !== normalizeLocation(news.location) |
| 337 | ) { |
| 338 | return { action: "replace" as const, deleteFirst: false }; |
| 339 | } |
| 340 | return undefined; |
| 341 | }), |
| 342 | |
| 343 | read: Effect.fn(function* ({ id, olds, output }) { |
| 344 | const env = yield* GcpEnvironment.current; |
| 345 | const location = normalizeLocation(olds?.location ?? output?.location); |
| 346 | const agent = olds?.agent ? expandAgent(olds.agent, env.project, location) : output?.agent; |
| 347 | const webhookId = yield* toResourceId(id, olds?.webhookId, output?.webhookId); |
| 348 | const name = output?.name ?? (agent !== undefined ? resourceName(agent, webhookId) : ""); |
| 349 | let existing = yield* getByName(name); |
| 350 | if (existing === undefined && agent !== undefined) { |
| 351 | const ownership = yield* internalLabels(id); |
| 352 | existing = yield* findByDisplayName( |
| 353 | agent, |
| 354 | encodeOwnershipLine(ownership, olds?.displayName), |
| 355 | ); |
| 356 | } |
| 357 | if (existing === undefined) return undefined; |
| 358 | const attrs = toAttrs(existing, env.project, agent); |
| 359 | return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs); |
| 360 | }), |
| 361 | |
| 362 | list: () => |
| 363 | Effect.gen(function* () { |
| 364 | const env = yield* GcpEnvironment.current; |
| 365 | const agents = yield* namedAgents(env.project); |
| 366 | const pages = yield* Effect.forEach(agents, (agent) => listAt(agent.name, env.project), { |
| 367 | concurrency: 4, |
| 368 | }); |
| 369 | return pages.flat(); |
| 370 | }), |
| 371 | |
| 372 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 373 | const env = yield* GcpEnvironment.current; |
| 374 | const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION); |
| 375 | const agent = expandAgent(news.agent, env.project, location); |
| 376 | const webhookId = yield* toResourceId(id, news.webhookId, output?.webhookId); |
| 377 | const name = output?.name ?? resourceName(agent, webhookId); |
| 378 | const ownership = yield* internalLabels(id); |
| 379 | const displayName = encodeOwnershipLine(ownership, news.displayName); |
| 380 | const disabled = news.disabled === true; |
| 381 | const body: dialogflow.GoogleCloudDialogflowCxV3Webhook = { |
| 382 | displayName, |
| 383 | timeout: news.timeout, |
| 384 | disabled, |
| 385 | genericWebService: news.genericWebService, |
| 386 | serviceDirectory: news.serviceDirectory, |
| 387 | }; |
| 388 | |
| 389 | let current = yield* getByName(output?.name ?? name); |
| 390 | if (current === undefined) { |
| 391 | current = yield* findByDisplayName(agent, displayName); |
| 392 | } |
| 393 | |
| 394 | if (current === undefined) { |
| 395 | const created = yield* dialogflow |
| 396 | .createProjectsLocationsAgentsWebhooks({ |
| 397 | parent: agent, |
| 398 | body, |
| 399 | }) |
| 400 | .pipe(Effect.catchTag("Conflict", () => findByDisplayName(agent, displayName))); |
| 401 | current = created ?? undefined; |
| 402 | } |
| 403 | |
| 404 | if (current === undefined) { |
| 405 | return yield* new AgentsWebhookNotResolved({ resourceName: name }); |
| 406 | } |
| 407 | |
| 408 | const currentName = current.name ?? name; |
| 409 | const displayChanged = !sameText(current.displayName, displayName); |
| 410 | const timeoutChanged = !sameText(current.timeout, news.timeout); |
| 411 | const disabledChanged = (current.disabled === true) !== disabled; |
| 412 | const genericChanged = |
| 413 | fingerprint(genericOf(current.genericWebService)) !== fingerprint(news.genericWebService); |
| 414 | const directoryChanged = |
| 415 | fingerprint(directoryOf(current.serviceDirectory)) !== fingerprint(news.serviceDirectory); |
| 416 | |
| 417 | if ( |
| 418 | displayChanged || |
| 419 | timeoutChanged || |
| 420 | disabledChanged || |
| 421 | genericChanged || |
| 422 | directoryChanged |
| 423 | ) { |
| 424 | current = yield* dialogflow.patchProjectsLocationsAgentsWebhooks({ |
| 425 | name: currentName, |
| 426 | updateMask: updateMaskOf( |
| 427 | displayChanged ? "display_name" : undefined, |
| 428 | timeoutChanged ? "timeout" : undefined, |
| 429 | disabledChanged ? "disabled" : undefined, |
| 430 | genericChanged ? "generic_web_service" : undefined, |
| 431 | directoryChanged ? "service_directory" : undefined, |
| 432 | ), |
| 433 | body: { ...body, name: currentName }, |
| 434 | }); |
| 435 | } |
| 436 | |
| 437 | return toAttrs(current, env.project, agent); |
| 438 | }, retryQuota), |
| 439 | |
| 440 | delete: Effect.fn(function* ({ output }) { |
| 441 | yield* dialogflow |
| 442 | .deleteProjectsLocationsAgentsWebhooks({ |
| 443 | name: output.name, |
| 444 | force: true, |
| 445 | }) |
| 446 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 447 | }, retryQuota), |
| 448 | }); |