@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 416 lines 14.1 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 Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeOwnership,
15 hasOwnershipMarker,
16 jsonEqual,
17 lastSegment,
18 locationOf,
19 locationParent,
20 ownedByAlchemy,
21 parentOf,
22 parseOwnership,
23 sameText,
24 toResourceId,
25 updateMaskOf,
26 } from "./ownership.ts";
27
28 export type QaQuestionType = "QA_QUESTION_TYPE_UNSPECIFIED" | "CUSTOMIZABLE" | "PREDEFINED";
29
30 export type QaQuestionAnswerChoice = {
31 /** String answer value. */
32 strValue?: string;
33 /** Short identifier for the choice. */
34 key?: string;
35 /** Numerical answer value. */
36 numValue?: number;
37 /** Boolean answer value. */
38 boolValue?: boolean;
39 /** When true, the answer is N/A and excluded from scoring. */
40 naValue?: boolean;
41 /** Numerical score contributed by this choice. */
42 score?: number;
43 };
44
45 export type QaQuestionPredefinedQuestionConfig = {
46 /** Predefined question type. */
47 type?:
48 | "PREDEFINED_QUESTION_TYPE_UNSPECIFIED"
49 | "CONVERSATION_OUTCOME"
50 | "CONVERSATION_OUTCOME_ESCALATION_INITIATOR_ROLE"
51 | (string & {});
52 };
53
54 export type QaQuestionDataOptions = {
55 /** Conversation transcript options used to generate the question. */
56 conversationDataOptions?: {
57 /** Include per-turn Dialogflow interaction data. */
58 includeDialogflowInteractionData?: boolean;
59 };
60 };
61
62 export type QaScorecardsRevisionsQaQuestionProps = {
63 /**
64 * Parent QaScorecardRevision resource name
65 * (`projects/{project}/locations/{location}/qaScorecards/{qa_scorecard}/revisions/{revision}`).
66 * Immutable — changing it replaces the question.
67 */
68 parent: string;
69 /**
70 * Question id (the `{qa_question}` segment). If omitted, a unique id is
71 * generated. Must match `^[a-z0-9-]{4,64}$`. Immutable — changing it
72 * replaces the question.
73 */
74 qaQuestionId?: string;
75 /**
76 * Full question text, e.g. "Did the agent greet the customer?"
77 */
78 questionBody?: string;
79 /**
80 * Short UI label, e.g. "Greeting".
81 */
82 abbreviation?: string;
83 /**
84 * Question type.
85 */
86 questionType?: QaQuestionType;
87 /**
88 * Instructions describing how to determine the answer. Questions have
89 * no labels field, so Alchemy ownership is stored in a `[alchemy …]`
90 * prefix and stripped from attributes.
91 */
92 answerInstructions?: string;
93 /**
94 * Order of the question within its parent revision.
95 */
96 order?: number;
97 /**
98 * Valid answers the model must choose from.
99 */
100 answerChoices?: QaQuestionAnswerChoice[];
101 /**
102 * Default or custom tags used to group and score the question.
103 */
104 tags?: string[];
105 /**
106 * Configuration for a predefined question. Set when `questionType` is
107 * `PREDEFINED`.
108 */
109 predefinedQuestionConfig?: QaQuestionPredefinedQuestionConfig;
110 /**
111 * Options for conversation data used to generate the question.
112 */
113 qaQuestionDataOptions?: QaQuestionDataOptions;
114 };
115
116 export type QaScorecardsRevisionsQaQuestion = Resource<
117 "GCP.ContactCenterInsights.QaScorecardsRevisionsQaQuestion",
118 QaScorecardsRevisionsQaQuestionProps,
119 {
120 /** Full resource name. */
121 name: string;
122 /** Question id (last path segment). */
123 qaQuestionId: string;
124 /** Parent revision resource name. */
125 parent: string;
126 /** Location id. */
127 location: string;
128 /** Project id. */
129 project: string;
130 /** Question text. */
131 questionBody: string | undefined;
132 /** Short UI label. */
133 abbreviation: string | undefined;
134 /** Question type. */
135 questionType: string | undefined;
136 /** User instructions with the Alchemy ownership prefix stripped. */
137 answerInstructions: string | undefined;
138 /** Order within the parent revision. */
139 order: number | undefined;
140 /** Valid answer choices. */
141 answerChoices: QaQuestionAnswerChoice[] | undefined;
142 /** Grouping tags. */
143 tags: string[];
144 /** Predefined question config. */
145 predefinedQuestionConfig: QaQuestionPredefinedQuestionConfig | undefined;
146 /** Question data options. */
147 qaQuestionDataOptions: QaQuestionDataOptions | undefined;
148 /** RFC3339 creation timestamp. */
149 createTime: string | undefined;
150 /** RFC3339 last-update timestamp. */
151 updateTime: string | undefined;
152 },
153 never,
154 Providers
155 >;
156
157 /**
158 * A question on a Contact Center AI Insights QA scorecard revision.
159 *
160 * Parent revision and question id are immutable. Questions have no
161 * labels field — Alchemy stamps ownership into `answerInstructions`.
162 * Question body, abbreviation, instructions, order, choices, and tags
163 * update in place while the parent revision is `EDITABLE`.
164 *
165 * ### Creating a QA Question
166 * **Example:** Greeting question
167 * ```typescript
168 * const question = yield* GCP.ContactCenterInsights.QaScorecardsRevisionsQaQuestion(
169 * "Greeting",
170 * {
171 * parent: revision.name,
172 * abbreviation: "Greeting",
173 * questionBody: "Did the agent greet the customer?",
174 * answerChoices: [
175 * { strValue: "Yes", score: 1 },
176 * { strValue: "No", score: 0 },
177 * ],
178 * },
179 * );
180 * ```
181 *
182 * @resource
183 * @category ContactCenterInsights
184 */
185 export const QaScorecardsRevisionsQaQuestion = Resource<QaScorecardsRevisionsQaQuestion>(
186 "GCP.ContactCenterInsights.QaScorecardsRevisionsQaQuestion",
187 );
188
189 export class QaScorecardsRevisionsQaQuestionNotResolved extends Data.TaggedError(
190 "GCP.ContactCenterInsights.QaScorecardsRevisionsQaQuestionNotResolved",
191 )<{
192 resourceName: string;
193 }> {}
194
195 const resourceName = (parent: string, qaQuestionId: string) =>
196 `${parent}/qaQuestions/${qaQuestionId}`;
197
198 const choicesOf = (
199 choices: cci.GoogleCloudContactcenterinsightsV1QaQuestionAnswerChoiceList | undefined,
200 ): QaQuestionAnswerChoice[] | undefined => {
201 if (choices === undefined) return undefined;
202 return choices.map((choice) => ({
203 strValue: choice.strValue,
204 key: choice.key,
205 numValue: choice.numValue,
206 boolValue: choice.boolValue,
207 naValue: choice.naValue,
208 score: choice.score,
209 }));
210 };
211
212 const optionalString = (value: string | undefined): string | undefined => value;
213
214 const toAttrs = (question: cci.GoogleCloudContactcenterinsightsV1QaQuestion, project: string) => {
215 const name = question.name ?? "";
216 const parsed = parseOwnership(question.answerInstructions);
217 return {
218 name,
219 qaQuestionId: lastSegment(name),
220 parent: parentOf(name),
221 location: locationOf(name),
222 project,
223 questionBody: question.questionBody,
224 abbreviation: question.abbreviation,
225 questionType: optionalString(question.questionType),
226 answerInstructions: parsed.text,
227 order: question.order,
228 answerChoices: choicesOf(question.answerChoices),
229 tags: [...(question.tags ?? [])],
230 predefinedQuestionConfig: question.predefinedQuestionConfig
231 ? { type: question.predefinedQuestionConfig.type }
232 : undefined,
233 qaQuestionDataOptions: question.qaQuestionDataOptions
234 ? {
235 conversationDataOptions: question.qaQuestionDataOptions.conversationDataOptions
236 ? {
237 includeDialogflowInteractionData:
238 question.qaQuestionDataOptions.conversationDataOptions
239 .includeDialogflowInteractionData,
240 }
241 : undefined,
242 }
243 : undefined,
244 createTime: question.createTime,
245 updateTime: question.updateTime,
246 };
247 };
248
249 const getByName = (name: string) =>
250 name.length === 0
251 ? Effect.undefined
252 : cci
253 .getProjectsLocationsQaScorecardsRevisionsQaQuestions({ name })
254 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
255
256 const listRevisions = (parent: string) =>
257 cci.listProjectsLocationsQaScorecardsRevisions.pages({ parent, pageSize: 100 }).pipe(
258 Stream.flatMap((page) => Stream.fromIterable(page.qaScorecardRevisions ?? [])),
259 Stream.map((revision) => revision.name ?? ""),
260 Stream.filter((name) => name.length > 0),
261 Stream.runCollect,
262 Effect.map((chunk) => Array.from(chunk)),
263 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
264 );
265
266 const listAtParent = (parent: string, project: string) =>
267 cci.listProjectsLocationsQaScorecardsRevisionsQaQuestions.pages({ parent, pageSize: 100 }).pipe(
268 Stream.flatMap((page) => Stream.fromIterable(page.qaQuestions ?? [])),
269 Stream.filter((question) => hasOwnershipMarker(question.answerInstructions)),
270 Stream.map((question) => toAttrs(question, project)),
271 Stream.runCollect,
272 Effect.map((chunk) => Array.from(chunk)),
273 Effect.catchTag("NotFound", () => Effect.succeed([])),
274 );
275
276 export const QaScorecardsRevisionsQaQuestionProvider = () =>
277 Provider.succeed(QaScorecardsRevisionsQaQuestion, {
278 stables: ["name", "qaQuestionId", "parent", "location", "project", "createTime"],
279
280 diff: Effect.fn(function* ({ news, olds, output }) {
281 if (!isResolved(news)) return undefined;
282 const previousParent = olds?.parent ?? output?.parent;
283 if (previousParent !== undefined && news.parent !== previousParent) {
284 return { action: "replace" as const, deleteFirst: false };
285 }
286 const previousId = olds?.qaQuestionId ?? output?.qaQuestionId;
287 if (
288 previousId !== undefined &&
289 news.qaQuestionId !== undefined &&
290 news.qaQuestionId !== previousId
291 ) {
292 return { action: "replace" as const, deleteFirst: true };
293 }
294 return undefined;
295 }),
296
297 read: Effect.fn(function* ({ id, olds, output, previous }) {
298 const env = yield* GcpEnvironment.current;
299 const qaQuestionId = yield* toResourceId(id, olds?.qaQuestionId, output?.qaQuestionId);
300 const name =
301 output?.name ?? (olds?.parent !== undefined ? resourceName(olds.parent, qaQuestionId) : "");
302 const existing = yield* getByName(name);
303 if (existing === undefined) return undefined;
304 const attrs = toAttrs(existing, env.project);
305 return (yield* ownedByAlchemy(id, existing.answerInstructions))
306 ? attrs
307 : unownedUnlessPrevious(attrs, previous, "name");
308 }),
309
310 list: () =>
311 Effect.gen(function* () {
312 const env = yield* GcpEnvironment.current;
313 const revisions = yield* listRevisions(
314 `${locationParent(env.project, env.region)}/qaScorecards/-`,
315 );
316 const pages = yield* Effect.forEach(
317 revisions,
318 (parent) => listAtParent(parent, env.project),
319 { concurrency: 4 },
320 );
321 return pages.flat();
322 }),
323
324 reconcile: Effect.fn(function* ({ id, news, output }) {
325 const env = yield* GcpEnvironment.current;
326 const qaQuestionId = yield* toResourceId(id, news.qaQuestionId, output?.qaQuestionId);
327 const name = resourceName(news.parent, qaQuestionId);
328 const ownership = yield* createInternalLabels(id);
329 const answerInstructions = encodeOwnership(ownership, news.answerInstructions);
330 const tags = news.tags ?? [];
331
332 let current = yield* getByName(output?.name ?? name);
333
334 if (current === undefined) {
335 const created = yield* cci
336 .createProjectsLocationsQaScorecardsRevisionsQaQuestions({
337 parent: news.parent,
338 qaQuestionId,
339 body: {
340 questionBody: news.questionBody,
341 abbreviation: news.abbreviation,
342 questionType: news.questionType,
343 answerInstructions,
344 order: news.order,
345 answerChoices: news.answerChoices,
346 tags: tags.length > 0 ? tags : undefined,
347 predefinedQuestionConfig: news.predefinedQuestionConfig,
348 qaQuestionDataOptions: news.qaQuestionDataOptions,
349 },
350 })
351 .pipe(
352 Effect.retry({
353 while: (error) => error._tag === "QaScorecardPreconditionFailed",
354 times: 8,
355 schedule: Schedule.exponential("250 millis"),
356 }),
357 Effect.catchTag("Conflict", () => getByName(name)),
358 );
359 current = created ?? undefined;
360 }
361
362 if (current === undefined) {
363 return yield* new QaScorecardsRevisionsQaQuestionNotResolved({
364 resourceName: name,
365 });
366 }
367
368 const currentName = current.name ?? name;
369 const bodyChanged = !sameText(current.questionBody, news.questionBody);
370 const abbreviationChanged = !sameText(current.abbreviation, news.abbreviation);
371 const instructionsChanged = (current.answerInstructions ?? "") !== answerInstructions;
372 const orderChanged = (current.order ?? 0) !== (news.order ?? 0);
373 const choicesChanged = !jsonEqual(choicesOf(current.answerChoices), news.answerChoices);
374 const tagsChanged = !jsonEqual(current.tags ?? [], tags);
375
376 if (
377 bodyChanged ||
378 abbreviationChanged ||
379 instructionsChanged ||
380 orderChanged ||
381 choicesChanged ||
382 tagsChanged
383 ) {
384 current = yield* cci.patchProjectsLocationsQaScorecardsRevisionsQaQuestions({
385 name: currentName,
386 updateMask: updateMaskOf(
387 bodyChanged ? "question_body" : undefined,
388 abbreviationChanged ? "abbreviation" : undefined,
389 instructionsChanged ? "answer_instructions" : undefined,
390 orderChanged ? "order" : undefined,
391 choicesChanged ? "answer_choices" : undefined,
392 tagsChanged ? "tags" : undefined,
393 ),
394 body: {
395 name: currentName,
396 questionBody: news.questionBody,
397 abbreviation: news.abbreviation,
398 answerInstructions,
399 order: news.order,
400 answerChoices: news.answerChoices,
401 tags,
402 },
403 });
404 }
405
406 return toAttrs(current, env.project);
407 }),
408
409 delete: Effect.fn(function* ({ output }) {
410 yield* cci
411 .deleteProjectsLocationsQaScorecardsRevisionsQaQuestions({
412 name: output.name,
413 })
414 .pipe(Effect.catchTag("NotFound", () => Effect.void));
415 }),
416 });