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

main
ts 213 lines 7.13 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import { tagRecord } from "alchemy/Tags";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as Stream from "effect/Stream";
6 import { alchemyLabelKeys, createInternalLabels, stripInternalLabels } from "../Labels.ts";
7
8 export const MAX_NAME_LENGTH = 63;
9 export const MAX_PIPELINE_JOB_ID_LENGTH = 128;
10
11 export class AiPlatformNotResolved extends Data.TaggedError("GCP.AIPlatform.NotResolved")<{
12 resourceName: string;
13 }> {}
14
15 export class AiPlatformStillExists extends Data.TaggedError("GCP.AIPlatform.StillExists")<{
16 resourceName: string;
17 }> {}
18
19 export type EncryptionSpec = {
20 /** Cloud KMS key resource name. Immutable on most Vertex resources. */
21 kmsKeyName?: string;
22 };
23
24 export type MachineSpec = {
25 /** Machine type (e.g. `e2-standard-4`, `n1-standard-4`). Immutable. */
26 machineType?: string;
27 /** Accelerator type (`NVIDIA_TESLA_T4`, …). Immutable. */
28 acceleratorType?: string;
29 /** Number of accelerators to attach. */
30 acceleratorCount?: number;
31 /** Nvidia GPU partition size (MIG). Immutable. */
32 gpuPartitionSize?: string;
33 /** TPU topology (e.g. `2x2x1`). Immutable. */
34 tpuTopology?: string;
35 };
36
37 export type NetworkSpec = {
38 /** Enable public internet access. @default false */
39 enableInternetAccess?: boolean;
40 /** Subnetwork resource name. */
41 subnetwork?: string;
42 /** VPC network resource name. */
43 network?: string;
44 };
45
46 export type PersistentDiskSpec = {
47 /** Disk type (`pd-standard`, `pd-ssd`, …). */
48 diskType?: string;
49 /** Size in GB (string, e.g. `"100"`). */
50 diskSizeGb?: string;
51 };
52
53 export type DiskSpec = {
54 /** Boot disk type (`pd-ssd`, `pd-standard`, `hyperdisk-balanced`). */
55 bootDiskType?: string;
56 /** Boot disk size in GB. @default 100 */
57 bootDiskSizeGb?: number;
58 };
59
60 export const lastSegment = (value: string) => {
61 const trimmed = value.replace(/\/+$/, "");
62 const parts = trimmed.split("/");
63 return parts[parts.length - 1] || trimmed;
64 };
65
66 export const normalizeLocation = (location: string | undefined, fallback: string) =>
67 lastSegment(location ?? fallback).toLowerCase();
68
69 export const locationParent = (project: string, location: string) =>
70 `projects/${project}/locations/${location}`;
71
72 export const parseResourceName = (name: string, collection: string) => {
73 const parts = name.split("/").filter((part) => part.length > 0);
74 const collectionAt = parts.lastIndexOf(collection);
75 const locationsAt = parts.lastIndexOf("locations");
76 const projectsAt = parts.lastIndexOf("projects");
77 return {
78 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
79 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
80 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
81 };
82 };
83
84 export const parentBefore = (name: string, collection: string) => {
85 const marker = `/${collection}/`;
86 const at = name.lastIndexOf(marker);
87 return at >= 0 ? name.slice(0, at) : name;
88 };
89
90 export const rfc1035 = (name: string, maxLength = MAX_NAME_LENGTH): string => {
91 let next = name
92 .toLowerCase()
93 .replace(/[^a-z0-9-]/g, "-")
94 .replace(/-+/g, "-")
95 .replace(/^-+|-+$/g, "");
96 if (!/^[a-z]/.test(next)) next = `a${next}`;
97 next = next.slice(0, maxLength).replace(/-+$/g, "");
98 if (next.length === 0) return "resource";
99 if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, maxLength - 1)}0`;
100 return next.slice(0, maxLength);
101 };
102
103 export const toPhysicalId = (
104 id: string,
105 explicit: string | undefined,
106 existing: string | undefined,
107 maxLength = MAX_NAME_LENGTH,
108 ) =>
109 Effect.gen(function* () {
110 if (explicit !== undefined) return explicit;
111 if (existing !== undefined) return existing;
112 return rfc1035(
113 yield* createPhysicalName({
114 id,
115 maxLength,
116 lowercase: true,
117 }),
118 maxLength,
119 );
120 });
121
122 export const userLabels = (
123 labels: Record<string, string | undefined> | null | undefined,
124 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
125
126 export const encodeDescription = (
127 labels: Record<string, string>,
128 description: string | undefined,
129 ): string => {
130 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
131 return description ? `${marker}\n${description}` : marker;
132 };
133
134 export const parseDescription = (
135 description: string | undefined,
136 ): {
137 labels: Record<string, string>;
138 description: string | undefined;
139 } => {
140 if (!description?.startsWith("[alchemy ")) {
141 return { labels: {}, description };
142 }
143 const end = description.indexOf("]");
144 if (end < 0) return { labels: {}, description };
145 const labels: Record<string, string> = {};
146 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
147 const eq = part.indexOf("=");
148 if (eq > 0) {
149 labels[part.slice(0, eq)] = part.slice(eq + 1);
150 }
151 }
152 const rest = description.slice(end + 1).replace(/^\n/, "");
153 return { labels, description: rest.length > 0 ? rest : undefined };
154 };
155
156 export const hasDescriptionOwnership = (description: string | undefined) =>
157 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
158
159 /**
160 * Compact displayName stamp for APIs that cap display names at 63
161 * characters and have no labels field.
162 */
163 const DISPLAY_ID_LENGTH = 20;
164
165 export const encodeDisplayName = (
166 labels: Record<string, string>,
167 displayName: string | undefined,
168 maxLength = 63,
169 ): string => {
170 const id = (labels[alchemyLabelKeys.id] ?? "x").slice(0, DISPLAY_ID_LENGTH);
171 const marker = `[alc ${id}]`;
172 const rest = (displayName ?? "").replace(/[\r\n]+/g, " ").trim();
173 const combined = rest.length > 0 ? `${marker} ${rest}` : marker;
174 return combined.slice(0, maxLength);
175 };
176
177 export const parseDisplayName = (
178 displayName: string | undefined,
179 ): {
180 labels: Record<string, string>;
181 displayName: string | undefined;
182 } => {
183 if (!displayName?.startsWith("[alc ")) {
184 return { labels: {}, displayName };
185 }
186 const end = displayName.indexOf("]");
187 if (end < 0) return { labels: {}, displayName };
188 const id = displayName.slice("[alc ".length, end).trim();
189 const rest = displayName.slice(end + 1).replace(/^[\s\n]+/, "");
190 return {
191 labels: id.length > 0 ? { [alchemyLabelKeys.id]: id } : {},
192 displayName: rest.length > 0 ? rest : undefined,
193 };
194 };
195
196 export const hasDisplayNameOwnership = (displayName: string | undefined) =>
197 Object.keys(parseDisplayName(displayName).labels).some((key) => key.startsWith("alchemy-"));
198
199 export const ownedById = (id: string, labels: Record<string, string>) =>
200 Effect.gen(function* () {
201 const expected = yield* createInternalLabels(id);
202 const expectedId = (expected[alchemyLabelKeys.id] ?? "").slice(0, DISPLAY_ID_LENGTH);
203 return labels[alchemyLabelKeys.id] === expectedId;
204 });
205
206 export const collectPages = <A, E, R>(stream: Stream.Stream<A, E, R>) =>
207 stream.pipe(
208 Stream.runCollect,
209 Effect.map((chunk) => Array.from(chunk)),
210 );
211
212 export const jsonEqual = (left: unknown, right: unknown) =>
213 JSON.stringify(left ?? null) === JSON.stringify(right ?? null);