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

main
ts 276 lines 10.1 KB
Raw
1 import * as cloudcontrolspartner from "@distilled.cloud/gcp/cloudcontrolspartner_v1";
2 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Config from "effect/Config";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
11
12 export const MAX_DISPLAY_NAME_LENGTH = 128;
13 export const LIST_LOCATIONS = ["global", "-"] as const;
14
15 export class OrganizationNotResolved extends Data.TaggedError(
16 "GCP.CloudControlsPartner.OrganizationNotResolved",
17 )<{
18 project: string;
19 }> {}
20
21 export class CustomerIdRequired extends Data.TaggedError(
22 "GCP.CloudControlsPartner.CustomerIdRequired",
23 )<{
24 id: string;
25 }> {}
26
27 export const lastSegment = (value: string) => {
28 const trimmed = value.replace(/\/+$/, "");
29 const parts = trimmed.split("/");
30 return parts[parts.length - 1] || trimmed;
31 };
32
33 export const normalizeName = (value: string) => value.replace(/\/+$/, "");
34
35 export const organizationParent = (value: string) =>
36 value.startsWith("organizations/")
37 ? `organizations/${lastSegment(value.split("/locations/")[0] ?? value)}`
38 : `organizations/${lastSegment(value)}`;
39
40 export const organizationIdOf = (value: string) => lastSegment(organizationParent(value));
41
42 export const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
43
44 export const locationParent = (organization: string, location: string) =>
45 `${organizationParent(organization)}/locations/${normalizeLocation(location)}`;
46
47 export const customerName = (organization: string, location: string, customerId: string) =>
48 `${locationParent(organization, location)}/customers/${customerId}`;
49
50 export const parseName = (name: string) => {
51 const parts = name.split("/").filter((part) => part.length > 0);
52 const orgsAt = parts.lastIndexOf("organizations");
53 const locationsAt = parts.lastIndexOf("locations");
54 const customersAt = parts.lastIndexOf("customers");
55 return {
56 organization: orgsAt >= 0 && parts[orgsAt + 1] ? `organizations/${parts[orgsAt + 1]}` : "",
57 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
58 customerId:
59 customersAt >= 0 && parts[customersAt + 1] ? parts[customersAt + 1]! : lastSegment(name),
60 parent:
61 customersAt > 0
62 ? parts.slice(0, customersAt).join("/")
63 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
64 };
65 };
66
67 export const toCustomerId = (value: string | undefined) => {
68 if (value === undefined) return undefined;
69 const trimmed = normalizeName(value);
70 if (trimmed.length === 0) return undefined;
71 if (trimmed.includes("/customers/")) return lastSegment(trimmed);
72 return lastSegment(trimmed);
73 };
74
75 export const sameText = (left: string | undefined, right: string | undefined) =>
76 (left ?? "") === (right ?? "");
77
78 export const replaceOn = (previous: string | undefined, next: string | undefined) =>
79 previous !== undefined && next !== undefined && previous !== next
80 ? ({ action: "replace" as const, deleteFirst: false } as const)
81 : undefined;
82
83 export const toDisplayName = (
84 id: string,
85 requested: string | undefined,
86 existing: string | undefined,
87 ) =>
88 Effect.gen(function* () {
89 if (requested !== undefined && requested.length > 0) return requested;
90 if (existing !== undefined && existing.length > 0) return existing;
91 return yield* createPhysicalName({
92 id,
93 maxLength: 40,
94 lowercase: true,
95 });
96 });
97
98 export const toCustomerResourceId = (
99 id: string,
100 requested: string | undefined,
101 existing: string | undefined,
102 ) =>
103 Effect.gen(function* () {
104 const explicit = toCustomerId(requested);
105 if (explicit !== undefined) return explicit;
106 const previous = toCustomerId(existing);
107 if (previous !== undefined) return previous;
108 return yield* new CustomerIdRequired({ id });
109 });
110
111 const markerOf = (stack: string, stage: string, id: string) =>
112 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
113
114 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
115 let stack = labels[alchemyLabelKeys.stack] ?? "x";
116 let stage = labels[alchemyLabelKeys.stage] ?? "x";
117 let id = labels[alchemyLabelKeys.id] ?? "x";
118 let marker = markerOf(stack, stage, id);
119 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
120 if (stack.length >= stage.length && stack.length >= id.length) {
121 stack = stack.slice(0, -1);
122 } else if (stage.length >= id.length) {
123 stage = stage.slice(0, -1);
124 } else {
125 id = id.slice(0, -1);
126 }
127 marker = markerOf(stack, stage, id);
128 }
129 return marker.slice(0, maxLength);
130 };
131
132 export const encodeDisplayName = (
133 labels: Record<string, string>,
134 text: string | undefined,
135 maxLength = MAX_DISPLAY_NAME_LENGTH,
136 ): string => {
137 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
138 if (!trimmed) return fitMarker(labels, maxLength);
139 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - 24));
140 const marker = fitMarker(labels, Math.max(24, maxLength - reserved));
141 return `${marker} ${trimmed}`.slice(0, maxLength);
142 };
143
144 export const parseOwnership = (
145 text: string | undefined,
146 ): {
147 labels: Record<string, string>;
148 text: string | undefined;
149 } => {
150 if (!text?.startsWith("[alchemy ")) {
151 return { labels: {}, text };
152 }
153 const end = text.indexOf("]");
154 if (end < 0) return { labels: {}, text };
155 const labels: Record<string, string> = {};
156 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
157 const eq = part.indexOf("=");
158 if (eq > 0) {
159 labels[part.slice(0, eq)] = part.slice(eq + 1);
160 }
161 }
162 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
163 return { labels, text: rest.length > 0 ? rest : undefined };
164 };
165
166 export const hasOwnershipMarker = (text: string | undefined) =>
167 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
168
169 const prefixMatch = (expected: string, observed: string) =>
170 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
171
172 export const ownedByAlchemy = (id: string, text: string | undefined) =>
173 Effect.gen(function* () {
174 const expected = yield* createInternalLabels(id);
175 const { labels } = parseOwnership(text);
176 if (!hasOwnershipMarker(text)) return false;
177 const exact = yield* hasAlchemyLabels(id, labels);
178 if (exact) return true;
179 return (
180 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
181 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
182 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
183 );
184 });
185
186 export const ownershipLabels = (id: string) => createInternalLabels(id);
187
188 const ancestryParent = (name: string) =>
189 name.startsWith("projects/")
190 ? resourcemanager.getProjects({ name }).pipe(
191 Effect.map((resource) => resource.parent),
192 Effect.catchTag("NotFound", () => Effect.undefined),
193 )
194 : name.startsWith("folders/")
195 ? resourcemanager.getFolders({ name }).pipe(
196 Effect.map((folder) => folder.parent),
197 Effect.catchTag("NotFound", () => Effect.undefined),
198 )
199 : Effect.undefined;
200
201 /** Organization from the ConfigProvider (env by default), if configured. */
202 const configuredOrganization = () =>
203 Effect.gen(function* () {
204 for (const key of ["GOOGLE_CLOUDCONTROLSPARTNER_ORGANIZATION", "GOOGLE_ORGANIZATION_ID"]) {
205 const raw = Option.getOrUndefined(yield* Config.option(Config.String(key)))?.trim();
206 if (raw) return organizationParent(raw);
207 }
208 return undefined;
209 });
210
211 export const tryResolveOrganization = () =>
212 Effect.gen(function* () {
213 const configured = yield* configuredOrganization();
214 if (configured !== undefined) return configured;
215 const env = yield* GcpEnvironment.current;
216 let current: string | undefined = `projects/${env.project}`;
217 for (let i = 0; i < 8; i++) {
218 if (current === undefined) return undefined;
219 if (current.startsWith("organizations/")) return current;
220 current = yield* ancestryParent(current);
221 }
222 return undefined;
223 });
224
225 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
226 Effect.gen(function* () {
227 if (explicit !== undefined && explicit.length > 0) {
228 return organizationParent(explicit);
229 }
230 if (existing !== undefined && existing.length > 0) {
231 return organizationParent(existing);
232 }
233 const resolved = yield* tryResolveOrganization();
234 if (resolved === undefined) {
235 const env = yield* GcpEnvironment.current;
236 return yield* new OrganizationNotResolved({ project: env.project });
237 }
238 return resolved;
239 });
240
241 export const listLocationParents = (organization: string, region: string) =>
242 [...new Set([region, ...LIST_LOCATIONS])].map((location) =>
243 locationParent(organization, location),
244 );
245
246 const emptyCustomers = () => Effect.succeed([] as cloudcontrolspartner.Customer[]);
247
248 export const listCustomers = (parent: string) =>
249 parent.length === 0
250 ? emptyCustomers()
251 : cloudcontrolspartner.listOrganizationsLocationsCustomers
252 .pages({ parent, pageSize: 100 })
253 .pipe(
254 Stream.flatMap((page) => Stream.fromIterable(page.customers ?? [])),
255 Stream.runCollect,
256 Effect.map((chunk) => Array.from(chunk)),
257 Effect.catchTag("NotFound", () => emptyCustomers()),
258 );
259
260 export const getCustomer = (name: string) =>
261 name.length === 0
262 ? Effect.undefined
263 : cloudcontrolspartner
264 .getOrganizationsLocationsCustomers({ name })
265 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
266
267 export const findOwnedCustomer = (id: string, parent: string) =>
268 Effect.gen(function* () {
269 const customers = yield* listCustomers(parent);
270 for (const customer of customers) {
271 if (yield* ownedByAlchemy(id, customer.displayName)) {
272 return customer;
273 }
274 }
275 return undefined;
276 });