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

main
ts 298 lines 10.2 KB
Raw
1 import * as registry from "@distilled.cloud/gcp/agentregistry_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Schedule from "effect/Schedule";
6 import * as Stream from "effect/Stream";
7 import { isTransientGcpError } from "../Errors.ts";
8 import { alchemyLabelKeys, hasAlchemyLabels } from "../Labels.ts";
9 import { waitForOperation as waitForGcpOperation } from "../Operation.ts";
10
11 export const MAX_ID_LENGTH = 63;
12 export const MAX_DESCRIPTION_LENGTH = 2048;
13 export const MAX_DISPLAY_NAME_LENGTH = 63;
14
15 export class ResourceNotResolved extends Data.TaggedError("GCP.AgentRegistry.NotResolved")<{
16 resourceName: string;
17 }> {}
18
19 export class ResourcePending extends Data.TaggedError("GCP.AgentRegistry.Pending")<{
20 resourceName: string;
21 }> {}
22
23 export const lastSegment = (value: string) => {
24 const trimmed = value.replace(/\/+$/, "");
25 const parts = trimmed.split("/");
26 return parts[parts.length - 1] || trimmed;
27 };
28
29 export const rfc1035 = (name: string, fallback = "bind"): string => {
30 let next = name
31 .toLowerCase()
32 .replace(/[^a-z0-9-]/g, "-")
33 .replace(/-+/g, "-")
34 .replace(/^-+|-+$/g, "");
35 if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "b"}${next}`;
36 next = next.slice(0, MAX_ID_LENGTH).replace(/-+$/g, "");
37 if (next.length === 0) return fallback;
38 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_ID_LENGTH - 1)}0`;
39 if (next.length < 4) next = `${next}xxxx`.slice(0, 4);
40 return next.slice(0, MAX_ID_LENGTH);
41 };
42
43 export const normalizeLocation = (location: string | undefined, defaultLocation: string) =>
44 lastSegment(location ?? defaultLocation).toLowerCase();
45
46 export const locationParent = (project: string, location: string) =>
47 `projects/${project}/locations/${lastSegment(location).toLowerCase()}`;
48
49 export const resourceName = (project: string, location: string, collection: string, id: string) =>
50 `${locationParent(project, location)}/${collection}/${id}`;
51
52 export const parseResourceName = (name: string, collection: string) => {
53 const parts = name.split("/").filter((part) => part.length > 0);
54 const collectionAt = parts.lastIndexOf(collection);
55 const locationsAt = parts.lastIndexOf("locations");
56 const projectsAt = parts.lastIndexOf("projects");
57 return {
58 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
59 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
60 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
61 parent:
62 collectionAt > 0
63 ? parts.slice(0, collectionAt).join("/")
64 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
65 };
66 };
67
68 export const toPhysicalId = (
69 id: string,
70 explicit: string | undefined,
71 existing: string | undefined,
72 fallback = "bind",
73 ) =>
74 Effect.gen(function* () {
75 if (explicit !== undefined) return rfc1035(explicit, fallback);
76 if (existing !== undefined) return existing;
77 return rfc1035(
78 yield* createPhysicalName({
79 id,
80 maxLength: MAX_ID_LENGTH,
81 lowercase: true,
82 }),
83 fallback,
84 );
85 });
86
87 export const sameText = (left: string | undefined, right: string | undefined) =>
88 (left ?? "") === (right ?? "");
89
90 export const canonical = (value: unknown): unknown => {
91 if (value === undefined || value === null) return undefined;
92 if (typeof value === "boolean" || typeof value === "number") return value;
93 if (typeof value === "string") {
94 return value.length === 0 ? undefined : value;
95 }
96 if (Array.isArray(value)) {
97 const items = value.map(canonical).filter((item) => item !== undefined);
98 return items.length === 0 ? undefined : items;
99 }
100 if (typeof value === "object") {
101 const entries = Object.entries(value as Record<string, unknown>)
102 .map(([key, item]) => [key, canonical(item)] as const)
103 .filter(([, item]) => item !== undefined)
104 .sort(([left], [right]) => left.localeCompare(right));
105 if (entries.length === 0) return undefined;
106 return Object.fromEntries(entries);
107 }
108 return undefined;
109 };
110
111 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
112
113 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
114
115 export const updateMaskOf = (...fields: Array<string | undefined>) =>
116 fields.filter((field): field is string => field !== undefined).join(",");
117
118 export const replaceOnIdentity = (input: {
119 previousId?: string;
120 nextId?: string;
121 previousLocation?: string;
122 nextLocation?: string;
123 extra?: boolean;
124 }) => {
125 const idChanged =
126 input.previousId !== undefined &&
127 input.nextId !== undefined &&
128 input.previousId !== input.nextId;
129 const locationChanged =
130 (input.previousLocation ?? "") !== "" &&
131 (input.nextLocation ?? "") !== "" &&
132 (input.previousLocation ?? "") !== (input.nextLocation ?? "");
133 if (!idChanged && !locationChanged && input.extra !== true) {
134 return undefined;
135 }
136 const samePhysical =
137 !locationChanged && input.previousId !== undefined && input.nextId === input.previousId;
138 return {
139 action: "replace" as const,
140 deleteFirst: samePhysical,
141 };
142 };
143
144 const markerOf = (stack: string, stage: string, id: string) =>
145 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
146
147 export const encodeOwnership = (
148 labels: Record<string, string>,
149 description: string | undefined,
150 ): string => {
151 const marker = markerOf(
152 labels[alchemyLabelKeys.stack] ?? "x",
153 labels[alchemyLabelKeys.stage] ?? "x",
154 labels[alchemyLabelKeys.id] ?? "x",
155 ).slice(0, MAX_DESCRIPTION_LENGTH);
156 const trimmed = description?.trim();
157 if (!trimmed) return marker;
158 return `${marker}\n${trimmed}`.slice(0, MAX_DESCRIPTION_LENGTH);
159 };
160
161 export const parseOwnership = (
162 description: string | undefined,
163 ): {
164 labels: Record<string, string>;
165 description: string | undefined;
166 } => {
167 if (!description?.startsWith("[alchemy ")) {
168 return { labels: {}, description };
169 }
170 const end = description.indexOf("]");
171 if (end < 0) return { labels: {}, description };
172 const labels: Record<string, string> = {};
173 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
174 const eq = part.indexOf("=");
175 if (eq > 0) {
176 labels[part.slice(0, eq)] = part.slice(eq + 1);
177 }
178 }
179 const rest = description.slice(end + 1).replace(/^\n/, "");
180 return { labels, description: rest.length > 0 ? rest : undefined };
181 };
182
183 export const hasOwnershipMarker = (description: string | undefined) =>
184 Object.keys(parseOwnership(description).labels).some((key) => key.startsWith("alchemy-"));
185
186 export const ownedByAlchemy = (id: string, description: string | undefined) =>
187 Effect.gen(function* () {
188 const { labels } = parseOwnership(description);
189 if (!hasOwnershipMarker(description)) return false;
190 return yield* hasAlchemyLabels(id, labels);
191 });
192
193 export const retryTransient = <A, E extends { readonly _tag: string }, R>(
194 effect: Effect.Effect<A, E, R>,
195 ) =>
196 effect.pipe(
197 Effect.retry({
198 while: isTransientGcpError,
199 times: 8,
200 schedule: Schedule.exponential("250 millis"),
201 }),
202 );
203
204 /** Wait for an Agent Registry operation (control plane: minutes). */
205 export const waitForOperation = (operation: registry.Operation) =>
206 waitForGcpOperation(operation, (name) => registry.getProjectsLocationsOperations({ name }), {
207 budget: "10 minutes",
208 });
209
210 /**
211 * Wait for a delete operation. The operation record may already be
212 * garbage-collected (`NotFound`) once the resource is gone.
213 */
214 export const waitForDeleteOperation = (operation: registry.Operation) =>
215 waitForGcpOperation(
216 operation,
217 (name) =>
218 registry
219 .getProjectsLocationsOperations({ name })
220 .pipe(
221 Effect.catchTag("NotFound", () =>
222 Effect.succeed<registry.Operation>({ name, done: true }),
223 ),
224 ),
225 { budget: "10 minutes" },
226 );
227
228 export const waitForVisible = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
229 get.pipe(
230 Effect.filterOrFail(
231 (value): value is A => value !== undefined,
232 () => new ResourcePending({ resourceName: "" }),
233 ),
234 Effect.retry({
235 while: (error) => error instanceof ResourcePending,
236 times: 8,
237 schedule: Schedule.exponential("250 millis"),
238 }),
239 Effect.catchIf(
240 (error): error is ResourcePending => error instanceof ResourcePending,
241 () => Effect.undefined,
242 ),
243 );
244
245 export class DeleteNotConfirmed extends Data.TaggedError(
246 "GCP.AgentRegistry.DeleteNotConfirmed",
247 )<{}> {}
248
249 /** Poll until the resource is gone; fails if it is still readable after ~60s. */
250 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
251 get.pipe(
252 Effect.repeat({
253 schedule: Schedule.spaced("2 seconds"),
254 until: (value) => value === undefined,
255 times: 30,
256 }),
257 Effect.flatMap((value): Effect.Effect<void, DeleteNotConfirmed> =>
258 value === undefined ? Effect.void : Effect.fail(new DeleteNotConfirmed()),
259 ),
260 );
261
262 const emptyList = <A>() => Effect.succeed<A[]>([]);
263
264 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
265 pages: Stream.Stream<Page, E, R>,
266 items: (page: Page) => readonly Item[] | null | undefined,
267 ) =>
268 pages.pipe(
269 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
270 Stream.runCollect,
271 Effect.map((chunk) => Array.from(chunk) as Item[]),
272 );
273
274 const listAt = (parent: string) =>
275 parent.length === 0
276 ? emptyList<registry.Binding>()
277 : collectPages(
278 registry.listProjectsLocationsBindings.pages({
279 parent,
280 pageSize: 500,
281 }),
282 (page) => page.bindings,
283 ).pipe(
284 // A missing location has no bindings.
285 Effect.catchTag("NotFound", () => emptyList<registry.Binding>()),
286 );
287
288 export const listBindings = (project: string, region: string) =>
289 listAt(`projects/${project}/locations/-`).pipe(
290 Effect.flatMap((items) =>
291 items.length > 0
292 ? Effect.succeed(items)
293 : Effect.all([
294 listAt(locationParent(project, region)),
295 listAt(locationParent(project, "global")),
296 ]).pipe(Effect.map((groups) => groups.flat())),
297 ),
298 );