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

main
ts 233 lines 8.17 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import { tagRecord } from "alchemy/Tags";
3 import * as Effect from "effect/Effect";
4 import {
5 alchemyLabelKeys,
6 createInternalLabels as createInternalLabelsImpl,
7 hasAlchemyLabels,
8 stripInternalLabels,
9 toLabels as toLabelsImpl,
10 } from "../Labels.ts";
11 import { resourceNameFromOperation as resourceNameFromOperationImpl } from "./operations.ts";
12
13 export const MAX_ID_LENGTH = 63;
14 export const MAX_DISPLAY_NAME_LENGTH = 128;
15 /** Locations `list` scans: the pre-`GCP.Region` default plus the stack region. */
16 export const listLocations = (region: string): string[] => [...new Set(["us-central1", region])];
17
18 export const createInternalLabels = createInternalLabelsImpl;
19 export const toLabels = toLabelsImpl;
20 export const resourceNameFromOperation = resourceNameFromOperationImpl;
21
22 export const lastSegment = (value: string) => {
23 const trimmed = value.replace(/\/+$/, "");
24 const parts = trimmed.split("/");
25 return parts[parts.length - 1] || trimmed;
26 };
27
28 export const normalizeLocation = (location: string | undefined, fallback: string) =>
29 lastSegment(location ?? fallback).toLowerCase();
30
31 export const parentOf = (project: string, location: string) =>
32 `projects/${project}/locations/${location}`;
33
34 export const locationOf = (name: string, fallback = "") => {
35 const parts = name.split("/");
36 const index = parts.indexOf("locations");
37 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
38 };
39
40 export const projectOf = (name: string, fallback = "") => {
41 const parts = name.split("/");
42 const index = parts.indexOf("projects");
43 return index >= 0 ? (parts[index + 1] ?? fallback) : fallback;
44 };
45
46 export const parseName = (name: string, collection: string) => {
47 const parts = name.split("/").filter((part) => part.length > 0);
48 const collectionAt = parts.lastIndexOf(collection);
49 const locationsAt = parts.lastIndexOf("locations");
50 const projectsAt = parts.lastIndexOf("projects");
51 const enginesAt = parts.lastIndexOf("reasoningEngines");
52 return {
53 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
54 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
55 reasoningEngineId: enginesAt >= 0 && parts[enginesAt + 1] ? parts[enginesAt + 1]! : "",
56 resourceId:
57 collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
58 };
59 };
60
61 export const toPhysicalId = (
62 id: string,
63 explicit: string | undefined,
64 existing?: string,
65 maxLength = MAX_ID_LENGTH,
66 ) =>
67 Effect.gen(function* () {
68 if (explicit !== undefined) return explicit;
69 if (existing !== undefined) return existing;
70 const generated = yield* createPhysicalName({
71 id,
72 maxLength,
73 lowercase: true,
74 });
75 const starts = /^[a-z]/.test(generated) ? generated : `a${generated}`;
76 return starts.replace(/-+$/g, "").slice(0, maxLength);
77 });
78
79 export const toResourceId = (
80 id: string,
81 requested: string | undefined,
82 existing: string | undefined,
83 maxLength = MAX_ID_LENGTH,
84 ) => toPhysicalId(id, requested, existing, maxLength);
85
86 export const toDisplayName = (
87 id: string,
88 explicit: string | undefined,
89 existing: string | undefined,
90 ) =>
91 Effect.gen(function* () {
92 if (explicit !== undefined) return explicit;
93 if (existing !== undefined) return existing;
94 return yield* toPhysicalId(id, undefined, undefined);
95 });
96
97 export const compact = <T extends Record<string, unknown>>(value: T): T =>
98 Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;
99
100 export const stableJson = (value: unknown): string =>
101 JSON.stringify(value ?? null, (_key, item) => {
102 if (item && typeof item === "object" && !Array.isArray(item)) {
103 return Object.fromEntries(
104 Object.entries(item as Record<string, unknown>).sort(([left], [right]) =>
105 left.localeCompare(right),
106 ),
107 );
108 }
109 return item;
110 });
111
112 export const userLabels = (
113 labels: Record<string, string | undefined> | null | undefined,
114 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
115
116 export const hasAlchemyPrefix = (labels: Record<string, string | undefined> | null | undefined) =>
117 Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-"));
118
119 export const alchemyIdFilter = (labels: Record<string, string>) => {
120 const id = labels[alchemyLabelKeys.id];
121 return id !== undefined && id.length > 0 ? `labels.${alchemyLabelKeys.id}="${id}"` : undefined;
122 };
123
124 export const labelsDiffer = (
125 observed: Record<string, string | undefined> | null | undefined,
126 desired: Record<string, string>,
127 ) => {
128 const left = tagRecord(observed);
129 const keys = new Set([...Object.keys(left), ...Object.keys(desired)]);
130 for (const key of keys) {
131 if ((left[key] ?? "") !== (desired[key] ?? "")) return true;
132 }
133 return false;
134 };
135
136 const markerOf = (labels: Record<string, string>) =>
137 `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
138
139 /** 64-bit FNV-1a, hex. Deterministic and dependency-free. */
140 const fnv1a64 = (input: string): string => {
141 let hash = 0xcbf29ce484222325n;
142 for (let index = 0; index < input.length; index++) {
143 hash ^= BigInt(input.charCodeAt(index));
144 hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;
145 }
146 return hash.toString(16).padStart(16, "0");
147 };
148
149 const HASH_KEY = "alchemy-hash";
150
151 const ownershipHash = (labels: Record<string, string>) =>
152 fnv1a64(
153 JSON.stringify([
154 labels[alchemyLabelKeys.stack],
155 labels[alchemyLabelKeys.stage],
156 labels[alchemyLabelKeys.id],
157 ]),
158 );
159
160 /**
161 * Prefix `displayName` with the ownership marker. When the full
162 * `[alchemy stack=… stage=… id=…]` marker would push the name past
163 * Vertex AI's 128-character limit (long stack names), a fixed-width
164 * `[alchemy alchemy-hash=…]` marker is used instead so it is never cut.
165 */
166 export const encodeDisplayName = (
167 labels: Record<string, string>,
168 displayName: string | undefined,
169 ): string => {
170 const trimmed = displayName?.replace(/[\r\n]+/g, " ").trim();
171 const withMarker = (marker: string) =>
172 trimmed && trimmed.length > 0 ? `${marker} ${trimmed}` : marker;
173 const full = withMarker(markerOf(labels));
174 if (full.length <= MAX_DISPLAY_NAME_LENGTH) return full;
175 return withMarker(`[alchemy ${HASH_KEY}=${ownershipHash(labels)}]`).slice(
176 0,
177 MAX_DISPLAY_NAME_LENGTH,
178 );
179 };
180
181 /** Whether a marked display name belongs to logical id `id` of this stack. */
182 export const ownsDisplayName = (id: string, displayName: string | undefined) =>
183 Effect.gen(function* () {
184 const { labels } = parseDisplayName(displayName);
185 const expected = yield* createInternalLabelsImpl(id);
186 if (labels[HASH_KEY] !== undefined) {
187 return labels[HASH_KEY] === ownershipHash(expected);
188 }
189 return yield* hasAlchemyLabels(id, labels);
190 });
191
192 export const parseDisplayName = (
193 displayName: string | undefined,
194 ): {
195 labels: Record<string, string>;
196 displayName: string | undefined;
197 } => {
198 if (!displayName?.startsWith("[alchemy ")) {
199 return { labels: {}, displayName };
200 }
201 const end = displayName.indexOf("]");
202 if (end < 0) return { labels: {}, displayName };
203 const labels: Record<string, string> = {};
204 for (const part of displayName.slice("[alchemy ".length, end).split(/\s+/)) {
205 const eq = part.indexOf("=");
206 if (eq > 0) {
207 labels[part.slice(0, eq)] = part.slice(eq + 1);
208 }
209 }
210 const rest = displayName.slice(end + 1).replace(/^[\s\n]+/, "");
211 return { labels, displayName: rest.length > 0 ? rest : undefined };
212 };
213
214 export const encodeDescription = (
215 labels: Record<string, string>,
216 description: string | undefined,
217 ): string => {
218 const marker = markerOf(labels);
219 return description ? `${marker}\n${description}` : marker;
220 };
221
222 export const parseDescription = (
223 description: string | undefined,
224 ): {
225 labels: Record<string, string>;
226 description: string | undefined;
227 } => {
228 const parsed = parseDisplayName(description);
229 return { labels: parsed.labels, description: parsed.displayName };
230 };
231
232 export const hasOwnershipMarker = (text: string | undefined) =>
233 Object.keys(parseDisplayName(text).labels).some((key) => key.startsWith("alchemy-"));