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

main
ts 335 lines 11.3 KB
Raw
1 import * as aiplatform from "@distilled.cloud/gcp/aiplatform_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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import {
13 createInternalLabels,
14 diffLabels,
15 hasAlchemyLabels,
16 stripInternalLabels,
17 toLabels,
18 } from "../Labels.ts";
19 import type { Providers } from "../Providers.ts";
20 import { listLocations } from "./names.ts";
21 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
22 import { lastSegment, locationOf, locationParent, parentOf, toResourceId } from "./ownership.ts";
23
24 export type ReasoningEnginesSessionProps = {
25 /**
26 * Parent ReasoningEngine resource name
27 * (`projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine}`).
28 * Immutable — changing it replaces the session.
29 */
30 parent: string;
31 /**
32 * Session id (the `{session}` segment). If omitted, a unique id is
33 * generated. Immutable.
34 */
35 sessionId?: string;
36 /**
37 * Immutable user id that owns the session.
38 */
39 userId: string;
40 /**
41 * User-facing display name.
42 */
43 displayName?: string;
44 /**
45 * User labels. Alchemy ownership labels are merged in automatically.
46 */
47 labels?: Record<string, string>;
48 /**
49 * Session TTL (for example `"86400s"`). Minimum 24 hours.
50 */
51 ttl?: string;
52 /**
53 * RFC3339 expiration timestamp. Minimum 24 hours from create time.
54 */
55 expireTime?: string;
56 /**
57 * Session-specific memory storing key conversation points.
58 */
59 sessionState?: Record<string, unknown>;
60 };
61
62 export type ReasoningEnginesSession = Resource<
63 "GCP.AIPlatform.ReasoningEnginesSession",
64 ReasoningEnginesSessionProps,
65 {
66 /** Full resource name. */
67 name: string;
68 /** Session id (last path segment). */
69 sessionId: string;
70 /** Parent ReasoningEngine resource name. */
71 parent: string;
72 /** Region id. */
73 location: string;
74 /** Project id. */
75 project: string;
76 /** User id that owns the session. */
77 userId: string | undefined;
78 /** User-facing display name. */
79 displayName: string | undefined;
80 /** User labels (Alchemy ownership labels stripped). */
81 labels: Record<string, string>;
82 /** Expiration timestamp. */
83 expireTime: string | undefined;
84 /** Session memory. */
85 sessionState: Record<string, unknown> | undefined;
86 /** RFC3339 creation timestamp. */
87 createTime: string | undefined;
88 /** RFC3339 last-update timestamp. */
89 updateTime: string | undefined;
90 },
91 never,
92 Providers
93 >;
94
95 /**
96 * A Vertex AI Reasoning Engine session between a user and an agent.
97 *
98 * Parent engine, session id, and user id are immutable. Display name,
99 * labels, expiration, and session state update in place.
100 *
101 * ### Creating a Session
102 * **Example:** Session for a user
103 * ```typescript
104 * const session = yield* GCP.AIPlatform.ReasoningEnginesSession("Chat", {
105 * parent: engine.name,
106 * userId: "user-123",
107 * displayName: "support-chat",
108 * });
109 * ```
110 *
111 * @resource
112 * @category AIPlatform
113 */
114 export const ReasoningEnginesSession = Resource<ReasoningEnginesSession>(
115 "GCP.AIPlatform.ReasoningEnginesSession",
116 );
117
118 export class ReasoningEnginesSessionNotResolved extends Data.TaggedError(
119 "GCP.AIPlatform.ReasoningEnginesSessionNotResolved",
120 )<{
121 resourceName: string;
122 }> {}
123
124 const userLabels = (
125 labels: Record<string, string | undefined> | null | undefined,
126 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
127
128 const resourceName = (parent: string, sessionId: string) => `${parent}/sessions/${sessionId}`;
129
130 const toAttrs = (session: aiplatform.GoogleCloudAiplatformV1Session, project: string) => {
131 const name = session.name ?? "";
132 return {
133 name,
134 sessionId: lastSegment(name),
135 parent: parentOf(name),
136 location: locationOf(name),
137 project,
138 userId: session.userId,
139 displayName: session.displayName,
140 labels: userLabels(session.labels),
141 expireTime: session.expireTime,
142 sessionState: session.sessionState,
143 createTime: session.createTime,
144 updateTime: session.updateTime,
145 };
146 };
147
148 const getByName = (name: string) =>
149 name.length === 0
150 ? Effect.undefined
151 : aiplatform
152 .getProjectsLocationsReasoningEnginesSessions({ name })
153 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
154
155 const waitUntilExists = (name: string) =>
156 getByName(name).pipe(
157 Effect.flatMap((session) =>
158 session
159 ? Effect.succeed(session)
160 : Effect.fail(new ReasoningEnginesSessionNotResolved({ resourceName: name })),
161 ),
162 Effect.retry({
163 while: (error) => error._tag === "GCP.AIPlatform.ReasoningEnginesSessionNotResolved",
164 times: 8,
165 schedule: Schedule.spaced("2 seconds"),
166 }),
167 );
168
169 const listEngines = (project: string, location: string) =>
170 aiplatform.listProjectsLocationsReasoningEngines
171 .pages({
172 parent: locationParent(project, location),
173 pageSize: 100,
174 })
175 .pipe(
176 Stream.flatMap((page) => Stream.fromIterable(page.reasoningEngines ?? [])),
177 Stream.map((engine) => engine.name ?? ""),
178 Stream.filter((name) => name.length > 0),
179 Stream.runCollect,
180 Effect.map((chunk) => Array.from(chunk)),
181 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
182 );
183
184 const listAtParent = (parent: string, project: string) =>
185 aiplatform.listProjectsLocationsReasoningEnginesSessions.pages({ parent, pageSize: 100 }).pipe(
186 Stream.flatMap((page) => Stream.fromIterable(page.sessions ?? [])),
187 Stream.filter((session) =>
188 Object.keys(session.labels ?? {}).some((key) => key.startsWith("alchemy-")),
189 ),
190 Stream.map((session) => toAttrs(session, project)),
191 Stream.runCollect,
192 Effect.map((chunk) => Array.from(chunk)),
193 Effect.catchTag("NotFound", () => Effect.succeed([])),
194 );
195
196 export const ReasoningEnginesSessionProvider = () =>
197 Provider.succeed(ReasoningEnginesSession, {
198 stables: ["name", "sessionId", "parent", "location", "project", "userId", "createTime"],
199
200 diff: Effect.fn(function* ({ news, olds, output }) {
201 if (!isResolved(news)) return undefined;
202 const previousParent = olds?.parent ?? output?.parent;
203 if (previousParent !== undefined && news.parent !== previousParent) {
204 return { action: "replace" as const, deleteFirst: false };
205 }
206 const previousId = olds?.sessionId ?? output?.sessionId;
207 if (
208 previousId !== undefined &&
209 news.sessionId !== undefined &&
210 news.sessionId !== previousId
211 ) {
212 return { action: "replace" as const, deleteFirst: true };
213 }
214 const previousUser = olds?.userId ?? output?.userId;
215 if (previousUser !== undefined && news.userId !== previousUser) {
216 return { action: "replace" as const, deleteFirst: true };
217 }
218 return undefined;
219 }),
220
221 read: Effect.fn(function* ({ id, olds, output, previous }) {
222 const env = yield* GcpEnvironment.current;
223 const sessionId = yield* toResourceId(id, olds?.sessionId, output?.sessionId);
224 const name =
225 output?.name ?? (olds?.parent !== undefined ? resourceName(olds.parent, sessionId) : "");
226 const existing = yield* getByName(name);
227 if (existing === undefined) return undefined;
228 const attrs = toAttrs(existing, env.project);
229 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
230 ? attrs
231 : unownedUnlessPrevious(attrs, previous, "name");
232 }),
233
234 list: () =>
235 Effect.gen(function* () {
236 const env = yield* GcpEnvironment.current;
237 const engines = (yield* Effect.forEach(listLocations(env.region), (location) =>
238 listEngines(env.project, location),
239 )).flat();
240 const pages = yield* Effect.forEach(
241 engines,
242 (parent) => listAtParent(parent, env.project),
243 { concurrency: 4 },
244 );
245 return pages.flat();
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const sessionId = yield* toResourceId(id, news.sessionId, output?.sessionId);
251 const name = resourceName(news.parent, sessionId);
252 const desiredLabels = {
253 ...toLabels(news.labels),
254 ...(yield* createInternalLabels(id)),
255 };
256
257 let current = yield* getByName(output?.name ?? name);
258
259 if (current === undefined) {
260 const created = yield* aiplatform
261 .createProjectsLocationsReasoningEnginesSessions({
262 parent: news.parent,
263 sessionId,
264 body: {
265 userId: news.userId,
266 displayName: news.displayName,
267 labels: desiredLabels,
268 ttl: news.ttl,
269 expireTime: news.expireTime,
270 sessionState: news.sessionState,
271 },
272 })
273 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
274 if (created !== undefined) {
275 const done = yield* waitForOperation(created, {
276 alreadyExistsOk: true,
277 });
278 const createdName = resourceNameFromOperation(done) ?? name;
279 current = yield* waitUntilExists(createdName);
280 } else {
281 current = yield* getByName(name);
282 }
283 }
284
285 if (current === undefined) {
286 return yield* new ReasoningEnginesSessionNotResolved({ resourceName: name });
287 }
288
289 const observedLabels = tagRecord(current.labels);
290 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
291 const labelsChanged = upsert.length > 0 || removed.length > 0;
292 const displayChanged = (current.displayName ?? "") !== (news.displayName ?? "");
293 const expireChanged =
294 news.expireTime !== undefined && (current.expireTime ?? "") !== news.expireTime;
295 const stateChanged =
296 news.sessionState !== undefined &&
297 JSON.stringify(current.sessionState ?? {}) !== JSON.stringify(news.sessionState ?? {});
298
299 if (labelsChanged || displayChanged || expireChanged || stateChanged) {
300 current = yield* aiplatform.patchProjectsLocationsReasoningEnginesSessions({
301 name: current.name ?? name,
302 updateMask: [
303 labelsChanged ? "labels" : undefined,
304 displayChanged ? "displayName" : undefined,
305 expireChanged ? "expireTime" : undefined,
306 stateChanged ? "sessionState" : undefined,
307 ]
308 .filter((field): field is string => field !== undefined)
309 .join(","),
310 body: {
311 name: current.name ?? name,
312 displayName: news.displayName,
313 labels: desiredLabels,
314 expireTime: news.expireTime,
315 sessionState: news.sessionState,
316 },
317 });
318 }
319
320 return toAttrs(current, env.project);
321 }),
322
323 delete: Effect.fn(function* ({ output }) {
324 const existing = yield* getByName(output.name);
325 if (existing === undefined) return;
326 const operation = yield* aiplatform
327 .deleteProjectsLocationsReasoningEnginesSessions({
328 name: output.name,
329 })
330 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
331 if (operation !== undefined) {
332 yield* waitForOperation(operation, { notFoundOk: true });
333 }
334 }),
335 });