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

main
ts 242 lines 8.13 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 toResourceId,
23 } from "./ownership.ts";
24
25 export type AuthorizedViewSetProps = {
26 /**
27 * AuthorizedViewSet id (the `{authorized_view_set}` segment of
28 * `projects/{project}/locations/{location}/authorizedViewSets/{authorized_view_set}`).
29 * If omitted, a unique id is generated. Must match
30 * `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$`. Immutable — changing it replaces
31 * the set.
32 */
33 authorizedViewSetId?: string;
34 /**
35 * Location (`us-central1`, …). Immutable — changing it replaces the set.
36 * `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). AuthorizedViewSets have no labels field, so ownership is
43 * stored in a `[alchemy …]` prefix and stripped from attributes.
44 */
45 displayName?: string;
46 };
47
48 export type AuthorizedViewSet = Resource<
49 "GCP.ContactCenterInsights.AuthorizedViewSet",
50 AuthorizedViewSetProps,
51 {
52 /** Full resource name `projects/{project}/locations/{location}/authorizedViewSets/{authorized_view_set}`. */
53 name: string;
54 /** AuthorizedViewSet id (last path segment). */
55 authorizedViewSetId: string;
56 /** Location id. */
57 location: string;
58 /** Project id. */
59 project: string;
60 /** User display name with the Alchemy ownership prefix stripped. */
61 displayName: string | undefined;
62 /** RFC3339 creation timestamp. */
63 createTime: string | undefined;
64 /** RFC3339 last-update timestamp. */
65 updateTime: string | undefined;
66 },
67 never,
68 Providers
69 >;
70
71 /**
72 * A Contact Center AI Insights AuthorizedViewSet, a container for
73 * AuthorizedView resources.
74 *
75 * AuthorizedViewSets have no labels field — Alchemy stamps ownership into
76 * the display name. Location and id are immutable. Display name updates
77 * in place.
78 *
79 * ### Creating an AuthorizedViewSet
80 * **Example:** Generated id
81 * ```typescript
82 * const set = yield* GCP.ContactCenterInsights.AuthorizedViewSet("QaViews", {
83 * displayName: "qa-reviewers",
84 * });
85 * ```
86 *
87 * **Example:** Named set
88 * ```typescript
89 * const set = yield* GCP.ContactCenterInsights.AuthorizedViewSet("QaViews", {
90 * authorizedViewSetId: "qa-reviewers",
91 * displayName: "qa-reviewers",
92 * });
93 * ```
94 *
95 * @resource
96 * @category ContactCenterInsights
97 */
98 export const AuthorizedViewSet = Resource<AuthorizedViewSet>(
99 "GCP.ContactCenterInsights.AuthorizedViewSet",
100 );
101
102 export class AuthorizedViewSetNotResolved extends Data.TaggedError(
103 "GCP.ContactCenterInsights.AuthorizedViewSetNotResolved",
104 )<{
105 resourceName: string;
106 }> {}
107
108 const resourceName = (project: string, location: string, authorizedViewSetId: string) =>
109 `${locationParent(project, location)}/authorizedViewSets/${authorizedViewSetId}`;
110
111 const toAttrs = (set: cci.GoogleCloudContactcenterinsightsV1AuthorizedViewSet, project: string) => {
112 const name = set.name ?? "";
113 const parsed = parseOwnership(set.displayName);
114 return {
115 name,
116 authorizedViewSetId: lastSegment(name),
117 location: locationOf(name),
118 project,
119 displayName: parsed.text,
120 createTime: set.createTime,
121 updateTime: set.updateTime,
122 };
123 };
124
125 const getByName = (name: string) =>
126 name.length === 0
127 ? Effect.undefined
128 : cci
129 .getProjectsLocationsAuthorizedViewSets({ name })
130 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
131
132 const listAt = (parent: string, project: string) =>
133 cci.listProjectsLocationsAuthorizedViewSets.pages({ parent, pageSize: 100 }).pipe(
134 Stream.flatMap((page) => Stream.fromIterable(page.authorizedViewSets ?? [])),
135 Stream.filter((set) => hasOwnershipMarker(set.displayName)),
136 Stream.map((set) => toAttrs(set, project)),
137 Stream.runCollect,
138 Effect.map((chunk) => Array.from(chunk)),
139 Effect.catchTag("NotFound", () => Effect.succeed([])),
140 );
141
142 export const AuthorizedViewSetProvider = () =>
143 Provider.succeed(AuthorizedViewSet, {
144 stables: ["name", "authorizedViewSetId", "location", "project", "createTime"],
145
146 diff: Effect.fn(function* ({ news, olds, output }) {
147 if (!isResolved(news)) return undefined;
148 const previousLocation = olds?.location ?? output?.location;
149 if (
150 previousLocation !== undefined &&
151 news.location !== undefined &&
152 normalizeLocation(previousLocation) !== normalizeLocation(news.location)
153 ) {
154 return { action: "replace" as const, deleteFirst: false };
155 }
156 const previousId = olds?.authorizedViewSetId ?? output?.authorizedViewSetId;
157 if (
158 previousId !== undefined &&
159 news.authorizedViewSetId !== undefined &&
160 news.authorizedViewSetId !== previousId
161 ) {
162 return { action: "replace" as const, deleteFirst: false };
163 }
164 return undefined;
165 }),
166
167 read: Effect.fn(function* ({ id, olds, output }) {
168 const env = yield* GcpEnvironment.current;
169 const authorizedViewSetId = yield* toResourceId(
170 id,
171 olds?.authorizedViewSetId,
172 output?.authorizedViewSetId,
173 );
174 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
175 const name = output?.name ?? resourceName(env.project, location, authorizedViewSetId);
176 const existing = yield* getByName(name);
177 if (existing === undefined) return undefined;
178 const attrs = toAttrs(existing, env.project);
179 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
180 }),
181
182 list: () =>
183 Effect.gen(function* () {
184 const env = yield* GcpEnvironment.current;
185 return yield* listAt(locationParent(env.project, env.region), env.project);
186 }),
187
188 reconcile: Effect.fn(function* ({ id, news, output }) {
189 const env = yield* GcpEnvironment.current;
190 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
191 const parent = locationParent(env.project, location);
192 const authorizedViewSetId = yield* toResourceId(
193 id,
194 news.authorizedViewSetId,
195 output?.authorizedViewSetId,
196 );
197 const name = resourceName(env.project, location, authorizedViewSetId);
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(output?.name ?? name);
206
207 if (current === undefined) {
208 const created = yield* cci
209 .createProjectsLocationsAuthorizedViewSets({
210 parent,
211 authorizedViewSetId,
212 body: { displayName },
213 })
214 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
215 current = created ?? undefined;
216 }
217
218 if (current === undefined) {
219 return yield* new AuthorizedViewSetNotResolved({ resourceName: name });
220 }
221
222 const currentName = current.name ?? name;
223 if ((current.displayName ?? "") !== displayName) {
224 current = yield* cci.patchProjectsLocationsAuthorizedViewSets({
225 name: currentName,
226 updateMask: "display_name",
227 body: { name: currentName, displayName },
228 });
229 }
230
231 return toAttrs(current, env.project);
232 }),
233
234 delete: Effect.fn(function* ({ output }) {
235 yield* cci
236 .deleteProjectsLocationsAuthorizedViewSets({
237 name: output.name,
238 force: true,
239 })
240 .pipe(Effect.catchTag("NotFound", () => Effect.void));
241 }),
242 });