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
| 1 | import * as ces from "@distilled.cloud/gcp/ces_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 | collectPages, |
| 13 | encodeOwnership, |
| 14 | expandApp, |
| 15 | forEachApp, |
| 16 | hasOwnershipMarker, |
| 17 | normalizeLocation, |
| 18 | ownedByAlchemy, |
| 19 | parseOwnership, |
| 20 | parseResourceName, |
| 21 | replaceOnIdentity, |
| 22 | retryTransient, |
| 23 | sameJson, |
| 24 | sameText, |
| 25 | toPhysicalId, |
| 26 | updateMaskOf, |
| 27 | waitUntilGone, |
| 28 | } from "./internal.ts"; |
| 29 | |
| 30 | const DEFAULT_CONTENT_FILTER: ces.GuardrailContentFilter = { |
| 31 | matchType: "SIMPLE_STRING_MATCH", |
| 32 | bannedContents: ["alchemy-ban"], |
| 33 | }; |
| 34 | |
| 35 | export type AppsGuardrailProps = { |
| 36 | /** |
| 37 | * Parent CES app. Full name |
| 38 | * `projects/{project}/locations/{location}/apps/{app}` or the app id |
| 39 | * (combined with `location`). Immutable — changing it replaces the |
| 40 | * guardrail. |
| 41 | */ |
| 42 | app: string; |
| 43 | /** |
| 44 | * Region used when `app` is a bare id. |
| 45 | * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`) |
| 46 | */ |
| 47 | location?: string; |
| 48 | /** |
| 49 | * Guardrail id. If omitted, a unique name is generated. Immutable — |
| 50 | * changing it replaces the guardrail. |
| 51 | */ |
| 52 | guardrailId?: string; |
| 53 | /** |
| 54 | * Human-readable name. Required by the API; Alchemy falls back to the |
| 55 | * generated guardrail id. |
| 56 | */ |
| 57 | displayName?: string; |
| 58 | /** |
| 59 | * Human-readable description. Guardrails have no labels field, so |
| 60 | * Alchemy stamps ownership into this field. |
| 61 | */ |
| 62 | description?: string; |
| 63 | /** |
| 64 | * Whether the guardrail is enabled. |
| 65 | * @default true |
| 66 | */ |
| 67 | enabled?: boolean; |
| 68 | /** |
| 69 | * Phrase / regexp content filter. Defaults to a simple-string match |
| 70 | * on `alchemy-ban` when no other check is set. |
| 71 | */ |
| 72 | contentFilter?: ces.GuardrailContentFilter; |
| 73 | /** |
| 74 | * LLM policy check. |
| 75 | */ |
| 76 | llmPolicy?: ces.GuardrailLlmPolicy; |
| 77 | /** |
| 78 | * Prompt-security check. |
| 79 | */ |
| 80 | llmPromptSecurity?: ces.GuardrailLlmPromptSecurity; |
| 81 | /** |
| 82 | * Model safety overrides. |
| 83 | */ |
| 84 | modelSafety?: ces.GuardrailModelSafety; |
| 85 | /** |
| 86 | * Code-callback check. |
| 87 | */ |
| 88 | codeCallback?: ces.GuardrailCodeCallback; |
| 89 | /** |
| 90 | * Action taken when the guardrail triggers. |
| 91 | */ |
| 92 | action?: ces.TriggerAction; |
| 93 | }; |
| 94 | |
| 95 | export type AppsGuardrail = Resource< |
| 96 | "GCP.CES.AppsGuardrail", |
| 97 | AppsGuardrailProps, |
| 98 | { |
| 99 | /** Full resource name `.../apps/{app}/guardrails/{guardrail}`. */ |
| 100 | name: string; |
| 101 | /** Guardrail id (last path segment). */ |
| 102 | guardrailId: string; |
| 103 | /** Parent app resource name. */ |
| 104 | app: string; |
| 105 | /** Location id. */ |
| 106 | location: string; |
| 107 | /** Project id. */ |
| 108 | project: string; |
| 109 | /** Display name. */ |
| 110 | displayName: string | undefined; |
| 111 | /** User description with the Alchemy ownership prefix stripped. */ |
| 112 | description: string | undefined; |
| 113 | /** Whether the guardrail is enabled. */ |
| 114 | enabled: boolean; |
| 115 | /** Content filter. */ |
| 116 | contentFilter: ces.GuardrailContentFilter | undefined; |
| 117 | /** LLM policy. */ |
| 118 | llmPolicy: ces.GuardrailLlmPolicy | undefined; |
| 119 | /** Prompt-security check. */ |
| 120 | llmPromptSecurity: ces.GuardrailLlmPromptSecurity | undefined; |
| 121 | /** Model safety overrides. */ |
| 122 | modelSafety: ces.GuardrailModelSafety | undefined; |
| 123 | /** Code-callback check. */ |
| 124 | codeCallback: ces.GuardrailCodeCallback | undefined; |
| 125 | /** Trigger action. */ |
| 126 | action: ces.TriggerAction | undefined; |
| 127 | /** RFC3339 creation timestamp. */ |
| 128 | createTime: string | undefined; |
| 129 | /** RFC3339 last-update timestamp. */ |
| 130 | updateTime: string | undefined; |
| 131 | /** Server-assigned etag. */ |
| 132 | etag: string | undefined; |
| 133 | }, |
| 134 | never, |
| 135 | Providers |
| 136 | >; |
| 137 | |
| 138 | /** |
| 139 | * A Customer Engagement Suite guardrail — content filter, LLM policy, |
| 140 | * model safety, or callback checks attached to an app or agent. |
| 141 | * |
| 142 | * Guardrails have no labels field — Alchemy stamps ownership into |
| 143 | * `description` so `list` / nuke can find them. Parent app, location, |
| 144 | * and guardrail id are immutable. |
| 145 | * |
| 146 | * ### Creating a Guardrail |
| 147 | * **Example:** Banned-phrase filter |
| 148 | * ```typescript |
| 149 | * const guardrail = yield* GCP.CES.AppsGuardrail("Safety", { |
| 150 | * app: app.name, |
| 151 | * displayName: "safety", |
| 152 | * contentFilter: { |
| 153 | * matchType: "SIMPLE_STRING_MATCH", |
| 154 | * bannedContents: ["forbidden"], |
| 155 | * }, |
| 156 | * }); |
| 157 | * ``` |
| 158 | * |
| 159 | * @resource |
| 160 | * @category CES |
| 161 | */ |
| 162 | export const AppsGuardrail = Resource<AppsGuardrail>("GCP.CES.AppsGuardrail"); |
| 163 | |
| 164 | export class AppsGuardrailNotResolved extends Data.TaggedError("GCP.CES.AppsGuardrailNotResolved")<{ |
| 165 | resourceName: string; |
| 166 | }> {} |
| 167 | |
| 168 | const resourceName = (app: string, guardrailId: string) => `${app}/guardrails/${guardrailId}`; |
| 169 | |
| 170 | const defaultFilter = (news: AppsGuardrailProps) => { |
| 171 | if ( |
| 172 | news.contentFilter || |
| 173 | news.llmPolicy || |
| 174 | news.llmPromptSecurity || |
| 175 | news.modelSafety || |
| 176 | news.codeCallback |
| 177 | ) { |
| 178 | return news.contentFilter; |
| 179 | } |
| 180 | return DEFAULT_CONTENT_FILTER; |
| 181 | }; |
| 182 | |
| 183 | const toAttrs = (guardrail: ces.Guardrail, project: string, region: string, appHint?: string) => { |
| 184 | const name = guardrail.name ?? ""; |
| 185 | const parsed = parseResourceName(name, "guardrails", region); |
| 186 | return { |
| 187 | name, |
| 188 | guardrailId: parsed.id, |
| 189 | app: name.includes("/guardrails/") ? parsed.app : (appHint ?? parsed.parent), |
| 190 | location: parsed.location, |
| 191 | project: parsed.project || project, |
| 192 | displayName: guardrail.displayName, |
| 193 | description: parseOwnership(guardrail.description).text, |
| 194 | enabled: guardrail.enabled !== false, |
| 195 | contentFilter: guardrail.contentFilter, |
| 196 | llmPolicy: guardrail.llmPolicy, |
| 197 | llmPromptSecurity: guardrail.llmPromptSecurity, |
| 198 | modelSafety: guardrail.modelSafety, |
| 199 | codeCallback: guardrail.codeCallback, |
| 200 | action: guardrail.action, |
| 201 | createTime: guardrail.createTime, |
| 202 | updateTime: guardrail.updateTime, |
| 203 | etag: guardrail.etag, |
| 204 | }; |
| 205 | }; |
| 206 | |
| 207 | const getByName = (name: string) => |
| 208 | name.length === 0 |
| 209 | ? Effect.undefined |
| 210 | : ces |
| 211 | .getProjectsLocationsAppsGuardrails({ name }) |
| 212 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 213 | |
| 214 | const listAt = (parent: string, project: string, region: string) => |
| 215 | collectPages( |
| 216 | ces.listProjectsLocationsAppsGuardrails.pages({ parent, pageSize: 100 }), |
| 217 | (page) => page.guardrails, |
| 218 | ).pipe( |
| 219 | Effect.map((guardrails) => |
| 220 | guardrails |
| 221 | .filter((guardrail) => hasOwnershipMarker(guardrail.description)) |
| 222 | .map((guardrail) => toAttrs(guardrail, project, region, parent)), |
| 223 | ), |
| 224 | ); |
| 225 | |
| 226 | export const AppsGuardrailProvider = () => |
| 227 | Provider.succeed(AppsGuardrail, { |
| 228 | stables: ["name", "guardrailId", "app", "location", "project", "createTime"], |
| 229 | |
| 230 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 231 | if (!isResolved(news)) return undefined; |
| 232 | return replaceOnIdentity({ |
| 233 | previousId: olds?.guardrailId ?? output?.guardrailId, |
| 234 | nextId: news.guardrailId, |
| 235 | previousParent: olds?.app ?? output?.app, |
| 236 | nextParent: news.app, |
| 237 | }); |
| 238 | }), |
| 239 | |
| 240 | read: Effect.fn(function* ({ id, olds, output }) { |
| 241 | const env = yield* GcpEnvironment.current; |
| 242 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 243 | const app = olds?.app ? expandApp(olds.app, env.project, location) : output?.app; |
| 244 | const guardrailId = yield* toPhysicalId(id, olds?.guardrailId, output?.guardrailId); |
| 245 | const name = output?.name ?? (app !== undefined ? resourceName(app, guardrailId) : ""); |
| 246 | const existing = yield* getByName(name); |
| 247 | if (existing === undefined) return undefined; |
| 248 | const attrs = toAttrs(existing, env.project, env.region, app); |
| 249 | return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs); |
| 250 | }), |
| 251 | |
| 252 | list: () => |
| 253 | Effect.gen(function* () { |
| 254 | const env = yield* GcpEnvironment.current; |
| 255 | return yield* forEachApp( |
| 256 | env.project, |
| 257 | (parent) => listAt(parent, env.project, env.region), |
| 258 | env.region, |
| 259 | ); |
| 260 | }), |
| 261 | |
| 262 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 263 | const env = yield* GcpEnvironment.current; |
| 264 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 265 | const app = expandApp(news.app, env.project, location); |
| 266 | const guardrailId = yield* toPhysicalId(id, news.guardrailId, output?.guardrailId); |
| 267 | const name = output?.name ?? resourceName(app, guardrailId); |
| 268 | const ownership = yield* createInternalLabels(id); |
| 269 | const description = encodeOwnership(ownership, news.description); |
| 270 | const displayName = news.displayName ?? guardrailId; |
| 271 | const enabled = news.enabled !== false; |
| 272 | const contentFilter = defaultFilter(news); |
| 273 | |
| 274 | let current = yield* getByName(name); |
| 275 | |
| 276 | if (current === undefined) { |
| 277 | const created = yield* retryTransient( |
| 278 | ces.createProjectsLocationsAppsGuardrails({ |
| 279 | parent: app, |
| 280 | guardrailId, |
| 281 | body: { |
| 282 | displayName, |
| 283 | description, |
| 284 | enabled, |
| 285 | contentFilter, |
| 286 | llmPolicy: news.llmPolicy, |
| 287 | llmPromptSecurity: news.llmPromptSecurity, |
| 288 | modelSafety: news.modelSafety, |
| 289 | codeCallback: news.codeCallback, |
| 290 | action: news.action, |
| 291 | }, |
| 292 | }), |
| 293 | ).pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 294 | current = created ?? undefined; |
| 295 | } |
| 296 | |
| 297 | if (current === undefined) { |
| 298 | return yield* new AppsGuardrailNotResolved({ resourceName: name }); |
| 299 | } |
| 300 | |
| 301 | const currentName = current.name ?? name; |
| 302 | const displayChanged = !sameText(current.displayName, displayName); |
| 303 | const descriptionChanged = !sameText(current.description, description); |
| 304 | const enabledChanged = (current.enabled !== false) !== enabled; |
| 305 | const filterChanged = !sameJson(current.contentFilter, contentFilter); |
| 306 | const policyChanged = !sameJson(current.llmPolicy, news.llmPolicy); |
| 307 | const promptChanged = !sameJson(current.llmPromptSecurity, news.llmPromptSecurity); |
| 308 | const safetyChanged = !sameJson(current.modelSafety, news.modelSafety); |
| 309 | const callbackChanged = !sameJson(current.codeCallback, news.codeCallback); |
| 310 | const actionChanged = !sameJson(current.action, news.action); |
| 311 | |
| 312 | if ( |
| 313 | displayChanged || |
| 314 | descriptionChanged || |
| 315 | enabledChanged || |
| 316 | filterChanged || |
| 317 | policyChanged || |
| 318 | promptChanged || |
| 319 | safetyChanged || |
| 320 | callbackChanged || |
| 321 | actionChanged |
| 322 | ) { |
| 323 | current = yield* retryTransient( |
| 324 | ces.patchProjectsLocationsAppsGuardrails({ |
| 325 | name: currentName, |
| 326 | updateMask: updateMaskOf( |
| 327 | displayChanged ? "display_name" : undefined, |
| 328 | descriptionChanged ? "description" : undefined, |
| 329 | enabledChanged ? "enabled" : undefined, |
| 330 | filterChanged ? "content_filter" : undefined, |
| 331 | policyChanged ? "llm_policy" : undefined, |
| 332 | promptChanged ? "llm_prompt_security" : undefined, |
| 333 | safetyChanged ? "model_safety" : undefined, |
| 334 | callbackChanged ? "code_callback" : undefined, |
| 335 | actionChanged ? "action" : undefined, |
| 336 | ), |
| 337 | body: { |
| 338 | displayName, |
| 339 | description, |
| 340 | enabled, |
| 341 | contentFilter, |
| 342 | llmPolicy: news.llmPolicy, |
| 343 | llmPromptSecurity: news.llmPromptSecurity, |
| 344 | modelSafety: news.modelSafety, |
| 345 | codeCallback: news.codeCallback, |
| 346 | action: news.action, |
| 347 | }, |
| 348 | }), |
| 349 | ); |
| 350 | } |
| 351 | |
| 352 | return toAttrs(current, env.project, env.region, app); |
| 353 | }), |
| 354 | |
| 355 | delete: Effect.fn(function* ({ output }) { |
| 356 | if (!output.name) return; |
| 357 | // `force: true` makes guardrail deletes fail with 500 INTERNAL. |
| 358 | yield* retryTransient(ces.deleteProjectsLocationsAppsGuardrails({ name: output.name })).pipe( |
| 359 | Effect.catchTag("NotFound", () => Effect.void), |
| 360 | ); |
| 361 | yield* waitUntilGone(getByName(output.name)); |
| 362 | }), |
| 363 | }); |