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

main
ts 342 lines 12 KB
Raw
1 import * as chromemanagement from "@distilled.cloud/gcp/chromemanagement_v1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Config from "effect/Config";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import * as Stream from "effect/Stream";
7 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8
9 /** Optional deploy-time setting from the ConfigProvider (env by default). */
10 const optionalSetting = (key: string) =>
11 Effect.gen(function* () {
12 const value = yield* Config.option(Config.String(key));
13 return Option.getOrUndefined(value)?.trim() || undefined;
14 });
15
16 export const CUSTOMER_PREFIX = "customers/";
17 export const MY_CUSTOMER = "customers/my_customer";
18 export const MAX_DISPLAY_NAME_LENGTH = 256;
19 export const MAX_CONNECTOR_CONFIG_ID_LENGTH = 63;
20 export const PROBE_CUSTOMER = "customers/0";
21 export const PROBE_CONNECTOR_CONFIG = `${PROBE_CUSTOMER}/connectorConfigs/alchemy-missing`;
22
23 const INPUT_ONLY_KEYS = new Set(["apiKey", "hecToken"]);
24
25 export const lastSegment = (value: string) => {
26 const trimmed = value.replace(/\/+$/, "");
27 const parts = trimmed.split("/");
28 return parts[parts.length - 1] || trimmed;
29 };
30
31 export const parentOf = (name: string) => {
32 const parts = name.split("/").filter((part) => part.length > 0);
33 return parts.slice(0, -2).join("/");
34 };
35
36 export const normalizeName = (value: string) => value.replace(/\/+$/, "").trim();
37
38 export const toCustomerName = (value: string) => {
39 const trimmed = normalizeName(value);
40 if (trimmed.length === 0) return "";
41 const customersIdx = trimmed.lastIndexOf("/customers/");
42 if (customersIdx >= 0) {
43 const rest = trimmed.slice(customersIdx + "/customers/".length);
44 const id = rest.split("/")[0] ?? "";
45 return id.length > 0 ? `${CUSTOMER_PREFIX}${id}` : "";
46 }
47 if (trimmed.startsWith(CUSTOMER_PREFIX)) {
48 const id = trimmed.slice(CUSTOMER_PREFIX.length).split("/")[0] ?? "";
49 return id.length > 0 ? `${CUSTOMER_PREFIX}${id}` : trimmed;
50 }
51 return `${CUSTOMER_PREFIX}${lastSegment(trimmed)}`;
52 };
53
54 export const toConnectorConfigName = (parent: string, connectorConfigId?: string) => {
55 if (connectorConfigId !== undefined && connectorConfigId.includes("/connectorConfigs/")) {
56 return normalizeName(connectorConfigId);
57 }
58 const customer = toCustomerName(parent);
59 if (connectorConfigId !== undefined && connectorConfigId.length > 0 && customer.length > 0) {
60 return `${customer}/connectorConfigs/${lastSegment(connectorConfigId)}`;
61 }
62 return "";
63 };
64
65 export const sameText = (left: string | undefined, right: string | undefined) =>
66 (left ?? "") === (right ?? "");
67
68 export const jsonEqual = (left: unknown, right: unknown) =>
69 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
70
71 export const updateMaskOf = (...fields: Array<string | undefined>) =>
72 fields.filter((field): field is string => field !== undefined).join(",");
73
74 export const replaceOnIdentity = (input: {
75 previousParent?: string;
76 nextParent: string;
77 previousId?: string;
78 nextId?: string;
79 previousType?: string;
80 nextType?: string;
81 }) => {
82 if (
83 input.previousParent !== undefined &&
84 input.previousParent.length > 0 &&
85 toCustomerName(input.previousParent) !== toCustomerName(input.nextParent)
86 ) {
87 return { action: "replace" as const, deleteFirst: false };
88 }
89 if (
90 input.previousId !== undefined &&
91 input.nextId !== undefined &&
92 lastSegment(input.previousId) !== lastSegment(input.nextId)
93 ) {
94 return { action: "replace" as const, deleteFirst: false };
95 }
96 if (
97 input.previousType !== undefined &&
98 input.nextType !== undefined &&
99 input.previousType !== input.nextType
100 ) {
101 return { action: "replace" as const, deleteFirst: false };
102 }
103 return undefined;
104 };
105
106 const stripInputOnly = (value: unknown): unknown => {
107 if (Array.isArray(value)) return value.map(stripInputOnly);
108 if (value === null || typeof value !== "object") return value;
109 const out: Record<string, unknown> = {};
110 for (const [key, child] of Object.entries(value)) {
111 if (INPUT_ONLY_KEYS.has(key)) continue;
112 out[key] = stripInputOnly(child);
113 }
114 return out;
115 };
116
117 export const visibleDetails = (
118 details: chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails | undefined,
119 ) =>
120 stripInputOnly(details) as
121 | chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails
122 | undefined;
123
124 const secretSlice = (
125 details: chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails | undefined,
126 ) => {
127 if (!details) return undefined;
128 return {
129 splunkHecToken: details.splunkConfig?.hecToken,
130 paloAltoApiKey: details.paloAltoNetworksConfig?.apiKey,
131 crowdStrikeApiKey: details.crowdStrikeConfig?.apiKey,
132 crowdStrikeFalconApiKey: details.crowdStrikeFalconNextGenConfig?.apiKey,
133 crowdStrikeXdrApiKey: details.crowdStrikeXdrConfig?.apiKey,
134 googleSecOpsApiKey: details.googleSecOpsConfig?.apiKey,
135 };
136 };
137
138 export const detailsNeedSync = (
139 observed: chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails | undefined,
140 desired: chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails | undefined,
141 previous: chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfigDetails | undefined,
142 ) =>
143 !jsonEqual(visibleDetails(observed), visibleDetails(desired)) ||
144 (previous !== undefined && !jsonEqual(secretSlice(desired), secretSlice(previous)));
145
146 const markerOf = (stack: string, stage: string, id: string) =>
147 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
148
149 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
150 let stack = labels[alchemyLabelKeys.stack] ?? "x";
151 let stage = labels[alchemyLabelKeys.stage] ?? "x";
152 let id = labels[alchemyLabelKeys.id] ?? "x";
153 let marker = markerOf(stack, stage, id);
154 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
155 if (stack.length >= stage.length && stack.length >= id.length) {
156 stack = stack.slice(0, -1);
157 } else if (stage.length >= id.length) {
158 stage = stage.slice(0, -1);
159 } else {
160 id = id.slice(0, -1);
161 }
162 marker = markerOf(stack, stage, id);
163 }
164 return marker.slice(0, maxLength);
165 };
166
167 export const encodeOwnershipLine = (
168 labels: Record<string, string>,
169 text: string | undefined,
170 maxLength = MAX_DISPLAY_NAME_LENGTH,
171 ): string => {
172 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
173 if (!trimmed) return fitMarker(labels, maxLength);
174 const minMarker = 24;
175 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
176 const marker = fitMarker(labels, maxLength - reserved);
177 return `${marker} ${trimmed}`.slice(0, maxLength);
178 };
179
180 export const parseOwnership = (
181 text: string | undefined,
182 ): {
183 labels: Record<string, string>;
184 text: string | undefined;
185 } => {
186 if (!text?.startsWith("[alchemy ")) {
187 return { labels: {}, text };
188 }
189 const end = text.indexOf("]");
190 if (end < 0) return { labels: {}, text };
191 const labels: Record<string, string> = {};
192 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
193 const eq = part.indexOf("=");
194 if (eq > 0) {
195 labels[part.slice(0, eq)] = part.slice(eq + 1);
196 }
197 }
198 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
199 return { labels, text: rest.length > 0 ? rest : undefined };
200 };
201
202 export const hasOwnershipMarker = (text: string | undefined) =>
203 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
204
205 const prefixMatch = (expected: string, observed: string) =>
206 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
207
208 export const ownedByAlchemy = (id: string, text: string | undefined) =>
209 Effect.gen(function* () {
210 const expected = yield* createInternalLabels(id);
211 const { labels } = parseOwnership(text);
212 if (!hasOwnershipMarker(text)) return false;
213 const exact = yield* hasAlchemyLabels(id, labels);
214 if (exact) return true;
215 return (
216 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
217 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
218 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
219 );
220 });
221
222 export const ownershipLabels = (id: string) => createInternalLabels(id);
223
224 export const toDisplayName = (
225 id: string,
226 requested: string | undefined,
227 existing: string | undefined,
228 maxLength = MAX_DISPLAY_NAME_LENGTH,
229 ) =>
230 Effect.gen(function* () {
231 if (requested !== undefined && requested.length > 0) {
232 return requested.slice(0, maxLength);
233 }
234 if (existing !== undefined && existing.length > 0) {
235 return existing.slice(0, maxLength);
236 }
237 return yield* createPhysicalName({
238 id,
239 maxLength: Math.min(40, maxLength),
240 lowercase: true,
241 });
242 });
243
244 export const toConnectorConfigId = (id: string, requested: string | undefined, existing?: string) =>
245 Effect.gen(function* () {
246 if (requested !== undefined && requested.length > 0) {
247 return lastSegment(requested);
248 }
249 if (existing !== undefined && existing.length > 0) {
250 return lastSegment(existing);
251 }
252 return yield* createPhysicalName({
253 id,
254 maxLength: MAX_CONNECTOR_CONFIG_ID_LENGTH,
255 lowercase: true,
256 });
257 });
258
259 const emptyList = <A>() => Effect.succeed([] as A[]);
260
261 export const collectPages = <Page, A, E, R>(
262 pages: Stream.Stream<Page, E, R>,
263 items: (page: Page) => readonly A[] | undefined,
264 ) =>
265 pages.pipe(
266 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
267 Stream.runCollect,
268 Effect.map((chunk) => Array.from(chunk)),
269 );
270
271 export const getConnectorConfig = (name: string) =>
272 name.length === 0
273 ? Effect.undefined
274 : chromemanagement
275 .getCustomersConnectorConfigs({ name })
276 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
277
278 export const listConnectorConfigsAt = (parent: string) =>
279 parent.length === 0
280 ? emptyList<chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfig>()
281 : collectPages(
282 chromemanagement.listCustomersConnectorConfigs.pages({
283 parent: toCustomerName(parent),
284 pageSize: 100,
285 }),
286 (page) => page.connectorConfigs,
287 ).pipe(
288 Effect.catchTag("NotFound", () =>
289 emptyList<chromemanagement.GoogleChromeManagementVersionsV1ConnectorConfig>(),
290 ),
291 );
292
293 /** `my_customer` plus any customers listed in the Chrome Management settings. */
294 export const configuredCustomers = () =>
295 Effect.gen(function* () {
296 const names = new Set<string>();
297 names.add(MY_CUSTOMER);
298 for (const key of [
299 "GCP_CHROMEMANAGEMENT_CUSTOMER",
300 "GCP_CHROMEMANAGEMENT_CUSTOMER_ID",
301 "GCP_CHROMEMANAGEMENT_CUSTOMERS",
302 ]) {
303 const raw = yield* optionalSetting(key);
304 for (const part of (raw ?? "").split(/[,\s]+/)) {
305 const name = toCustomerName(part);
306 if (name.length > 0) names.add(name);
307 }
308 }
309 return [...names];
310 });
311
312 export const findOwnedConnectorConfig = (id: string, parent?: string) =>
313 Effect.gen(function* () {
314 const parents =
315 parent !== undefined && parent.length > 0
316 ? [toCustomerName(parent)]
317 : yield* configuredCustomers();
318 for (const next of parents) {
319 const rows = yield* listConnectorConfigsAt(next);
320 for (const row of rows) {
321 if (yield* ownedByAlchemy(id, row.displayName)) {
322 return row;
323 }
324 }
325 }
326 return undefined;
327 });
328
329 export const findConnectorConfigByName = (displayName: string, parent: string) =>
330 Effect.gen(function* () {
331 const rows = yield* listConnectorConfigsAt(parent);
332 return rows.find((row) => row.displayName === displayName);
333 });
334
335 export const listOwnedConnectorConfigs = () =>
336 Effect.gen(function* () {
337 const parents = yield* configuredCustomers();
338 const pages = yield* Effect.forEach(parents, (parent) => listConnectorConfigsAt(parent), {
339 concurrency: 4,
340 });
341 return pages.flat().filter((row) => hasOwnershipMarker(row.displayName));
342 });