@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 421 lines 14 KB
Raw
1 import * as cci from "@distilled.cloud/gcp/contactcenterinsights_v1";
2 import { unownedUnlessPrevious } 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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import {
12 createInternalLabels,
13 diffLabels,
14 hasAlchemyLabels,
15 stripInternalLabels,
16 toLabels,
17 } from "../Labels.ts";
18 import type { Providers } from "../Providers.ts";
19 import {
20 lastSegment,
21 locationOf,
22 locationParent,
23 normalizeLocation,
24 sameText,
25 toResourceId,
26 updateMaskOf,
27 } from "./ownership.ts";
28
29 export type ConversationMedium = "MEDIUM_UNSPECIFIED" | "PHONE_CALL" | "CHAT";
30
31 export type GcsSource = {
32 /** Cloud Storage URI of conversation audio. */
33 audioUri?: string;
34 /** Cloud Storage URI of the conversation transcript. Immutable. */
35 transcriptUri?: string;
36 };
37
38 export type ConversationDataSource = {
39 /** Cloud Storage audio and/or transcript. */
40 gcsSource?: GcsSource;
41 /** Cloud Storage URI of conversation metadata. */
42 metadataUri?: string;
43 };
44
45 export type CallMetadata = {
46 /** Audio channel that contains the customer. */
47 customerChannel?: number;
48 /** Audio channel that contains the agent. */
49 agentChannel?: number;
50 };
51
52 export type ConversationProps = {
53 /**
54 * Conversation id (the `{conversation}` segment of
55 * `projects/{project}/locations/{location}/conversations/{conversation}`).
56 * If omitted, a unique id is generated. Must match `^[a-z0-9-]{4,64}$`.
57 * Immutable — changing it replaces the conversation.
58 */
59 conversationId?: string;
60 /**
61 * Location (`us-central1`, …). Immutable — changing it replaces the
62 * conversation. `US-CENTRAL1` is accepted and normalized to
63 * `us-central1`.
64 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
65 */
66 location?: string;
67 /**
68 * Conversation medium. Immutable — changing it replaces the
69 * conversation.
70 * @default "CHAT"
71 */
72 medium?: ConversationMedium | (string & {});
73 /**
74 * User labels. Alchemy ownership labels are merged in automatically.
75 * At most 100 labels, 256 characters per entry.
76 */
77 labels?: Record<string, string>;
78 /** Opaque id of the human agent who handled the conversation. */
79 agentId?: string;
80 /** BCP-47 language code. */
81 languageCode?: string;
82 /** RFC3339 conversation start time. */
83 startTime?: string;
84 /**
85 * RFC3339 expiry. After this time the conversation and its analyses
86 * are deleted.
87 */
88 expireTime?: string;
89 /**
90 * Input-only TTL used to compute `expireTime` (e.g. `"86400s"`).
91 */
92 ttl?: string;
93 /** Audio and transcript source. */
94 dataSource?: ConversationDataSource;
95 /** Call-specific channel metadata. */
96 callMetadata?: CallMetadata;
97 /** Telephony-system JSON metadata. */
98 metadataJson?: string;
99 /** Obfuscated end-user id. */
100 obfuscatedUserId?: string;
101 /**
102 * Delete analyses together with the conversation.
103 * @default true
104 */
105 forceDestroy?: boolean;
106 };
107
108 export type Conversation = Resource<
109 "GCP.ContactCenterInsights.Conversation",
110 ConversationProps,
111 {
112 /** Full resource name `projects/{project}/locations/{location}/conversations/{conversation}`. */
113 name: string;
114 /** Conversation id (last path segment). */
115 conversationId: string;
116 /** Location id. */
117 location: string;
118 /** Project id. */
119 project: string;
120 /** Conversation medium. */
121 medium: string | undefined;
122 /** User labels (Alchemy ownership labels stripped). */
123 labels: Record<string, string>;
124 /** Agent id. */
125 agentId: string | undefined;
126 /** Language code. */
127 languageCode: string | undefined;
128 /** RFC3339 start time. */
129 startTime: string | undefined;
130 /** RFC3339 expiry. */
131 expireTime: string | undefined;
132 /** Data source. */
133 dataSource: ConversationDataSource | undefined;
134 /** Call metadata. */
135 callMetadata: CallMetadata | undefined;
136 /** Duration of the conversation. */
137 duration: string | undefined;
138 /** Number of turns. */
139 turnCount: number | undefined;
140 /** RFC3339 creation timestamp. */
141 createTime: string | undefined;
142 /** RFC3339 last-update timestamp. */
143 updateTime: string | undefined;
144 },
145 never,
146 Providers
147 >;
148
149 /**
150 * A Contact Center AI Insights conversation (chat or phone call).
151 *
152 * `create` does not transcribe or redact audio — use `conversations.upload`
153 * for that. Location, id, and medium are immutable. Labels, agent id,
154 * language, and expiry update in place.
155 *
156 * ### Creating a Conversation
157 * **Example:** Chat conversation with labels
158 * ```typescript
159 * const conversation = yield* GCP.ContactCenterInsights.Conversation(
160 * "Chat",
161 * {
162 * medium: "CHAT",
163 * languageCode: "en-US",
164 * agentId: "agent-1",
165 * labels: { env: "test" },
166 * },
167 * );
168 * ```
169 *
170 * **Example:** Transcript from Cloud Storage
171 * ```typescript
172 * const conversation = yield* GCP.ContactCenterInsights.Conversation(
173 * "Chat",
174 * {
175 * medium: "CHAT",
176 * dataSource: {
177 * gcsSource: { transcriptUri: "gs://bucket/transcript.json" },
178 * },
179 * },
180 * );
181 * ```
182 *
183 * @resource
184 * @category ContactCenterInsights
185 */
186 export const Conversation = Resource<Conversation>("GCP.ContactCenterInsights.Conversation");
187
188 export class ConversationNotResolved extends Data.TaggedError(
189 "GCP.ContactCenterInsights.ConversationNotResolved",
190 )<{
191 resourceName: string;
192 }> {}
193
194 const DEFAULT_MEDIUM = "CHAT";
195
196 const userLabels = (
197 labels: Record<string, string | undefined> | null | undefined,
198 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
199
200 const resourceName = (project: string, location: string, conversationId: string) =>
201 `${locationParent(project, location)}/conversations/${conversationId}`;
202
203 const dataSourceOf = (
204 source: cci.GoogleCloudContactcenterinsightsV1ConversationDataSource | undefined,
205 ): ConversationDataSource | undefined => {
206 if (source === undefined) return undefined;
207 return {
208 gcsSource: source.gcsSource
209 ? {
210 audioUri: source.gcsSource.audioUri,
211 transcriptUri: source.gcsSource.transcriptUri,
212 }
213 : undefined,
214 metadataUri: source.metadataUri,
215 };
216 };
217
218 const callMetadataOf = (
219 metadata: cci.GoogleCloudContactcenterinsightsV1ConversationCallMetadata | undefined,
220 ): CallMetadata | undefined => {
221 if (metadata === undefined) return undefined;
222 return {
223 customerChannel: metadata.customerChannel,
224 agentChannel: metadata.agentChannel,
225 };
226 };
227
228 const toAttrs = (
229 conversation: cci.GoogleCloudContactcenterinsightsV1Conversation,
230 project: string,
231 ) => {
232 const name = conversation.name ?? "";
233 return {
234 name,
235 conversationId: lastSegment(name),
236 location: locationOf(name),
237 project,
238 medium: conversation.medium,
239 labels: userLabels(conversation.labels),
240 agentId: conversation.agentId,
241 languageCode: conversation.languageCode,
242 startTime: conversation.startTime,
243 expireTime: conversation.expireTime,
244 dataSource: dataSourceOf(conversation.dataSource),
245 callMetadata: callMetadataOf(conversation.callMetadata),
246 duration: conversation.duration,
247 turnCount: conversation.turnCount,
248 createTime: conversation.createTime,
249 updateTime: conversation.updateTime,
250 };
251 };
252
253 const getByName = (name: string) =>
254 name.length === 0
255 ? Effect.undefined
256 : cci
257 .getProjectsLocationsConversations({ name, view: "BASIC" })
258 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
259
260 const listAt = (parent: string, project: string) =>
261 cci.listProjectsLocationsConversations.pages({ parent, pageSize: 100, view: "BASIC" }).pipe(
262 Stream.flatMap((page) => Stream.fromIterable(page.conversations ?? [])),
263 Stream.filter((conversation) =>
264 Object.keys(conversation.labels ?? {}).some((key) => key.startsWith("alchemy-")),
265 ),
266 Stream.map((conversation) => toAttrs(conversation, project)),
267 Stream.runCollect,
268 Effect.map((chunk) => Array.from(chunk)),
269 Effect.catchTag("NotFound", () => Effect.succeed([])),
270 );
271
272 export const ConversationProvider = () =>
273 Provider.succeed(Conversation, {
274 stables: ["name", "conversationId", "location", "project", "medium", "createTime"],
275
276 diff: Effect.fn(function* ({ news, olds, output }) {
277 if (!isResolved(news)) return undefined;
278 const previousLocation = olds?.location ?? output?.location;
279 if (
280 previousLocation !== undefined &&
281 news.location !== undefined &&
282 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
283 ) {
284 return { action: "replace" as const, deleteFirst: false };
285 }
286 const previousId = olds?.conversationId ?? output?.conversationId;
287 if (
288 previousId !== undefined &&
289 news.conversationId !== undefined &&
290 news.conversationId !== previousId
291 ) {
292 return { action: "replace" as const, deleteFirst: false };
293 }
294 const previousMedium = olds?.medium ?? output?.medium;
295 const nextMedium = news.medium ?? DEFAULT_MEDIUM;
296 if (previousMedium !== undefined && previousMedium !== nextMedium) {
297 return { action: "replace" as const, deleteFirst: true };
298 }
299 return undefined;
300 }),
301
302 read: Effect.fn(function* ({ id, olds, output, previous }) {
303 const env = yield* GcpEnvironment.current;
304 const conversationId = yield* toResourceId(id, olds?.conversationId, output?.conversationId);
305 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
306 const name = output?.name ?? resourceName(env.project, location, conversationId);
307 const existing = yield* getByName(name);
308 if (existing === undefined) return undefined;
309 const attrs = toAttrs(existing, env.project);
310 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
311 ? attrs
312 : unownedUnlessPrevious(attrs, previous, "name");
313 }),
314
315 list: () =>
316 Effect.gen(function* () {
317 const env = yield* GcpEnvironment.current;
318 return yield* listAt(locationParent(env.project, env.region), env.project);
319 }),
320
321 reconcile: Effect.fn(function* ({ id, news, output }) {
322 const env = yield* GcpEnvironment.current;
323 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
324 const parent = locationParent(env.project, location);
325 const conversationId = yield* toResourceId(id, news.conversationId, output?.conversationId);
326 const name = resourceName(env.project, location, conversationId);
327 const desiredLabels = {
328 ...toLabels(news.labels),
329 ...(yield* createInternalLabels(id)),
330 };
331 const medium = news.medium ?? DEFAULT_MEDIUM;
332
333 let current = yield* getByName(output?.name ?? name);
334
335 if (current === undefined) {
336 const created = yield* cci
337 .createProjectsLocationsConversations({
338 parent,
339 conversationId,
340 body: {
341 medium,
342 labels: desiredLabels,
343 agentId: news.agentId,
344 languageCode: news.languageCode,
345 startTime: news.startTime,
346 expireTime: news.expireTime,
347 ttl: news.ttl,
348 dataSource: news.dataSource,
349 callMetadata: news.callMetadata,
350 metadataJson: news.metadataJson,
351 obfuscatedUserId: news.obfuscatedUserId,
352 },
353 })
354 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
355 current = created ?? undefined;
356 }
357
358 if (current === undefined) {
359 return yield* new ConversationNotResolved({ resourceName: name });
360 }
361
362 const currentName = current.name ?? name;
363 const observedLabels = tagRecord(current.labels);
364 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
365 const labelsChanged = upsert.length > 0 || removed.length > 0;
366 const agentChanged = !sameText(current.agentId, news.agentId);
367 const languageChanged = !sameText(current.languageCode, news.languageCode);
368 // Insights assigns a start time when none is given; only a
369 // caller-supplied one can be updated.
370 const startChanged =
371 news.startTime !== undefined && !sameText(current.startTime, news.startTime);
372 const expireChanged =
373 news.expireTime !== undefined && !sameText(current.expireTime, news.expireTime);
374 const callChanged =
375 news.callMetadata !== undefined &&
376 ((current.callMetadata?.customerChannel ?? undefined) !==
377 news.callMetadata.customerChannel ||
378 (current.callMetadata?.agentChannel ?? undefined) !== news.callMetadata.agentChannel);
379
380 if (
381 labelsChanged ||
382 agentChanged ||
383 languageChanged ||
384 startChanged ||
385 expireChanged ||
386 callChanged
387 ) {
388 current = yield* cci.patchProjectsLocationsConversations({
389 name: currentName,
390 updateMask: updateMaskOf(
391 labelsChanged ? "labels" : undefined,
392 agentChanged ? "agent_id" : undefined,
393 languageChanged ? "language_code" : undefined,
394 startChanged ? "start_time" : undefined,
395 expireChanged ? "expire_time" : undefined,
396 callChanged ? "call_metadata" : undefined,
397 ),
398 body: {
399 name: currentName,
400 labels: desiredLabels,
401 agentId: news.agentId,
402 languageCode: news.languageCode,
403 startTime: news.startTime,
404 expireTime: news.expireTime,
405 callMetadata: news.callMetadata,
406 },
407 });
408 }
409
410 return toAttrs(current, env.project);
411 }),
412
413 delete: Effect.fn(function* ({ output, olds }) {
414 yield* cci
415 .deleteProjectsLocationsConversations({
416 name: output.name,
417 force: olds?.forceDestroy !== false,
418 })
419 .pipe(Effect.catchTag("NotFound", () => Effect.void));
420 }),
421 });