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

main
ts 255 lines 8.62 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 MAX_VIEW_DISPLAY_NAME_LENGTH,
19 normalizeLocation,
20 ownedByAlchemy,
21 parseOwnership,
22 sameText,
23 toResourceId,
24 updateMaskOf,
25 } from "./ownership.ts";
26
27 export type ViewProps = {
28 /**
29 * View id (the `{view}` segment of
30 * `projects/{project}/locations/{location}/views/{view}`). If omitted, a
31 * unique id is generated. Immutable — changing it replaces the view.
32 */
33 viewId?: string;
34 /**
35 * Location (`us-central1`, …). Immutable — changing it replaces the
36 * view. `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 * Display name (max 64 characters including Alchemy's ownership
42 * marker). Views have no labels field, so ownership is stored in a
43 * `[alchemy …]` prefix and stripped from attributes.
44 */
45 displayName?: string;
46 /**
47 * Filter reducing conversation results to a subset. See
48 * https://cloud.google.com/contact-center/insights/docs/filtering.
49 */
50 value?: string;
51 };
52
53 export type View = Resource<
54 "GCP.ContactCenterInsights.View",
55 ViewProps,
56 {
57 /** Full resource name `projects/{project}/locations/{location}/views/{view}`. */
58 name: string;
59 /** View id (last path segment). */
60 viewId: string;
61 /** Location id. */
62 location: string;
63 /** Project id. */
64 project: string;
65 /** User display name with the Alchemy ownership prefix stripped. */
66 displayName: string | undefined;
67 /** Conversation filter. */
68 value: string | undefined;
69 /** RFC3339 creation timestamp. */
70 createTime: string | undefined;
71 /** RFC3339 last-update timestamp. */
72 updateTime: string | undefined;
73 },
74 never,
75 Providers
76 >;
77
78 /**
79 * A Contact Center AI Insights saved view — a named conversation filter.
80 *
81 * Views have no labels field — Alchemy stamps ownership into the display
82 * name. Location and id are immutable. Display name and filter value
83 * update in place.
84 *
85 * ### Creating a View
86 * **Example:** Chat-only view
87 * ```typescript
88 * const view = yield* GCP.ContactCenterInsights.View("Chat", {
89 * displayName: "chat",
90 * value: 'medium="CHAT"',
91 * });
92 * ```
93 *
94 * @resource
95 * @category ContactCenterInsights
96 */
97 export const View = Resource<View>("GCP.ContactCenterInsights.View");
98
99 export class ViewNotResolved extends Data.TaggedError("GCP.ContactCenterInsights.ViewNotResolved")<{
100 resourceName: string;
101 }> {}
102
103 const resourceName = (project: string, location: string, viewId: string) =>
104 `${locationParent(project, location)}/views/${viewId}`;
105
106 const toAttrs = (view: cci.GoogleCloudContactcenterinsightsV1View, project: string) => {
107 const name = view.name ?? "";
108 const parsed = parseOwnership(view.displayName);
109 return {
110 name,
111 viewId: lastSegment(name),
112 location: locationOf(name),
113 project,
114 displayName: parsed.text,
115 value: view.value,
116 createTime: view.createTime,
117 updateTime: view.updateTime,
118 };
119 };
120
121 const getByName = (name: string) =>
122 name.length === 0
123 ? Effect.undefined
124 : cci
125 .getProjectsLocationsViews({ name })
126 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
127
128 const listAt = (parent: string, project: string) =>
129 cci.listProjectsLocationsViews.pages({ parent, pageSize: 100 }).pipe(
130 Stream.flatMap((page) => Stream.fromIterable(page.views ?? [])),
131 Stream.filter((view) => hasOwnershipMarker(view.displayName)),
132 Stream.map((view) => toAttrs(view, project)),
133 Stream.runCollect,
134 Effect.map((chunk) => Array.from(chunk)),
135 Effect.catchTag("NotFound", () => Effect.succeed([])),
136 );
137
138 const findByDisplayName = (parent: string, displayName: string) =>
139 cci.listProjectsLocationsViews.pages({ parent, pageSize: 100 }).pipe(
140 Stream.flatMap((page) => Stream.fromIterable(page.views ?? [])),
141 Stream.filter((view) => view.displayName === displayName),
142 Stream.runHead,
143 Effect.map((option) => (option._tag === "Some" ? option.value : undefined)),
144 Effect.catchTag("NotFound", () => Effect.undefined),
145 );
146
147 export const ViewProvider = () =>
148 Provider.succeed(View, {
149 stables: ["name", "viewId", "location", "project", "createTime"],
150
151 diff: Effect.fn(function* ({ news, olds, output }) {
152 if (!isResolved(news)) return undefined;
153 const previousLocation = olds?.location ?? output?.location;
154 if (
155 previousLocation !== undefined &&
156 news.location !== undefined &&
157 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
158 ) {
159 return { action: "replace" as const, deleteFirst: false };
160 }
161 const previousId = olds?.viewId ?? output?.viewId;
162 if (previousId !== undefined && news.viewId !== undefined && news.viewId !== previousId) {
163 return { action: "replace" as const, deleteFirst: false };
164 }
165 return undefined;
166 }),
167
168 read: Effect.fn(function* ({ id, olds, output }) {
169 const env = yield* GcpEnvironment.current;
170 const viewId = yield* toResourceId(id, olds?.viewId, output?.viewId);
171 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
172 const name = output?.name ?? resourceName(env.project, location, viewId);
173 let existing = yield* getByName(name);
174 if (existing === undefined && output?.name === undefined) {
175 const ownership = yield* createInternalLabels(id);
176 existing = yield* findByDisplayName(
177 locationParent(env.project, location),
178 encodeOwnershipLine(ownership, olds?.displayName, MAX_VIEW_DISPLAY_NAME_LENGTH),
179 );
180 }
181 if (existing === undefined) return undefined;
182 const attrs = toAttrs(existing, env.project);
183 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
184 }),
185
186 list: () =>
187 Effect.gen(function* () {
188 const env = yield* GcpEnvironment.current;
189 return yield* listAt(locationParent(env.project, env.region), env.project);
190 }),
191
192 reconcile: Effect.fn(function* ({ id, news, output }) {
193 const env = yield* GcpEnvironment.current;
194 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
195 const parent = locationParent(env.project, location);
196 const viewId = yield* toResourceId(id, news.viewId, output?.viewId);
197 const name = output?.name ?? resourceName(env.project, location, viewId);
198 const ownership = yield* createInternalLabels(id);
199 const displayName = encodeOwnershipLine(
200 ownership,
201 news.displayName,
202 MAX_VIEW_DISPLAY_NAME_LENGTH,
203 );
204
205 let current = yield* getByName(name);
206 if (current === undefined) {
207 current = yield* findByDisplayName(parent, displayName);
208 }
209
210 if (current === undefined) {
211 const created = yield* cci
212 .createProjectsLocationsViews({
213 parent,
214 body: {
215 name,
216 displayName,
217 value: news.value,
218 },
219 })
220 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
221 current = created ?? (yield* findByDisplayName(parent, displayName));
222 }
223
224 if (current === undefined) {
225 return yield* new ViewNotResolved({ resourceName: name });
226 }
227
228 const currentName = current.name ?? name;
229 const displayChanged = (current.displayName ?? "") !== displayName;
230 const valueChanged = !sameText(current.value, news.value);
231
232 if (displayChanged || valueChanged) {
233 current = yield* cci.patchProjectsLocationsViews({
234 name: currentName,
235 updateMask: updateMaskOf(
236 displayChanged ? "display_name" : undefined,
237 valueChanged ? "value" : undefined,
238 ),
239 body: {
240 name: currentName,
241 displayName,
242 value: news.value,
243 },
244 });
245 }
246
247 return toAttrs(current, env.project);
248 }),
249
250 delete: Effect.fn(function* ({ output }) {
251 yield* cci
252 .deleteProjectsLocationsViews({ name: output.name })
253 .pipe(Effect.catchTag("NotFound", () => Effect.void));
254 }),
255 });