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

main
ts 374 lines 12.6 KB
Raw
1 import * as aiplatform from "@distilled.cloud/gcp/aiplatform_v1";
2 import * as GcpRetry from "@distilled.cloud/gcp/Retry";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Schedule from "effect/Schedule";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { createInternalLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { listLocations } from "./names.ts";
15 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
16 import { listAlchemyReasoningEngines } from "./ReasoningEngine.ts";
17 import {
18 AiPlatformNotResolved,
19 AiPlatformStillExists,
20 collectPages,
21 encodeDisplayName,
22 hasDisplayNameOwnership,
23 lastSegment,
24 locationParent,
25 normalizeLocation,
26 ownedById,
27 parentBefore,
28 parseDisplayName,
29 parseResourceName,
30 } from "./shared.ts";
31
32 const COLLECTION = "sandboxEnvironments";
33
34 export type SandboxEnvironmentSpec = {
35 /** Code execution environment. */
36 codeExecutionEnvironment?: {
37 machineConfig?: string;
38 codeLanguage?: string;
39 };
40 };
41
42 export type ReasoningEnginesSandboxEnvironmentProps = {
43 /**
44 * Parent Reasoning Engine. Full name or engine id. Immutable —
45 * changing it replaces the sandbox.
46 */
47 reasoningEngine: string;
48 /**
49 * Vertex AI location. Used when `reasoningEngine` is a bare id.
50 * Immutable. @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
51 */
52 location?: string;
53 /**
54 * Display name. Required by the API. SandboxEnvironment has no labels
55 * field, so Alchemy ownership is stored in a compact `[alc …]`
56 * displayName prefix for `list` / nuke.
57 */
58 displayName?: string;
59 /**
60 * Template name (id under the parent engine) to create from.
61 */
62 sandboxEnvironmentTemplate?: string;
63 /**
64 * Snapshot resource name to restore from.
65 */
66 sandboxEnvironmentSnapshot?: string;
67 /**
68 * Sandbox spec (code execution environment).
69 */
70 spec?: SandboxEnvironmentSpec;
71 /**
72 * TTL (e.g. `"3600s"`). Input only.
73 */
74 ttl?: string;
75 /**
76 * Owner identity. A sandbox can only restore snapshots of the same owner.
77 */
78 owner?: string;
79 };
80
81 export type ReasoningEnginesSandboxEnvironment = Resource<
82 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironment",
83 ReasoningEnginesSandboxEnvironmentProps,
84 {
85 /** Full resource name. */
86 name: string;
87 /** Sandbox id (last path segment). */
88 sandboxEnvironmentId: string;
89 /** Parent Reasoning Engine resource name. */
90 reasoningEngine: string;
91 /** Project id. */
92 project: string;
93 /** Location id. */
94 location: string;
95 /** User display name with the Alchemy ownership prefix stripped. */
96 displayName: string | undefined;
97 /** Runtime state. */
98 state: string | undefined;
99 /** Template name, if created from a template. */
100 sandboxEnvironmentTemplate: string | undefined;
101 /** Latest snapshot resource name. */
102 latestSandboxEnvironmentSnapshot: string | undefined;
103 /** Load-balancer hostname. */
104 loadBalancerHostname: string | undefined;
105 /** RFC3339 expire time. */
106 expireTime: string | undefined;
107 /** RFC3339 creation timestamp. */
108 createTime: string | undefined;
109 /** RFC3339 last-update timestamp. */
110 updateTime: string | undefined;
111 },
112 never,
113 Providers
114 >;
115
116 /**
117 * A Vertex AI sandbox environment — a containerized secure execution
118 * runtime for Agent Engine workloads.
119 *
120 * There is no update API. Changing parent or location replaces the
121 * sandbox. Ownership is stamped into the display name.
122 *
123 * ### Creating a Sandbox
124 * **Example:** From a template
125 * ```typescript
126 * const sandbox = yield* GCP.AIPlatform.ReasoningEnginesSandboxEnvironment(
127 * "Box",
128 * {
129 * reasoningEngine: engine.name,
130 * displayName: "dev-box",
131 * sandboxEnvironmentTemplate: template.sandboxEnvironmentTemplateId,
132 * ttl: "3600s",
133 * },
134 * );
135 * ```
136 *
137 * @resource
138 * @category AIPlatform
139 */
140 export const ReasoningEnginesSandboxEnvironment = Resource<ReasoningEnginesSandboxEnvironment>(
141 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironment",
142 );
143
144 export class ReasoningEnginesSandboxEnvironmentNotResolved extends Data.TaggedError(
145 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentNotResolved",
146 )<{
147 resourceName: string;
148 }> {}
149
150 const engineNameOf = (project: string, location: string, reasoningEngine: string) =>
151 reasoningEngine.includes("/")
152 ? reasoningEngine
153 : `${locationParent(project, location)}/reasoningEngines/${reasoningEngine}`;
154
155 const toAttrs = (
156 sandbox: aiplatform.GoogleCloudAiplatformV1SandboxEnvironment,
157 project: string,
158 ) => {
159 const name = sandbox.name ?? "";
160 const parsed = parseResourceName(name, COLLECTION);
161 const display = parseDisplayName(sandbox.displayName);
162 return {
163 name,
164 sandboxEnvironmentId: parsed.id,
165 reasoningEngine: parentBefore(name, COLLECTION),
166 project: parsed.project || project,
167 location: parsed.location,
168 displayName: display.displayName,
169 state: sandbox.state,
170 sandboxEnvironmentTemplate: sandbox.sandboxEnvironmentTemplate,
171 latestSandboxEnvironmentSnapshot: sandbox.latestSandboxEnvironmentSnapshot,
172 loadBalancerHostname: sandbox.connectionInfo?.loadBalancerHostname,
173 expireTime: sandbox.expireTime,
174 createTime: sandbox.createTime,
175 updateTime: sandbox.updateTime,
176 };
177 };
178
179 const getByName = (name: string) =>
180 name.length === 0
181 ? Effect.undefined
182 : aiplatform.getReasoningEnginesSandboxEnvironments({ name }).pipe(
183 Effect.catchTags({
184 NotFound: () => Effect.undefined,
185 SandboxEnvironmentsNotEnabled: () => Effect.undefined,
186 }),
187 );
188
189 const waitUntilExists = (name: string) =>
190 getByName(name).pipe(
191 Effect.filterOrFail(
192 (sandbox): sandbox is aiplatform.GoogleCloudAiplatformV1SandboxEnvironment =>
193 sandbox !== undefined,
194 () => new AiPlatformNotResolved({ resourceName: name }),
195 ),
196 Effect.retry({
197 while: (error) => error._tag === "GCP.AIPlatform.NotResolved",
198 times: 8,
199 schedule: Schedule.spaced("2 seconds"),
200 }),
201 );
202
203 const waitUntilGone = (name: string) =>
204 getByName(name).pipe(
205 Effect.filterOrFail(
206 (sandbox) => sandbox === undefined,
207 () => new AiPlatformStillExists({ resourceName: name }),
208 ),
209 Effect.asVoid,
210 Effect.retry({
211 while: (error) => error._tag === "GCP.AIPlatform.StillExists",
212 times: 10,
213 schedule: Schedule.spaced("2 seconds"),
214 }),
215 );
216
217 const listSandboxes = (parent: string) =>
218 collectPages(
219 aiplatform.listReasoningEnginesSandboxEnvironments.pages({
220 parent,
221 pageSize: 100,
222 }),
223 ).pipe(
224 Effect.map((pages) => pages.flatMap((page) => page.sandboxEnvironments ?? [])),
225 Effect.catchTag("NotFound", () =>
226 Effect.succeed<aiplatform.GoogleCloudAiplatformV1SandboxEnvironment[]>([]),
227 ),
228 );
229
230 const findOwned = (parent: string, id: string) =>
231 Effect.gen(function* () {
232 const sandboxes = yield* listSandboxes(parent);
233 for (const sandbox of sandboxes) {
234 const parsed = parseDisplayName(sandbox.displayName);
235 if (yield* ownedById(id, parsed.labels)) {
236 return sandbox;
237 }
238 }
239 return undefined;
240 });
241
242 export const ReasoningEnginesSandboxEnvironmentProvider = () =>
243 Provider.succeed(ReasoningEnginesSandboxEnvironment, {
244 stables: [
245 "name",
246 "sandboxEnvironmentId",
247 "reasoningEngine",
248 "project",
249 "location",
250 "createTime",
251 ],
252
253 diff: Effect.fn(function* ({ news, olds, output }) {
254 const env = yield* GcpEnvironment.current;
255 if (!isResolved(news)) return undefined;
256 const previousParent = lastSegment(olds?.reasoningEngine ?? output?.reasoningEngine ?? "");
257 const nextParent = lastSegment(news.reasoningEngine);
258 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
259 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
260 const templateChanged =
261 (news.sandboxEnvironmentTemplate ?? "") !== (olds?.sandboxEnvironmentTemplate ?? "");
262 const replace =
263 (previousParent.length > 0 && previousParent !== nextParent) ||
264 previousLocation !== nextLocation ||
265 (olds !== undefined && templateChanged);
266 if (!replace) return undefined;
267 return {
268 action: "replace" as const,
269 deleteFirst: previousLocation === nextLocation && previousParent === nextParent,
270 };
271 }),
272
273 read: Effect.fn(function* ({ id, olds, output }) {
274 const env = yield* GcpEnvironment.current;
275 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
276 const parentRef = olds?.reasoningEngine ?? output?.reasoningEngine;
277 // A create interrupted before its parent resolved has nothing to find.
278 if (output?.name === undefined && typeof parentRef !== "string") {
279 return undefined;
280 }
281 const parent = engineNameOf(env.project, location, parentRef ?? "");
282 const existing =
283 output?.name !== undefined ? yield* getByName(output.name) : yield* findOwned(parent, id);
284 if (existing === undefined) return undefined;
285 const attrs = toAttrs(existing, env.project);
286 const parsed = parseDisplayName(existing.displayName);
287 return (yield* ownedById(id, parsed.labels)) ? attrs : Unowned(attrs);
288 }),
289
290 list: () =>
291 Effect.gen(function* () {
292 const env = yield* GcpEnvironment.current;
293 const engines = (yield* Effect.forEach(listLocations(env.region), (location) =>
294 listAlchemyReasoningEngines(env.project, location),
295 )).flat();
296 const sandboxes = yield* Effect.forEach(
297 engines,
298 (engine) =>
299 engine.name
300 ? listSandboxes(engine.name)
301 : Effect.succeed<aiplatform.GoogleCloudAiplatformV1SandboxEnvironment[]>([]),
302 { concurrency: 4 },
303 );
304 return sandboxes
305 .flat()
306 .filter((sandbox) => hasDisplayNameOwnership(sandbox.displayName))
307 .map((sandbox) => toAttrs(sandbox, env.project));
308 }),
309
310 reconcile: Effect.fn(function* ({ id, news, output }) {
311 const env = yield* GcpEnvironment.current;
312 const location = normalizeLocation(news.location ?? output?.location, env.region);
313 const parent = engineNameOf(env.project, location, news.reasoningEngine);
314 const internal = yield* createInternalLabels(id);
315 const displayName = encodeDisplayName(internal, news.displayName ?? "sandbox");
316
317 let current =
318 output?.name !== undefined ? yield* getByName(output.name) : yield* findOwned(parent, id);
319
320 if (current === undefined) {
321 const created = yield* aiplatform
322 .createReasoningEnginesSandboxEnvironments({
323 parent,
324 body: {
325 displayName,
326 sandboxEnvironmentTemplate: news.sandboxEnvironmentTemplate,
327 sandboxEnvironmentSnapshot: news.sandboxEnvironmentSnapshot,
328 spec: news.spec,
329 ttl: news.ttl,
330 owner: news.owner,
331 },
332 })
333 .pipe(
334 GcpRetry.none,
335 Effect.catchTags({
336 SandboxEnvironmentsNotEnabled: () => Effect.undefined,
337 BadRequest: () => Effect.undefined,
338 Conflict: () => Effect.undefined,
339 }),
340 Effect.timeoutOption("20 seconds"),
341 );
342 const createdOp = Option.getOrUndefined(created);
343 if (createdOp !== undefined) {
344 yield* waitForOperation(createdOp, { alreadyExistsOk: true });
345 }
346 const createdName =
347 createdOp !== undefined ? resourceNameFromOperation(createdOp) : undefined;
348 current =
349 createdName !== undefined
350 ? yield* waitUntilExists(createdName)
351 : yield* findOwned(parent, id);
352 }
353
354 if (current === undefined || current.name === undefined) {
355 return yield* new ReasoningEnginesSandboxEnvironmentNotResolved({
356 resourceName: output?.name ?? parent,
357 });
358 }
359
360 return toAttrs(current, env.project);
361 }),
362
363 delete: Effect.fn(function* ({ output }) {
364 const operation = yield* aiplatform
365 .deleteReasoningEnginesSandboxEnvironments({
366 name: output.name,
367 })
368 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
369 if (operation !== undefined) {
370 yield* waitForOperation(operation, { notFoundOk: true });
371 }
372 yield* waitUntilGone(output.name);
373 }),
374 });