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

main
ts 343 lines 12.1 KB
Raw
1 import * as aiplatform from "@distilled.cloud/gcp/aiplatform_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 Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 compact,
15 encodeDisplayName,
16 hasOwnershipMarker,
17 lastSegment,
18 normalizeLocation,
19 parentOf,
20 ownsDisplayName,
21 parseDisplayName,
22 parseName,
23 listLocations,
24 } from "./names.ts";
25 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
26
27 export type SandboxEnvironmentTemplateDefaultContainerEnvironment =
28 aiplatform.GoogleCloudAiplatformV1SandboxEnvironmentTemplateDefaultContainerEnvironment;
29 export type SandboxEnvironmentTemplateCustomContainerEnvironment =
30 aiplatform.GoogleCloudAiplatformV1SandboxEnvironmentTemplateCustomContainerEnvironment;
31 export type SandboxEnvironmentTemplateEgressControlConfig =
32 aiplatform.GoogleCloudAiplatformV1SandboxEnvironmentTemplateEgressControlConfig;
33
34 export type ReasoningEnginesSandboxEnvironmentTemplateProps = {
35 /**
36 * Parent Reasoning Engine. Full name
37 * `projects/{project}/locations/{location}/reasoningEngines/{engine}`
38 * or the engine id (combined with `location`). Immutable — changing it
39 * replaces the template.
40 */
41 reasoningEngine: string;
42 /**
43 * Vertex AI location. Used when `reasoningEngine` is a bare id.
44 * Immutable. @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * Display name. Required by Vertex. SandboxEnvironmentTemplate has no
49 * labels field, so Alchemy ownership is stored in a `[alchemy …]`
50 * prefix for `list` / nuke.
51 */
52 displayName?: string;
53 /**
54 * Default container environment.
55 */
56 defaultContainerEnvironment?: SandboxEnvironmentTemplateDefaultContainerEnvironment;
57 /**
58 * Custom (BYOC) container environment.
59 */
60 customContainerEnvironment?: SandboxEnvironmentTemplateCustomContainerEnvironment;
61 /**
62 * Egress control (internet access).
63 */
64 egressControlConfig?: SandboxEnvironmentTemplateEgressControlConfig;
65 };
66
67 export type ReasoningEnginesSandboxEnvironmentTemplate = Resource<
68 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplate",
69 ReasoningEnginesSandboxEnvironmentTemplateProps,
70 {
71 /** Full resource name. */
72 name: string;
73 /** Template id (last path segment). */
74 sandboxEnvironmentTemplateId: string;
75 /** Parent Reasoning Engine resource name. */
76 reasoningEngine: string;
77 /** Location id. */
78 location: string;
79 /** Project id. */
80 project: string;
81 /** User display name with the Alchemy ownership prefix stripped. */
82 displayName: string | undefined;
83 /** Server-reported state. */
84 state: string | undefined;
85 /** RFC3339 creation timestamp. */
86 createTime: string | undefined;
87 /** RFC3339 last-update timestamp. */
88 updateTime: string | undefined;
89 },
90 never,
91 Providers
92 >;
93
94 /**
95 * A Vertex AI sandbox environment template — the blueprint used to
96 * create Agent Engine sandbox environments.
97 *
98 * There is no update API. Changing parent or location replaces the
99 * template. Ownership is stamped into the display name.
100 *
101 * ### Creating a Template
102 * **Example:** Default computer-use container
103 * ```typescript
104 * const template = yield* GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplate(
105 * "Sandbox",
106 * {
107 * reasoningEngine: engine.name,
108 * displayName: "computer-use",
109 * defaultContainerEnvironment: {
110 * defaultContainerCategory: "DEFAULT_CONTAINER_CATEGORY_COMPUTER_USE",
111 * },
112 * },
113 * );
114 * ```
115 *
116 * @resource
117 * @category AIPlatform
118 */
119 export const ReasoningEnginesSandboxEnvironmentTemplate =
120 Resource<ReasoningEnginesSandboxEnvironmentTemplate>(
121 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplate",
122 );
123
124 export class ReasoningEnginesSandboxEnvironmentTemplateNotResolved extends Data.TaggedError(
125 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplateNotResolved",
126 )<{
127 resourceName: string;
128 }> {}
129
130 export class ReasoningEnginesSandboxEnvironmentTemplateStillExists extends Data.TaggedError(
131 "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplateStillExists",
132 )<{
133 resourceName: string;
134 }> {}
135
136 const engineNameOf = (project: string, location: string, reasoningEngine: string) =>
137 reasoningEngine.includes("/")
138 ? reasoningEngine
139 : `${parentOf(project, location)}/reasoningEngines/${reasoningEngine}`;
140
141 const toAttrs = (
142 template: aiplatform.GoogleCloudAiplatformV1SandboxEnvironmentTemplate,
143 project: string,
144 ) => {
145 const name = template.name ?? "";
146 const parsed = parseName(name, "sandboxEnvironmentTemplates");
147 const display = parseDisplayName(template.displayName);
148 const parts = name.split("/").filter((part) => part.length > 0);
149 const enginesAt = parts.lastIndexOf("reasoningEngines");
150 const reasoningEngine =
151 enginesAt >= 0
152 ? parts.slice(0, enginesAt + 2).join("/")
153 : name.replace(/\/sandboxEnvironmentTemplates\/[^/]+$/, "");
154 return {
155 name,
156 sandboxEnvironmentTemplateId: parsed.resourceId,
157 reasoningEngine,
158 location: parsed.location,
159 project: parsed.project || project,
160 displayName: display.displayName,
161 state: template.state,
162 createTime: template.createTime,
163 updateTime: template.updateTime,
164 };
165 };
166
167 const getByName = (name: string) =>
168 name.length === 0
169 ? Effect.undefined
170 : aiplatform
171 .getProjectsLocationsReasoningEnginesSandboxEnvironmentTemplates({
172 name,
173 })
174 .pipe(
175 Effect.catchTags({
176 NotFound: () => Effect.undefined,
177 SandboxEnvironmentsNotEnabled: () => Effect.undefined,
178 }),
179 );
180
181 const listAt = (parent: string) =>
182 aiplatform.listProjectsLocationsReasoningEnginesSandboxEnvironmentTemplates
183 .pages({ parent, pageSize: 100 })
184 .pipe(
185 Stream.flatMap((page) => Stream.fromIterable(page.sandboxEnvironmentTemplates ?? [])),
186 Stream.take(500),
187 Stream.runCollect,
188 Effect.map((chunk) => Array.from(chunk)),
189 Effect.catchTag("NotFound", () => Effect.succeed([])),
190 );
191
192 const findOwned = (id: string, parent: string) =>
193 Effect.gen(function* () {
194 const templates = yield* listAt(parent);
195 for (const template of templates) {
196 if (yield* ownsDisplayName(id, template.displayName)) {
197 return template;
198 }
199 }
200 return undefined;
201 });
202
203 const waitUntilGone = (name: string) =>
204 getByName(name).pipe(
205 Effect.flatMap((template) =>
206 template === undefined
207 ? Effect.void
208 : Effect.fail(
209 new ReasoningEnginesSandboxEnvironmentTemplateStillExists({
210 resourceName: name,
211 }),
212 ),
213 ),
214 Effect.retry({
215 while: (error) =>
216 error._tag === "GCP.AIPlatform.ReasoningEnginesSandboxEnvironmentTemplateStillExists",
217 times: 10,
218 schedule: Schedule.spaced("2 seconds"),
219 }),
220 );
221
222 const listEngines = (parent: string) =>
223 aiplatform.listProjectsLocationsReasoningEngines.pages({ parent, pageSize: 100 }).pipe(
224 Stream.flatMap((page) => Stream.fromIterable(page.reasoningEngines ?? [])),
225 Stream.take(200),
226 Stream.runCollect,
227 Effect.map((chunk) => Array.from(chunk)),
228 Effect.catchTag("NotFound", () => Effect.succeed([])),
229 );
230
231 export const ReasoningEnginesSandboxEnvironmentTemplateProvider = () =>
232 Provider.succeed(ReasoningEnginesSandboxEnvironmentTemplate, {
233 stables: [
234 "name",
235 "sandboxEnvironmentTemplateId",
236 "reasoningEngine",
237 "location",
238 "project",
239 "createTime",
240 ],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 const env = yield* GcpEnvironment.current;
244 if (!isResolved(news)) return undefined;
245 const previousParent = lastSegment(olds?.reasoningEngine ?? output?.reasoningEngine ?? "");
246 const nextParent = lastSegment(news.reasoningEngine);
247 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
248 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
249 if (
250 (previousParent.length > 0 && previousParent !== nextParent) ||
251 previousLocation !== nextLocation
252 ) {
253 return { action: "replace" as const, deleteFirst: false };
254 }
255 return undefined;
256 }),
257
258 read: Effect.fn(function* ({ id, olds, output }) {
259 const env = yield* GcpEnvironment.current;
260 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
261 const parentRef = olds?.reasoningEngine ?? output?.reasoningEngine;
262 // A create interrupted before its parent resolved has nothing to find.
263 if (output?.name === undefined && typeof parentRef !== "string") {
264 return undefined;
265 }
266 const parent = engineNameOf(env.project, location, parentRef ?? "");
267 const existing =
268 (output?.name !== undefined ? yield* getByName(output.name) : undefined) ??
269 (yield* findOwned(id, parent));
270 if (existing === undefined) return undefined;
271 const attrs = toAttrs(existing, env.project);
272 return (yield* ownsDisplayName(id, existing.displayName)) ? attrs : Unowned(attrs);
273 }),
274
275 list: () =>
276 Effect.gen(function* () {
277 const env = yield* GcpEnvironment.current;
278 const engines = (yield* Effect.forEach(listLocations(env.region), (location) =>
279 listEngines(parentOf(env.project, location)),
280 )).flat();
281 const templates = yield* Effect.forEach(
282 engines,
283 (engine) => (engine.name ? listAt(engine.name) : Effect.succeed([])),
284 { concurrency: 4 },
285 );
286 return templates
287 .flat()
288 .filter((template) => hasOwnershipMarker(template.displayName))
289 .map((template) => toAttrs(template, env.project));
290 }),
291
292 reconcile: Effect.fn(function* ({ id, news, output }) {
293 const env = yield* GcpEnvironment.current;
294 const location = normalizeLocation(news.location ?? output?.location, env.region);
295 const parent = engineNameOf(env.project, location, news.reasoningEngine);
296 const internal = yield* createInternalLabels(id);
297 const displayName = encodeDisplayName(internal, news.displayName ?? "sandbox-template");
298
299 let current =
300 (output?.name !== undefined ? yield* getByName(output.name) : undefined) ??
301 (yield* findOwned(id, parent));
302
303 if (current === undefined) {
304 const created = yield* aiplatform
305 .createProjectsLocationsReasoningEnginesSandboxEnvironmentTemplates({
306 parent,
307 body: compact({
308 displayName,
309 defaultContainerEnvironment: news.defaultContainerEnvironment,
310 customContainerEnvironment: news.customContainerEnvironment,
311 egressControlConfig: news.egressControlConfig,
312 }),
313 })
314 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
315 const done =
316 created !== undefined
317 ? yield* waitForOperation(created, { alreadyExistsOk: true })
318 : undefined;
319 const createdName = done !== undefined ? resourceNameFromOperation(done) : undefined;
320 current =
321 createdName !== undefined ? yield* getByName(createdName) : yield* findOwned(id, parent);
322 }
323
324 if (current === undefined || current.name === undefined) {
325 return yield* new ReasoningEnginesSandboxEnvironmentTemplateNotResolved({
326 resourceName: output?.name ?? parent,
327 });
328 }
329 return toAttrs(current, env.project);
330 }),
331
332 delete: Effect.fn(function* ({ output }) {
333 const operation = yield* aiplatform
334 .deleteProjectsLocationsReasoningEnginesSandboxEnvironmentTemplates({
335 name: output.name,
336 })
337 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
338 if (operation !== undefined) {
339 yield* waitForOperation(operation, { notFoundOk: true });
340 }
341 yield* waitUntilGone(output.name);
342 }),
343 });