@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 316 lines 10.8 KB
Raw
1 import * as discoveryengine from "@distilled.cloud/gcp/discoveryengine_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 { alchemyLabelKeys, hasAlchemyLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 expandDataStore,
14 internalLabels,
15 listProjectDataStores,
16 parseResourceName,
17 sameStringList,
18 sessionIdOf,
19 toPhysical,
20 } from "./internal.ts";
21
22 export type DataStoresSessionProps = {
23 /**
24 * Parent Data Store resource name
25 * `projects/{project}/locations/{location}/dataStores/{dataStore}`.
26 * Immutable — changing it replaces the session.
27 */
28 dataStore: string;
29 /**
30 * Session id (1-63 characters, lowercase alphanumeric). If omitted, a
31 * unique id is generated. Immutable — changing it replaces the session.
32 */
33 sessionId?: string;
34 /**
35 * Display name shown in the UI.
36 */
37 displayName?: string;
38 /**
39 * Unique identifier for tracking users.
40 */
41 userPseudoId?: string;
42 /**
43 * Session state (`IN_PROGRESS`, `STATE_UNSPECIFIED`).
44 */
45 state?: string;
46 /**
47 * When true, the session is pinned to the top of the list.
48 * @default false
49 */
50 isPinned?: boolean;
51 /**
52 * User labels (string values). Alchemy adds `alchemy-stack=…`,
53 * `alchemy-stage=…`, and `alchemy-id=…` entries to mark ownership.
54 */
55 labels?: string[];
56 };
57
58 export type DataStoresSession = Resource<
59 "GCP.DiscoveryEngine.DataStoresSession",
60 DataStoresSessionProps,
61 {
62 /** Full resource name `.../dataStores/{dataStore}/sessions/{session}`. */
63 name: string;
64 /** Session id (last path segment). */
65 sessionId: string;
66 /** Parent data store resource name. */
67 dataStore: string;
68 /** Project id. */
69 project: string;
70 /** Location id. */
71 location: string;
72 /** Display name. */
73 displayName: string | undefined;
74 /** User pseudo id. */
75 userPseudoId: string | undefined;
76 /** Session state. */
77 state: string | undefined;
78 /** Whether the session is pinned. */
79 isPinned: boolean;
80 /** User labels (without Alchemy's `alchemy-*` entries). */
81 labels: string[];
82 /** RFC3339 start timestamp. */
83 startTime: string | undefined;
84 /** RFC3339 end timestamp. */
85 endTime: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 /**
92 * A Vertex AI Search Session attached to a Data Store.
93 *
94 * Alchemy marks ownership with `alchemy-*` entries in the session's
95 * string-list `labels`. Parent and session id are immutable; display name, pin, user id, and labels
96 * update in place.
97 *
98 * ### Creating a Session
99 * **Example:** Generated id
100 * ```typescript
101 * const session = yield* GCP.DiscoveryEngine.DataStoresSession("Chat", {
102 * dataStore: dataStore.name,
103 * displayName: "support",
104 * });
105 * ```
106 *
107 * ### Updating a Session
108 * **Example:** Pin and rename
109 * ```typescript
110 * // Same logical id as before; only the changed props differ.
111 * const session = yield* GCP.DiscoveryEngine.DataStoresSession("Chat", {
112 * dataStore: dataStore.name,
113 * displayName: "vip-support",
114 * isPinned: true,
115 * });
116 * ```
117 *
118 * @resource
119 * @category DiscoveryEngine
120 */
121 export const DataStoresSession = Resource<DataStoresSession>(
122 "GCP.DiscoveryEngine.DataStoresSession",
123 );
124
125 export class DataStoresSessionNotResolved extends Data.TaggedError(
126 "GCP.DiscoveryEngine.DataStoresSessionNotResolved",
127 )<{
128 resourceName: string;
129 }> {}
130
131 const resourceName = (dataStore: string, sessionId: string) => `${dataStore}/sessions/${sessionId}`;
132
133 const ownershipLabels = (labels: Record<string, string>): string[] => [
134 `${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]}`,
135 `${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]}`,
136 `${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}`,
137 ];
138
139 const userStringLabels = (labels: readonly string[] | undefined): string[] =>
140 [...(labels ?? [])].filter((label) => !label.startsWith("alchemy-"));
141
142 /** Parse `alchemy-*=value` session labels back into a label map. */
143 const alchemyLabelsOf = (labels: readonly string[] | undefined) =>
144 Object.fromEntries(
145 (labels ?? [])
146 .filter((label) => label.startsWith("alchemy-") && label.includes("="))
147 .map((label) => {
148 const at = label.indexOf("=");
149 return [label.slice(0, at), label.slice(at + 1)] as const;
150 }),
151 );
152
153 const toAttrs = (session: discoveryengine.GoogleCloudDiscoveryengineV1Session, project: string) => {
154 const name = session.name ?? "";
155 const parsed = parseResourceName(name, "sessions");
156 return {
157 name,
158 sessionId: parsed.id,
159 dataStore: parsed.dataStore,
160 project: parsed.project || project,
161 location: parsed.location,
162 displayName: session.displayName,
163 userPseudoId: session.userPseudoId,
164 state: session.state,
165 isPinned: session.isPinned === true,
166 labels: userStringLabels(session.labels),
167 startTime: session.startTime,
168 endTime: session.endTime,
169 };
170 };
171
172 const getByName = (name: string) =>
173 name.length === 0
174 ? Effect.undefined
175 : discoveryengine
176 .getProjectsLocationsDataStoresSessions({ name })
177 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
178
179 const listAtParent = (parent: string) =>
180 discoveryengine.listProjectsLocationsDataStoresSessions.pages({ parent, pageSize: 100 }).pipe(
181 Stream.flatMap((page) => Stream.fromIterable(page.sessions ?? [])),
182 Stream.filter((session) =>
183 (session.labels ?? []).some((label) => label.startsWith("alchemy-")),
184 ),
185 Stream.runCollect,
186 Effect.map((chunk) => Array.from(chunk)),
187 Effect.catchTag("NotFound", () => Effect.succeed([])),
188 );
189
190 export const DataStoresSessionProvider = () =>
191 Provider.succeed(DataStoresSession, {
192 stables: ["name", "sessionId", "dataStore", "project", "location", "startTime"],
193
194 diff: Effect.fn(function* ({ news, olds, output }) {
195 if (!isResolved(news)) return undefined;
196 const previousParent = olds?.dataStore ?? output?.dataStore;
197 if (previousParent !== undefined && news.dataStore !== previousParent) {
198 return { action: "replace" as const, deleteFirst: false };
199 }
200 const previousId = olds?.sessionId ?? output?.sessionId;
201 if (
202 previousId !== undefined &&
203 news.sessionId !== undefined &&
204 news.sessionId !== previousId
205 ) {
206 return { action: "replace" as const, deleteFirst: true };
207 }
208 return undefined;
209 }),
210
211 read: Effect.fn(function* ({ id, olds, output, previous }) {
212 const env = yield* GcpEnvironment.current;
213 const sessionId = yield* toPhysical(id, olds?.sessionId, output?.sessionId, sessionIdOf);
214 const parent = olds?.dataStore
215 ? expandDataStore(olds.dataStore, env.project, output?.location ?? "global")
216 : undefined;
217 const name = output?.name ?? (parent ? resourceName(parent, sessionId) : "");
218 const existing = yield* getByName(name);
219 if (existing === undefined) return undefined;
220 const attrs = toAttrs(existing, env.project);
221 return (yield* hasAlchemyLabels(id, alchemyLabelsOf(existing.labels)))
222 ? attrs
223 : unownedUnlessPrevious(attrs, previous, "name");
224 }),
225
226 list: () =>
227 Effect.gen(function* () {
228 const env = yield* GcpEnvironment.current;
229 const stores = yield* listProjectDataStores(env.project);
230 const pages = yield* Effect.forEach(
231 stores,
232 (store) =>
233 store.name
234 ? listAtParent(store.name).pipe(
235 Effect.map((sessions) =>
236 sessions.map((session) => toAttrs(session, env.project)),
237 ),
238 )
239 : Effect.succeed([]),
240 { concurrency: 4 },
241 );
242 return pages.flat();
243 }),
244
245 reconcile: Effect.fn(function* ({ id, news, output }) {
246 const env = yield* GcpEnvironment.current;
247 const parent = expandDataStore(news.dataStore, env.project, output?.location ?? "global");
248 const sessionId = yield* toPhysical(id, news.sessionId, output?.sessionId, sessionIdOf);
249 const name = resourceName(parent, sessionId);
250 const displayName = news.displayName;
251 const labels = yield* internalLabels(id);
252 const desiredLabels = [...ownershipLabels(labels), ...userStringLabels(news.labels)];
253
254 let current = yield* getByName(output?.name ?? name);
255
256 if (current === undefined) {
257 const created = yield* discoveryengine
258 .createProjectsLocationsDataStoresSessions({
259 parent,
260 sessionId,
261 body: {
262 displayName,
263 userPseudoId: news.userPseudoId,
264 state: news.state,
265 isPinned: news.isPinned === true ? true : undefined,
266 labels: desiredLabels,
267 },
268 })
269 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
270 current = created ?? undefined;
271 }
272
273 if (current === undefined) {
274 return yield* new DataStoresSessionNotResolved({ resourceName: name });
275 }
276
277 const displayChanged = (current.displayName ?? "") !== (displayName ?? "");
278 const userChanged = (current.userPseudoId ?? "") !== (news.userPseudoId ?? "");
279 const stateChanged = news.state !== undefined && (current.state ?? "") !== news.state;
280 const pinChanged = (current.isPinned === true) !== (news.isPinned === true);
281 const labelsChanged = !sameStringList(current.labels, desiredLabels);
282
283 if (displayChanged || userChanged || stateChanged || pinChanged || labelsChanged) {
284 current = yield* discoveryengine.patchProjectsLocationsDataStoresSessions({
285 name: current.name ?? name,
286 updateMask: [
287 displayChanged ? "display_name" : undefined,
288 userChanged ? "user_pseudo_id" : undefined,
289 stateChanged ? "state" : undefined,
290 pinChanged ? "is_pinned" : undefined,
291 labelsChanged ? "labels" : undefined,
292 ]
293 .filter((field): field is string => field !== undefined)
294 .join(","),
295 body: {
296 name: current.name ?? name,
297 displayName,
298 userPseudoId: news.userPseudoId,
299 state: news.state,
300 isPinned: news.isPinned === true,
301 labels: desiredLabels,
302 },
303 });
304 }
305
306 return toAttrs(current, env.project);
307 }),
308
309 delete: Effect.fn(function* ({ output }) {
310 const existing = yield* getByName(output.name);
311 if (existing === undefined) return;
312 yield* discoveryengine
313 .deleteProjectsLocationsDataStoresSessions({ name: output.name })
314 .pipe(Effect.catchTag("NotFound", () => Effect.void));
315 }),
316 });