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

main
ts 430 lines 14.7 KB
Raw
1 import * as datalabeling from "@distilled.cloud/gcp/datalabeling_v1beta1";
2 import { Retry as GcpRetry } from "@distilled.cloud/gcp/Retry";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Layer from "effect/Layer";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { isTransientGcpError } from "../Errors.ts";
10 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
11
12 /**
13 * Data Labeling is shut down. The frontend hangs ~20s then returns HTTP
14 * 502 (`BadGateway`), which distilled retries as transient. Disable that
15 * retry so list/get/create fail in one round trip instead of eight.
16 */
17 export const noRetryLayer = Layer.succeed(GcpRetry, {
18 while: () => false,
19 });
20
21 export const MAX_DISPLAY_NAME_LENGTH = 64;
22 export const MAX_DESCRIPTION_LENGTH = 10_000;
23 export const MAX_EVALUATION_DESCRIPTION_LENGTH = 25_000;
24 export const MAX_FEEDBACK_BODY_LENGTH = 10_000;
25
26 export class DatalabelingPending extends Data.TaggedError("GCP.DataLabeling.Pending")<{
27 resourceName: string;
28 }> {}
29
30 export const lastSegment = (value: string) => {
31 const trimmed = value.replace(/\/+$/, "");
32 const parts = trimmed.split("/");
33 return parts[parts.length - 1] || trimmed;
34 };
35
36 export const parentOf = (name: string) => {
37 const parts = name.split("/").filter((part) => part.length > 0);
38 return parts.slice(0, -2).join("/");
39 };
40
41 export const projectParent = (project: string) => `projects/${project}`;
42
43 export const parseResourceName = (name: string, collection: string) => {
44 const parts = name.split("/").filter((part) => part.length > 0);
45 const collectionAt = parts.lastIndexOf(collection);
46 const projectsAt = parts.lastIndexOf("projects");
47 const datasetsAt = parts.lastIndexOf("datasets");
48 return {
49 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
50 datasetId: datasetsAt >= 0 && parts[datasetsAt + 1] ? parts[datasetsAt + 1]! : "",
51 dataset: datasetsAt >= 0 ? parts.slice(0, datasetsAt + 2).join("/") : parentOf(name),
52 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
53 parent:
54 collectionAt > 0
55 ? parts.slice(0, collectionAt).join("/")
56 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
57 };
58 };
59
60 export const sameText = (left: string | undefined, right: string | undefined) =>
61 (left ?? "") === (right ?? "");
62
63 export const canonical = (value: unknown): unknown => {
64 if (value === undefined || value === null) return undefined;
65 if (typeof value === "boolean" || typeof value === "number") return value;
66 if (typeof value === "string") {
67 return value.length === 0 ? undefined : value;
68 }
69 if (Array.isArray(value)) {
70 const items = value.map(canonical).filter((item) => item !== undefined);
71 return items.length === 0 ? undefined : items;
72 }
73 if (typeof value === "object") {
74 const entries = Object.entries(value as Record<string, unknown>)
75 .map(([key, item]) => [key, canonical(item)] as const)
76 .filter(([, item]) => item !== undefined)
77 .sort(([left], [right]) => left.localeCompare(right));
78 if (entries.length === 0) return undefined;
79 return Object.fromEntries(entries);
80 }
81 return undefined;
82 };
83
84 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
85
86 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
87
88 export const updateMaskOf = (...fields: Array<string | undefined>) =>
89 fields.filter((field): field is string => field !== undefined).join(",");
90
91 export const toDisplayName = (
92 id: string,
93 explicit: string | undefined,
94 existing: string | undefined,
95 maxLength = MAX_DISPLAY_NAME_LENGTH,
96 ) =>
97 Effect.gen(function* () {
98 if (explicit !== undefined) return explicit;
99 if (existing !== undefined) return existing;
100 const generated = yield* createPhysicalName({
101 id,
102 maxLength,
103 lowercase: true,
104 });
105 const next = /^[a-z]/.test(generated) ? generated : `d${generated}`.slice(0, maxLength);
106 return next.length > 0 ? next : "d";
107 });
108
109 const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) =>
110 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
111
112 const shrinkMarker = (labels: Record<string, string>, maxLength: number) => {
113 let stack = labels[alchemyLabelKeys.stack] ?? "x";
114 let stage = labels[alchemyLabelKeys.stage] ?? "x";
115 let id = labels[alchemyLabelKeys.id] ?? "x";
116 let marker = markerOf(labels, stack, stage, id);
117 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
118 if (stack.length >= stage.length && stack.length >= id.length) {
119 stack = stack.slice(0, -1);
120 } else if (stage.length >= id.length) {
121 stage = stage.slice(0, -1);
122 } else {
123 id = id.slice(0, -1);
124 }
125 marker = markerOf(labels, stack, stage, id);
126 }
127 return marker.slice(0, maxLength);
128 };
129
130 export const encodeOwnership = (
131 labels: Record<string, string>,
132 text: string | undefined,
133 maxLength = MAX_DESCRIPTION_LENGTH,
134 ): string => {
135 const marker = shrinkMarker(labels, maxLength);
136 const trimmed = text?.trim();
137 if (!trimmed) return marker;
138 return `${marker}\n${trimmed}`.slice(0, maxLength);
139 };
140
141 export const parseOwnership = (
142 text: string | undefined,
143 ): {
144 labels: Record<string, string>;
145 text: string | undefined;
146 } => {
147 if (!text?.startsWith("[alchemy ")) {
148 return { labels: {}, text };
149 }
150 const end = text.indexOf("]");
151 if (end < 0) return { labels: {}, text };
152 const labels: Record<string, string> = {};
153 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
154 const eq = part.indexOf("=");
155 if (eq > 0) {
156 labels[part.slice(0, eq)] = part.slice(eq + 1);
157 }
158 }
159 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
160 return { labels, text: rest.length > 0 ? rest : undefined };
161 };
162
163 export const hasOwnershipMarker = (text: string | undefined) =>
164 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
165
166 const prefixMatch = (expected: string, observed: string) =>
167 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
168
169 export const ownedByAlchemy = (id: string, text: string | undefined) =>
170 Effect.gen(function* () {
171 const expected = yield* createInternalLabels(id);
172 const { labels } = parseOwnership(text);
173 if (!hasOwnershipMarker(text)) return false;
174 const exact = yield* hasAlchemyLabels(id, labels);
175 if (exact) return true;
176 return (
177 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
178 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
179 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
180 );
181 });
182
183 export const replaceOnIdentity = (input: {
184 previousId?: string;
185 nextId?: string;
186 previousParent?: string;
187 nextParent?: string;
188 extra?: boolean;
189 }) => {
190 if (input.extra === true) {
191 return { action: "replace" as const, deleteFirst: false };
192 }
193 if (
194 input.previousId !== undefined &&
195 input.nextId !== undefined &&
196 input.previousId !== input.nextId
197 ) {
198 return { action: "replace" as const, deleteFirst: false };
199 }
200 if (
201 input.previousParent !== undefined &&
202 input.nextParent !== undefined &&
203 input.previousParent !== input.nextParent
204 ) {
205 return { action: "replace" as const, deleteFirst: false };
206 }
207 return undefined;
208 };
209
210 export const retryTransient = <A, E extends { readonly _tag: string }, R>(
211 effect: Effect.Effect<A, E, R>,
212 ) =>
213 effect.pipe(
214 Effect.provide(noRetryLayer),
215 Effect.retry({
216 while: isTransientGcpError,
217 times: 8,
218 schedule: Schedule.exponential("250 millis"),
219 }),
220 );
221
222 export const retryDelete = <A, E extends { readonly _tag: string }, R>(
223 effect: Effect.Effect<A, E, R>,
224 ) =>
225 effect.pipe(
226 Effect.provide(noRetryLayer),
227 Effect.retry({
228 while: (error) => error._tag === "Conflict" || isTransientGcpError(error),
229 times: 8,
230 schedule: Schedule.exponential("250 millis"),
231 }),
232 );
233
234 const isGone = <E extends { readonly _tag: string }>(
235 error: E,
236 ): error is E & { readonly _tag: "NotFound" | "BadGateway" } =>
237 error._tag === "NotFound" || error._tag === "BadGateway";
238
239 /** A missing parent (NotFound) has no children. */
240 const isMissingList = <E extends { readonly _tag: string }>(
241 error: E,
242 ): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound";
243
244 export const ignoreGone = <A, E extends { readonly _tag: string }, R>(
245 effect: Effect.Effect<A, E, R>,
246 ) => effect.pipe(Effect.catchIf(isGone, () => Effect.void));
247
248 export class DeleteNotConfirmed extends Data.TaggedError(
249 "GCP.DataLabeling.DeleteNotConfirmed",
250 )<{}> {}
251
252 /** Poll until the resource is gone; fails if it is still readable after ~60s. */
253 export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
254 get.pipe(
255 Effect.repeat({
256 schedule: Schedule.spaced("2 seconds"),
257 until: (value) => value === undefined,
258 times: 30,
259 }),
260 Effect.flatMap((value): Effect.Effect<void, DeleteNotConfirmed> =>
261 value === undefined ? Effect.void : Effect.fail(new DeleteNotConfirmed()),
262 ),
263 );
264
265 export const waitForVisible = <A, E, R>(get: Effect.Effect<A | undefined, E, R>) =>
266 get.pipe(
267 Effect.filterOrFail(
268 (value): value is A => value !== undefined,
269 () => new DatalabelingPending({ resourceName: "" }),
270 ),
271 Effect.retry({
272 while: (error) => error instanceof DatalabelingPending,
273 times: 8,
274 schedule: Schedule.exponential("250 millis"),
275 }),
276 Effect.catchIf(
277 (error): error is DatalabelingPending => error instanceof DatalabelingPending,
278 () => Effect.undefined,
279 ),
280 );
281
282 const emptyList = <A>() => Effect.succeed<A[]>([]);
283
284 export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>(
285 pages: Stream.Stream<Page, E, R>,
286 items: (page: Page) => readonly Item[] | null | undefined,
287 ) =>
288 pages.pipe(
289 Stream.provide(noRetryLayer),
290 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
291 Stream.runCollect,
292 Effect.map((chunk) => Array.from(chunk) as Item[]),
293 Effect.provide(noRetryLayer),
294 Effect.catchIf(isMissingList, () => emptyList<Item>()),
295 );
296
297 export const listAnnotationSpecSets = (parent: string) =>
298 parent.length === 0
299 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1AnnotationSpecSet>()
300 : collectPages(
301 datalabeling.listProjectsAnnotationSpecSets.pages({
302 parent,
303 pageSize: 100,
304 }),
305 (page) => page.annotationSpecSets,
306 );
307
308 export const listDatasets = (parent: string) =>
309 parent.length === 0
310 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1Dataset>()
311 : collectPages(
312 datalabeling.listProjectsDatasets.pages({ parent, pageSize: 100 }),
313 (page) => page.datasets,
314 );
315
316 export const listInstructions = (parent: string) =>
317 parent.length === 0
318 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1Instruction>()
319 : collectPages(
320 datalabeling.listProjectsInstructions.pages({ parent, pageSize: 100 }),
321 (page) => page.instructions,
322 );
323
324 export const listEvaluationJobs = (parent: string) =>
325 parent.length === 0
326 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1EvaluationJob>()
327 : collectPages(
328 datalabeling.listProjectsEvaluationJobs.pages({
329 parent,
330 pageSize: 100,
331 }),
332 (page) => page.evaluationJobs,
333 );
334
335 export const listAnnotatedDatasets = (parent: string) =>
336 parent.length === 0
337 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1AnnotatedDataset>()
338 : collectPages(
339 datalabeling.listProjectsDatasetsAnnotatedDatasets.pages({
340 parent,
341 pageSize: 100,
342 }),
343 (page) => page.annotatedDatasets,
344 );
345
346 export const listFeedbackThreads = (parent: string) =>
347 parent.length === 0
348 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1FeedbackThread>()
349 : collectPages(
350 datalabeling.listProjectsDatasetsAnnotatedDatasetsFeedbackThreads.pages({
351 parent,
352 pageSize: 100,
353 }),
354 (page) => page.feedbackThreads,
355 );
356
357 export const listFeedbackMessages = (parent: string) =>
358 parent.length === 0
359 ? emptyList<datalabeling.GoogleCloudDatalabelingV1beta1FeedbackMessage>()
360 : collectPages(
361 datalabeling.listProjectsDatasetsAnnotatedDatasetsFeedbackThreadsFeedbackMessages.pages({
362 parent,
363 pageSize: 100,
364 }),
365 (page) => page.feedbackMessages,
366 );
367
368 export const listAllFeedbackMessages = (project: string) =>
369 Effect.gen(function* () {
370 const datasets = yield* listDatasets(projectParent(project));
371 const namedDatasets = datasets.filter(
372 (
373 dataset,
374 ): dataset is datalabeling.GoogleCloudDatalabelingV1beta1Dataset & {
375 name: string;
376 } => typeof dataset.name === "string" && dataset.name.length > 0,
377 );
378 const groups = yield* Effect.forEach(
379 namedDatasets,
380 (dataset) =>
381 Effect.gen(function* () {
382 const annotated = yield* listAnnotatedDatasets(dataset.name);
383 const namedAnnotated = annotated.filter(
384 (
385 row,
386 ): row is datalabeling.GoogleCloudDatalabelingV1beta1AnnotatedDataset & {
387 name: string;
388 } => typeof row.name === "string" && row.name.length > 0,
389 );
390 const threadGroups = yield* Effect.forEach(
391 namedAnnotated,
392 (annotatedDataset) =>
393 Effect.gen(function* () {
394 const threads = yield* listFeedbackThreads(annotatedDataset.name);
395 const namedThreads = threads.filter(
396 (
397 thread,
398 ): thread is datalabeling.GoogleCloudDatalabelingV1beta1FeedbackThread & {
399 name: string;
400 } => typeof thread.name === "string" && thread.name.length > 0,
401 );
402 const messages = yield* Effect.forEach(
403 namedThreads,
404 (thread) => listFeedbackMessages(thread.name),
405 { concurrency: 4 },
406 );
407 return messages.flat();
408 }),
409 { concurrency: 4 },
410 );
411 return threadGroups.flat();
412 }),
413 { concurrency: 4 },
414 );
415 return groups.flat();
416 });
417
418 export const findOwned = <A>(
419 id: string,
420 items: readonly A[],
421 textOf: (item: A) => string | undefined,
422 ) =>
423 Effect.gen(function* () {
424 for (const item of items) {
425 if (yield* ownedByAlchemy(id, textOf(item))) {
426 return item;
427 }
428 }
429 return undefined;
430 });