@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 293 lines 9.3 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 * 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 MAX_LABEL_LENGTH,
19 ownedByAlchemy,
20 parentOf,
21 parseOwnership,
22 sameJson,
23 toResourceId,
24 } from "./ownership.ts";
25
26 type QaAnswerLabel = {
27 /** Skip this question. */
28 skipValue?: boolean;
29 /** Not-applicable value. */
30 naValue?: boolean;
31 /** Answer-choice key. */
32 key?: string;
33 /** Numeric value. */
34 numValue?: number;
35 /** Boolean value. */
36 boolValue?: boolean;
37 /** String value. */
38 strValue?: string;
39 };
40
41 export type ConversationsFeedbackLabelProps = {
42 /**
43 * Parent Conversation resource name
44 * (`projects/{project}/locations/{location}/conversations/{conversation}`).
45 * Immutable — changing it replaces the feedback label.
46 */
47 parent: string;
48 /**
49 * Feedback label id (the `{feedback_label}` segment). If omitted, a
50 * unique id is generated. Immutable — changing it replaces the label.
51 */
52 feedbackLabelId?: string;
53 /**
54 * Topic-modeling string label. Feedback labels have no labels field, so
55 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
56 * from attributes.
57 */
58 label?: string;
59 /**
60 * Resource being labeled (scorecard question, issue model, or generator).
61 */
62 labeledResource?: string;
63 /**
64 * Quality-AI answer label.
65 */
66 qaAnswerLabel?: QaAnswerLabel;
67 };
68
69 export type ConversationsFeedbackLabel = Resource<
70 "GCP.ContactCenterInsights.ConversationsFeedbackLabel",
71 ConversationsFeedbackLabelProps,
72 {
73 /** Full resource name. */
74 name: string;
75 /** Feedback label id (last path segment). */
76 feedbackLabelId: string;
77 /** Parent conversation resource name. */
78 parent: string;
79 /** Region id. */
80 location: string;
81 /** Project id. */
82 project: string;
83 /** User label with the Alchemy ownership prefix stripped. */
84 label: string | undefined;
85 /** Resource being labeled. */
86 labeledResource: string | undefined;
87 /** Quality-AI answer label. */
88 qaAnswerLabel: QaAnswerLabel | undefined;
89 /** RFC3339 creation timestamp. */
90 createTime: string | undefined;
91 /** RFC3339 last-update timestamp. */
92 updateTime: string | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A feedback label on a Contact Center Insights conversation.
100 *
101 * Parent conversation and feedback label id are immutable. Feedback
102 * labels have no labels map — Alchemy stamps ownership into the `label`
103 * string. The label text, labeled resource, and QA answer update in
104 * place.
105 *
106 * ### Creating a Feedback Label
107 * **Example:** Topic-modeling label
108 * ```typescript
109 * const label = yield* GCP.ContactCenterInsights.ConversationsFeedbackLabel(
110 * "Topic",
111 * {
112 * parent: conversation.name,
113 * label: "billing",
114 * },
115 * );
116 * ```
117 *
118 * @resource
119 * @category ContactCenterInsights
120 */
121 export const ConversationsFeedbackLabel = Resource<ConversationsFeedbackLabel>(
122 "GCP.ContactCenterInsights.ConversationsFeedbackLabel",
123 );
124
125 export class ConversationsFeedbackLabelNotResolved extends Data.TaggedError(
126 "GCP.ContactCenterInsights.ConversationsFeedbackLabelNotResolved",
127 )<{
128 resourceName: string;
129 }> {}
130
131 const resourceName = (parent: string, feedbackLabelId: string) =>
132 `${parent}/feedbackLabels/${feedbackLabelId}`;
133
134 const toQa = (
135 value: cci.GoogleCloudContactcenterinsightsV1QaAnswerAnswerValue | QaAnswerLabel | undefined,
136 ): QaAnswerLabel | undefined => {
137 if (value === undefined) return undefined;
138 return {
139 skipValue: value.skipValue,
140 naValue: value.naValue,
141 key: value.key,
142 numValue: value.numValue,
143 boolValue: value.boolValue,
144 strValue: value.strValue,
145 };
146 };
147
148 const toAttrs = (label: cci.GoogleCloudContactcenterinsightsV1FeedbackLabel, project: string) => {
149 const name = label.name ?? "";
150 const parsed = parseOwnership(label.label);
151 return {
152 name,
153 feedbackLabelId: lastSegment(name),
154 parent: parentOf(name),
155 location: locationOf(name),
156 project,
157 label: parsed.text,
158 labeledResource: label.labeledResource,
159 qaAnswerLabel: toQa(label.qaAnswerLabel),
160 createTime: label.createTime,
161 updateTime: label.updateTime,
162 };
163 };
164
165 const getByName = (name: string) =>
166 name.length === 0
167 ? Effect.undefined
168 : cci
169 .getProjectsLocationsConversationsFeedbackLabels({ name })
170 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
171
172 const listAll = (parent: string, project: string) =>
173 cci.listAllFeedbackLabelsProjectsLocations.pages({ parent, pageSize: 100 }).pipe(
174 Stream.flatMap((page) => Stream.fromIterable(page.feedbackLabels ?? [])),
175 Stream.filter((label) => hasOwnershipMarker(label.label)),
176 Stream.filter((label) => !label.name?.includes("/datasets/")),
177 Stream.map((label) => toAttrs(label, project)),
178 Stream.runCollect,
179 Effect.map((chunk) => Array.from(chunk)),
180 Effect.catchTag("NotFound", () => Effect.succeed([])),
181 );
182
183 export const ConversationsFeedbackLabelProvider = () =>
184 Provider.succeed(ConversationsFeedbackLabel, {
185 stables: ["name", "feedbackLabelId", "parent", "location", "project", "createTime"],
186
187 diff: Effect.fn(function* ({ news, olds, output }) {
188 if (!isResolved(news)) return undefined;
189 const previousParent = olds?.parent ?? output?.parent;
190 if (previousParent !== undefined && news.parent !== previousParent) {
191 return { action: "replace" as const, deleteFirst: false };
192 }
193 const previousId = olds?.feedbackLabelId ?? output?.feedbackLabelId;
194 if (
195 previousId !== undefined &&
196 news.feedbackLabelId !== undefined &&
197 news.feedbackLabelId !== previousId
198 ) {
199 return { action: "replace" as const, deleteFirst: true };
200 }
201 return undefined;
202 }),
203
204 read: Effect.fn(function* ({ id, olds, output, previous }) {
205 const env = yield* GcpEnvironment.current;
206 const feedbackLabelId = yield* toResourceId(
207 id,
208 olds?.feedbackLabelId,
209 output?.feedbackLabelId,
210 );
211 const name =
212 output?.name ??
213 (olds?.parent !== undefined ? resourceName(olds.parent, feedbackLabelId) : "");
214 const existing = yield* getByName(name);
215 if (existing === undefined) return undefined;
216 const attrs = toAttrs(existing, env.project);
217 return (yield* ownedByAlchemy(id, existing.label))
218 ? attrs
219 : unownedUnlessPrevious(attrs, previous, "name");
220 }),
221
222 list: () =>
223 Effect.gen(function* () {
224 const env = yield* GcpEnvironment.current;
225 return yield* listAll(locationParent(env.project, env.region), env.project);
226 }),
227
228 reconcile: Effect.fn(function* ({ id, news, output }) {
229 const env = yield* GcpEnvironment.current;
230 const feedbackLabelId = yield* toResourceId(
231 id,
232 news.feedbackLabelId,
233 output?.feedbackLabelId,
234 );
235 const name = resourceName(news.parent, feedbackLabelId);
236 const ownership = yield* createInternalLabels(id);
237 const label = encodeOwnershipLine(ownership, news.label, MAX_LABEL_LENGTH);
238
239 let current = yield* getByName(output?.name ?? name);
240
241 if (current === undefined) {
242 const created = yield* cci
243 .createProjectsLocationsConversationsFeedbackLabels({
244 parent: news.parent,
245 feedbackLabelId,
246 body: {
247 label,
248 labeledResource: news.labeledResource,
249 qaAnswerLabel: news.qaAnswerLabel,
250 },
251 })
252 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
253 current = created ?? undefined;
254 }
255
256 if (current === undefined) {
257 return yield* new ConversationsFeedbackLabelNotResolved({ resourceName: name });
258 }
259
260 const labelChanged = (current.label ?? "") !== label;
261 const resourceChanged = (current.labeledResource ?? "") !== (news.labeledResource ?? "");
262 const qaChanged = !sameJson(toQa(current.qaAnswerLabel), news.qaAnswerLabel);
263
264 if (labelChanged || resourceChanged || qaChanged) {
265 current = yield* cci.patchProjectsLocationsConversationsFeedbackLabels({
266 name: current.name ?? name,
267 updateMask: [
268 labelChanged ? "label" : undefined,
269 resourceChanged ? "labeled_resource" : undefined,
270 qaChanged ? "qa_answer_label" : undefined,
271 ]
272 .filter((field): field is string => field !== undefined)
273 .join(","),
274 body: {
275 name: current.name ?? name,
276 label,
277 labeledResource: news.labeledResource,
278 qaAnswerLabel: news.qaAnswerLabel,
279 },
280 });
281 }
282
283 return toAttrs(current, env.project);
284 }),
285
286 delete: Effect.fn(function* ({ output }) {
287 yield* cci
288 .deleteProjectsLocationsConversationsFeedbackLabels({
289 name: output.name,
290 })
291 .pipe(Effect.catchTag("NotFound", () => Effect.void));
292 }),
293 });