@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 531 lines 18.5 KB
Raw
1 import * as ccaip from "@distilled.cloud/gcp/contactcenteraiplatform_v1alpha1";
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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 ContactCenterNotResolved,
14 DEFAULT_INSTANCE_SIZE,
15 fingerprint,
16 isTerminated,
17 listOwnedContactCenters,
18 locationParent,
19 normalizeLocation,
20 parseName,
21 releaseChannelOf,
22 replaceOnIdentity,
23 retryTransient,
24 sameBool,
25 sameJson,
26 sameText,
27 toDomainPrefix,
28 toPhysicalId,
29 updateMaskOf,
30 userLabels,
31 waitUntilExists,
32 waitUntilGone,
33 waitUntilReady,
34 } from "./internal.ts";
35 import { waitForDeleteOperation, waitForOperation } from "./operations.ts";
36
37 export type ContactCenterProps = {
38 /**
39 * Contact Center id (the `{contactCenter}` segment of
40 * `projects/{project}/locations/{location}/contactCenters/{contactCenter}`).
41 * If omitted, a unique RFC1035 name is generated. Immutable — changing
42 * it replaces the instance.
43 */
44 contactCenterId?: string;
45 /**
46 * Location (`us-central1`, …). Immutable — changing it replaces the
47 * instance. `US-CENTRAL1` is accepted and normalized to `us-central1`.
48 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
49 */
50 location?: string;
51 /**
52 * User-facing display name. Required by the API; Alchemy falls back to
53 * the generated contact center id.
54 */
55 displayName?: string;
56 /**
57 * Customer domain prefix (2–16 RFC1035 characters). Used as the
58 * instance subdomain. Immutable — changing it replaces the instance.
59 * If omitted, a unique prefix is generated.
60 */
61 customerDomainPrefix?: string;
62 /**
63 * Instance size (`DEV_SMALL`, `STANDARD_SMALL`, `TRIAL_SMALL`, …).
64 * Immutable — changing it replaces the instance.
65 * @default "DEV_SMALL"
66 */
67 instanceSize?: ccaip.InstanceConfigInstanceSizeEnum | (string & {});
68 /**
69 * Full instance configuration. Wins over `instanceSize` when set.
70 * Immutable — changing it replaces the instance.
71 */
72 instanceConfig?: ccaip.InstanceConfig;
73 /**
74 * User labels. Alchemy ownership labels are merged in automatically.
75 */
76 labels?: Record<string, string>;
77 /**
78 * Email of the first admin user.
79 */
80 userEmail?: string;
81 /**
82 * First admin given/family name.
83 */
84 adminUser?: ccaip.AdminUser;
85 /**
86 * Customer-managed KMS key that encrypts user input. Immutable —
87 * changing it replaces the instance.
88 */
89 kmsKey?: string;
90 /**
91 * When true, users can be created in the CCAIP instance in addition to
92 * Cloud Identity.
93 * @default false
94 */
95 ccaipManagedUsers?: boolean;
96 /**
97 * SAML parameters that set up Google as IdP.
98 */
99 samlParams?: ccaip.SAMLParams;
100 /**
101 * Feature flags (for example agent desktop).
102 */
103 featureConfig?: ccaip.FeatureConfig;
104 /**
105 * VPC-SC private ingress/egress settings.
106 */
107 privateAccess?: ccaip.PrivateAccess;
108 /**
109 * Whether advanced reporting is enabled.
110 * @default false
111 */
112 advancedReportingEnabled?: boolean;
113 /**
114 * Release channel. `early` is for test instances, `normal` lags early
115 * by two days, `critical` only updates outside `critical.peakHours`.
116 */
117 releaseChannel?: "early" | "normal" | "critical";
118 /**
119 * Peak hours used when `releaseChannel` is `critical`.
120 */
121 critical?: ccaip.Critical;
122 };
123
124 export type ContactCenter = Resource<
125 "GCP.ContactCenterAIPlatform.ContactCenter",
126 ContactCenterProps,
127 {
128 /** Full resource name `projects/{project}/locations/{location}/contactCenters/{contactCenter}`. */
129 name: string;
130 /** Contact Center id (last path segment). */
131 contactCenterId: string;
132 /** Location id. */
133 location: string;
134 /** Project id. */
135 project: string;
136 /** User-facing display name. */
137 displayName: string | undefined;
138 /** Customer domain prefix. */
139 customerDomainPrefix: string | undefined;
140 /** Instance size. */
141 instanceSize: string | undefined;
142 /** User labels (Alchemy ownership labels stripped). */
143 labels: Record<string, string>;
144 /** First admin email. */
145 userEmail: string | undefined;
146 /** First admin given/family name. */
147 adminUser: ccaip.AdminUser | undefined;
148 /** Customer-managed KMS key. */
149 kmsKey: string | undefined;
150 /** Whether CCAIP-managed users are enabled. */
151 ccaipManagedUsers: boolean;
152 /** SAML IdP parameters. */
153 samlParams: ccaip.SAMLParams | undefined;
154 /** Feature flags. */
155 featureConfig: ccaip.FeatureConfig | undefined;
156 /** Private networking settings. */
157 privateAccess: ccaip.PrivateAccess | undefined;
158 /** Whether advanced reporting is enabled. */
159 advancedReportingEnabled: boolean;
160 /** Release channel currently applied. */
161 releaseChannel: "early" | "normal" | "critical" | undefined;
162 /** Peak hours for the critical channel. */
163 critical: ccaip.Critical | undefined;
164 /** Server-reported state (`STATE_DEPLOYED`, …). */
165 state: string | undefined;
166 /** UJET release version. */
167 releaseVersion: string | undefined;
168 /** Access URIs for the deployed instance. */
169 uris: ccaip.URIs | undefined;
170 /** Private-path component names. */
171 privateComponents: string[] | undefined;
172 /** RFC3339 creation timestamp. */
173 createTime: string | undefined;
174 /** RFC3339 last-update timestamp. */
175 updateTime: string | undefined;
176 /** RFC3339 soft-delete timestamp. */
177 deleteTime: string | undefined;
178 /** RFC3339 expiry timestamp. */
179 expireTime: string | undefined;
180 /** RFC3339 hard-delete timestamp. */
181 purgeTime: string | undefined;
182 },
183 never,
184 Providers
185 >;
186
187 /**
188 * A Contact Center AI Platform (CCAIP) instance.
189 *
190 * Create, update, and delete are long-running operations. Location,
191 * contact center id, `customerDomainPrefix`, `instanceConfig`, and
192 * `kmsKey` are immutable. Display name, labels, admin user, SAML, feature
193 * flags, private access, advanced reporting, and release channel update
194 * in place.
195 *
196 * Provisioning is entitlement-gated and typically takes several minutes.
197 *
198 * ### Creating a Contact Center
199 * **Example:** Generated name
200 * ```typescript
201 * const center = yield* GCP.ContactCenterAIPlatform.ContactCenter("Support", {
202 * displayName: "support",
203 * instanceSize: "DEV_SMALL",
204 * });
205 * ```
206 *
207 * **Example:** Explicit id, domain prefix, and labels
208 * ```typescript
209 * const center = yield* GCP.ContactCenterAIPlatform.ContactCenter("Support", {
210 * contactCenterId: "support-desk",
211 * location: "us-central1",
212 * displayName: "Support desk",
213 * customerDomainPrefix: "supdesk",
214 * instanceSize: "DEV_SMALL",
215 * labels: { env: "prod" },
216 * });
217 * ```
218 *
219 * ### Updating a Contact Center
220 * **Example:** Display name and labels
221 * ```typescript
222 * const center = yield* GCP.ContactCenterAIPlatform.ContactCenter("Support", {
223 * customerDomainPrefix: "supdesk",
224 * displayName: "Support desk v2",
225 * labels: { env: "prod", team: "cx" },
226 * });
227 * ```
228 *
229 * @resource
230 * @category ContactCenterAIPlatform
231 */
232 export const ContactCenter = Resource<ContactCenter>("GCP.ContactCenterAIPlatform.ContactCenter");
233
234 const resourceName = (project: string, location: string, contactCenterId: string) =>
235 `${locationParent(project, location)}/contactCenters/${contactCenterId}`;
236
237 const instanceConfigOf = (news: ContactCenterProps): ccaip.InstanceConfig =>
238 news.instanceConfig ?? {
239 instanceSize: news.instanceSize ?? DEFAULT_INSTANCE_SIZE,
240 };
241
242 const channelBody = (news: ContactCenterProps) => {
243 const channel = news.releaseChannel ?? (news.critical !== undefined ? "critical" : undefined);
244 return {
245 early: channel === "early" ? {} : undefined,
246 normal: channel === "normal" ? {} : undefined,
247 critical: channel === "critical" ? (news.critical ?? {}) : news.critical,
248 };
249 };
250
251 const toAttrs = (item: ccaip.ContactCenter, project: string, region: string) => {
252 const name = item.name ?? "";
253 const parsed = parseName(name, region);
254 return {
255 name,
256 contactCenterId: parsed.id,
257 location: parsed.location,
258 project: parsed.project || project,
259 displayName: item.displayName,
260 customerDomainPrefix: item.customerDomainPrefix,
261 instanceSize: item.instanceConfig?.instanceSize,
262 labels: userLabels(item.labels),
263 userEmail: item.userEmail,
264 adminUser: item.adminUser,
265 kmsKey: item.kmsKey,
266 ccaipManagedUsers: item.ccaipManagedUsers === true,
267 samlParams: item.samlParams,
268 featureConfig: item.featureConfig,
269 privateAccess: item.privateAccess,
270 advancedReportingEnabled: item.advancedReportingEnabled === true,
271 releaseChannel: releaseChannelOf(item),
272 critical: item.critical,
273 state: item.state,
274 releaseVersion: item.releaseVersion,
275 uris: item.uris,
276 privateComponents: item.privateComponents,
277 createTime: item.createTime,
278 updateTime: item.updateTime,
279 deleteTime: item.deleteTime,
280 expireTime: item.expireTime,
281 purgeTime: item.purgeTime,
282 };
283 };
284
285 const getByName = (name: string) =>
286 name.length === 0
287 ? Effect.undefined
288 : ccaip
289 .getProjectsLocationsContactCenters({ name })
290 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
291
292 const getLive = (name: string) =>
293 getByName(name).pipe(
294 Effect.map((item) => (item === undefined || isTerminated(item.state) ? undefined : item)),
295 );
296
297 export const ContactCenterProvider = () =>
298 Provider.succeed(ContactCenter, {
299 stables: [
300 "name",
301 "contactCenterId",
302 "location",
303 "project",
304 "customerDomainPrefix",
305 "createTime",
306 ],
307
308 diff: Effect.fn(function* ({ news, olds, output }) {
309 if (!isResolved(news)) return undefined;
310 const env = yield* GcpEnvironment.current;
311 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
312 const nextLocation = normalizeLocation(
313 news.location ?? olds?.location ?? output?.location,
314 env.region,
315 );
316 const previousSize =
317 olds?.instanceConfig?.instanceSize ?? olds?.instanceSize ?? output?.instanceSize;
318 const nextSize = news.instanceConfig?.instanceSize ?? news.instanceSize;
319 const previousPrefix = olds?.customerDomainPrefix ?? output?.customerDomainPrefix;
320 const previousKms = olds?.kmsKey ?? output?.kmsKey;
321 return replaceOnIdentity({
322 previousId: olds?.contactCenterId ?? output?.contactCenterId,
323 nextId: news.contactCenterId,
324 previousLocation,
325 nextLocation,
326 extra:
327 (previousPrefix !== undefined &&
328 news.customerDomainPrefix !== undefined &&
329 previousPrefix !== news.customerDomainPrefix) ||
330 (previousSize !== undefined && nextSize !== undefined && previousSize !== nextSize) ||
331 (previousKms !== undefined && news.kmsKey !== undefined && previousKms !== news.kmsKey) ||
332 (olds?.instanceConfig !== undefined &&
333 news.instanceConfig !== undefined &&
334 fingerprint(olds.instanceConfig) !== fingerprint(news.instanceConfig)),
335 });
336 }),
337
338 read: Effect.fn(function* ({ id, olds, output }) {
339 const env = yield* GcpEnvironment.current;
340 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
341 const contactCenterId = yield* toPhysicalId(
342 id,
343 olds?.contactCenterId,
344 output?.contactCenterId,
345 );
346 const name = output?.name ?? resourceName(env.project, location, contactCenterId);
347 const existing = yield* getLive(name);
348 if (existing === undefined) {
349 return undefined;
350 }
351 const attrs = toAttrs(existing, env.project, env.region);
352 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
353 }),
354
355 list: () =>
356 Effect.gen(function* () {
357 const env = yield* GcpEnvironment.current;
358 const items: ccaip.ContactCenter[] = yield* listOwnedContactCenters(
359 env.project,
360 env.region,
361 );
362 return items
363 .filter((item) => !isTerminated(item.state))
364 .map((item) => toAttrs(item, env.project, env.region));
365 }),
366
367 reconcile: Effect.fn(function* ({ id, news, output }) {
368 const env = yield* GcpEnvironment.current;
369 const location = normalizeLocation(news.location ?? output?.location, env.region);
370 const contactCenterId = yield* toPhysicalId(
371 id,
372 news.contactCenterId,
373 output?.contactCenterId,
374 );
375 const name = output?.name ?? resourceName(env.project, location, contactCenterId);
376 const parent = locationParent(env.project, location);
377 const customerDomainPrefix = yield* toDomainPrefix(
378 news.customerDomainPrefix,
379 output?.customerDomainPrefix,
380 id,
381 );
382 const displayName = news.displayName ?? contactCenterId;
383 const instanceConfig = instanceConfigOf(news);
384 const desiredLabels = {
385 ...toLabels(news.labels),
386 ...(yield* createInternalLabels(id)),
387 };
388 const channel = channelBody(news);
389
390 let current = yield* getLive(name);
391
392 if (current === undefined) {
393 const created = yield* retryTransient(
394 ccaip.createProjectsLocationsContactCenters({
395 parent,
396 contactCenterId,
397 body: {
398 displayName,
399 customerDomainPrefix,
400 instanceConfig,
401 labels: desiredLabels,
402 userEmail: news.userEmail,
403 adminUser: news.adminUser,
404 kmsKey: news.kmsKey,
405 ccaipManagedUsers: news.ccaipManagedUsers,
406 samlParams: news.samlParams,
407 featureConfig: news.featureConfig,
408 privateAccess: news.privateAccess,
409 advancedReportingEnabled: news.advancedReportingEnabled,
410 early: channel.early,
411 normal: channel.normal,
412 critical: channel.critical,
413 },
414 }),
415 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
416 if (created !== undefined) {
417 yield* waitForOperation(created);
418 }
419 current = yield* waitUntilExists(getLive(name), name);
420 }
421
422 if (current === undefined) {
423 return yield* new ContactCenterNotResolved({ resourceName: name });
424 }
425
426 const currentName = current.name ?? name;
427 let live: ccaip.ContactCenter = yield* waitUntilReady(
428 getLive(currentName),
429 currentName,
430 (item) => item.state,
431 ).pipe(
432 Effect.catchTag("GCP.ContactCenterAIPlatform.ContactCenterNotReady", () =>
433 waitUntilExists(getLive(currentName), currentName),
434 ),
435 );
436
437 const observedLabels = tagRecord(live.labels);
438 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
439 const labelsChanged = upsert.length > 0 || removed.length > 0;
440 const displayChanged = !sameText(live.displayName, displayName);
441 const emailChanged = !sameText(live.userEmail, news.userEmail);
442 const adminChanged = !sameJson(live.adminUser, news.adminUser);
443 const managedChanged = !sameBool(live.ccaipManagedUsers, news.ccaipManagedUsers);
444 const samlChanged =
445 news.samlParams !== undefined && !sameJson(live.samlParams, news.samlParams);
446 const featureChanged =
447 news.featureConfig !== undefined && !sameJson(live.featureConfig, news.featureConfig);
448 const privateChanged =
449 news.privateAccess !== undefined && !sameJson(live.privateAccess, news.privateAccess);
450 const reportingChanged = !sameBool(
451 live.advancedReportingEnabled,
452 news.advancedReportingEnabled,
453 );
454 const desiredChannel =
455 news.releaseChannel ?? (news.critical !== undefined ? "critical" : undefined);
456 const channelChanged =
457 desiredChannel !== undefined && releaseChannelOf(live) !== desiredChannel;
458 const criticalChanged =
459 news.critical !== undefined && !sameJson(live.critical, news.critical);
460
461 const mask = updateMaskOf(
462 labelsChanged && "labels",
463 displayChanged && "displayName",
464 emailChanged && "userEmail",
465 adminChanged && "adminUser",
466 managedChanged && "ccaipManagedUsers",
467 samlChanged && "samlParams",
468 featureChanged && "featureConfig",
469 privateChanged && "privateAccess",
470 reportingChanged && "advancedReportingEnabled",
471 channelChanged && desiredChannel === "early" && "early",
472 channelChanged && desiredChannel === "normal" && "normal",
473 (channelChanged && desiredChannel === "critical") || criticalChanged
474 ? "critical"
475 : undefined,
476 );
477
478 if (mask.length > 0) {
479 const patched = yield* retryTransient(
480 ccaip.patchProjectsLocationsContactCenters({
481 name: currentName,
482 updateMask: mask,
483 body: {
484 labels: desiredLabels,
485 displayName,
486 userEmail: news.userEmail,
487 adminUser: news.adminUser,
488 ccaipManagedUsers: news.ccaipManagedUsers,
489 samlParams: news.samlParams,
490 featureConfig: news.featureConfig,
491 privateAccess: news.privateAccess,
492 advancedReportingEnabled: news.advancedReportingEnabled,
493 early: channel.early,
494 normal: channel.normal,
495 critical: channel.critical,
496 },
497 }),
498 ).pipe(
499 Effect.retry({
500 while: (error) => error._tag === "Conflict",
501 times: 8,
502 schedule: Schedule.spaced("2 seconds"),
503 }),
504 );
505 yield* waitForOperation(patched);
506 live = yield* waitUntilExists(getLive(currentName), currentName);
507 }
508
509 return toAttrs(live, env.project, env.region);
510 }),
511
512 delete: Effect.fn(function* ({ output }) {
513 if (!output.name) return;
514 const deleted = yield* retryTransient(
515 ccaip.deleteProjectsLocationsContactCenters({ name: output.name }),
516 ).pipe(
517 Effect.catchTag("NotFound", () => Effect.undefined),
518 Effect.retry({
519 while: (error) => error._tag === "Conflict",
520 times: 8,
521 schedule: Schedule.spaced("5 seconds"),
522 }),
523 );
524 if (deleted !== undefined) {
525 yield* waitForDeleteOperation(deleted);
526 }
527 yield* waitUntilGone(getLive(output.name), output.name);
528 }),
529 });
530
531 export { ContactCenterFailed, ContactCenterNotResolved } from "./internal.ts";