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

main
ts 343 lines 11.7 KB
Raw
1 import * as aiplatform from "@distilled.cloud/gcp/aiplatform_v1";
2 import { unownedUnlessPrevious } 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 * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import { listLocations } from "./names.ts";
14 import { resourceNameFromOperation, waitForOperation } from "./operations.ts";
15 import {
16 encodeOwnership,
17 hasOwnershipMarker,
18 lastSegment,
19 locationOf,
20 locationParent,
21 ownedByAlchemy,
22 parseOwnership,
23 toResourceId,
24 } from "./ownership.ts";
25
26 export type McpTool = {
27 /**
28 * MCP server resource name
29 * (`projects/{project}/locations/{location}/mcpServers/{mcp_server}`).
30 */
31 mcpServer?: string;
32 /** MCP tool resource names. Omit to apply to every tool on the server. */
33 tools?: string[];
34 };
35
36 export type SemanticGovernancePolicyProps = {
37 /**
38 * Region (`us-central1`, …). Immutable — changing it replaces the
39 * policy.
40 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
41 */
42 location?: string;
43 /**
44 * Policy id (the `{semantic_governance_policy}` segment). If omitted, a
45 * unique id is generated. Immutable.
46 */
47 semanticGovernancePolicyId?: string;
48 /**
49 * User-facing display name.
50 */
51 displayName?: string;
52 /**
53 * Human-readable description. SemanticGovernancePolicy has no labels
54 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix.
55 */
56 description?: string;
57 /**
58 * Agent Registry resource name affected by this policy.
59 */
60 agent: string;
61 /**
62 * Natural-language constraint enforced by the policy.
63 */
64 naturalLanguageConstraint: string;
65 /**
66 * Optional MCP tools the policy applies to.
67 */
68 mcpTools?: McpTool[];
69 };
70
71 export type SemanticGovernancePolicy = Resource<
72 "GCP.AIPlatform.SemanticGovernancePolicy",
73 SemanticGovernancePolicyProps,
74 {
75 /** Full resource name. */
76 name: string;
77 /** Policy id (last path segment). */
78 semanticGovernancePolicyId: string;
79 /** Region id. */
80 location: string;
81 /** Project id. */
82 project: string;
83 /** User-facing display name. */
84 displayName: string | undefined;
85 /** User description with the Alchemy ownership prefix stripped. */
86 description: string | undefined;
87 /** Agent Registry resource name. */
88 agent: string | undefined;
89 /** Natural-language constraint. */
90 naturalLanguageConstraint: string | undefined;
91 /** Agent identity used by the PDP. */
92 agentIdentity: string | undefined;
93 /** MCP tools covered by the policy. */
94 mcpTools: McpTool[];
95 /** RFC3339 creation timestamp. */
96 createTime: string | undefined;
97 /** RFC3339 last-update timestamp. */
98 updateTime: string | undefined;
99 },
100 never,
101 Providers
102 >;
103
104 /**
105 * A Vertex AI SemanticGovernancePolicy constraining an Agent's tools.
106 *
107 * Policies have no labels field — Alchemy stamps ownership into the
108 * description. Location and policy id are immutable.
109 *
110 * ### Creating a Policy
111 * **Example:** Natural-language constraint on an agent
112 * ```typescript
113 * const policy = yield* GCP.AIPlatform.SemanticGovernancePolicy("Safety", {
114 * agent: "projects/my-project/locations/us-central1/agents/support",
115 * naturalLanguageConstraint: "Never share customer PII.",
116 * });
117 * ```
118 *
119 * @resource
120 * @category AIPlatform
121 */
122 export const SemanticGovernancePolicy = Resource<SemanticGovernancePolicy>(
123 "GCP.AIPlatform.SemanticGovernancePolicy",
124 );
125
126 export class SemanticGovernancePolicyNotResolved extends Data.TaggedError(
127 "GCP.AIPlatform.SemanticGovernancePolicyNotResolved",
128 )<{
129 resourceName: string;
130 }> {}
131
132 const resourceName = (parent: string, policyId: string) =>
133 `${parent}/semanticGovernancePolicies/${policyId}`;
134
135 const toAttrs = (
136 policy: aiplatform.GoogleCloudAiplatformV1SemanticGovernancePolicy,
137 project: string,
138 ) => {
139 const name = policy.name ?? "";
140 const parsed = parseOwnership(policy.description);
141 return {
142 name,
143 semanticGovernancePolicyId: lastSegment(name),
144 location: locationOf(name),
145 project,
146 displayName: policy.displayName,
147 description: parsed.text,
148 agent: policy.agent,
149 naturalLanguageConstraint: policy.naturalLanguageConstraint,
150 agentIdentity: policy.agentIdentity,
151 mcpTools: (policy.mcpTools ?? []).map((tool) => ({
152 mcpServer: tool.mcpServer,
153 tools: tool.tools,
154 })),
155 createTime: policy.createTime,
156 updateTime: policy.updateTime,
157 };
158 };
159
160 const getByName = (name: string) =>
161 name.length === 0
162 ? Effect.undefined
163 : aiplatform
164 .getProjectsLocationsSemanticGovernancePolicies({ name })
165 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
166
167 const waitUntilExists = (name: string) =>
168 getByName(name).pipe(
169 Effect.flatMap((policy) =>
170 policy
171 ? Effect.succeed(policy)
172 : Effect.fail(new SemanticGovernancePolicyNotResolved({ resourceName: name })),
173 ),
174 Effect.retry({
175 while: (error) => error._tag === "GCP.AIPlatform.SemanticGovernancePolicyNotResolved",
176 times: 8,
177 schedule: Schedule.spaced("2 seconds"),
178 }),
179 );
180
181 const listAt = (parent: string, project: string) =>
182 aiplatform.listProjectsLocationsSemanticGovernancePolicies.pages({ parent, pageSize: 100 }).pipe(
183 Stream.flatMap((page) => Stream.fromIterable(page.semanticGovernancePolicies ?? [])),
184 Stream.filter((policy) => hasOwnershipMarker(policy.description)),
185 Stream.map((policy) => toAttrs(policy, project)),
186 Stream.runCollect,
187 Effect.map((chunk) => Array.from(chunk)),
188 Effect.catchTag("NotFound", () => Effect.succeed([])),
189 );
190
191 const mcpKey = (tools: McpTool[] | undefined) =>
192 JSON.stringify(
193 (tools ?? []).map((tool) => ({
194 mcpServer: tool.mcpServer ?? "",
195 tools: [...(tool.tools ?? [])].sort(),
196 })),
197 );
198
199 export const SemanticGovernancePolicyProvider = () =>
200 Provider.succeed(SemanticGovernancePolicy, {
201 stables: ["name", "semanticGovernancePolicyId", "location", "project", "createTime"],
202
203 diff: Effect.fn(function* ({ news, olds, output }) {
204 if (!isResolved(news)) return undefined;
205 const previousLocation = olds?.location ?? output?.location;
206 const nextLocation = news.location ?? previousLocation;
207 if (previousLocation !== undefined && previousLocation !== nextLocation) {
208 return { action: "replace" as const, deleteFirst: false };
209 }
210 const previousId = olds?.semanticGovernancePolicyId ?? output?.semanticGovernancePolicyId;
211 if (
212 previousId !== undefined &&
213 news.semanticGovernancePolicyId !== undefined &&
214 news.semanticGovernancePolicyId !== previousId
215 ) {
216 return { action: "replace" as const, deleteFirst: true };
217 }
218 return undefined;
219 }),
220
221 read: Effect.fn(function* ({ id, olds, output, previous }) {
222 const env = yield* GcpEnvironment.current;
223 const policyId = yield* toResourceId(
224 id,
225 olds?.semanticGovernancePolicyId,
226 output?.semanticGovernancePolicyId,
227 );
228 const location = olds?.location ?? output?.location ?? env.region;
229 const name = output?.name ?? resourceName(locationParent(env.project, location), policyId);
230 const existing = yield* getByName(name);
231 if (existing === undefined) return undefined;
232 const attrs = toAttrs(existing, env.project);
233 return (yield* ownedByAlchemy(id, existing.description))
234 ? attrs
235 : unownedUnlessPrevious(attrs, previous, "name");
236 }),
237
238 list: () =>
239 Effect.gen(function* () {
240 const env = yield* GcpEnvironment.current;
241 return (yield* Effect.forEach(listLocations(env.region), (location) =>
242 listAt(locationParent(env.project, location), env.project),
243 )).flat();
244 }),
245
246 reconcile: Effect.fn(function* ({ id, news, output }) {
247 const env = yield* GcpEnvironment.current;
248 const location = news.location ?? output?.location ?? env.region;
249 const parent = locationParent(env.project, location);
250 const policyId = yield* toResourceId(
251 id,
252 news.semanticGovernancePolicyId,
253 output?.semanticGovernancePolicyId,
254 );
255 const name = resourceName(parent, policyId);
256 const ownership = yield* createInternalLabels(id);
257 const desiredDescription = encodeOwnership(ownership, news.description);
258 const displayName = news.displayName ?? policyId;
259 const mcpTools = news.mcpTools?.map((tool) => ({
260 mcpServer: tool.mcpServer,
261 tools: tool.tools,
262 }));
263
264 let current = yield* getByName(output?.name ?? name);
265
266 if (current === undefined) {
267 const created = yield* aiplatform
268 .createProjectsLocationsSemanticGovernancePolicies({
269 parent,
270 semanticGovernancePolicyId: policyId,
271 body: {
272 displayName,
273 description: desiredDescription,
274 agent: news.agent,
275 naturalLanguageConstraint: news.naturalLanguageConstraint,
276 mcpTools,
277 },
278 })
279 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
280 if (created !== undefined) {
281 const done = yield* waitForOperation(created, {
282 alreadyExistsOk: true,
283 });
284 const createdName = resourceNameFromOperation(done) ?? name;
285 current = yield* waitUntilExists(createdName);
286 } else {
287 current = yield* getByName(name);
288 }
289 }
290
291 if (current === undefined) {
292 return yield* new SemanticGovernancePolicyNotResolved({ resourceName: name });
293 }
294
295 const displayChanged = (current.displayName ?? "") !== displayName;
296 const descriptionChanged = (current.description ?? "") !== desiredDescription;
297 const agentChanged = (current.agent ?? "") !== news.agent;
298 const constraintChanged =
299 (current.naturalLanguageConstraint ?? "") !== news.naturalLanguageConstraint;
300 const mcpChanged = mcpKey(current.mcpTools) !== mcpKey(news.mcpTools);
301
302 if (displayChanged || descriptionChanged || agentChanged || constraintChanged || mcpChanged) {
303 const patched = yield* aiplatform.patchProjectsLocationsSemanticGovernancePolicies({
304 name,
305 updateMask: [
306 displayChanged ? "displayName" : undefined,
307 descriptionChanged ? "description" : undefined,
308 agentChanged ? "agent" : undefined,
309 constraintChanged ? "naturalLanguageConstraint" : undefined,
310 mcpChanged ? "mcpTools" : undefined,
311 ]
312 .filter((field): field is string => field !== undefined)
313 .join(","),
314 body: {
315 name,
316 displayName,
317 description: desiredDescription,
318 agent: news.agent,
319 naturalLanguageConstraint: news.naturalLanguageConstraint,
320 mcpTools,
321 etag: current.etag,
322 },
323 });
324 yield* waitForOperation(patched);
325 current = yield* waitUntilExists(name);
326 }
327
328 return toAttrs(current, env.project);
329 }),
330
331 delete: Effect.fn(function* ({ output }) {
332 const existing = yield* getByName(output.name);
333 if (existing === undefined) return;
334 const operation = yield* aiplatform
335 .deleteProjectsLocationsSemanticGovernancePolicies({
336 name: output.name,
337 })
338 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
339 if (operation !== undefined) {
340 yield* waitForOperation(operation, { notFoundOk: true });
341 }
342 }),
343 });