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

main
ts 246 lines 8.42 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 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 { listLocations } from "./names.ts";
13 import { lastSegment, locationOf, locationParent, parentOf } from "./ownership.ts";
14 import { hasStudyOwnership } from "./Study.ts";
15
16 export type TrialParameter = {
17 /** Parameter id defined on the parent Study. */
18 parameterId: string;
19 /** Assigned value (`number` for numeric parameters, `string` for categorical). */
20 value?: unknown;
21 };
22
23 export type StudiesTrialProps = {
24 /**
25 * Parent Study resource name
26 * (`projects/{project}/locations/{location}/studies/{study}`).
27 * Immutable — changing it replaces the Trial.
28 */
29 parent: string;
30 /**
31 * User-provided parameter assignments. Immutable after create.
32 */
33 parameters?: TrialParameter[];
34 /**
35 * Client identifier recorded on the Trial. Alchemy stores the logical
36 * id here when omitted so `list` / nuke can find user-provided trials.
37 */
38 clientId?: string;
39 };
40
41 export type StudiesTrial = Resource<
42 "GCP.AIPlatform.StudiesTrial",
43 StudiesTrialProps,
44 {
45 /** Full resource name. */
46 name: string;
47 /** Trial id assigned by Vizier. */
48 trialId: string;
49 /** Parent Study resource name. */
50 parent: string;
51 /** Region id. */
52 location: string;
53 /** Project id. */
54 project: string;
55 /** Client identifier. */
56 clientId: string | undefined;
57 /** Parameter assignments. */
58 parameters: TrialParameter[];
59 /** Server-reported state. */
60 state: string | undefined;
61 /** Final measurement, if the trial completed. */
62 finalMeasurement: aiplatform.GoogleCloudAiplatformV1Measurement | undefined;
63 /** RFC3339 start timestamp. */
64 startTime: string | undefined;
65 /** RFC3339 end timestamp. */
66 endTime: string | undefined;
67 },
68 never,
69 Providers
70 >;
71
72 /**
73 * A user-provided Vertex AI Vizier Trial attached to a Study.
74 *
75 * Trials have no labels and no update RPC. Alchemy records the logical
76 * id in `clientId` so `list` can find them. Parent and parameters are
77 * immutable.
78 *
79 * ### Creating a Trial
80 * **Example:** User-provided trial
81 * ```typescript
82 * const trial = yield* GCP.AIPlatform.StudiesTrial("Seed", {
83 * parent: study.name,
84 * parameters: [{ parameterId: "learning_rate", value: 0.01 }],
85 * });
86 * ```
87 *
88 * @resource
89 * @category AIPlatform
90 */
91 export const StudiesTrial = Resource<StudiesTrial>("GCP.AIPlatform.StudiesTrial");
92
93 export class StudiesTrialNotResolved extends Data.TaggedError(
94 "GCP.AIPlatform.StudiesTrialNotResolved",
95 )<{
96 resourceName: string;
97 }> {}
98
99 const toAttrs = (trial: aiplatform.GoogleCloudAiplatformV1Trial, project: string) => {
100 const name = trial.name ?? "";
101 return {
102 name,
103 trialId: trial.id ?? lastSegment(name),
104 parent: parentOf(name),
105 location: locationOf(name),
106 project,
107 clientId: trial.clientId,
108 parameters: (trial.parameters ?? []).map((parameter) => ({
109 parameterId: parameter.parameterId ?? "",
110 value: parameter.value,
111 })),
112 state: trial.state,
113 finalMeasurement: trial.finalMeasurement,
114 startTime: trial.startTime,
115 endTime: trial.endTime,
116 };
117 };
118
119 const getByName = (name: string) =>
120 name.length === 0
121 ? Effect.undefined
122 : aiplatform
123 .getProjectsLocationsStudiesTrials({ name })
124 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
125
126 const listStudies = (parent: string) =>
127 aiplatform.listProjectsLocationsStudies.pages({ parent, pageSize: 100 }).pipe(
128 Stream.flatMap((page) => Stream.fromIterable(page.studies ?? [])),
129 Stream.filter((study) => hasStudyOwnership(study.displayName)),
130 Stream.map((study) => study.name ?? ""),
131 Stream.filter((name) => name.length > 0),
132 Stream.runCollect,
133 Effect.map((chunk) => Array.from(chunk)),
134 Effect.catchTag("NotFound", () => Effect.succeed([] as string[])),
135 );
136
137 const listAtParent = (parent: string, project: string, clientId?: string) =>
138 aiplatform.listProjectsLocationsStudiesTrials.pages({ parent, pageSize: 100 }).pipe(
139 Stream.flatMap((page) => Stream.fromIterable(page.trials ?? [])),
140 Stream.filter((trial) => (clientId !== undefined ? trial.clientId === clientId : true)),
141 Stream.map((trial) => toAttrs(trial, project)),
142 Stream.runCollect,
143 Effect.map((chunk) => Array.from(chunk)),
144 Effect.catchTag("NotFound", () => Effect.succeed([])),
145 );
146
147 const findByClientId = (parent: string, clientId: string, project: string) =>
148 listAtParent(parent, project, clientId).pipe(Effect.map((trials) => trials[0]));
149
150 export const StudiesTrialProvider = () =>
151 Provider.succeed(StudiesTrial, {
152 stables: ["name", "trialId", "parent", "location", "project", "startTime"],
153
154 diff: Effect.fn(function* ({ news, olds, output }) {
155 if (!isResolved(news)) return undefined;
156 const previousParent = olds?.parent ?? output?.parent;
157 if (previousParent !== undefined && news.parent !== previousParent) {
158 return { action: "replace" as const, deleteFirst: false };
159 }
160 return undefined;
161 }),
162
163 read: Effect.fn(function* ({ id, olds, output }) {
164 const env = yield* GcpEnvironment.current;
165 const existing = yield* getByName(output?.name ?? "");
166 if (existing !== undefined) {
167 return toAttrs(existing, env.project);
168 }
169 if (olds?.parent === undefined) return undefined;
170 const ownership = yield* createInternalLabels(id);
171 const clientId = olds.clientId ?? `alchemy-${ownership["alchemy-id"]}`;
172 const match = yield* findByClientId(olds.parent, clientId, env.project);
173 if (match === undefined) return undefined;
174 const fetched = yield* getByName(match.name);
175 if (fetched === undefined) return undefined;
176 const attrs = toAttrs(fetched, env.project);
177 return fetched.clientId === clientId ? attrs : Unowned(attrs);
178 }),
179
180 list: () =>
181 Effect.gen(function* () {
182 const env = yield* GcpEnvironment.current;
183 const studies = (yield* Effect.forEach(listLocations(env.region), (location) =>
184 listStudies(locationParent(env.project, location)),
185 )).flat();
186 const pages = yield* Effect.forEach(
187 studies,
188 (parent) => listAtParent(parent, env.project),
189 { concurrency: 4 },
190 );
191 return pages.flat();
192 }),
193
194 reconcile: Effect.fn(function* ({ id, news, output }) {
195 const env = yield* GcpEnvironment.current;
196 const ownership = yield* createInternalLabels(id);
197 const clientId = news.clientId ?? `alchemy-${ownership["alchemy-id"]}`;
198
199 let current = yield* getByName(output?.name ?? "");
200 if (current === undefined) {
201 const match = yield* findByClientId(news.parent, clientId, env.project);
202 if (match !== undefined) {
203 current = yield* getByName(match.name);
204 }
205 }
206
207 if (current === undefined) {
208 const created = yield* aiplatform
209 .createProjectsLocationsStudiesTrials({
210 parent: news.parent,
211 body: {
212 clientId,
213 // Vizier rejects user trials without a status ("Can not add
214 // trial with status: UNKNOWN").
215 state: "ACTIVE",
216 parameters: news.parameters?.map((parameter) => ({
217 parameterId: parameter.parameterId,
218 value: parameter.value,
219 })),
220 },
221 })
222 .pipe(
223 Effect.catchTag("Conflict", () =>
224 findByClientId(news.parent, clientId, env.project).pipe(
225 Effect.flatMap((match) => (match ? getByName(match.name) : Effect.undefined)),
226 ),
227 ),
228 );
229 current = created ?? undefined;
230 }
231
232 if (current === undefined) {
233 return yield* new StudiesTrialNotResolved({
234 resourceName: output?.name ?? `${news.parent}/trials/-`,
235 });
236 }
237
238 return toAttrs(current, env.project);
239 }),
240
241 delete: Effect.fn(function* ({ output }) {
242 yield* aiplatform
243 .deleteProjectsLocationsStudiesTrials({ name: output.name })
244 .pipe(Effect.catchTag("NotFound", () => Effect.void));
245 }),
246 });