The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cci from "@distilled.cloud/gcp/contactcenterinsights_v1"; |
| 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 { createInternalLabels } from "../Labels.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | encodeOwnershipLine, |
| 14 | hasOwnershipMarker, |
| 15 | jsonEqual, |
| 16 | lastSegment, |
| 17 | locationOf, |
| 18 | locationParent, |
| 19 | normalizeLocation, |
| 20 | ownedByAlchemy, |
| 21 | parseOwnership, |
| 22 | toResourceId, |
| 23 | updateMaskOf, |
| 24 | } from "./ownership.ts"; |
| 25 | |
| 26 | export type ScheduleInfo = { |
| 27 | /** Time zone used to interpret `schedule`. Defaults to UTC. */ |
| 28 | timeZone?: string; |
| 29 | /** RFC3339 start. Omitted starts as soon as the rule is created. */ |
| 30 | startTime?: string; |
| 31 | /** RFC3339 end. Omitted keeps scheduling until the rule is deleted. */ |
| 32 | endTime?: string; |
| 33 | /** |
| 34 | * Groc expression (e.g. `"every 5 minutes"` or |
| 35 | * `"every 1 hours synchronized"`). |
| 36 | */ |
| 37 | schedule?: string; |
| 38 | }; |
| 39 | |
| 40 | export type SampleRule = { |
| 41 | /** |
| 42 | * Group-by dimension. Currently |
| 43 | * `quality_metadata.agent_info.agent_id` is supported. Empty samples |
| 44 | * at the project level. |
| 45 | */ |
| 46 | dimension?: string; |
| 47 | /** Filter selecting conversations to sample. Empty applies to all. */ |
| 48 | conversationFilter?: string; |
| 49 | /** Fraction of conversations to sample, in `[0, 1]`. */ |
| 50 | samplePercentage?: number; |
| 51 | /** Absolute number of conversations to sample. */ |
| 52 | sampleRow?: string; |
| 53 | }; |
| 54 | |
| 55 | export type AssessmentRuleProps = { |
| 56 | /** |
| 57 | * Assessment rule id (the `{assessment_rule}` segment of |
| 58 | * `projects/{project}/locations/{location}/assessmentRules/{assessment_rule}`). |
| 59 | * If omitted, a unique id is generated. Must match `^[A-Za-z0-9]{4,64}$` |
| 60 | * (no dashes). Immutable — changing it replaces the rule. |
| 61 | */ |
| 62 | assessmentRuleId?: string; |
| 63 | /** |
| 64 | * Location (`us-central1`, …). Immutable — changing it replaces the rule. |
| 65 | * `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 66 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 67 | */ |
| 68 | location?: string; |
| 69 | /** |
| 70 | * Display name. Assessment rules have no labels field, so Alchemy |
| 71 | * ownership is stored in a `[alchemy …]` prefix and stripped from |
| 72 | * attributes. |
| 73 | */ |
| 74 | displayName?: string; |
| 75 | /** |
| 76 | * When true, the rule is applied to sampled conversations. |
| 77 | * @default false |
| 78 | */ |
| 79 | active?: boolean; |
| 80 | /** Sampling configuration. */ |
| 81 | sampleRule?: SampleRule; |
| 82 | /** Schedule on which sampled conversations are assessed. */ |
| 83 | scheduleInfo?: ScheduleInfo; |
| 84 | }; |
| 85 | |
| 86 | export type AssessmentRule = Resource< |
| 87 | "GCP.ContactCenterInsights.AssessmentRule", |
| 88 | AssessmentRuleProps, |
| 89 | { |
| 90 | /** Full resource name `projects/{project}/locations/{location}/assessmentRules/{assessment_rule}`. */ |
| 91 | name: string; |
| 92 | /** Assessment rule id (last path segment). */ |
| 93 | assessmentRuleId: string; |
| 94 | /** Location id. */ |
| 95 | location: string; |
| 96 | /** Project id. */ |
| 97 | project: string; |
| 98 | /** User display name with the Alchemy ownership prefix stripped. */ |
| 99 | displayName: string | undefined; |
| 100 | /** Whether the rule is active. */ |
| 101 | active: boolean; |
| 102 | /** Sampling configuration. */ |
| 103 | sampleRule: SampleRule | undefined; |
| 104 | /** Schedule configuration. */ |
| 105 | scheduleInfo: ScheduleInfo | undefined; |
| 106 | /** RFC3339 creation timestamp. */ |
| 107 | createTime: string | undefined; |
| 108 | /** RFC3339 last-update timestamp. */ |
| 109 | updateTime: string | undefined; |
| 110 | }, |
| 111 | never, |
| 112 | Providers |
| 113 | >; |
| 114 | |
| 115 | /** |
| 116 | * A Contact Center AI Insights assessment rule that samples conversations |
| 117 | * on a schedule for quality assessment. |
| 118 | * |
| 119 | * Assessment rules have no labels field — Alchemy stamps ownership into |
| 120 | * the display name. Location and id are immutable. Active flag, sample |
| 121 | * rule, and schedule update in place. |
| 122 | * |
| 123 | * ### Creating an Assessment Rule |
| 124 | * **Example:** Inactive hourly sample |
| 125 | * ```typescript |
| 126 | * const rule = yield* GCP.ContactCenterInsights.AssessmentRule("Qa", { |
| 127 | * displayName: "hourly-qa", |
| 128 | * active: false, |
| 129 | * sampleRule: { samplePercentage: 0.1 }, |
| 130 | * scheduleInfo: { schedule: "every 1 hours", timeZone: "UTC" }, |
| 131 | * }); |
| 132 | * ``` |
| 133 | * |
| 134 | * @resource |
| 135 | * @category ContactCenterInsights |
| 136 | */ |
| 137 | export const AssessmentRule = Resource<AssessmentRule>("GCP.ContactCenterInsights.AssessmentRule"); |
| 138 | |
| 139 | export class AssessmentRuleNotResolved extends Data.TaggedError( |
| 140 | "GCP.ContactCenterInsights.AssessmentRuleNotResolved", |
| 141 | )<{ |
| 142 | resourceName: string; |
| 143 | }> {} |
| 144 | |
| 145 | // Assessment rule ids allow only `[A-Za-z0-9]{4,64}`, unlike the dashed |
| 146 | // ids `toResourceId` generates. |
| 147 | const toAssessmentRuleId = ( |
| 148 | id: string, |
| 149 | requested: string | undefined, |
| 150 | existing: string | undefined, |
| 151 | ) => |
| 152 | requested !== undefined || existing !== undefined |
| 153 | ? toResourceId(id, requested, existing) |
| 154 | : toResourceId(id, undefined, undefined).pipe( |
| 155 | Effect.map((generated) => generated.replace(/[^a-z0-9]/g, "")), |
| 156 | ); |
| 157 | |
| 158 | const resourceName = (project: string, location: string, assessmentRuleId: string) => |
| 159 | `${locationParent(project, location)}/assessmentRules/${assessmentRuleId}`; |
| 160 | |
| 161 | const sampleOf = ( |
| 162 | sample: cci.GoogleCloudContactcenterinsightsV1SampleRule | undefined, |
| 163 | ): SampleRule | undefined => { |
| 164 | if (sample === undefined) return undefined; |
| 165 | return { |
| 166 | dimension: sample.dimension, |
| 167 | conversationFilter: sample.conversationFilter, |
| 168 | samplePercentage: sample.samplePercentage, |
| 169 | sampleRow: sample.sampleRow, |
| 170 | }; |
| 171 | }; |
| 172 | |
| 173 | const scheduleOf = ( |
| 174 | schedule: cci.GoogleCloudContactcenterinsightsV1ScheduleInfo | undefined, |
| 175 | ): ScheduleInfo | undefined => { |
| 176 | if (schedule === undefined) return undefined; |
| 177 | return { |
| 178 | timeZone: schedule.timeZone, |
| 179 | startTime: schedule.startTime, |
| 180 | endTime: schedule.endTime, |
| 181 | schedule: schedule.schedule, |
| 182 | }; |
| 183 | }; |
| 184 | |
| 185 | const toAttrs = (rule: cci.GoogleCloudContactcenterinsightsV1AssessmentRule, project: string) => { |
| 186 | const name = rule.name ?? ""; |
| 187 | const parsed = parseOwnership(rule.displayName); |
| 188 | return { |
| 189 | name, |
| 190 | assessmentRuleId: lastSegment(name), |
| 191 | location: locationOf(name), |
| 192 | project, |
| 193 | displayName: parsed.text, |
| 194 | active: rule.active === true, |
| 195 | sampleRule: sampleOf(rule.sampleRule), |
| 196 | scheduleInfo: scheduleOf(rule.scheduleInfo), |
| 197 | createTime: rule.createTime, |
| 198 | updateTime: rule.updateTime, |
| 199 | }; |
| 200 | }; |
| 201 | |
| 202 | const getByName = (name: string) => |
| 203 | name.length === 0 |
| 204 | ? Effect.undefined |
| 205 | : cci |
| 206 | .getProjectsLocationsAssessmentRules({ name }) |
| 207 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 208 | |
| 209 | const listAt = (parent: string, project: string) => |
| 210 | cci.listProjectsLocationsAssessmentRules.pages({ parent, pageSize: 100 }).pipe( |
| 211 | Stream.flatMap((page) => Stream.fromIterable(page.assessmentRules ?? [])), |
| 212 | Stream.filter((rule) => hasOwnershipMarker(rule.displayName)), |
| 213 | Stream.map((rule) => toAttrs(rule, project)), |
| 214 | Stream.runCollect, |
| 215 | Effect.map((chunk) => Array.from(chunk)), |
| 216 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 217 | ); |
| 218 | |
| 219 | /** Assessment rules reject display names over 64 characters ("Request contains an invalid argument"). */ |
| 220 | const MAX_RULE_DISPLAY_NAME = 64; |
| 221 | |
| 222 | export const AssessmentRuleProvider = () => |
| 223 | Provider.succeed(AssessmentRule, { |
| 224 | stables: ["name", "assessmentRuleId", "location", "project", "createTime"], |
| 225 | |
| 226 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 227 | if (!isResolved(news)) return undefined; |
| 228 | const previousLocation = olds?.location ?? output?.location; |
| 229 | if ( |
| 230 | previousLocation !== undefined && |
| 231 | news.location !== undefined && |
| 232 | normalizeLocation(previousLocation) !== normalizeLocation(news.location) |
| 233 | ) { |
| 234 | return { action: "replace" as const, deleteFirst: false }; |
| 235 | } |
| 236 | const previousId = olds?.assessmentRuleId ?? output?.assessmentRuleId; |
| 237 | if ( |
| 238 | previousId !== undefined && |
| 239 | news.assessmentRuleId !== undefined && |
| 240 | news.assessmentRuleId !== previousId |
| 241 | ) { |
| 242 | return { action: "replace" as const, deleteFirst: false }; |
| 243 | } |
| 244 | return undefined; |
| 245 | }), |
| 246 | |
| 247 | read: Effect.fn(function* ({ id, olds, output }) { |
| 248 | const env = yield* GcpEnvironment.current; |
| 249 | const assessmentRuleId = yield* toAssessmentRuleId( |
| 250 | id, |
| 251 | olds?.assessmentRuleId, |
| 252 | output?.assessmentRuleId, |
| 253 | ); |
| 254 | const location = normalizeLocation(olds?.location ?? output?.location ?? env.region); |
| 255 | const name = output?.name ?? resourceName(env.project, location, assessmentRuleId); |
| 256 | const existing = yield* getByName(name); |
| 257 | if (existing === undefined) return undefined; |
| 258 | const attrs = toAttrs(existing, env.project); |
| 259 | return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs); |
| 260 | }), |
| 261 | |
| 262 | list: () => |
| 263 | Effect.gen(function* () { |
| 264 | const env = yield* GcpEnvironment.current; |
| 265 | return yield* listAt(locationParent(env.project, env.region), env.project); |
| 266 | }), |
| 267 | |
| 268 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 269 | const env = yield* GcpEnvironment.current; |
| 270 | const location = normalizeLocation(news.location ?? output?.location ?? env.region); |
| 271 | const parent = locationParent(env.project, location); |
| 272 | const assessmentRuleId = yield* toAssessmentRuleId( |
| 273 | id, |
| 274 | news.assessmentRuleId, |
| 275 | output?.assessmentRuleId, |
| 276 | ); |
| 277 | const name = resourceName(env.project, location, assessmentRuleId); |
| 278 | const ownership = yield* createInternalLabels(id); |
| 279 | const displayName = encodeOwnershipLine(ownership, news.displayName, MAX_RULE_DISPLAY_NAME); |
| 280 | const active = news.active === true; |
| 281 | |
| 282 | let current = yield* getByName(output?.name ?? name); |
| 283 | |
| 284 | if (current === undefined) { |
| 285 | const created = yield* cci |
| 286 | .createProjectsLocationsAssessmentRules({ |
| 287 | parent, |
| 288 | assessmentRuleId, |
| 289 | body: { |
| 290 | displayName, |
| 291 | active, |
| 292 | sampleRule: news.sampleRule, |
| 293 | scheduleInfo: news.scheduleInfo, |
| 294 | }, |
| 295 | }) |
| 296 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 297 | current = created ?? undefined; |
| 298 | } |
| 299 | |
| 300 | if (current === undefined) { |
| 301 | return yield* new AssessmentRuleNotResolved({ resourceName: name }); |
| 302 | } |
| 303 | |
| 304 | const currentName = current.name ?? name; |
| 305 | const displayChanged = (current.displayName ?? "") !== displayName; |
| 306 | const activeChanged = (current.active === true) !== active; |
| 307 | const sampleChanged = !jsonEqual(sampleOf(current.sampleRule), news.sampleRule); |
| 308 | const scheduleChanged = !jsonEqual(scheduleOf(current.scheduleInfo), news.scheduleInfo); |
| 309 | |
| 310 | if (displayChanged || activeChanged || sampleChanged || scheduleChanged) { |
| 311 | current = yield* cci.patchProjectsLocationsAssessmentRules({ |
| 312 | name: currentName, |
| 313 | updateMask: updateMaskOf( |
| 314 | displayChanged ? "display_name" : undefined, |
| 315 | activeChanged ? "active" : undefined, |
| 316 | sampleChanged ? "sample_rule" : undefined, |
| 317 | scheduleChanged ? "schedule_info" : undefined, |
| 318 | ), |
| 319 | body: { |
| 320 | name: currentName, |
| 321 | displayName, |
| 322 | active, |
| 323 | sampleRule: news.sampleRule, |
| 324 | scheduleInfo: news.scheduleInfo, |
| 325 | }, |
| 326 | }); |
| 327 | } |
| 328 | |
| 329 | return toAttrs(current, env.project); |
| 330 | }), |
| 331 | |
| 332 | delete: Effect.fn(function* ({ output }) { |
| 333 | yield* cci |
| 334 | .deleteProjectsLocationsAssessmentRules({ name: output.name }) |
| 335 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 336 | }), |
| 337 | }); |