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

main
ts 283 lines 9.87 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 lastSegment,
16 locationOf,
17 locationParent,
18 ownedByAlchemy,
19 parentOf,
20 parseOwnership,
21 } from "./ownership.ts";
22
23 export type AgentInfo = {
24 /** Opaque agent id the assessment is for. Required on create. */
25 agentId?: string;
26 /** Agent display name. */
27 displayName?: string;
28 /** Agent type (e.g. `HUMAN_AGENT`). */
29 agentType?: string;
30 /** Agent team. */
31 team?: string;
32 /** Agent teams. */
33 teams?: string[];
34 /** Agent location. */
35 location?: string;
36 };
37
38 export type AuthorizedViewSetsAuthorizedViewsConversationsAssessmentProps = {
39 /**
40 * Parent conversation under an AuthorizedView
41 * (`{authorizedView}/conversations/{conversation}`). Immutable —
42 * changing it replaces the assessment.
43 */
44 parent: string;
45 /**
46 * Agent the assessment is for. Assessments have no labels or
47 * description field, so Alchemy ownership is stored in
48 * `agentInfo.displayName`.
49 */
50 agentInfo: AgentInfo;
51 };
52
53 export type AuthorizedViewSetsAuthorizedViewsConversationsAssessment = Resource<
54 "GCP.ContactCenterInsights.AuthorizedViewSetsAuthorizedViewsConversationsAssessment",
55 AuthorizedViewSetsAuthorizedViewsConversationsAssessmentProps,
56 {
57 /** Full resource name. */
58 name: string;
59 /** Assessment id (last path segment). */
60 assessmentId: string;
61 /** Parent conversation under the AuthorizedView. */
62 parent: string;
63 /** Location id. */
64 location: string;
65 /** Project id. */
66 project: string;
67 /** Assessment state. */
68 state: string | undefined;
69 /** Agent info with the Alchemy ownership prefix stripped from displayName. */
70 agentInfo: AgentInfo | undefined;
71 /** RFC3339 creation timestamp. */
72 createTime: string | undefined;
73 /** RFC3339 last-update timestamp. */
74 updateTime: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A Contact Center AI Insights quality assessment of a conversation,
82 * created through an AuthorizedView.
83 *
84 * Assessments have no labels field and no patch API — Alchemy stamps
85 * ownership into `agentInfo.displayName`. Parent conversation is
86 * immutable. Reconcile is observe-then-ensure.
87 *
88 * ### Creating an Assessment
89 * **Example:** Assess a conversation through a view
90 * ```typescript
91 * const assessment =
92 * yield* GCP.ContactCenterInsights.AuthorizedViewSetsAuthorizedViewsConversationsAssessment(
93 * "Qa",
94 * {
95 * parent: `${view.name}/conversations/${conversation.conversationId}`,
96 * agentInfo: { agentId: "agent-1", displayName: "Ada" },
97 * },
98 * );
99 * ```
100 *
101 * @resource
102 * @category ContactCenterInsights
103 */
104 export const AuthorizedViewSetsAuthorizedViewsConversationsAssessment =
105 Resource<AuthorizedViewSetsAuthorizedViewsConversationsAssessment>(
106 "GCP.ContactCenterInsights.AuthorizedViewSetsAuthorizedViewsConversationsAssessment",
107 );
108
109 export class AuthorizedViewSetsAuthorizedViewsConversationsAssessmentNotResolved extends Data.TaggedError(
110 "GCP.ContactCenterInsights.AuthorizedViewSetsAuthorizedViewsConversationsAssessmentNotResolved",
111 )<{
112 resourceName: string;
113 }> {}
114
115 const agentInfoOf = (
116 info: cci.GoogleCloudContactcenterinsightsV1ConversationQualityMetadataAgentInfo | undefined,
117 ): AgentInfo | undefined => {
118 if (info === undefined) return undefined;
119 const parsed = parseOwnership(info.displayName);
120 return {
121 agentId: info.agentId,
122 displayName: parsed.text,
123 agentType: info.agentType,
124 team: info.team,
125 teams: info.teams,
126 location: info.location,
127 };
128 };
129
130 const toAttrs = (assessment: cci.GoogleCloudContactcenterinsightsV1Assessment, project: string) => {
131 const name = assessment.name ?? "";
132 return {
133 name,
134 assessmentId: lastSegment(name),
135 parent: parentOf(name),
136 location: locationOf(name),
137 project,
138 state: assessment.state,
139 agentInfo: agentInfoOf(assessment.agentInfo),
140 createTime: assessment.createTime,
141 updateTime: assessment.updateTime,
142 };
143 };
144
145 const getByName = (name: string) =>
146 name.length === 0
147 ? Effect.undefined
148 : cci
149 .getProjectsLocationsAuthorizedViewSetsAuthorizedViewsConversationsAssessments({ name })
150 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
151
152 const listAtParent = (parent: string, project: string) =>
153 cci.listProjectsLocationsAuthorizedViewSetsAuthorizedViewsConversationsAssessments
154 .pages({ parent, pageSize: 100 })
155 .pipe(
156 Stream.flatMap((page) => Stream.fromIterable(page.assessments ?? [])),
157 Stream.filter((assessment) => hasOwnershipMarker(assessment.agentInfo?.displayName)),
158 Stream.map((assessment) => toAttrs(assessment, project)),
159 Stream.runCollect,
160 Effect.map((chunk) => Array.from(chunk)),
161 Effect.catchTag("NotFound", () => Effect.succeed([])),
162 );
163
164 const findOwned = (parent: string, displayName: string, agentId: string | undefined) =>
165 cci.listProjectsLocationsAuthorizedViewSetsAuthorizedViewsConversationsAssessments
166 .pages({ parent, pageSize: 100 })
167 .pipe(
168 Stream.flatMap((page) => Stream.fromIterable(page.assessments ?? [])),
169 Stream.filter(
170 (assessment) =>
171 assessment.agentInfo?.displayName === displayName &&
172 (agentId === undefined || assessment.agentInfo?.agentId === agentId),
173 ),
174 Stream.runHead,
175 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
176 Effect.catchTag("NotFound", () => Effect.undefined),
177 );
178
179 export const AuthorizedViewSetsAuthorizedViewsConversationsAssessmentProvider = () =>
180 Provider.succeed(AuthorizedViewSetsAuthorizedViewsConversationsAssessment, {
181 stables: ["name", "assessmentId", "parent", "location", "project", "createTime"],
182
183 diff: Effect.fn(function* ({ news, olds, output }) {
184 if (!isResolved(news)) return undefined;
185 const previousParent = olds?.parent ?? output?.parent;
186 if (previousParent !== undefined && news.parent !== previousParent) {
187 return { action: "replace" as const, deleteFirst: false };
188 }
189 const previousAgent = olds?.agentInfo?.agentId ?? output?.agentInfo?.agentId;
190 if (
191 previousAgent !== undefined &&
192 news.agentInfo.agentId !== undefined &&
193 news.agentInfo.agentId !== previousAgent
194 ) {
195 return { action: "replace" as const, deleteFirst: false };
196 }
197 return undefined;
198 }),
199
200 read: Effect.fn(function* ({ id, olds, output }) {
201 const env = yield* GcpEnvironment.current;
202 let existing = yield* getByName(output?.name ?? "");
203 if (existing === undefined && olds?.parent !== undefined) {
204 const ownership = yield* createInternalLabels(id);
205 existing = yield* findOwned(
206 olds.parent,
207 encodeOwnershipLine(ownership, olds.agentInfo?.displayName),
208 olds.agentInfo?.agentId,
209 );
210 }
211 if (existing === undefined) return undefined;
212 const attrs = toAttrs(existing, env.project);
213 return (yield* ownedByAlchemy(id, existing.agentInfo?.displayName)) ? attrs : Unowned(attrs);
214 }),
215
216 list: () =>
217 Effect.gen(function* () {
218 const env = yield* GcpEnvironment.current;
219 const viewsParent = `${locationParent(env.project, env.region)}/authorizedViewSets/-`;
220 const views = yield* cci.listProjectsLocationsAuthorizedViewSetsAuthorizedViews
221 .pages({ parent: viewsParent, pageSize: 100 })
222 .pipe(
223 Stream.flatMap((page) => Stream.fromIterable(page.authorizedViews ?? [])),
224 Stream.map((view) => view.name ?? ""),
225 Stream.filter((name) => name.length > 0),
226 Stream.runCollect,
227 Effect.map((chunk) => Array.from(chunk)),
228 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
229 );
230 const pages = yield* Effect.forEach(
231 views,
232 (view) => listAtParent(`${view}/conversations/-`, env.project),
233 { concurrency: 4 },
234 );
235 return pages.flat();
236 }),
237
238 reconcile: Effect.fn(function* ({ id, news, output }) {
239 const env = yield* GcpEnvironment.current;
240 const ownership = yield* createInternalLabels(id);
241 const displayName = encodeOwnershipLine(ownership, news.agentInfo.displayName);
242 const agentInfo = {
243 ...news.agentInfo,
244 displayName,
245 };
246
247 let current = yield* getByName(output?.name ?? "");
248 if (current === undefined) {
249 current = yield* findOwned(news.parent, displayName, news.agentInfo.agentId);
250 }
251
252 if (current === undefined) {
253 const created = yield* cci
254 .createProjectsLocationsAuthorizedViewSetsAuthorizedViewsConversationsAssessments({
255 parent: news.parent,
256 body: { agentInfo },
257 })
258 .pipe(
259 Effect.catchTag("Conflict", () =>
260 findOwned(news.parent, displayName, news.agentInfo.agentId),
261 ),
262 );
263 current = created ?? undefined;
264 }
265
266 if (current === undefined) {
267 return yield* new AuthorizedViewSetsAuthorizedViewsConversationsAssessmentNotResolved({
268 resourceName: output?.name ?? `${news.parent}/assessments/-`,
269 });
270 }
271
272 return toAttrs(current, env.project);
273 }),
274
275 delete: Effect.fn(function* ({ output }) {
276 yield* cci
277 .deleteProjectsLocationsAuthorizedViewSetsAuthorizedViewsConversationsAssessments({
278 name: output.name,
279 force: true,
280 })
281 .pipe(Effect.catchTag("NotFound", () => Effect.void));
282 }),
283 });