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

main
ts 396 lines 13.1 KB
Raw
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 sameText,
23 updateMaskOf,
24 } from "./ownership.ts";
25
26 export type PhraseMatcherType = "PHRASE_MATCHER_TYPE_UNSPECIFIED" | "ALL_OF" | "ANY_OF";
27
28 export type PhraseMatcherRole =
29 | "ROLE_UNSPECIFIED"
30 | "HUMAN_AGENT"
31 | "AUTOMATED_AGENT"
32 | "END_USER"
33 | "ANY_AGENT";
34
35 export type PhraseMatchRuleGroupType =
36 | "PHRASE_MATCH_RULE_GROUP_TYPE_UNSPECIFIED"
37 | "ALL_OF"
38 | "ANY_OF";
39
40 export type ExactMatchConfig = {
41 /** Whether matching is case sensitive. */
42 caseSensitive?: boolean;
43 };
44
45 export type PhraseMatchRule = {
46 /** Phrase or regex to match. */
47 query?: string;
48 /** When true, the phrase must be absent from the transcript. */
49 negated?: boolean;
50 /** Match configuration. */
51 config?: {
52 /** Exact-match options. */
53 exactMatchConfig?: ExactMatchConfig;
54 };
55 };
56
57 export type PhraseMatchRuleGroup = {
58 /** How rules in this group combine (`ALL_OF` or `ANY_OF`). */
59 type?: PhraseMatchRuleGroupType;
60 /** Phrase match rules in this group. */
61 phraseMatchRules?: PhraseMatchRule[];
62 };
63
64 export type PhraseMatcherProps = {
65 /**
66 * Phrase matcher id (the `{phrase_matcher}` segment of
67 * `projects/{project}/locations/{location}/phraseMatchers/{phrase_matcher}`).
68 * If omitted, a unique id is generated. Immutable — changing it replaces
69 * the matcher.
70 */
71 phraseMatcherId?: string;
72 /**
73 * Location (`us-central1`, …). Immutable — changing it replaces the
74 * matcher. `US-CENTRAL1` is accepted and normalized to `us-central1`.
75 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
76 */
77 location?: string;
78 /**
79 * Display name. Phrase matchers have no labels field, so Alchemy
80 * ownership is stored in a `[alchemy …]` prefix and stripped from
81 * attributes.
82 */
83 displayName?: string;
84 /**
85 * How rule groups combine. Required by the API.
86 * @default "ALL_OF"
87 */
88 type?: PhraseMatcherType;
89 /**
90 * When true, the matcher is applied to conversations.
91 * @default false
92 */
93 active?: boolean;
94 /**
95 * Speaker role whose utterances this matcher evaluates.
96 */
97 roleMatch?: PhraseMatcherRole;
98 /**
99 * Custom version tag. Defaults to the server revision id when omitted.
100 */
101 versionTag?: string;
102 /**
103 * Phrase match rule groups.
104 */
105 phraseMatchRuleGroups?: PhraseMatchRuleGroup[];
106 };
107
108 export type PhraseMatcher = Resource<
109 "GCP.ContactCenterInsights.PhraseMatcher",
110 PhraseMatcherProps,
111 {
112 /** Full resource name `projects/{project}/locations/{location}/phraseMatchers/{phrase_matcher}`. */
113 name: string;
114 /** Phrase matcher id (last path segment). */
115 phraseMatcherId: string;
116 /** Location id. */
117 location: string;
118 /** Project id. */
119 project: string;
120 /** User display name with the Alchemy ownership prefix stripped. */
121 displayName: string | undefined;
122 /** How rule groups combine. */
123 type: string | undefined;
124 /** Whether the matcher is active. */
125 active: boolean;
126 /** Speaker role match. */
127 roleMatch: string | undefined;
128 /** Custom version tag. */
129 versionTag: string | undefined;
130 /** Phrase match rule groups. */
131 phraseMatchRuleGroups: PhraseMatchRuleGroup[] | undefined;
132 /** Server revision id. */
133 revisionId: string | undefined;
134 /** RFC3339 revision create timestamp. */
135 revisionCreateTime: string | undefined;
136 /** RFC3339 last-update timestamp. */
137 updateTime: string | undefined;
138 /** RFC3339 last activation-status change. */
139 activationUpdateTime: string | undefined;
140 },
141 never,
142 Providers
143 >;
144
145 /**
146 * A Contact Center AI Insights phrase matcher that flags conversations
147 * containing configured phrases.
148 *
149 * Phrase matchers have no labels field — Alchemy stamps ownership into
150 * the display name so `list` / nuke can find them. Location and id are
151 * immutable. Display name, type, active flag, role, version tag, and
152 * rule groups update in place.
153 *
154 * ### Creating a Phrase Matcher
155 * **Example:** Inactive exact-match matcher
156 * ```typescript
157 * const matcher = yield* GCP.ContactCenterInsights.PhraseMatcher("Refunds", {
158 * displayName: "refunds",
159 * type: "ALL_OF",
160 * active: false,
161 * phraseMatchRuleGroups: [
162 * {
163 * type: "ANY_OF",
164 * phraseMatchRules: [
165 * {
166 * query: "refund",
167 * config: { exactMatchConfig: { caseSensitive: false } },
168 * },
169 * ],
170 * },
171 * ],
172 * });
173 * ```
174 *
175 * @resource
176 * @category ContactCenterInsights
177 */
178 export const PhraseMatcher = Resource<PhraseMatcher>("GCP.ContactCenterInsights.PhraseMatcher");
179
180 export class PhraseMatcherNotResolved extends Data.TaggedError(
181 "GCP.ContactCenterInsights.PhraseMatcherNotResolved",
182 )<{
183 resourceName: string;
184 }> {}
185
186 const DEFAULT_TYPE: PhraseMatcherType = "ALL_OF";
187
188 const resourceName = (project: string, location: string, phraseMatcherId: string) =>
189 `${locationParent(project, location)}/phraseMatchers/${phraseMatcherId}`;
190
191 const groupsOf = (
192 groups: cci.GoogleCloudContactcenterinsightsV1PhraseMatchRuleGroupList | undefined,
193 ): PhraseMatchRuleGroup[] | undefined => {
194 if (groups === undefined) return undefined;
195 return groups.map((group) => ({
196 type: group.type as PhraseMatchRuleGroupType | undefined,
197 phraseMatchRules: group.phraseMatchRules?.map((rule) => ({
198 query: rule.query,
199 negated: rule.negated,
200 config: rule.config
201 ? {
202 exactMatchConfig: rule.config.exactMatchConfig
203 ? {
204 caseSensitive: rule.config.exactMatchConfig.caseSensitive,
205 }
206 : undefined,
207 }
208 : undefined,
209 })),
210 }));
211 };
212
213 const toAttrs = (matcher: cci.GoogleCloudContactcenterinsightsV1PhraseMatcher, project: string) => {
214 const name = matcher.name ?? "";
215 const parsed = parseOwnership(matcher.displayName);
216 return {
217 name,
218 phraseMatcherId: lastSegment(name),
219 location: locationOf(name),
220 project,
221 displayName: parsed.text,
222 type: matcher.type,
223 active: matcher.active === true,
224 roleMatch: matcher.roleMatch,
225 versionTag: matcher.versionTag,
226 phraseMatchRuleGroups: groupsOf(matcher.phraseMatchRuleGroups),
227 revisionId: matcher.revisionId,
228 revisionCreateTime: matcher.revisionCreateTime,
229 updateTime: matcher.updateTime,
230 activationUpdateTime: matcher.activationUpdateTime,
231 };
232 };
233
234 const getByName = (name: string) =>
235 name.length === 0
236 ? Effect.undefined
237 : cci
238 .getProjectsLocationsPhraseMatchers({ name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 const listAt = (parent: string, project: string) =>
242 cci.listProjectsLocationsPhraseMatchers.pages({ parent, pageSize: 100 }).pipe(
243 Stream.flatMap((page) => Stream.fromIterable(page.phraseMatchers ?? [])),
244 Stream.filter((matcher) => hasOwnershipMarker(matcher.displayName)),
245 Stream.map((matcher) => toAttrs(matcher, project)),
246 Stream.runCollect,
247 Effect.map((chunk) => Array.from(chunk)),
248 Effect.catchTag("NotFound", () => Effect.succeed([])),
249 );
250
251 const findByDisplayName = (parent: string, displayName: string) =>
252 cci.listProjectsLocationsPhraseMatchers.pages({ parent, pageSize: 100 }).pipe(
253 Stream.flatMap((page) => Stream.fromIterable(page.phraseMatchers ?? [])),
254 Stream.filter((matcher) => matcher.displayName === displayName),
255 Stream.runHead,
256 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
257 Effect.catchTag("NotFound", () => Effect.undefined),
258 );
259
260 export const PhraseMatcherProvider = () =>
261 Provider.succeed(PhraseMatcher, {
262 stables: ["name", "phraseMatcherId", "location", "project", "revisionCreateTime"],
263
264 diff: Effect.fn(function* ({ news, olds, output }) {
265 if (!isResolved(news)) return undefined;
266 const previousLocation = olds?.location ?? output?.location;
267 if (
268 previousLocation !== undefined &&
269 news.location !== undefined &&
270 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
271 ) {
272 return { action: "replace" as const, deleteFirst: false };
273 }
274 const previousId = olds?.phraseMatcherId ?? output?.phraseMatcherId;
275 if (
276 previousId !== undefined &&
277 news.phraseMatcherId !== undefined &&
278 news.phraseMatcherId !== previousId
279 ) {
280 return { action: "replace" as const, deleteFirst: false };
281 }
282 return undefined;
283 }),
284
285 read: Effect.fn(function* ({ id, olds, output }) {
286 const env = yield* GcpEnvironment.current;
287 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
288 const knownId = olds?.phraseMatcherId ?? output?.phraseMatcherId;
289 const name = output?.name ?? (knownId ? resourceName(env.project, location, knownId) : "");
290 let existing = yield* getByName(name);
291 if (existing === undefined) {
292 const ownership = yield* createInternalLabels(id);
293 existing = yield* findByDisplayName(
294 locationParent(env.project, location),
295 encodeOwnershipLine(ownership, olds?.displayName),
296 );
297 }
298 if (existing === undefined) return undefined;
299 const attrs = toAttrs(existing, env.project);
300 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
301 }),
302
303 list: () =>
304 Effect.gen(function* () {
305 const env = yield* GcpEnvironment.current;
306 return yield* listAt(locationParent(env.project, env.region), env.project);
307 }),
308
309 reconcile: Effect.fn(function* ({ id, news, output }) {
310 const env = yield* GcpEnvironment.current;
311 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
312 const parent = locationParent(env.project, location);
313 const knownId = news.phraseMatcherId ?? output?.phraseMatcherId;
314 const name = output?.name ?? (knownId ? resourceName(env.project, location, knownId) : "");
315 const ownership = yield* createInternalLabels(id);
316 const displayName = encodeOwnershipLine(ownership, news.displayName);
317 const type = news.type ?? DEFAULT_TYPE;
318 const active = news.active === true;
319 const phraseMatchRuleGroups = news.phraseMatchRuleGroups;
320
321 let current = yield* getByName(name);
322 if (current === undefined) {
323 current = yield* findByDisplayName(parent, displayName);
324 }
325
326 if (current === undefined) {
327 const created = yield* cci
328 .createProjectsLocationsPhraseMatchers({
329 parent,
330 body: {
331 displayName,
332 type,
333 active,
334 roleMatch: news.roleMatch,
335 versionTag: news.versionTag,
336 phraseMatchRuleGroups,
337 },
338 })
339 .pipe(Effect.catchTag("Conflict", () => findByDisplayName(parent, displayName)));
340 current = created ?? (yield* findByDisplayName(parent, displayName));
341 }
342
343 if (current === undefined) {
344 return yield* new PhraseMatcherNotResolved({ resourceName: name });
345 }
346
347 const currentName = current.name ?? name;
348 const displayChanged = (current.displayName ?? "") !== displayName;
349 const typeChanged = (current.type ?? DEFAULT_TYPE) !== type;
350 const activeChanged = (current.active === true) !== active;
351 const roleChanged = !sameText(current.roleMatch, news.roleMatch);
352 const versionChanged = !sameText(current.versionTag, news.versionTag);
353 const groupsChanged = !jsonEqual(
354 groupsOf(current.phraseMatchRuleGroups),
355 phraseMatchRuleGroups,
356 );
357
358 if (
359 displayChanged ||
360 typeChanged ||
361 activeChanged ||
362 roleChanged ||
363 versionChanged ||
364 groupsChanged
365 ) {
366 current = yield* cci.patchProjectsLocationsPhraseMatchers({
367 name: currentName,
368 updateMask: updateMaskOf(
369 displayChanged ? "display_name" : undefined,
370 typeChanged ? "type" : undefined,
371 activeChanged ? "active" : undefined,
372 roleChanged ? "role_match" : undefined,
373 versionChanged ? "version_tag" : undefined,
374 groupsChanged ? "phrase_match_rule_groups" : undefined,
375 ),
376 body: {
377 name: currentName,
378 displayName,
379 type,
380 active,
381 roleMatch: news.roleMatch,
382 versionTag: news.versionTag,
383 phraseMatchRuleGroups,
384 },
385 });
386 }
387
388 return toAttrs(current, env.project);
389 }),
390
391 delete: Effect.fn(function* ({ output }) {
392 yield* cci
393 .deleteProjectsLocationsPhraseMatchers({ name: output.name })
394 .pipe(Effect.catchTag("NotFound", () => Effect.void));
395 }),
396 });