@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 444 lines 15.4 KB
Raw
1 import * as networkservices from "@distilled.cloud/gcp/networkservices_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 changedFields,
14 collectPages,
15 hasAlchemyLabelKeys,
16 normalizeLocation,
17 parentOf,
18 parseName,
19 resourceName,
20 rfc1035,
21 sameJson,
22 sameStringList,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilGone,
27 waitUntilPresent,
28 } from "./internal.ts";
29
30 const COLLECTION = "agentGateways";
31
32 export type AgentGatewayGovernedAccessPath =
33 | networkservices.AgentGatewayGoogleManagedGovernedAccessPathEnum
34 | (string & {});
35
36 export type AgentGatewayProtocol = networkservices.AgentGatewayProtocolsItemEnum | (string & {});
37
38 export type AgentGatewayGoogleManaged = {
39 /**
40 * Operating mode of a Google-managed Agent Gateway.
41 */
42 governedAccessPath?: AgentGatewayGovernedAccessPath;
43 };
44
45 export type AgentGatewaySelfManaged = {
46 /**
47 * Existing Application Load Balancer or Secure Web Proxy resource URI
48 * in the same project and location.
49 */
50 resourceUri?: string;
51 };
52
53 export type AgentGatewayNetworkConfigEgress = {
54 /** Network Attachment URI used for private VPC egress. */
55 networkAttachment?: string;
56 };
57
58 export type AgentGatewayDnsPeeringConfig = {
59 /** Domain names whose queries are forwarded to the target network. */
60 domains?: string[];
61 /** Project id that owns the target network. */
62 targetProject?: string;
63 /**
64 * Target network in
65 * `projects/{project}/global/networks/{network}` form.
66 */
67 targetNetwork?: string;
68 };
69
70 export type AgentGatewayNetworkConfig = {
71 /** PSC-interface network attachment for private VPC connectivity. */
72 egress?: AgentGatewayNetworkConfigEgress;
73 /** DNS peering configuration for the user VPC. */
74 dnsPeeringConfig?: AgentGatewayDnsPeeringConfig;
75 };
76
77 export type AgentGatewayOutputCard = {
78 /** mTLS endpoint associated with this Agent Gateway. */
79 mtlsEndpoint?: string;
80 /** Root certificates agents use to validate this Agent Gateway. */
81 rootCertificates?: string[];
82 /** Service account used by Service Extensions. */
83 serviceExtensionsServiceAccount?: string;
84 };
85
86 export type AgentGatewayProps = {
87 /**
88 * AgentGateway id (the `{agentGateway}` segment of
89 * `projects/{project}/locations/{location}/agentGateways/{agentGateway}`).
90 * If omitted, a unique name is generated from the stack, stage, and
91 * logical id. Must be 1-63 characters and not start with a number.
92 * Immutable — changing it replaces the gateway.
93 */
94 agentGatewayId?: string;
95 /**
96 * Location (`us-central1`, …). Immutable — changing it replaces the
97 * gateway. `US-CENTRAL1` is accepted and normalized to `us-central1`.
98 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
99 */
100 location?: string;
101 /**
102 * Google-managed deployment. Mutually exclusive with `selfManaged`.
103 */
104 googleManaged?: AgentGatewayGoogleManaged;
105 /**
106 * Attach to an existing Application Load Balancer or Secure Web Proxy.
107 * Mutually exclusive with `googleManaged`.
108 */
109 selfManaged?: AgentGatewaySelfManaged;
110 /**
111 * Agent registries containing agents, MCP servers, and tools. Must be
112 * project-scoped
113 * `//agentregistry.googleapis.com/projects/{project}/locations/{location}/...`
114 * names.
115 */
116 registries?: string[];
117 /**
118 * Deprecated protocol list. Prefer `googleManaged` / `selfManaged`.
119 */
120 protocols?: AgentGatewayProtocol[];
121 /**
122 * Network configuration for private VPC connectivity.
123 */
124 networkConfig?: AgentGatewayNetworkConfig;
125 /**
126 * Human-readable description. Max length 1024 characters.
127 */
128 description?: string;
129 /**
130 * User labels. Alchemy ownership labels are merged in automatically.
131 */
132 labels?: Record<string, string>;
133 };
134
135 export type AgentGateway = Resource<
136 "GCP.NetworkServices.AgentGateway",
137 AgentGatewayProps,
138 {
139 /** Full resource name `projects/{project}/locations/{location}/agentGateways/{agentGateway}`. */
140 name: string;
141 /** AgentGateway id (last path segment). */
142 agentGatewayId: string;
143 /** Project id. */
144 project: string;
145 /** Location id (`us-central1`, …). */
146 location: string;
147 /** Google-managed deployment, if set. */
148 googleManaged: AgentGatewayGoogleManaged | undefined;
149 /** Self-managed proxy attachment, if set. */
150 selfManaged: AgentGatewaySelfManaged | undefined;
151 /** Agent registry resource names. */
152 registries: string[];
153 /** Deprecated protocol list. */
154 protocols: string[];
155 /** Network configuration, if set. */
156 networkConfig: AgentGatewayNetworkConfig | undefined;
157 /** Output-only Agent Gateway card. */
158 agentGatewayCard: AgentGatewayOutputCard | undefined;
159 /** User-provided description. */
160 description: string | undefined;
161 /** User labels (Alchemy ownership labels stripped). */
162 labels: Record<string, string>;
163 /** Server etag. */
164 etag: string | undefined;
165 /** RFC3339 creation timestamp. */
166 createTime: string | undefined;
167 /** RFC3339 last-update timestamp. */
168 updateTime: string | undefined;
169 },
170 never,
171 Providers
172 >;
173
174 /**
175 * A Network Services Agent Gateway — the proxy that governs access to
176 * agents, MCP servers, and tools.
177 *
178 * Changing `agentGatewayId` or `location` replaces the gateway.
179 * Description, labels, registries, network config, and deployment mode
180 * update in place.
181 *
182 * ### Creating an AgentGateway
183 * **Example:** Google-managed gateway
184 * ```typescript
185 * const gateway = yield* GCP.NetworkServices.AgentGateway("Agents", {
186 * googleManaged: { governedAccessPath: "AGENT_TO_ANYWHERE" },
187 * });
188 * ```
189 *
190 * **Example:** Named gateway with labels
191 * ```typescript
192 * const gateway = yield* GCP.NetworkServices.AgentGateway("Agents", {
193 * agentGatewayId: "app-agents",
194 * location: "us-central1",
195 * description: "prod agents",
196 * labels: { env: "prod" },
197 * googleManaged: { governedAccessPath: "CLIENT_TO_AGENT" },
198 * });
199 * ```
200 *
201 * @resource
202 * @category NetworkServices
203 */
204 export const AgentGateway = Resource<AgentGateway>("GCP.NetworkServices.AgentGateway");
205
206 const toGoogleManaged = (
207 value: AgentGatewayGoogleManaged | networkservices.AgentGatewayGoogleManaged | undefined,
208 ): AgentGatewayGoogleManaged | undefined => {
209 if (value === undefined) return undefined;
210 return { governedAccessPath: value.governedAccessPath };
211 };
212
213 const toSelfManaged = (
214 value: AgentGatewaySelfManaged | networkservices.AgentGatewaySelfManaged | undefined,
215 ): AgentGatewaySelfManaged | undefined => {
216 if (value === undefined) return undefined;
217 return { resourceUri: value.resourceUri };
218 };
219
220 const toNetworkConfig = (
221 value: AgentGatewayNetworkConfig | networkservices.AgentGatewayNetworkConfig | undefined,
222 ): AgentGatewayNetworkConfig | undefined => {
223 if (value === undefined) return undefined;
224 return {
225 egress: value.egress ? { networkAttachment: value.egress.networkAttachment } : undefined,
226 dnsPeeringConfig: value.dnsPeeringConfig
227 ? {
228 domains: value.dnsPeeringConfig.domains ?? [],
229 targetProject: value.dnsPeeringConfig.targetProject,
230 targetNetwork: value.dnsPeeringConfig.targetNetwork,
231 }
232 : undefined,
233 };
234 };
235
236 const toCard = (
237 value: networkservices.AgentGatewayAgentGatewayOutputCard | undefined,
238 ): AgentGatewayOutputCard | undefined => {
239 if (value === undefined) return undefined;
240 return {
241 mtlsEndpoint: value.mtlsEndpoint,
242 rootCertificates: value.rootCertificates ?? [],
243 serviceExtensionsServiceAccount: value.serviceExtensionsServiceAccount,
244 };
245 };
246
247 const toAttrs = (gateway: networkservices.AgentGateway, project: string, region: string) => {
248 const name = gateway.name ?? "";
249 const parsed = parseName(name, COLLECTION, region);
250 return {
251 name,
252 agentGatewayId: parsed.id,
253 project: parsed.project || project,
254 location: parsed.location || region,
255 googleManaged: toGoogleManaged(gateway.googleManaged),
256 selfManaged: toSelfManaged(gateway.selfManaged),
257 registries: gateway.registries ?? [],
258 protocols: gateway.protocols ?? [],
259 networkConfig: toNetworkConfig(gateway.networkConfig),
260 agentGatewayCard: toCard(gateway.agentGatewayCard),
261 description: gateway.description,
262 labels: userLabels(gateway.labels),
263 etag: gateway.etag,
264 createTime: gateway.createTime,
265 updateTime: gateway.updateTime,
266 };
267 };
268
269 const getByName = (name: string) =>
270 networkservices
271 .getProjectsLocationsAgentGateways({ name })
272 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
273
274 export const AgentGatewayProvider = () =>
275 Provider.succeed(AgentGateway, {
276 stables: ["name", "agentGatewayId", "project", "location", "createTime"],
277
278 diff: Effect.fn(function* ({ news, olds, output }) {
279 if (!isResolved(news)) return undefined;
280 const env = yield* GcpEnvironment.current;
281 const previousId = olds?.agentGatewayId ?? output?.agentGatewayId;
282 const nextId = news.agentGatewayId
283 ? rfc1035(news.agentGatewayId, "agent-gateway")
284 : previousId;
285 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
286 const nextLocation = normalizeLocation(
287 news.location ?? olds?.location ?? output?.location,
288 env.region,
289 );
290 if (
291 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
292 previousLocation !== nextLocation
293 ) {
294 return { action: "replace" as const };
295 }
296 return undefined;
297 }),
298
299 read: Effect.fn(function* ({ id, olds, output }) {
300 const env = yield* GcpEnvironment.current;
301 const agentGatewayId = yield* toPhysicalId(
302 id,
303 olds?.agentGatewayId,
304 output?.agentGatewayId,
305 "agent-gateway",
306 );
307 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
308 const name = output?.name ?? resourceName(env.project, location, COLLECTION, agentGatewayId);
309 const existing = yield* getByName(name);
310 if (existing === undefined) return undefined;
311 const attrs = toAttrs(existing, env.project, env.region);
312 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
313 }),
314
315 list: () =>
316 Effect.gen(function* () {
317 const env = yield* GcpEnvironment.current;
318 const items = yield* collectPages(
319 networkservices.listProjectsLocationsAgentGateways.pages({
320 parent: parentOf(env.project, "-"),
321 pageSize: 1000,
322 returnPartialSuccess: true,
323 }),
324 (page) => page.agentGateways,
325 );
326 return items
327 .filter((item) => hasAlchemyLabelKeys(item.labels))
328 .map((item) => toAttrs(item, env.project, env.region));
329 }),
330
331 reconcile: Effect.fn(function* ({ id, news, output }) {
332 const env = yield* GcpEnvironment.current;
333 const agentGatewayId = yield* toPhysicalId(
334 id,
335 news.agentGatewayId,
336 output?.agentGatewayId,
337 "agent-gateway",
338 );
339 const location = normalizeLocation(news.location ?? output?.location, env.region);
340 const name = resourceName(env.project, location, COLLECTION, agentGatewayId);
341 const desiredLabels = {
342 ...toLabels(news.labels),
343 ...(yield* createInternalLabels(id)),
344 };
345 const desiredGoogle = toGoogleManaged(news.googleManaged);
346 const desiredSelf = toSelfManaged(news.selfManaged);
347 const desiredNetwork = toNetworkConfig(news.networkConfig);
348 const desiredRegistries = news.registries ?? [];
349 const desiredProtocols = news.protocols ?? [];
350
351 let current = yield* getByName(name);
352
353 if (current === undefined) {
354 const created = yield* networkservices
355 .createProjectsLocationsAgentGateways({
356 parent: parentOf(env.project, location),
357 agentGatewayId,
358 body: {
359 labels: desiredLabels,
360 description: news.description,
361 googleManaged: desiredGoogle,
362 selfManaged: desiredSelf,
363 registries: desiredRegistries,
364 protocols: desiredProtocols,
365 networkConfig: desiredNetwork,
366 },
367 })
368 .pipe(
369 Effect.retry({
370 while: (error) => error._tag === "Conflict",
371 times: 5,
372 schedule: Schedule.spaced("2 seconds"),
373 }),
374 Effect.catchTag("Conflict", () => Effect.undefined),
375 );
376 if (created !== undefined) {
377 yield* waitForOperation(created);
378 }
379 current = yield* waitUntilPresent(getByName(name), name);
380 }
381
382 const observedLabels = tagRecord(current.labels);
383 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
384 const labelsChanged = upsert.length > 0 || removed.length > 0;
385 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
386 const googleChanged = !sameJson(toGoogleManaged(current.googleManaged), desiredGoogle);
387 const selfChanged = !sameJson(toSelfManaged(current.selfManaged), desiredSelf);
388 const registriesChanged = !sameStringList(current.registries, desiredRegistries);
389 const protocolsChanged = !sameStringList(current.protocols, desiredProtocols);
390 const networkChanged = !sameJson(toNetworkConfig(current.networkConfig), desiredNetwork);
391
392 const updateMask = changedFields([
393 ["labels", labelsChanged],
394 ["description", descriptionChanged],
395 ["googleManaged", googleChanged],
396 ["selfManaged", selfChanged],
397 ["registries", registriesChanged],
398 ["protocols", protocolsChanged],
399 ["networkConfig", networkChanged],
400 ]);
401
402 if (updateMask.length > 0) {
403 const operation = yield* networkservices.patchProjectsLocationsAgentGateways({
404 name: current.name ?? name,
405 updateMask: updateMask.join(","),
406 body: {
407 name: current.name ?? name,
408 etag: current.etag,
409 labels: desiredLabels,
410 description: news.description,
411 googleManaged: desiredGoogle,
412 selfManaged: desiredSelf,
413 registries: desiredRegistries,
414 protocols: desiredProtocols,
415 networkConfig: desiredNetwork,
416 },
417 });
418 yield* waitForOperation(operation);
419 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
420 }
421
422 return toAttrs(current, env.project, env.region);
423 }),
424
425 delete: Effect.fn(function* ({ output }) {
426 const operation = yield* networkservices
427 .deleteProjectsLocationsAgentGateways({
428 name: output.name,
429 etag: output.etag,
430 })
431 .pipe(
432 Effect.retry({
433 while: (error) => error._tag === "Conflict",
434 times: 8,
435 schedule: Schedule.spaced("2 seconds"),
436 }),
437 Effect.catchTag("NotFound", () => Effect.undefined),
438 );
439 if (operation !== undefined) {
440 yield* waitForOperation(operation, { notFoundOk: true });
441 }
442 yield* waitUntilGone(getByName(output.name), output.name);
443 }),
444 });