The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ccaip from "@distilled.cloud/gcp/contactcenteraiplatform_v1alpha1"; |
| 2 | import { Retry as GcpRetry } from "@distilled.cloud/gcp/Retry"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import { tagRecord } from "alchemy/Tags"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { isTransientGcpError } from "../Errors.ts"; |
| 11 | import { stripInternalLabels } from "../Labels.ts"; |
| 12 | |
| 13 | const noRetryLayer = Layer.succeed(GcpRetry, { while: () => false }); |
| 14 | |
| 15 | export const DEFAULT_INSTANCE_SIZE = "DEV_SMALL"; |
| 16 | export const MAX_ID_LENGTH = 63; |
| 17 | export const MAX_DOMAIN_PREFIX_LENGTH = 16; |
| 18 | export const MIN_DOMAIN_PREFIX_LENGTH = 2; |
| 19 | |
| 20 | export class ContactCenterNotResolved extends Data.TaggedError( |
| 21 | "GCP.ContactCenterAIPlatform.ContactCenterNotResolved", |
| 22 | )<{ |
| 23 | resourceName: string; |
| 24 | }> {} |
| 25 | |
| 26 | export class ContactCenterNotReady extends Data.TaggedError( |
| 27 | "GCP.ContactCenterAIPlatform.ContactCenterNotReady", |
| 28 | )<{ |
| 29 | resourceName: string; |
| 30 | state: string; |
| 31 | }> {} |
| 32 | |
| 33 | export class ContactCenterFailed extends Data.TaggedError( |
| 34 | "GCP.ContactCenterAIPlatform.ContactCenterFailed", |
| 35 | )<{ |
| 36 | resourceName: string; |
| 37 | state: string; |
| 38 | }> {} |
| 39 | |
| 40 | export class ContactCenterStillExists extends Data.TaggedError( |
| 41 | "GCP.ContactCenterAIPlatform.ContactCenterStillExists", |
| 42 | )<{ |
| 43 | resourceName: string; |
| 44 | }> {} |
| 45 | |
| 46 | export const lastSegment = (value: string) => { |
| 47 | const trimmed = value.replace(/\/+$/, ""); |
| 48 | const parts = trimmed.split("/"); |
| 49 | return parts[parts.length - 1] || trimmed; |
| 50 | }; |
| 51 | |
| 52 | export const locationParent = (project: string, location: string) => |
| 53 | `projects/${project}/locations/${location}`; |
| 54 | |
| 55 | export const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 56 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 57 | |
| 58 | export const rfc1035 = (name: string, maxLength: number, fallback: string): string => { |
| 59 | let next = name |
| 60 | .toLowerCase() |
| 61 | .replace(/[^a-z0-9-]/g, "-") |
| 62 | .replace(/-+/g, "-") |
| 63 | .replace(/^-+|-+$/g, ""); |
| 64 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "c"}${next}`; |
| 65 | next = next.slice(0, maxLength).replace(/-+$/g, ""); |
| 66 | if (next.length === 0) return fallback.slice(0, maxLength); |
| 67 | if (!/[a-z0-9]$/.test(next)) { |
| 68 | next = `${next.slice(0, maxLength - 1)}0`; |
| 69 | } |
| 70 | return next.slice(0, maxLength); |
| 71 | }; |
| 72 | |
| 73 | export const domainPrefixOf = (name: string): string => { |
| 74 | const next = rfc1035(name, MAX_DOMAIN_PREFIX_LENGTH, "cc"); |
| 75 | return next.length >= MIN_DOMAIN_PREFIX_LENGTH |
| 76 | ? next |
| 77 | : `${next}x`.slice(0, MAX_DOMAIN_PREFIX_LENGTH); |
| 78 | }; |
| 79 | |
| 80 | export const toPhysicalId = ( |
| 81 | id: string, |
| 82 | explicit: string | undefined, |
| 83 | existing: string | undefined, |
| 84 | ) => |
| 85 | Effect.gen(function* () { |
| 86 | if (explicit !== undefined) return rfc1035(explicit, MAX_ID_LENGTH, "cc"); |
| 87 | if (existing !== undefined) return existing; |
| 88 | return rfc1035( |
| 89 | yield* createPhysicalName({ |
| 90 | id, |
| 91 | maxLength: MAX_ID_LENGTH, |
| 92 | lowercase: true, |
| 93 | }), |
| 94 | MAX_ID_LENGTH, |
| 95 | "cc", |
| 96 | ); |
| 97 | }); |
| 98 | |
| 99 | export const toDomainPrefix = ( |
| 100 | explicit: string | undefined, |
| 101 | existing: string | undefined, |
| 102 | id: string, |
| 103 | ) => |
| 104 | Effect.gen(function* () { |
| 105 | if (explicit !== undefined) return domainPrefixOf(explicit); |
| 106 | if (existing !== undefined) return existing; |
| 107 | return domainPrefixOf( |
| 108 | yield* createPhysicalName({ |
| 109 | id, |
| 110 | maxLength: MAX_DOMAIN_PREFIX_LENGTH, |
| 111 | lowercase: true, |
| 112 | }), |
| 113 | ); |
| 114 | }); |
| 115 | |
| 116 | export const parseName = (name: string, defaultLocation: string) => { |
| 117 | const parts = name.split("/").filter((part) => part.length > 0); |
| 118 | const collectionAt = parts.lastIndexOf("contactCenters"); |
| 119 | const locationsAt = parts.lastIndexOf("locations"); |
| 120 | const projectsAt = parts.lastIndexOf("projects"); |
| 121 | return { |
| 122 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 123 | location: |
| 124 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, |
| 125 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 126 | }; |
| 127 | }; |
| 128 | |
| 129 | export const userLabels = ( |
| 130 | labels: Record<string, string | undefined> | null | undefined, |
| 131 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 132 | |
| 133 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 134 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 135 | |
| 136 | export const canonical = (value: unknown): unknown => { |
| 137 | if (value === undefined || value === null) return undefined; |
| 138 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 139 | if (typeof value === "string") { |
| 140 | return value.length === 0 ? undefined : value; |
| 141 | } |
| 142 | if (Array.isArray(value)) { |
| 143 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 144 | return items.length === 0 ? undefined : items; |
| 145 | } |
| 146 | if (typeof value === "object") { |
| 147 | const entries = Object.entries(value as Record<string, unknown>) |
| 148 | .map(([key, item]) => [key, canonical(item)] as const) |
| 149 | .filter(([, item]) => item !== undefined) |
| 150 | .sort(([left], [right]) => left.localeCompare(right)); |
| 151 | if (entries.length === 0) return undefined; |
| 152 | return Object.fromEntries(entries); |
| 153 | } |
| 154 | return undefined; |
| 155 | }; |
| 156 | |
| 157 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 158 | |
| 159 | export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right); |
| 160 | |
| 161 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 162 | (left ?? "") === (right ?? ""); |
| 163 | |
| 164 | export const sameBool = (left: boolean | undefined, right: boolean | undefined) => |
| 165 | (left === true) === (right === true); |
| 166 | |
| 167 | export const updateMaskOf = (...fields: Array<string | false | undefined>) => |
| 168 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 169 | |
| 170 | export const replaceOnIdentity = (input: { |
| 171 | previousId?: string; |
| 172 | nextId?: string; |
| 173 | previousLocation?: string; |
| 174 | nextLocation?: string; |
| 175 | extra?: boolean; |
| 176 | }) => { |
| 177 | if (input.extra === true) { |
| 178 | return { action: "replace" as const, deleteFirst: false }; |
| 179 | } |
| 180 | if ( |
| 181 | input.previousId !== undefined && |
| 182 | input.nextId !== undefined && |
| 183 | input.previousId !== input.nextId |
| 184 | ) { |
| 185 | return { action: "replace" as const, deleteFirst: false }; |
| 186 | } |
| 187 | if ( |
| 188 | input.previousLocation !== undefined && |
| 189 | input.nextLocation !== undefined && |
| 190 | input.previousLocation !== input.nextLocation |
| 191 | ) { |
| 192 | return { action: "replace" as const, deleteFirst: false }; |
| 193 | } |
| 194 | return undefined; |
| 195 | }; |
| 196 | |
| 197 | export const retryTransient = <A, E extends { readonly _tag: string }, R>( |
| 198 | effect: Effect.Effect<A, E, R>, |
| 199 | ) => |
| 200 | effect.pipe( |
| 201 | Effect.retry({ |
| 202 | while: isTransientGcpError, |
| 203 | times: 8, |
| 204 | schedule: Schedule.exponential("250 millis"), |
| 205 | }), |
| 206 | ); |
| 207 | |
| 208 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 209 | get: Effect.Effect<A, E, R>, |
| 210 | name: string, |
| 211 | ): Effect.Effect<Exclude<A, undefined>, E | ContactCenterNotResolved, R> => |
| 212 | get.pipe( |
| 213 | Effect.filterOrFail( |
| 214 | (value): value is Exclude<A, undefined> => value !== undefined, |
| 215 | () => new ContactCenterNotResolved({ resourceName: name }), |
| 216 | ), |
| 217 | Effect.retry({ |
| 218 | while: (error) => error._tag === "GCP.ContactCenterAIPlatform.ContactCenterNotResolved", |
| 219 | times: 8, |
| 220 | schedule: Schedule.spaced("1 second"), |
| 221 | }), |
| 222 | ); |
| 223 | |
| 224 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 225 | get: Effect.Effect<A, E, R>, |
| 226 | name: string, |
| 227 | ): Effect.Effect<void, E | ContactCenterStillExists, R> => |
| 228 | get.pipe( |
| 229 | Effect.filterOrFail( |
| 230 | (value) => value === undefined, |
| 231 | () => new ContactCenterStillExists({ resourceName: name }), |
| 232 | ), |
| 233 | Effect.asVoid, |
| 234 | Effect.retry({ |
| 235 | while: (error) => error._tag === "GCP.ContactCenterAIPlatform.ContactCenterStillExists", |
| 236 | times: 10, |
| 237 | schedule: Schedule.spaced("2 seconds"), |
| 238 | }), |
| 239 | ); |
| 240 | |
| 241 | const FAILED_STATES = new Set(["STATE_FAILED", "STATE_TERMINATING_FAILED"]); |
| 242 | |
| 243 | const READY_STATES = new Set(["STATE_DEPLOYED", "STATE_IN_GRACE_PERIOD", "STATE_DEGRADED"]); |
| 244 | |
| 245 | export const isTerminated = (state: string | undefined) => |
| 246 | (state ?? "").toUpperCase() === "STATE_TERMINATED"; |
| 247 | |
| 248 | const stateOfUpper = (state: string | undefined) => (state ?? "").toUpperCase(); |
| 249 | |
| 250 | export const waitUntilReady = <A, E extends { readonly _tag: string }, R>( |
| 251 | get: Effect.Effect<A, E, R>, |
| 252 | name: string, |
| 253 | stateOf: (value: Exclude<A, undefined>) => string | undefined, |
| 254 | ): Effect.Effect< |
| 255 | Exclude<A, undefined>, |
| 256 | E | ContactCenterNotResolved | ContactCenterFailed | ContactCenterNotReady, |
| 257 | R |
| 258 | > => |
| 259 | get.pipe( |
| 260 | Effect.filterOrFail( |
| 261 | (value): value is Exclude<A, undefined> => value !== undefined, |
| 262 | () => new ContactCenterNotResolved({ resourceName: name }), |
| 263 | ), |
| 264 | Effect.filterOrFail( |
| 265 | (value) => !FAILED_STATES.has(stateOfUpper(stateOf(value))), |
| 266 | (value) => |
| 267 | new ContactCenterFailed({ |
| 268 | resourceName: name, |
| 269 | state: stateOfUpper(stateOf(value)), |
| 270 | }), |
| 271 | ), |
| 272 | Effect.filterOrFail( |
| 273 | (value) => READY_STATES.has(stateOfUpper(stateOf(value))), |
| 274 | (value) => |
| 275 | new ContactCenterNotReady({ |
| 276 | resourceName: name, |
| 277 | state: stateOfUpper(stateOf(value)), |
| 278 | }), |
| 279 | ), |
| 280 | Effect.retry({ |
| 281 | while: (error) => |
| 282 | error._tag === "GCP.ContactCenterAIPlatform.ContactCenterNotReady" || |
| 283 | error._tag === "GCP.ContactCenterAIPlatform.ContactCenterNotResolved", |
| 284 | times: 10, |
| 285 | schedule: Schedule.spaced("8 seconds"), |
| 286 | }), |
| 287 | ); |
| 288 | |
| 289 | export const releaseChannelOf = ( |
| 290 | item: Pick<ccaip.ContactCenter, "early" | "normal" | "critical">, |
| 291 | ): "early" | "normal" | "critical" | undefined => { |
| 292 | if (item.critical !== undefined) return "critical"; |
| 293 | if (item.early !== undefined) return "early"; |
| 294 | if (item.normal !== undefined) return "normal"; |
| 295 | return undefined; |
| 296 | }; |
| 297 | |
| 298 | const emptyContactCenters = Effect.succeed<ccaip.ContactCenter[]>([]); |
| 299 | |
| 300 | export const listContactCenters = (parent: string) => |
| 301 | parent.length === 0 |
| 302 | ? emptyContactCenters |
| 303 | : ccaip.listProjectsLocationsContactCenters.pages({ parent, pageSize: 1000 }).pipe( |
| 304 | Stream.flatMap((page) => Stream.fromIterable(page.contactCenters ?? [])), |
| 305 | Stream.filter((item) => hasAlchemyLabelMap(item.labels)), |
| 306 | Stream.runCollect, |
| 307 | Effect.map((chunk) => Array.from(chunk)), |
| 308 | Effect.provide(noRetryLayer), |
| 309 | Effect.catchTag("NotFound", () => emptyContactCenters), |
| 310 | ); |
| 311 | |
| 312 | const FALLBACK_LOCATIONS = ["us-central1", "us-east1", "europe-west1", "asia-southeast1"] as const; |
| 313 | |
| 314 | const listLocationIds = (project: string) => |
| 315 | ccaip.listProjectsLocations.pages({ name: `projects/${project}`, pageSize: 100 }).pipe( |
| 316 | Stream.flatMap((page) => Stream.fromIterable(page.locations ?? [])), |
| 317 | Stream.map((location) => location.locationId || lastSegment(location.name ?? "")), |
| 318 | Stream.filter((id) => id.length > 0 && id !== "-"), |
| 319 | Stream.runCollect, |
| 320 | Effect.map((chunk) => Array.from(new Set(chunk))), |
| 321 | ); |
| 322 | |
| 323 | const listAcrossLocations = (project: string, region: string) => |
| 324 | Effect.gen(function* () { |
| 325 | const discovered = yield* listLocationIds(project); |
| 326 | const locations = |
| 327 | discovered.length > 0 ? discovered : [...new Set([region, ...FALLBACK_LOCATIONS])]; |
| 328 | const pages = yield* Effect.forEach( |
| 329 | locations, |
| 330 | (location) => listContactCenters(locationParent(project, location)), |
| 331 | { concurrency: 4 }, |
| 332 | ); |
| 333 | return pages.flat(); |
| 334 | }); |
| 335 | |
| 336 | export const listOwnedContactCenters = (project: string, region: string) => |
| 337 | listContactCenters(`projects/${project}/locations/-`).pipe( |
| 338 | Effect.catchIf( |
| 339 | (error) => |
| 340 | error._tag === "ServiceUnavailable" || |
| 341 | error._tag === "InternalServerError" || |
| 342 | error._tag === "BadGateway" || |
| 343 | error._tag === "GatewayTimeout", |
| 344 | () => listAcrossLocations(project, region), |
| 345 | ), |
| 346 | ); |