@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 385 lines 13.1 KB
Raw
1 import * as registry from "@distilled.cloud/gcp/agentregistry_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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 MAX_DISPLAY_NAME_LENGTH,
13 encodeOwnership,
14 hasOwnershipMarker,
15 listBindings,
16 locationParent,
17 normalizeLocation,
18 ownedByAlchemy,
19 parseOwnership,
20 parseResourceName,
21 replaceOnIdentity,
22 resourceName,
23 retryTransient,
24 sameJson,
25 sameText,
26 toPhysicalId,
27 updateMaskOf,
28 waitForDeleteOperation,
29 waitForOperation,
30 waitForVisible,
31 waitUntilGone,
32 } from "./internal.ts";
33
34 export type AuthProviderBinding = {
35 /**
36 * Auth provider resource name
37 * `projects/{project}/locations/{location}/connectors/{auth_provider}`
38 * or `.../authProviders/{auth_provider}`.
39 */
40 authProvider: string;
41 /**
42 * OAuth2 scopes requested from the auth provider.
43 */
44 scopes?: string[];
45 /**
46 * Continue URI used to reauthenticate the user and finalize the
47 * managed OAuth flow.
48 */
49 continueUri?: string;
50 };
51
52 export type BindingProps = {
53 /**
54 * Binding id (the `{binding}` segment of
55 * `projects/{project}/locations/{location}/bindings/{binding}`). If
56 * omitted, a unique RFC1035 name is generated. Must be 4-63 characters
57 * matching `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$`. Immutable — changing
58 * it replaces the binding.
59 */
60 bindingId?: string;
61 /**
62 * Location of the binding (`us-central1`, `global`, …). Multi-region
63 * `us` and `eu` are not supported. Immutable — changing it replaces
64 * the binding.
65 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
66 */
67 location?: string;
68 /**
69 * URN of the source agent (`urn:agent:{publisher}:{namespace}:{name}`).
70 * Immutable — changing it replaces the binding.
71 */
72 sourceIdentifier: string;
73 /**
74 * URN of the target agent, MCP server, or endpoint
75 * (`urn:agent:…`, `urn:mcp:…`, or `urn:endpoint:…`). Immutable —
76 * changing it replaces the binding.
77 */
78 targetIdentifier: string;
79 /**
80 * Human-readable name. Max 63 characters. Defaults to the binding id.
81 */
82 displayName?: string;
83 /**
84 * Human-readable description (max 2048 characters). Bindings have no
85 * labels field, so Alchemy stamps ownership into a `[alchemy …]`
86 * prefix and strips it from attributes.
87 */
88 description?: string;
89 /**
90 * Optional auth-provider binding for delegated permissions.
91 */
92 authProviderBinding?: AuthProviderBinding;
93 };
94
95 export type Binding = Resource<
96 "GCP.AgentRegistry.Binding",
97 BindingProps,
98 {
99 /** Full resource name `projects/{project}/locations/{location}/bindings/{binding}`. */
100 name: string;
101 /** Binding id (last path segment). */
102 bindingId: string;
103 /** Project id. */
104 project: string;
105 /** Location id of the resource. */
106 location: string;
107 /** Source agent URN. */
108 sourceIdentifier: string | undefined;
109 /** Target agent, MCP server, or endpoint URN. */
110 targetIdentifier: string | undefined;
111 /** Display name. */
112 displayName: string | undefined;
113 /** User description with the Alchemy ownership prefix stripped. */
114 description: string | undefined;
115 /** Auth-provider binding, if set. */
116 authProviderBinding: AuthProviderBinding | undefined;
117 /** RFC3339 creation timestamp. */
118 createTime: string | undefined;
119 /** RFC3339 last-update timestamp. */
120 updateTime: string | undefined;
121 },
122 never,
123 Providers
124 >;
125
126 /**
127 * An Agent Registry binding connecting a source agent to a target
128 * agent, MCP server, or endpoint.
129 *
130 * Create, update, and delete are long-running operations. `bindingId`,
131 * `location`, `sourceIdentifier`, and `targetIdentifier` replace the
132 * resource. Display name, description, and auth-provider settings
133 * update in place. Bindings have no labels API, so Alchemy stamps
134 * ownership into `description` so `list` / nuke can find them.
135 *
136 * ### Creating a Binding
137 * **Example:** Generated name
138 * ```typescript
139 * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", {
140 * sourceIdentifier:
141 * "urn:agent:projects-123:projects:123:locations:us-central1:agentregistry:source",
142 * targetIdentifier:
143 * "urn:mcp:projects-123:projects:123:locations:us-central1:agentregistry:tools",
144 * });
145 * ```
146 *
147 * **Example:** Named binding with a description
148 * ```typescript
149 * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", {
150 * bindingId: "orchestrator-tools",
151 * location: "us-central1",
152 * displayName: "orchestrator tools",
153 * description: "routes the orchestrator to the tools MCP server",
154 * sourceIdentifier: source.agentId,
155 * targetIdentifier: tools.mcpServerId,
156 * });
157 * ```
158 *
159 * ### Updating a Binding
160 * Change props on the same logical id; the engine keeps the physical id.
161 *
162 * **Example:** Display name and description
163 * ```typescript
164 * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", {
165 * sourceIdentifier: source.agentId,
166 * targetIdentifier: tools.mcpServerId,
167 * displayName: "orchestrator tools v2",
168 * description: "updated routing",
169 * });
170 * ```
171 *
172 * @resource
173 * @category AgentRegistry
174 */
175 export const Binding = Resource<Binding>("GCP.AgentRegistry.Binding");
176
177 export class BindingNotResolved extends Data.TaggedError("GCP.AgentRegistry.BindingNotResolved")<{
178 resourceName: string;
179 }> {}
180
181 const COLLECTION = "bindings";
182
183 const toAuth = (
184 binding: registry.AuthProviderBinding | undefined,
185 ): AuthProviderBinding | undefined => {
186 if (binding === undefined) return undefined;
187 const authProvider = binding.authProvider;
188 if (authProvider === undefined || authProvider.length === 0) {
189 return undefined;
190 }
191 return {
192 authProvider,
193 scopes: binding.scopes,
194 continueUri: binding.continueUri,
195 };
196 };
197
198 const desiredAuth = (
199 binding: AuthProviderBinding | undefined,
200 ): registry.AuthProviderBinding | undefined => {
201 if (binding === undefined) return undefined;
202 return {
203 authProvider: binding.authProvider,
204 scopes: binding.scopes,
205 continueUri: binding.continueUri,
206 };
207 };
208
209 const authKey = (binding: AuthProviderBinding | registry.AuthProviderBinding | undefined) =>
210 binding === undefined
211 ? undefined
212 : {
213 authProvider: binding.authProvider,
214 continueUri: binding.continueUri,
215 scopes: [...(binding.scopes ?? [])].slice().sort(),
216 };
217
218 const toAttrs = (item: registry.Binding, project: string, location: string) => {
219 const name = item.name ?? "";
220 const parsed = parseResourceName(name, COLLECTION);
221 const owned = parseOwnership(item.description);
222 return {
223 name,
224 bindingId: parsed.id,
225 project: parsed.project || project,
226 location: parsed.location || location,
227 sourceIdentifier: item.source?.identifier,
228 targetIdentifier: item.target?.identifier,
229 displayName: item.displayName,
230 description: owned.description,
231 authProviderBinding: toAuth(item.authProviderBinding),
232 createTime: item.createTime,
233 updateTime: item.updateTime,
234 };
235 };
236
237 const getByName = (name: string) =>
238 name.length === 0
239 ? Effect.undefined
240 : registry
241 .getProjectsLocationsBindings({ name })
242 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
243
244 const displayNameOf = (news: BindingProps, bindingId: string) =>
245 (news.displayName ?? bindingId).slice(0, MAX_DISPLAY_NAME_LENGTH);
246
247 export const BindingProvider = () =>
248 Provider.succeed(Binding, {
249 stables: ["name", "bindingId", "project", "location", "createTime"],
250
251 diff: Effect.fn(function* ({ news, olds, output }) {
252 if (!isResolved(news)) return undefined;
253 const env = yield* GcpEnvironment.current;
254 const previousSource = olds?.sourceIdentifier ?? output?.sourceIdentifier;
255 const previousTarget = olds?.targetIdentifier ?? output?.targetIdentifier;
256 return replaceOnIdentity({
257 previousId: olds?.bindingId ?? output?.bindingId,
258 nextId: news.bindingId ?? olds?.bindingId ?? output?.bindingId,
259 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
260 nextLocation: normalizeLocation(
261 news.location ?? olds?.location ?? output?.location,
262 env.region,
263 ),
264 extra:
265 (previousSource !== undefined && previousSource !== news.sourceIdentifier) ||
266 (previousTarget !== undefined && previousTarget !== news.targetIdentifier),
267 });
268 }),
269
270 read: Effect.fn(function* ({ id, olds, output }) {
271 const env = yield* GcpEnvironment.current;
272 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
273 const bindingId = yield* toPhysicalId(id, olds?.bindingId, output?.bindingId);
274 const name = output?.name ?? resourceName(env.project, location, COLLECTION, bindingId);
275 const existing = yield* getByName(name);
276 if (existing === undefined) return undefined;
277 const attrs = toAttrs(existing, env.project, location);
278 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
279 }),
280
281 list: () =>
282 Effect.gen(function* () {
283 const env = yield* GcpEnvironment.current;
284 const items = yield* listBindings(env.project, env.region);
285 return items
286 .filter((item) => hasOwnershipMarker(item.description))
287 .map((item) => toAttrs(item, env.project, env.region));
288 }),
289
290 reconcile: Effect.fn(function* ({ id, news, output }) {
291 const env = yield* GcpEnvironment.current;
292 const location = normalizeLocation(news.location ?? output?.location, env.region);
293 const bindingId = yield* toPhysicalId(id, news.bindingId, output?.bindingId);
294 const name = resourceName(env.project, location, COLLECTION, bindingId);
295 const parent = locationParent(env.project, location);
296 const ownership = yield* createInternalLabels(id);
297 const description = encodeOwnership(ownership, news.description);
298 const displayName = displayNameOf(news, bindingId);
299 const source = { identifier: news.sourceIdentifier };
300 const target = { identifier: news.targetIdentifier };
301 const authProviderBinding = desiredAuth(news.authProviderBinding);
302
303 let current = yield* getByName(output?.name ?? name);
304
305 if (current === undefined) {
306 const created = yield* retryTransient(
307 registry.createProjectsLocationsBindings({
308 parent,
309 bindingId,
310 body: {
311 source,
312 target,
313 displayName,
314 description,
315 authProviderBinding,
316 },
317 }),
318 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
319 if (created !== undefined) {
320 // ALREADY_EXISTS (code 6): a concurrent create won the race.
321 yield* waitForOperation(created).pipe(
322 Effect.catchIf(
323 (error) => error._tag === "GCP.OperationFailed" && error.code === 6,
324 () => Effect.void,
325 ),
326 );
327 }
328 current = yield* waitForVisible(getByName(name));
329 }
330
331 if (current === undefined) {
332 return yield* new BindingNotResolved({ resourceName: name });
333 }
334
335 const currentName = current.name ?? name;
336 const displayChanged = !sameText(current.displayName, displayName);
337 const descriptionChanged = !sameText(current.description, description);
338 const sourceChanged = !sameText(current.source?.identifier, news.sourceIdentifier);
339 const targetChanged = !sameText(current.target?.identifier, news.targetIdentifier);
340 const authChanged = !sameJson(
341 authKey(current.authProviderBinding),
342 authKey(news.authProviderBinding),
343 );
344
345 const mask = updateMaskOf(
346 displayChanged ? "display_name" : undefined,
347 descriptionChanged ? "description" : undefined,
348 sourceChanged ? "source" : undefined,
349 targetChanged ? "target" : undefined,
350 authChanged ? "auth_provider_binding" : undefined,
351 );
352
353 if (mask.length > 0) {
354 const operation = yield* retryTransient(
355 registry.patchProjectsLocationsBindings({
356 name: currentName,
357 updateMask: mask,
358 body: {
359 name: currentName,
360 displayName,
361 description,
362 source,
363 target,
364 authProviderBinding,
365 },
366 }),
367 );
368 yield* waitForOperation(operation);
369 current = (yield* waitForVisible(getByName(currentName))) ?? current;
370 }
371
372 return toAttrs(current, env.project, location);
373 }),
374
375 delete: Effect.fn(function* ({ output }) {
376 if (!output.name) return;
377 const deleted = yield* retryTransient(
378 registry.deleteProjectsLocationsBindings({ name: output.name }),
379 ).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
380 if (deleted !== undefined) {
381 yield* waitForDeleteOperation(deleted);
382 }
383 yield* waitUntilGone(getByName(output.name));
384 }),
385 });