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

main
ts 259 lines 8.67 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 encodeOwnership,
14 hasOwnershipMarker,
15 lastSegment,
16 locationOf,
17 locationParent,
18 normalizeLocation,
19 ownedByAlchemy,
20 parseOwnership,
21 sameText,
22 toResourceId,
23 updateMaskOf,
24 } from "./ownership.ts";
25
26 export type QaScorecardProps = {
27 /**
28 * Scorecard id (the `{qa_scorecard}` segment of
29 * `projects/{project}/locations/{location}/qaScorecards/{qa_scorecard}`).
30 * If omitted, a unique id is generated. Must match `^[a-z0-9-]{4,64}$`.
31 * Immutable — changing it replaces the scorecard.
32 */
33 qaScorecardId?: string;
34 /**
35 * Location (`us-central1`, …). Immutable — changing it replaces the
36 * scorecard. `US-CENTRAL1` is accepted and normalized to `us-central1`.
37 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
38 */
39 location?: string;
40 /**
41 * User-facing display name.
42 */
43 displayName?: string;
44 /**
45 * Human-readable description. Scorecards have no labels field, so
46 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
47 * from attributes.
48 */
49 description?: string;
50 /**
51 * Whether this scorecard is the project default. Default scorecards
52 * cannot be deleted.
53 * @default false
54 */
55 isDefault?: boolean;
56 };
57
58 export type QaScorecard = Resource<
59 "GCP.ContactCenterInsights.QaScorecard",
60 QaScorecardProps,
61 {
62 /** Full resource name `projects/{project}/locations/{location}/qaScorecards/{qa_scorecard}`. */
63 name: string;
64 /** Scorecard id (last path segment). */
65 qaScorecardId: string;
66 /** Location id. */
67 location: string;
68 /** Project id. */
69 project: string;
70 /** User-facing display name. */
71 displayName: string | undefined;
72 /** User description with the Alchemy ownership prefix stripped. */
73 description: string | undefined;
74 /** Whether this is the project default scorecard. */
75 isDefault: boolean;
76 /** Server-reported scorecard source. */
77 source: string | undefined;
78 /** RFC3339 creation timestamp. */
79 createTime: string | undefined;
80 /** RFC3339 last-update timestamp. */
81 updateTime: string | undefined;
82 },
83 never,
84 Providers
85 >;
86
87 /**
88 * A Contact Center AI Insights QA scorecard — a collection of questions
89 * scored during analysis.
90 *
91 * Scorecards have no labels field — Alchemy stamps ownership into the
92 * description. Location and id are immutable. Display name and
93 * description update in place. Delete uses `force` so child revisions
94 * and questions are removed.
95 *
96 * ### Creating a QA Scorecard
97 * **Example:** Generated id
98 * ```typescript
99 * const card = yield* GCP.ContactCenterInsights.QaScorecard("Quality", {
100 * displayName: "quality",
101 * description: "call quality",
102 * });
103 * ```
104 *
105 * @resource
106 * @category ContactCenterInsights
107 */
108 export const QaScorecard = Resource<QaScorecard>("GCP.ContactCenterInsights.QaScorecard");
109
110 export class QaScorecardNotResolved extends Data.TaggedError(
111 "GCP.ContactCenterInsights.QaScorecardNotResolved",
112 )<{
113 resourceName: string;
114 }> {}
115
116 const resourceName = (project: string, location: string, qaScorecardId: string) =>
117 `${locationParent(project, location)}/qaScorecards/${qaScorecardId}`;
118
119 const toAttrs = (card: cci.GoogleCloudContactcenterinsightsV1QaScorecard, project: string) => {
120 const name = card.name ?? "";
121 const parsed = parseOwnership(card.description);
122 return {
123 name,
124 qaScorecardId: lastSegment(name),
125 location: locationOf(name),
126 project,
127 displayName: card.displayName,
128 description: parsed.text,
129 isDefault: card.isDefault === true,
130 source: card.source,
131 createTime: card.createTime,
132 updateTime: card.updateTime,
133 };
134 };
135
136 const getByName = (name: string) =>
137 name.length === 0
138 ? Effect.undefined
139 : cci
140 .getProjectsLocationsQaScorecards({ name })
141 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
142
143 const listAt = (parent: string, project: string) =>
144 cci.listProjectsLocationsQaScorecards.pages({ parent, pageSize: 100 }).pipe(
145 Stream.flatMap((page) => Stream.fromIterable(page.qaScorecards ?? [])),
146 Stream.filter((card) => hasOwnershipMarker(card.description)),
147 Stream.map((card) => toAttrs(card, project)),
148 Stream.runCollect,
149 Effect.map((chunk) => Array.from(chunk)),
150 Effect.catchTag("NotFound", () => Effect.succeed([])),
151 );
152
153 export const QaScorecardProvider = () =>
154 Provider.succeed(QaScorecard, {
155 stables: ["name", "qaScorecardId", "location", "project", "createTime"],
156
157 diff: Effect.fn(function* ({ news, olds, output }) {
158 if (!isResolved(news)) return undefined;
159 const previousLocation = olds?.location ?? output?.location;
160 if (
161 previousLocation !== undefined &&
162 news.location !== undefined &&
163 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
164 ) {
165 return { action: "replace" as const, deleteFirst: false };
166 }
167 const previousId = olds?.qaScorecardId ?? output?.qaScorecardId;
168 if (
169 previousId !== undefined &&
170 news.qaScorecardId !== undefined &&
171 news.qaScorecardId !== previousId
172 ) {
173 return { action: "replace" as const, deleteFirst: true };
174 }
175 return undefined;
176 }),
177
178 read: Effect.fn(function* ({ id, olds, output, previous }) {
179 const env = yield* GcpEnvironment.current;
180 const qaScorecardId = yield* toResourceId(id, olds?.qaScorecardId, output?.qaScorecardId);
181 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
182 const name = output?.name ?? resourceName(env.project, location, qaScorecardId);
183 const existing = yield* getByName(name);
184 if (existing === undefined) return undefined;
185 const attrs = toAttrs(existing, env.project);
186 return (yield* ownedByAlchemy(id, existing.description))
187 ? attrs
188 : unownedUnlessPrevious(attrs, previous, "name");
189 }),
190
191 list: () =>
192 Effect.gen(function* () {
193 const env = yield* GcpEnvironment.current;
194 return yield* listAt(locationParent(env.project, env.region), env.project);
195 }),
196
197 reconcile: Effect.fn(function* ({ id, news, output }) {
198 const env = yield* GcpEnvironment.current;
199 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
200 const parent = locationParent(env.project, location);
201 const qaScorecardId = yield* toResourceId(id, news.qaScorecardId, output?.qaScorecardId);
202 const name = resourceName(env.project, location, qaScorecardId);
203 const ownership = yield* createInternalLabels(id);
204 const description = encodeOwnership(ownership, news.description);
205 const displayName = news.displayName ?? qaScorecardId;
206 const isDefault = news.isDefault === true;
207
208 let current = yield* getByName(output?.name ?? name);
209
210 if (current === undefined) {
211 const created = yield* cci
212 .createProjectsLocationsQaScorecards({
213 parent,
214 qaScorecardId,
215 body: {
216 displayName,
217 description,
218 isDefault,
219 },
220 })
221 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
222 current = created ?? undefined;
223 }
224
225 if (current === undefined) {
226 return yield* new QaScorecardNotResolved({ resourceName: name });
227 }
228
229 const currentName = current.name ?? name;
230 const displayChanged = !sameText(current.displayName, displayName);
231 const descriptionChanged = (current.description ?? "") !== description;
232
233 if (displayChanged || descriptionChanged) {
234 current = yield* cci.patchProjectsLocationsQaScorecards({
235 name: currentName,
236 updateMask: updateMaskOf(
237 displayChanged ? "display_name" : undefined,
238 descriptionChanged ? "description" : undefined,
239 ),
240 body: {
241 name: currentName,
242 displayName,
243 description,
244 },
245 });
246 }
247
248 return toAttrs(current, env.project);
249 }),
250
251 delete: Effect.fn(function* ({ output }) {
252 yield* cci
253 .deleteProjectsLocationsQaScorecards({
254 name: output.name,
255 force: true,
256 })
257 .pipe(Effect.catchTag("NotFound", () => Effect.void));
258 }),
259 });