sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ AgentRegistry/ Binding.ts

import * as registry from "@distilled.cloud/gcp/agentregistry_v1";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import { GcpEnvironment } from "../Environment.ts";
import { createInternalLabels } from "../Labels.ts";
import type { Providers } from "../Providers.ts";
import {
  MAX_DISPLAY_NAME_LENGTH,
  encodeOwnership,
  hasOwnershipMarker,
  listBindings,
  locationParent,
  normalizeLocation,
  ownedByAlchemy,
  parseOwnership,
  parseResourceName,
  replaceOnIdentity,
  resourceName,
  retryTransient,
  sameJson,
  sameText,
  toPhysicalId,
  updateMaskOf,
  waitForDeleteOperation,
  waitForOperation,
  waitForVisible,
  waitUntilGone,
} from "./internal.ts";

export type AuthProviderBinding = {
  /**
   * Auth provider resource name
   * `projects/{project}/locations/{location}/connectors/{auth_provider}`
   * or `.../authProviders/{auth_provider}`.
   */
  authProvider: string;
  /**
   * OAuth2 scopes requested from the auth provider.
   */
  scopes?: string[];
  /**
   * Continue URI used to reauthenticate the user and finalize the
   * managed OAuth flow.
   */
  continueUri?: string;
};

export type BindingProps = {
  /**
   * Binding id (the `{binding}` segment of
   * `projects/{project}/locations/{location}/bindings/{binding}`). If
   * omitted, a unique RFC1035 name is generated. Must be 4-63 characters
   * matching `^[a-z]([a-z0-9-]{0,61}[a-z0-9])?

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/gcp/src/AgentRegistry/Binding.ts at main · sailfork/t3code-github · Sailfork
	
		
. Immutable — changing * it replaces the binding. */ bindingId?: string; /** * Location of the binding (`us-central1`, `global`, …). Multi-region * `us` and `eu` are not supported. Immutable — changing it replaces * the binding. * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) */ location?: string; /** * URN of the source agent (`urn:agent:{publisher}:{namespace}:{name}`). * Immutable — changing it replaces the binding. */ sourceIdentifier: string; /** * URN of the target agent, MCP server, or endpoint * (`urn:agent:…`, `urn:mcp:…`, or `urn:endpoint:…`). Immutable — * changing it replaces the binding. */ targetIdentifier: string; /** * Human-readable name. Max 63 characters. Defaults to the binding id. */ displayName?: string; /** * Human-readable description (max 2048 characters). Bindings have no * labels field, so Alchemy stamps ownership into a `[alchemy …]` * prefix and strips it from attributes. */ description?: string; /** * Optional auth-provider binding for delegated permissions. */ authProviderBinding?: AuthProviderBinding; }; export type Binding = Resource< "GCP.AgentRegistry.Binding", BindingProps, { /** Full resource name `projects/{project}/locations/{location}/bindings/{binding}`. */ name: string; /** Binding id (last path segment). */ bindingId: string; /** Project id. */ project: string; /** Location id of the resource. */ location: string; /** Source agent URN. */ sourceIdentifier: string | undefined; /** Target agent, MCP server, or endpoint URN. */ targetIdentifier: string | undefined; /** Display name. */ displayName: string | undefined; /** User description with the Alchemy ownership prefix stripped. */ description: string | undefined; /** Auth-provider binding, if set. */ authProviderBinding: AuthProviderBinding | undefined; /** RFC3339 creation timestamp. */ createTime: string | undefined; /** RFC3339 last-update timestamp. */ updateTime: string | undefined; }, never, Providers >; /** * An Agent Registry binding connecting a source agent to a target * agent, MCP server, or endpoint. * * Create, update, and delete are long-running operations. `bindingId`, * `location`, `sourceIdentifier`, and `targetIdentifier` replace the * resource. Display name, description, and auth-provider settings * update in place. Bindings have no labels API, so Alchemy stamps * ownership into `description` so `list` / nuke can find them. * * ### Creating a Binding * **Example:** Generated name * ```typescript * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", { * sourceIdentifier: * "urn:agent:projects-123:projects:123:locations:us-central1:agentregistry:source", * targetIdentifier: * "urn:mcp:projects-123:projects:123:locations:us-central1:agentregistry:tools", * }); * ``` * * **Example:** Named binding with a description * ```typescript * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", { * bindingId: "orchestrator-tools", * location: "us-central1", * displayName: "orchestrator tools", * description: "routes the orchestrator to the tools MCP server", * sourceIdentifier: source.agentId, * targetIdentifier: tools.mcpServerId, * }); * ``` * * ### Updating a Binding * Change props on the same logical id; the engine keeps the physical id. * * **Example:** Display name and description * ```typescript * const binding = yield* GCP.AgentRegistry.Binding("Orchestrator", { * sourceIdentifier: source.agentId, * targetIdentifier: tools.mcpServerId, * displayName: "orchestrator tools v2", * description: "updated routing", * }); * ``` * * @resource * @category AgentRegistry */ export const Binding = Resource<Binding>("GCP.AgentRegistry.Binding"); export class BindingNotResolved extends Data.TaggedError("GCP.AgentRegistry.BindingNotResolved")<{ resourceName: string; }> {} const COLLECTION = "bindings"; const toAuth = ( binding: registry.AuthProviderBinding | undefined, ): AuthProviderBinding | undefined => { if (binding === undefined) return undefined; const authProvider = binding.authProvider; if (authProvider === undefined || authProvider.length === 0) { return undefined; } return { authProvider, scopes: binding.scopes, continueUri: binding.continueUri, }; }; const desiredAuth = ( binding: AuthProviderBinding | undefined, ): registry.AuthProviderBinding | undefined => { if (binding === undefined) return undefined; return { authProvider: binding.authProvider, scopes: binding.scopes, continueUri: binding.continueUri, }; }; const authKey = (binding: AuthProviderBinding | registry.AuthProviderBinding | undefined) => binding === undefined ? undefined : { authProvider: binding.authProvider, continueUri: binding.continueUri, scopes: [...(binding.scopes ?? [])].slice().sort(), }; const toAttrs = (item: registry.Binding, project: string, location: string) => { const name = item.name ?? ""; const parsed = parseResourceName(name, COLLECTION); const owned = parseOwnership(item.description); return { name, bindingId: parsed.id, project: parsed.project || project, location: parsed.location || location, sourceIdentifier: item.source?.identifier, targetIdentifier: item.target?.identifier, displayName: item.displayName, description: owned.description, authProviderBinding: toAuth(item.authProviderBinding), createTime: item.createTime, updateTime: item.updateTime, }; }; const getByName = (name: string) => name.length === 0 ? Effect.undefined : registry .getProjectsLocationsBindings({ name }) .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); const displayNameOf = (news: BindingProps, bindingId: string) => (news.displayName ?? bindingId).slice(0, MAX_DISPLAY_NAME_LENGTH); export const BindingProvider = () => Provider.succeed(Binding, { stables: ["name", "bindingId", "project", "location", "createTime"], diff: Effect.fn(function* ({ news, olds, output }) { if (!isResolved(news)) return undefined; const env = yield* GcpEnvironment.current; const previousSource = olds?.sourceIdentifier ?? output?.sourceIdentifier; const previousTarget = olds?.targetIdentifier ?? output?.targetIdentifier; return replaceOnIdentity({ previousId: olds?.bindingId ?? output?.bindingId, nextId: news.bindingId ?? olds?.bindingId ?? output?.bindingId, previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region), nextLocation: normalizeLocation( news.location ?? olds?.location ?? output?.location, env.region, ), extra: (previousSource !== undefined && previousSource !== news.sourceIdentifier) || (previousTarget !== undefined && previousTarget !== news.targetIdentifier), }); }), read: Effect.fn(function* ({ id, olds, output }) { const env = yield* GcpEnvironment.current; const location = normalizeLocation(olds?.location ?? output?.location, env.region); const bindingId = yield* toPhysicalId(id, olds?.bindingId, output?.bindingId); const name = output?.name ?? resourceName(env.project, location, COLLECTION, bindingId); const existing = yield* getByName(name); if (existing === undefined) return undefined; const attrs = toAttrs(existing, env.project, location); return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs); }), list: () => Effect.gen(function* () { const env = yield* GcpEnvironment.current; const items = yield* listBindings(env.project, env.region); return items .filter((item) => hasOwnershipMarker(item.description)) .map((item) => toAttrs(item, env.project, env.region)); }), reconcile: Effect.fn(function* ({ id, news, output }) { const env = yield* GcpEnvironment.current; const location = normalizeLocation(news.location ?? output?.location, env.region); const bindingId = yield* toPhysicalId(id, news.bindingId, output?.bindingId); const name = resourceName(env.project, location, COLLECTION, bindingId); const parent = locationParent(env.project, location); const ownership = yield* createInternalLabels(id); const description = encodeOwnership(ownership, news.description); const displayName = displayNameOf(news, bindingId); const source = { identifier: news.sourceIdentifier }; const target = { identifier: news.targetIdentifier }; const authProviderBinding = desiredAuth(news.authProviderBinding); let current = yield* getByName(output?.name ?? name); if (current === undefined) { const created = yield* retryTransient( registry.createProjectsLocationsBindings({ parent, bindingId, body: { source, target, displayName, description, authProviderBinding, }, }), ).pipe(Effect.catchTag("Conflict", () => Effect.undefined)); if (created !== undefined) { // ALREADY_EXISTS (code 6): a concurrent create won the race. yield* waitForOperation(created).pipe( Effect.catchIf( (error) => error._tag === "GCP.OperationFailed" && error.code === 6, () => Effect.void, ), ); } current = yield* waitForVisible(getByName(name)); } if (current === undefined) { return yield* new BindingNotResolved({ resourceName: name }); } const currentName = current.name ?? name; const displayChanged = !sameText(current.displayName, displayName); const descriptionChanged = !sameText(current.description, description); const sourceChanged = !sameText(current.source?.identifier, news.sourceIdentifier); const targetChanged = !sameText(current.target?.identifier, news.targetIdentifier); const authChanged = !sameJson( authKey(current.authProviderBinding), authKey(news.authProviderBinding), ); const mask = updateMaskOf( displayChanged ? "display_name" : undefined, descriptionChanged ? "description" : undefined, sourceChanged ? "source" : undefined, targetChanged ? "target" : undefined, authChanged ? "auth_provider_binding" : undefined, ); if (mask.length > 0) { const operation = yield* retryTransient( registry.patchProjectsLocationsBindings({ name: currentName, updateMask: mask, body: { name: currentName, displayName, description, source, target, authProviderBinding, }, }), ); yield* waitForOperation(operation); current = (yield* waitForVisible(getByName(currentName))) ?? current; } return toAttrs(current, env.project, location); }), delete: Effect.fn(function* ({ output }) { if (!output.name) return; const deleted = yield* retryTransient( registry.deleteProjectsLocationsBindings({ name: output.name }), ).pipe(Effect.catchTag("NotFound", () => Effect.undefined)); if (deleted !== undefined) { yield* waitForDeleteOperation(deleted); } yield* waitUntilGone(getByName(output.name)); }), });
.repos/alchemy-effect/packages/gcp/src/AgentRegistry/Binding.ts at main · sailfork/t3code-github · Sailfork
. Immutable — changing\n * it replaces the binding.\n */\n bindingId?: string;\n /**\n * Location of the binding (`us-central1`, `global`, …). Multi-region\n * `us` and `eu` are not supported. Immutable — changing it replaces\n * the binding.\n * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)\n */\n location?: string;\n /**\n * URN of the source agent (`urn:agent:{publisher}:{namespace}:{name}`).\n * Immutable — changing it replaces the binding.\n */\n sourceIdentifier: string;\n /**\n * URN of the target agent, MCP server, or endpoint\n * (`urn:agent:…`, `urn:mcp:…`, or `urn:endpoint:…`). Immutable —\n * changing it replaces the binding.\n */\n targetIdentifier: string;\n /**\n * Human-readable name. Max 63 characters. Defaults to the binding id.\n */\n displayName?: string;\n /**\n * Human-readable description (max 2048 characters). Bindings have no\n * labels field, so Alchemy stamps ownership into a `[alchemy …]`\n * prefix and strips it from attributes.\n */\n description?: string;\n /**\n * Optional auth-provider binding for delegated permissions.\n */\n authProviderBinding?: AuthProviderBinding;\n};\n\nexport type Binding = Resource\u003c\n \"GCP.AgentRegistry.Binding\",\n BindingProps,\n {\n /** Full resource name `projects/{project}/locations/{location}/bindings/{binding}`. */\n name: string;\n /** Binding id (last path segment). */\n bindingId: string;\n /** Project id. */\n project: string;\n /** Location id of the resource. */\n location: string;\n /** Source agent URN. */\n sourceIdentifier: string | undefined;\n /** Target agent, MCP server, or endpoint URN. */\n targetIdentifier: string | undefined;\n /** Display name. */\n displayName: string | undefined;\n /** User description with the Alchemy ownership prefix stripped. */\n description: string | undefined;\n /** Auth-provider binding, if set. */\n authProviderBinding: AuthProviderBinding | undefined;\n /** RFC3339 creation timestamp. */\n createTime: string | undefined;\n /** RFC3339 last-update timestamp. */\n updateTime: string | undefined;\n },\n never,\n Providers\n>;\n\n/**\n * An Agent Registry binding connecting a source agent to a target\n * agent, MCP server, or endpoint.\n *\n * Create, update, and delete are long-running operations. `bindingId`,\n * `location`, `sourceIdentifier`, and `targetIdentifier` replace the\n * resource. Display name, description, and auth-provider settings\n * update in place. Bindings have no labels API, so Alchemy stamps\n * ownership into `description` so `list` / nuke can find them.\n *\n * ### Creating a Binding\n * **Example:** Generated name\n * ```typescript\n * const binding = yield* GCP.AgentRegistry.Binding(\"Orchestrator\", {\n * sourceIdentifier:\n * \"urn:agent:projects-123:projects:123:locations:us-central1:agentregistry:source\",\n * targetIdentifier:\n * \"urn:mcp:projects-123:projects:123:locations:us-central1:agentregistry:tools\",\n * });\n * ```\n *\n * **Example:** Named binding with a description\n * ```typescript\n * const binding = yield* GCP.AgentRegistry.Binding(\"Orchestrator\", {\n * bindingId: \"orchestrator-tools\",\n * location: \"us-central1\",\n * displayName: \"orchestrator tools\",\n * description: \"routes the orchestrator to the tools MCP server\",\n * sourceIdentifier: source.agentId,\n * targetIdentifier: tools.mcpServerId,\n * });\n * ```\n *\n * ### Updating a Binding\n * Change props on the same logical id; the engine keeps the physical id.\n *\n * **Example:** Display name and description\n * ```typescript\n * const binding = yield* GCP.AgentRegistry.Binding(\"Orchestrator\", {\n * sourceIdentifier: source.agentId,\n * targetIdentifier: tools.mcpServerId,\n * displayName: \"orchestrator tools v2\",\n * description: \"updated routing\",\n * });\n * ```\n *\n * @resource\n * @category AgentRegistry\n */\nexport const Binding = Resource\u003cBinding>(\"GCP.AgentRegistry.Binding\");\n\nexport class BindingNotResolved extends Data.TaggedError(\"GCP.AgentRegistry.BindingNotResolved\")\u003c{\n resourceName: string;\n}> {}\n\nconst COLLECTION = \"bindings\";\n\nconst toAuth = (\n binding: registry.AuthProviderBinding | undefined,\n): AuthProviderBinding | undefined => {\n if (binding === undefined) return undefined;\n const authProvider = binding.authProvider;\n if (authProvider === undefined || authProvider.length === 0) {\n return undefined;\n }\n return {\n authProvider,\n scopes: binding.scopes,\n continueUri: binding.continueUri,\n };\n};\n\nconst desiredAuth = (\n binding: AuthProviderBinding | undefined,\n): registry.AuthProviderBinding | undefined => {\n if (binding === undefined) return undefined;\n return {\n authProvider: binding.authProvider,\n scopes: binding.scopes,\n continueUri: binding.continueUri,\n };\n};\n\nconst authKey = (binding: AuthProviderBinding | registry.AuthProviderBinding | undefined) =>\n binding === undefined\n ? undefined\n : {\n authProvider: binding.authProvider,\n continueUri: binding.continueUri,\n scopes: [...(binding.scopes ?? [])].slice().sort(),\n };\n\nconst toAttrs = (item: registry.Binding, project: string, location: string) => {\n const name = item.name ?? \"\";\n const parsed = parseResourceName(name, COLLECTION);\n const owned = parseOwnership(item.description);\n return {\n name,\n bindingId: parsed.id,\n project: parsed.project || project,\n location: parsed.location || location,\n sourceIdentifier: item.source?.identifier,\n targetIdentifier: item.target?.identifier,\n displayName: item.displayName,\n description: owned.description,\n authProviderBinding: toAuth(item.authProviderBinding),\n createTime: item.createTime,\n updateTime: item.updateTime,\n };\n};\n\nconst getByName = (name: string) =>\n name.length === 0\n ? Effect.undefined\n : registry\n .getProjectsLocationsBindings({ name })\n .pipe(Effect.catchTag(\"NotFound\", () => Effect.undefined));\n\nconst displayNameOf = (news: BindingProps, bindingId: string) =>\n (news.displayName ?? bindingId).slice(0, MAX_DISPLAY_NAME_LENGTH);\n\nexport const BindingProvider = () =>\n Provider.succeed(Binding, {\n stables: [\"name\", \"bindingId\", \"project\", \"location\", \"createTime\"],\n\n diff: Effect.fn(function* ({ news, olds, output }) {\n if (!isResolved(news)) return undefined;\n const env = yield* GcpEnvironment.current;\n const previousSource = olds?.sourceIdentifier ?? output?.sourceIdentifier;\n const previousTarget = olds?.targetIdentifier ?? output?.targetIdentifier;\n return replaceOnIdentity({\n previousId: olds?.bindingId ?? output?.bindingId,\n nextId: news.bindingId ?? olds?.bindingId ?? output?.bindingId,\n previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),\n nextLocation: normalizeLocation(\n news.location ?? olds?.location ?? output?.location,\n env.region,\n ),\n extra:\n (previousSource !== undefined && previousSource !== news.sourceIdentifier) ||\n (previousTarget !== undefined && previousTarget !== news.targetIdentifier),\n });\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const env = yield* GcpEnvironment.current;\n const location = normalizeLocation(olds?.location ?? output?.location, env.region);\n const bindingId = yield* toPhysicalId(id, olds?.bindingId, output?.bindingId);\n const name = output?.name ?? resourceName(env.project, location, COLLECTION, bindingId);\n const existing = yield* getByName(name);\n if (existing === undefined) return undefined;\n const attrs = toAttrs(existing, env.project, location);\n return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);\n }),\n\n list: () =>\n Effect.gen(function* () {\n const env = yield* GcpEnvironment.current;\n const items = yield* listBindings(env.project, env.region);\n return items\n .filter((item) => hasOwnershipMarker(item.description))\n .map((item) => toAttrs(item, env.project, env.region));\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output }) {\n const env = yield* GcpEnvironment.current;\n const location = normalizeLocation(news.location ?? output?.location, env.region);\n const bindingId = yield* toPhysicalId(id, news.bindingId, output?.bindingId);\n const name = resourceName(env.project, location, COLLECTION, bindingId);\n const parent = locationParent(env.project, location);\n const ownership = yield* createInternalLabels(id);\n const description = encodeOwnership(ownership, news.description);\n const displayName = displayNameOf(news, bindingId);\n const source = { identifier: news.sourceIdentifier };\n const target = { identifier: news.targetIdentifier };\n const authProviderBinding = desiredAuth(news.authProviderBinding);\n\n let current = yield* getByName(output?.name ?? name);\n\n if (current === undefined) {\n const created = yield* retryTransient(\n registry.createProjectsLocationsBindings({\n parent,\n bindingId,\n body: {\n source,\n target,\n displayName,\n description,\n authProviderBinding,\n },\n }),\n ).pipe(Effect.catchTag(\"Conflict\", () => Effect.undefined));\n if (created !== undefined) {\n // ALREADY_EXISTS (code 6): a concurrent create won the race.\n yield* waitForOperation(created).pipe(\n Effect.catchIf(\n (error) => error._tag === \"GCP.OperationFailed\" && error.code === 6,\n () => Effect.void,\n ),\n );\n }\n current = yield* waitForVisible(getByName(name));\n }\n\n if (current === undefined) {\n return yield* new BindingNotResolved({ resourceName: name });\n }\n\n const currentName = current.name ?? name;\n const displayChanged = !sameText(current.displayName, displayName);\n const descriptionChanged = !sameText(current.description, description);\n const sourceChanged = !sameText(current.source?.identifier, news.sourceIdentifier);\n const targetChanged = !sameText(current.target?.identifier, news.targetIdentifier);\n const authChanged = !sameJson(\n authKey(current.authProviderBinding),\n authKey(news.authProviderBinding),\n );\n\n const mask = updateMaskOf(\n displayChanged ? \"display_name\" : undefined,\n descriptionChanged ? \"description\" : undefined,\n sourceChanged ? \"source\" : undefined,\n targetChanged ? \"target\" : undefined,\n authChanged ? \"auth_provider_binding\" : undefined,\n );\n\n if (mask.length > 0) {\n const operation = yield* retryTransient(\n registry.patchProjectsLocationsBindings({\n name: currentName,\n updateMask: mask,\n body: {\n name: currentName,\n displayName,\n description,\n source,\n target,\n authProviderBinding,\n },\n }),\n );\n yield* waitForOperation(operation);\n current = (yield* waitForVisible(getByName(currentName))) ?? current;\n }\n\n return toAttrs(current, env.project, location);\n }),\n\n delete: Effect.fn(function* ({ output }) {\n if (!output.name) return;\n const deleted = yield* retryTransient(\n registry.deleteProjectsLocationsBindings({ name: output.name }),\n ).pipe(Effect.catchTag(\"NotFound\", () => Effect.undefined));\n if (deleted !== undefined) {\n yield* waitForDeleteOperation(deleted);\n }\n yield* waitUntilGone(getByName(output.name));\n }),\n });\n","preview":null,"history":null,"version":"7356379f2c1b01b9376f9af5dfb3323fce04508a"},"/_session?shell=1":null}